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 (#7112)

白熱2ef6b4210c4a
diff --git a/codecov.yml b/codecov.yml
index 604e2010ce..fa5534cd57 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -3,7 +3,7 @@ coverage:
project:
default:
# basic
- target: 70%
+ target: 78%
threshold: 0
base: auto
# advanced settings
diff --git a/common/shared/vitest/index.ts b/common/shared/vitest/index.ts
index 5d0982fc9f..b0a708d27e 100644
--- a/common/shared/vitest/index.ts
+++ b/common/shared/vitest/index.ts
@@ -58,7 +58,6 @@ export default function createConfig(options?: any) {
'lib/**',
'src/locale/**',
'**/*.stories.tsx',
- '**/__testing__/**',
'**/*/tailwind.config.ts',
'packages/protocol/**',
'packages/slides/**',
@@ -68,6 +67,7 @@ export default function createConfig(options?: any) {
'**/src/mobile-plugin.ts',
'**/src/facade/index.ts',
'**/src/config/config.ts',
+ '**/src/controllers/components.controller.ts',
],
},
},
diff --git a/packages/core/package.json b/packages/core/package.json
index f343261de7..d4a89f65bf 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -85,7 +85,6 @@
"fast-diff": "1.3.0",
"kdbush": "^4.1.0",
"lodash-es": "^4.18.1",
- "nanoid": "5.1.11",
"numfmt": "3.2.6",
"ot-json1": "^1.0.2",
"rbush": "^4.0.1"
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 6ce69f7594..7d6efe4129 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -20,7 +20,8 @@ import type { IPaddingData } from '../../types/interfaces/i-style-data';
import type { JSONXActions } from './json-x/json-x';
import { BehaviorSubject } from 'rxjs';
import { UnitModel, UniverInstanceType } from '../../common/unit';
-import { generateRandomId, Tools } from '../../shared/tools';
+import { generateRandomId } from '../../shared/random-id';
+import { Tools } from '../../shared/tools';
import { getEmptySnapshot } from './empty-snapshot';
import { JSONX } from './json-x/json-x';
import { PRESET_LIST_TYPE } from './preset-list-type';
diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.ts
index 9b35fc2917..a9e2f0c0d3 100644
--- a/packages/core/src/docs/data-model/empty-snapshot.ts
+++ b/packages/core/src/docs/data-model/empty-snapshot.ts
@@ -15,7 +15,7 @@
*/
import type { IDocumentData } from '../../types/interfaces';
-import { generateRandomId } from '../../shared/tools';
+import { generateRandomId } from '../../shared/random-id';
import { DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '../../types/const';
import { BooleanNumber } from '../../types/enum';
import { LocaleType } from '../../types/enum/locale-type';
diff --git a/packages/core/src/docs/data-model/rich-text-builder.ts b/packages/core/src/docs/data-model/rich-text-builder.ts
index a9bdbce689..5f539b9173 100644
--- a/packages/core/src/docs/data-model/rich-text-builder.ts
+++ b/packages/core/src/docs/data-model/rich-text-builder.ts
@@ -16,8 +16,23 @@
import type { Nullable } from '../../shared';
import type { BaselineOffset, HorizontalAlign, TextDecoration, TextDirection } from '../../types/enum';
-import type { IBorderData, IColorStyle, IDocumentBody, IDocumentData, INumberUnit, IParagraphBorder, IParagraphStyle, IShading, ITabStop, ITextDecoration, ITextStyle, NamedStyleType, SpacingRule } from '../../types/interfaces';
-import { generateRandomId, Tools } from '../../shared';
+import type {
+ IBorderData,
+ IColorStyle,
+ IDocumentBody,
+ IDocumentData,
+ INumberUnit,
+ IParagraphBorder,
+ IParagraphStyle,
+ IShading,
+ ITabStop,
+ ITextDecoration,
+ ITextStyle,
+ NamedStyleType,
+ SpacingRule,
+} from '../../types/interfaces';
+import { Tools } from '../../shared';
+import { generateRandomId } from '../../shared/random-id';
import { BooleanNumber } from '../../types/enum';
import { CustomRangeType } from '../../types/interfaces';
import { createParagraphId } from '../paragraph-id';
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/__tests__/custom-decoration.spec.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-decoration.spec.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/custom-decoration.spec.ts
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/custom-range.spec.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-range.spec.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/custom-range.spec.ts
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/__tests__/drawings.spec.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/drawings.spec.ts
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/__tests__/paragraph.spec.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/paragraph.spec.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/paragraph.spec.ts
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/__tests__/parse.spec.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/parse.spec.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/parse.spec.ts
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/selection.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/selection.spec.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/selection.spec.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/selection.spec.ts
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/text-x.ts b/packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x.ts
similarity index 100%
rename from packages/core/src/docs/data-model/text-x/build-utils/__test__/text-x.ts
rename to packages/core/src/docs/data-model/text-x/build-utils/__tests__/text-x.ts
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
index 6eb7208d1c..88c4886617 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/custom-range.ts
@@ -16,7 +16,8 @@
import type { ITextRange } from '../../../../sheets/typedef';
import type { CustomRangeType, ICustomRange, IDocumentBody } from '../../../../types/interfaces';
-import { generateRandomId, Tools } from '../../../../shared';
+import { Tools } from '../../../../shared';
+import { generateRandomId } from '../../../../shared/random-id';
/**
* Check if two ranges intersect
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts
index 2409629265..6dad0364c6 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts
@@ -18,7 +18,8 @@ import type { ITextRange } from '../../../../sheets/typedef';
import type { ICustomTable, IParagraph, IParagraphStyle, ITextStyle } from '../../../../types/interfaces';
import type { DocumentDataModel } from '../../document-data-model';
import { MemoryCursor } from '../../../../common/memory-cursor';
-import { generateRandomId, UpdateDocsAttributeType } from '../../../../shared';
+import { UpdateDocsAttributeType } from '../../../../shared';
+import { generateRandomId } from '../../../../shared/random-id';
import { PRESET_LIST_TYPE, PresetListType } from '../../preset-list-type';
import { TextXActionType } from '../action-types';
import { TextX } from '../text-x';
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/parse.ts b/packages/core/src/docs/data-model/text-x/build-utils/parse.ts
index f063a91442..0129a0840e 100644
--- a/packages/core/src/docs/data-model/text-x/build-utils/parse.ts
+++ b/packages/core/src/docs/data-model/text-x/build-utils/parse.ts
@@ -15,7 +15,8 @@
*/
import type { ICustomRange, IDocumentBody, IParagraph } from '../../../../types/interfaces';
-import { generateRandomId, Tools } from '../../../../shared';
+import { Tools } from '../../../../shared';
+import { generateRandomId } from '../../../../shared/random-id';
import { CustomRangeType } from '../../../../types/interfaces';
import { createParagraphId } from '../../../paragraph-id';
import { DataStreamTreeTokenType } from '../../types';
diff --git a/packages/core/src/docs/paragraph-id.ts b/packages/core/src/docs/paragraph-id.ts
index 944a1497fe..14752c50bc 100644
--- a/packages/core/src/docs/paragraph-id.ts
+++ b/packages/core/src/docs/paragraph-id.ts
@@ -15,7 +15,7 @@
*/
import type { IDocumentBody, IParagraph } from '../types/interfaces/i-document-data';
-import { generateRandomId } from '../shared/tools';
+import { generateRandomId } from '../shared/random-id';
export const PARAGRAPH_ID_PREFIX = 'para_';
diff --git a/packages/core/src/facade/f-util.ts b/packages/core/src/facade/f-util.ts
index e2c2729c66..39382b8527 100644
--- a/packages/core/src/facade/f-util.ts
+++ b/packages/core/src/facade/f-util.ts
@@ -89,7 +89,7 @@ export class FUtil {
*
* @example
* ```ts
- * const key = univerAPI.Util.tools.generateRandomId(6);
+ * const key = univerAPI.Util.tools.isDate();
* console.log(key);
* ```
*/
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 6f4634258e..81050be31c 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -103,8 +103,8 @@ export {
cloneBodyWithFreshParagraphIds,
cloneParagraphWithId,
createParagraphId,
- PARAGRAPH_ID_PREFIX,
type IParagraphIdScope,
+ PARAGRAPH_ID_PREFIX,
} from './docs/paragraph-id';
export { EventState, EventSubject, fromEventSubject, type IEventObserver } from './observer/observable';
export { AuthzIoLocalService } from './services/authz-io/authz-io-local.service';
@@ -183,6 +183,7 @@ export { isBlackColor, isWhiteColor } from './shared/color/color-kit';
export { cellToRange } from './shared/common';
export { customNameCharacterCheck, nameCharacterCheck } from './shared/name';
export { type BBox, type IRTreeItem, RBush, RTree } from './shared/r-tree';
+export { generateRandomId } from './shared/random-id';
export { getIntersectRange } from './shared/range';
export { afterTime, bufferDebounceTime, convertObservableToBehaviorSubject, fromCallback, takeAfter } from './shared/rxjs';
export { awaitTime, delayAnimationFrame } from './shared/timer';
diff --git a/packages/core/src/services/authz-io/authz-io-local.service.ts b/packages/core/src/services/authz-io/authz-io-local.service.ts
index 49e1876cd2..f6496d9271 100644
--- a/packages/core/src/services/authz-io/authz-io-local.service.ts
+++ b/packages/core/src/services/authz-io/authz-io-local.service.ts
@@ -33,7 +33,7 @@ import type { IAuthzIoService } from './type';
import { ObjectScope, UnitRole } from '@univerjs/protocol';
import { Inject } from '../../common/di';
import { UniverInstanceType } from '../../common/unit';
-import { generateRandomId } from '../../shared/tools';
+import { generateRandomId } from '../../shared/random-id';
import { IResourceManagerService } from '../resource-manager/type';
import { createDefaultUser, isDevRole } from '../user-manager/const';
diff --git a/packages/core/src/services/user-manager/const.ts b/packages/core/src/services/user-manager/const.ts
index 776cd83d6c..534e6a00b2 100644
--- a/packages/core/src/services/user-manager/const.ts
+++ b/packages/core/src/services/user-manager/const.ts
@@ -16,7 +16,7 @@
import type { IUser } from '@univerjs/protocol';
import { UnitRole } from '@univerjs/protocol';
-import { generateRandomId } from '../../shared/tools';
+import { generateRandomId } from '../../shared/random-id';
const nameMap = {
[UnitRole.Editor]: 'Editor',
diff --git a/packages/core/src/shared/__tests__/random-id.spec.ts b/packages/core/src/shared/__tests__/random-id.spec.ts
new file mode 100644
index 0000000000..252e023065
--- /dev/null
+++ b/packages/core/src/shared/__tests__/random-id.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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { createRandomId, generateRandomId } from '../random-id';
+
+function mockCrypto(bytes: number[]) {
+ let offset = 0;
+ const getRandomValues = vi.fn((array: Uint8Array) => {
+ for (let i = 0; i < array.length; i++) {
+ array[i] = bytes[offset++ % bytes.length];
+ }
+ return array;
+ });
+
+ vi.stubGlobal('crypto', { getRandomValues });
+
+ return getRandomValues;
+}
+
+describe('createRandomId', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('should generate a URL-safe id with the default size', () => {
+ expect(createRandomId()).toHaveLength(21);
+ expect(createRandomId()).toMatch(/^[A-Za-z0-9_-]{21}$/);
+ });
+
+ it('should use the requested size and custom alphabet', () => {
+ mockCrypto([0, 1, 2, 3]);
+
+ expect(createRandomId(6, 'abcd')).toBe('abcdab');
+ });
+
+ it('should return an empty id for size 0', () => {
+ expect(createRandomId(0)).toBe('');
+ });
+
+ it('should skip biased crypto bytes outside the safe cutoff', () => {
+ mockCrypto([250, 0, 1, 2]);
+
+ expect(createRandomId(3, '0123456789')).toBe('012');
+ });
+
+ it('should read random values from self.crypto when global crypto is unavailable', () => {
+ const getRandomValues = vi.fn((array: Uint8Array) => {
+ array.fill(1);
+ return array;
+ });
+
+ vi.stubGlobal('crypto', undefined);
+ vi.stubGlobal('self', { crypto: { getRandomValues } });
+
+ expect(createRandomId(4, 'ab')).toBe('bbbb');
+ expect(getRandomValues).toHaveBeenCalled();
+ });
+
+ it('should fall back to Math.random when crypto is unavailable', () => {
+ vi.stubGlobal('crypto', undefined);
+ vi.stubGlobal('self', undefined);
+ vi.stubGlobal('window', undefined);
+ vi.spyOn(Math, 'random').mockReturnValue(0.75);
+
+ expect(createRandomId(4, 'ab')).toBe('bbbb');
+ });
+
+ it('should expose generateRandomId as the compatibility API', () => {
+ mockCrypto([0, 1]);
+
+ expect(generateRandomId(4, 'ab')).toBe('abab');
+ });
+});
diff --git a/packages/core/src/shared/__tests__/tools.spec.ts b/packages/core/src/shared/__tests__/tools.spec.ts
index 58d98a4b8c..7c0af5de61 100644
--- a/packages/core/src/shared/__tests__/tools.spec.ts
+++ b/packages/core/src/shared/__tests__/tools.spec.ts
@@ -15,7 +15,7 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createREGEXFromWildChar, generateRandomId, Tools } from '../tools';
+import { createREGEXFromWildChar, Tools } from '../tools';
class CustomProto {
value = 1;
@@ -115,10 +115,6 @@ describe('Tools extra coverage', () => {
expect(Tools.now()).toBe(123.456);
- const customId = generateRandomId(6, 'ab');
- expect(customId).toMatch(/^[ab]{6}$/);
- expect(generateRandomId(5)).toHaveLength(5);
-
const regex = createREGEXFromWildChar('file-??-*.ts');
expect(regex.test('file-ab-index.ts')).toBe(true);
expect(regex.test('file-a-index.ts')).toBe(false);
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index 2f2472f240..a65e677f43 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -46,6 +46,7 @@ export {
} from './numfmt';
export * from './object-matrix';
export { queryObjectMatrix } from './object-matrix-query';
+export * from './random-id';
export { moveRangeByOffset, splitIntoGrid } from './range';
export * from './rectangle';
export { RefAlias } from './ref-alias';
diff --git a/packages/core/src/shared/random-id.ts b/packages/core/src/shared/random-id.ts
new file mode 100644
index 0000000000..159067bdd3
--- /dev/null
+++ b/packages/core/src/shared/random-id.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.
+ */
+
+const URL_SAFE_ALPHABET = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
+
+type GetRandomValues = (array: Uint8Array) => Uint8Array;
+
+function getRandomValues(): GetRandomValues | undefined {
+ const cryptoSource =
+ typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function'
+ ? crypto
+ : typeof self !== 'undefined' && self.crypto && typeof self.crypto.getRandomValues === 'function'
+ ? self.crypto
+ : typeof window !== 'undefined' && window.crypto && typeof window.crypto.getRandomValues === 'function'
+ ? window.crypto
+ : undefined;
+
+ return cryptoSource?.getRandomValues.bind(cryptoSource) as GetRandomValues | undefined;
+}
+
+function createIdByMathRandom(size: number, alphabet: string): string {
+ let id = '';
+ for (let i = 0; i < size; i++) {
+ id += alphabet[Math.floor(Math.random() * alphabet.length)];
+ }
+ return id;
+}
+
+function createIdByCrypto(size: number, alphabet: string, getCryptoRandomValues: GetRandomValues): string {
+ const safeByteCutoff = 256 - (256 % alphabet.length);
+ const step = Math.ceil((1.6 * 256 * size) / safeByteCutoff);
+ let id = '';
+
+ while (id.length < size) {
+ const bytes = getCryptoRandomValues(new Uint8Array(step));
+ for (let i = 0; i < step && id.length < size; i++) {
+ const byte = bytes[i];
+ if (byte < safeByteCutoff) {
+ id += alphabet[byte % alphabet.length];
+ }
+ }
+ }
+
+ return id;
+}
+
+export function createRandomId(size: number = 21, alphabet: string = URL_SAFE_ALPHABET): string {
+ if (!size) {
+ return '';
+ }
+
+ const getCryptoRandomValues = getRandomValues();
+ if (!getCryptoRandomValues) {
+ return createIdByMathRandom(size, alphabet);
+ }
+
+ return createIdByCrypto(size, alphabet, getCryptoRandomValues);
+}
+
+export function generateRandomId(n: number = 21, alphabet?: string): string {
+ return createRandomId(n, alphabet);
+}
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index ec5e790254..21e6061af0 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -16,7 +16,6 @@
import type { IStyleData } from '../types/interfaces';
import type { Nullable } from './types';
-import { customAlphabet, nanoid } from 'nanoid';
import { isLegalUrl, normalizeUrl, topLevelDomainSet } from '../common/url';
/**
@@ -508,14 +507,6 @@ export class Tools {
}
}
-export function generateRandomId(n: number = 21, alphabet?: string): string {
- if (alphabet) {
- return customAlphabet(alphabet, n)();
- }
-
- return nanoid(n);
-}
-
interface IStyleDataObject {
[key: string]: unknown;
}
diff --git a/packages/core/src/sheets/styles.ts b/packages/core/src/sheets/styles.ts
index 4c676f3616..fd5aebd14b 100644
--- a/packages/core/src/sheets/styles.ts
+++ b/packages/core/src/sheets/styles.ts
@@ -17,7 +17,8 @@
import type { Nullable } from '../shared';
import type { IStyleData } from '../types/interfaces';
import type { ICellDataForSheetInterceptor } from './typedef';
-import { generateRandomId, LRUMap, Tools } from '../shared';
+import { LRUMap, Tools } from '../shared';
+import { generateRandomId } from '../shared/random-id';
/**
* Styles in a workbook, cells locate styles based on style IDs
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index 93f95d520c..84176a2d27 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -21,7 +21,8 @@ import type { CustomData, IRangeType, IWorkbookData, IWorksheetData } from './ty
import { BehaviorSubject, Subject } from 'rxjs';
import { UnitModel, UniverInstanceType } from '../common/unit';
import { ILogService } from '../services/log/log.service';
-import { generateRandomId, Tools } from '../shared';
+import { Tools } from '../shared';
+import { generateRandomId } from '../shared/random-id';
import { BooleanNumber } from '../types/enum';
import { getEmptySnapshot } from './empty-snapshot';
import { Styles } from './styles';
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 8989f1f445..29c1a5d73d 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -24,8 +24,8 @@ import type { CustomData, ICellData, ICellDataForSheetInterceptor, ICellDataWith
import { BuildTextUtils, DocumentDataModel } from '../docs';
import { convertTextRotation, getFontStyleString } from '../docs/data-model/utils';
import { composeStyles, ObjectMatrix, toDisposable, Tools } from '../shared';
+import { generateRandomId } from '../shared/random-id';
import { createRowColIter } from '../shared/row-col-iter';
-import { generateRandomId } from '../shared/tools';
import { DEFAULT_STYLES } from '../types/const';
import { CellValueType } from '../types/enum';
import { DocumentFlavor } from '../types/interfaces';
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..bb199a41fc
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.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 { UndoCommand } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { describe, expect, it, vi } from 'vitest';
+import { DocDrawingAddRemoveController } from '../doc-drawing-notification.controller';
+
+function createController() {
+ const beforeHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
+ const executedHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
+ const refreshControls = vi.fn();
+ const drawingManagerService = {
+ applyJson1: vi.fn(),
+ addNotification: vi.fn(),
+ removeNotification: vi.fn(),
+ getFocusDrawings: vi.fn(() => [{ drawingId: 'drawing-1' }]),
+ setDrawingOrder: vi.fn(),
+ orderNotification: vi.fn(),
+ };
+ const docDrawingService = {
+ getBatchAddOp: vi.fn(() => ({ subUnitId: 'doc-1', redo: 'add-op', objects: [{ drawingId: 'drawing-1' }] })),
+ getBatchRemoveOp: vi.fn(() => ({ subUnitId: 'doc-1', redo: 'remove-op', objects: [{ drawingId: 'drawing-1' }] })),
+ applyJson1: vi.fn(),
+ addNotification: vi.fn(),
+ removeNotification: vi.fn(),
+ setDrawingOrder: vi.fn(),
+ orderNotification: vi.fn(),
+ };
+ const controller = new DocDrawingAddRemoveController(
+ {
+ getCurrentUniverDocInstance: vi.fn(() => ({ getUnitId: () => 'doc-1' })),
+ getUniverDocInstance: vi.fn(() => ({ getSnapshot: () => ({ drawingsOrder: ['drawing-2', 'drawing-1'] }) })),
+ } as never,
+ {
+ beforeCommandExecuted: vi.fn((handler) => {
+ beforeHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ onCommandExecuted: vi.fn((handler) => {
+ executedHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ drawingManagerService as never,
+ docDrawingService as never,
+ { getRenderById: vi.fn(() => ({ scene: { getTransformerByCreate: () => ({ refreshControls }) } })) } as never
+ );
+
+ return { controller, beforeHandlers, executedHandlers, drawingManagerService, docDrawingService, refreshControls };
+}
+
+describe('DocDrawingAddRemoveController', () => {
+ it('mirrors added and removed doc drawings into drawing services when rich text mutates drawings', () => {
+ const { controller, beforeHandlers, drawingManagerService, docDrawingService } = createController();
+ const drawing = { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'drawing-1' };
+
+ beforeHandlers[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-1',
+ actions: [['drawings', 'drawing-1', { i: drawing }]],
+ },
+ });
+ beforeHandlers[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-1',
+ actions: [['drawings', 'drawing-1', { d: drawing }]],
+ },
+ });
+
+ expect(docDrawingService.getBatchAddOp).toHaveBeenCalledWith([drawing]);
+ expect(drawingManagerService.applyJson1).toHaveBeenCalledWith('doc-1', 'doc-1', 'add-op');
+ expect(docDrawingService.applyJson1).toHaveBeenCalledWith('doc-1', 'doc-1', 'add-op');
+ expect(drawingManagerService.addNotification).toHaveBeenCalledWith([{ drawingId: 'drawing-1' }]);
+ expect(docDrawingService.addNotification).toHaveBeenCalledWith([{ drawingId: 'drawing-1' }]);
+
+ expect(docDrawingService.getBatchRemoveOp).toHaveBeenCalledWith([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'drawing-1' }]);
+ expect(drawingManagerService.removeNotification).toHaveBeenCalledWith([{ drawingId: 'drawing-1' }]);
+ expect(docDrawingService.removeNotification).toHaveBeenCalledWith([{ drawingId: 'drawing-1' }]);
+
+ controller.dispose();
+ });
+
+ it('updates drawing order and refreshes controls after reorder and undo commands', () => {
+ const { controller, executedHandlers, drawingManagerService, docDrawingService, refreshControls } = createController();
+
+ executedHandlers[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-1',
+ actions: ['drawingsOrder', [0, { d: 0 }], [1, { p: 0 }]],
+ },
+ });
+ executedHandlers[1]({ id: UndoCommand.id });
+
+ expect(drawingManagerService.setDrawingOrder).toHaveBeenCalledWith('doc-1', 'doc-1', ['drawing-2', 'drawing-1']);
+ expect(docDrawingService.setDrawingOrder).toHaveBeenCalledWith('doc-1', 'doc-1', ['drawing-2', 'drawing-1']);
+ expect(drawingManagerService.orderNotification).toHaveBeenCalledWith({
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingIds: ['drawing-2', 'drawing-1'],
+ });
+ expect(docDrawingService.orderNotification).toHaveBeenCalledWith({
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingIds: ['drawing-2', 'drawing-1'],
+ });
+ expect(refreshControls).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.ts
new file mode 100644
index 0000000000..2d01bfa386
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.ts
@@ -0,0 +1,119 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DOC_DRAWING_PRINTING_COMPONENT_KEY, DrawingTypeEnum } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { mountDocPrintingFloatDom } from '../../views/DocPrintingFloatDom';
+import { DocDrawingPrintingController } from '../doc-drawing-printing.controller';
+
+vi.mock('../../views/DocPrintingFloatDom', () => ({
+ mountDocPrintingFloatDom: vi.fn(() => vi.fn()),
+}));
+
+function createController() {
+ const interceptors = new Map<string, any>();
+ const points = {
+ PRINTING_COMPONENT_COLLECT: 'PRINTING_COMPONENT_COLLECT',
+ PRINTING_DOM_COLLECT: 'PRINTING_DOM_COLLECT',
+ };
+ const drawings = {
+ 'unit-1': {
+ order: ['image-1', 'chart-1', 'dom-1'],
+ data: {
+ 'image-1': { drawingId: 'image-1', drawingType: DrawingTypeEnum.DRAWING_IMAGE },
+ 'chart-1': { drawingId: 'chart-1', drawingType: DrawingTypeEnum.DRAWING_CHART },
+ 'dom-1': { drawingId: 'dom-1', drawingType: DrawingTypeEnum.DRAWING_DOM, componentKey: 'custom-dom' },
+ },
+ },
+ };
+ const controller = new DocDrawingPrintingController(
+ {
+ getPrintComponent: vi.fn((key: string) => `${key}-print`),
+ interceptor: {
+ getInterceptPoints: vi.fn(() => points),
+ intercept: vi.fn((point, config) => {
+ interceptors.set(point, config);
+ return { dispose: vi.fn() };
+ }),
+ },
+ } as never,
+ { renderDrawing: vi.fn() } as never,
+ { getDrawingDataForUnit: vi.fn(() => drawings) } as never,
+ {
+ get: vi.fn((key) => {
+ if (key === DOC_DRAWING_PRINTING_COMPONENT_KEY) return 'ChartPrintingComponent';
+ return `${key}-Component`;
+ }),
+ } as never,
+ {} as never
+ );
+
+ return { controller, interceptors, points };
+}
+
+describe('DocDrawingPrintingController', () => {
+ it('renders printable image drawings into the print scene and skips chart/dom canvas rendering', () => {
+ const { controller, interceptors, points } = createController();
+ const next = vi.fn();
+ const scene = {};
+
+ interceptors.get(points.PRINTING_COMPONENT_COLLECT).handler(null, { unitId: 'unit-1', scene }, next);
+
+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledTimes(1);
+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(
+ expect.objectContaining({ drawingId: 'image-1' }),
+ scene
+ );
+ expect(next).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('mounts chart and dom float components for printing and registers cleanup', () => {
+ const { controller, interceptors, points } = createController();
+ const unmount = vi.fn();
+ vi.mocked(mountDocPrintingFloatDom).mockReturnValueOnce(unmount);
+ const add = vi.fn((dispose: () => void) => dispose());
+ const next = vi.fn((value) => value);
+ const disposableCollection = { add };
+
+ const result = interceptors.get(points.PRINTING_DOM_COLLECT).handler(disposableCollection, {
+ unitId: 'unit-1',
+ scene: 'scene',
+ skeleton: 'skeleton',
+ offset: 'offset',
+ bound: 'bound',
+ root: 'root',
+ }, next);
+
+ expect(mountDocPrintingFloatDom).toHaveBeenCalledWith(
+ expect.objectContaining({
+ unitId: 'unit-1',
+ floatDomInfos: [
+ expect.objectContaining({ drawingId: 'chart-1', componentKey: 'ChartPrintingComponent' }),
+ expect.objectContaining({ drawingId: 'dom-1', componentKey: 'custom-dom-print-Component' }),
+ ],
+ }),
+ 'root',
+ expect.any(Object)
+ );
+ expect(add).toHaveBeenCalled();
+ expect(unmount).toHaveBeenCalled();
+ expect(result).toBe(disposableCollection);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.spec.ts
new file mode 100644
index 0000000000..b6baa75f5a
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-float-dom.controller.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 { DrawingTypeEnum } from '@univerjs/core';
+import { Rect } from '@univerjs/engine-render';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { InsertDocDrawingCommand } from '../../commands/commands/insert-doc-drawing.command';
+import { calcDocFloatDomPositionByRect, DocFloatDomController } from '../doc-float-dom.controller';
+
+function createScene() {
+ return {
+ getViewport: vi.fn(() => ({ viewportScrollX: 10, viewportScrollY: 20, onScrollAfter$: new Subject() })),
+ getAncestorScale: vi.fn(() => ({ scaleX: 2, scaleY: 3 })),
+ getTransformerByCreate: vi.fn(() => ({})),
+ removeObject: vi.fn(),
+ };
+}
+
+function createController(options: { rects?: Rect[]; page?: any } = {}) {
+ const add$ = new Subject<any[]>();
+ const remove$ = new Subject<any[]>();
+ const commandHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
+ const scene = createScene();
+ const canvas = { dispatchEvent: vi.fn() };
+ const renderUnit = {
+ scene,
+ engine: { getCanvasElement: () => canvas },
+ with: vi.fn(() => ({
+ getSkeleton: () => ({
+ getSkeletonData: () => ({ pages: [options.page ?? { pageWidth: 240, marginLeft: 20, marginRight: 30 }] }),
+ }),
+ })),
+ };
+ const renderManagerService = {
+ getRenderById: vi.fn(() => renderUnit),
+ };
+ const drawing = {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'dom-1',
+ componentKey: 'FloatDom',
+ drawingType: DrawingTypeEnum.DRAWING_DOM,
+ data: { value: 1 },
+ };
+ const drawingManagerService = {
+ add$,
+ remove$,
+ getDrawingByParam: vi.fn(() => drawing),
+ };
+ const drawingRenderService = {
+ renderFloatDom: vi.fn(async () => options.rects ?? []),
+ };
+ const canvasFloatDomService = {
+ addFloatDom: vi.fn(),
+ removeFloatDom: vi.fn(),
+ };
+ const doc = { getUnitId: () => 'doc-1' };
+ const univerInstanceService = {
+ getUnit: vi.fn(() => doc),
+ getCurrentUnitOfType: vi.fn(() => doc),
+ getCurrentTypeOfUnit$: vi.fn(() => new BehaviorSubject(null)),
+ };
+ const commandService = {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ syncExecuteCommand: vi.fn(),
+ };
+
+ const controller = new DocFloatDomController(
+ renderManagerService as never,
+ drawingManagerService as never,
+ drawingRenderService as never,
+ canvasFloatDomService as never,
+ univerInstanceService as never,
+ commandService as never
+ );
+
+ return {
+ controller,
+ add$,
+ remove$,
+ commandHandlers,
+ scene,
+ canvas,
+ renderUnit,
+ drawingRenderService,
+ canvasFloatDomService,
+ commandService,
+ };
+}
+
+describe('DocFloatDomController', () => {
+ it('calculates float dom bounds using doc viewport scroll and ancestor scale', () => {
+ const scene = createScene();
+
+ expect(calcDocFloatDomPositionByRect({ left: 30, top: 50, right: 80, bottom: 90 }, scene as never, 0.4, 15)).toEqual({
+ startX: 40,
+ startY: 90,
+ endX: 140,
+ endY: 210,
+ width: 100,
+ height: 120,
+ rotate: 15,
+ absolute: { left: false, top: false },
+ opacity: 0.4,
+ });
+ });
+
+ it('adds rendered float doms, updates their position, and removes them with their rect object', async () => {
+ const rect = new Rect('dom-rect', {
+ left: 30,
+ top: 50,
+ width: 50,
+ height: 40,
+ } as never);
+ rect.setOpacity(0.8);
+ const { controller, add$, remove$, scene, drawingRenderService, canvasFloatDomService } = createController({ rects: [rect] });
+
+ add$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'dom-1' }]);
+ await Promise.resolve();
+
+ expect(drawingRenderService.renderFloatDom).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'dom-1' }), scene);
+ expect(canvasFloatDomService.addFloatDom).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'dom-1',
+ componentKey: 'FloatDom',
+ unitId: 'doc-1',
+ data: { value: 1 },
+ }));
+
+ const position$ = canvasFloatDomService.addFloatDom.mock.calls[0][0].position$;
+ const positions: unknown[] = [];
+ const sub = position$.subscribe((position: unknown) => positions.push(position));
+ rect.transformByState({ left: 40, top: 60 });
+
+ expect(positions.at(-1)).toMatchObject({
+ startX: 60,
+ startY: 120,
+ width: 100,
+ height: 120,
+ opacity: 0.8,
+ });
+
+ remove$.next([{ drawingId: 'dom-1' }]);
+ expect(canvasFloatDomService.removeFloatDom).toHaveBeenCalledWith('dom-1');
+ expect(scene.removeObject).toHaveBeenCalledWith(rect);
+
+ sub.unsubscribe();
+ controller.dispose();
+ });
+
+ it('inserts a float dom using page content width when no explicit width is provided', () => {
+ const { controller, commandService } = createController();
+
+ const drawingId = controller.insertFloatDom(
+ { componentKey: 'FloatDom', data: { text: 'hello' } } as never,
+ { height: 36, drawingId: 'fixed-dom-id' }
+ );
+
+ expect(drawingId).toBe('fixed-dom-id');
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(
+ InsertDocDrawingCommand.id,
+ expect.objectContaining({
+ unitId: 'doc-1',
+ drawings: [
+ expect.objectContaining({
+ drawingId: 'fixed-dom-id',
+ drawingType: DrawingTypeEnum.DRAWING_DOM,
+ layoutType: expect.any(Number),
+ docTransform: expect.objectContaining({
+ size: { width: 190, height: 36 },
+ }),
+ }),
+ ],
+ })
+ );
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-drawing-ui/src/controllers/shortcuts/__tests__/drawing.shortcut.spec.ts b/packages/docs-drawing-ui/src/controllers/shortcuts/__tests__/drawing.shortcut.spec.ts
new file mode 100644
index 0000000000..6982d934b9
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/shortcuts/__tests__/drawing.shortcut.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 { Direction, FOCUSING_COMMON_DRAWINGS, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';
+import { KeyCode } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { DeleteDocDrawingsCommand } from '../../../commands/commands/delete-doc-drawing.command';
+import { MoveDocDrawingsCommand } from '../../../commands/commands/move-drawings.command';
+import {
+ DeleteDrawingsShortcutItem,
+ MoveDrawingDownShortcutItem,
+ MoveDrawingLeftShortcutItem,
+ MoveDrawingRightShortcutItem,
+ MoveDrawingUpShortcutItem,
+ whenDocDrawingFocused,
+} from '../drawing.shortcut';
+
+function createContext(values: Record<string, boolean>) {
+ return {
+ getContextValue: vi.fn((key: string) => values[key]),
+ };
+}
+
+describe('doc drawing shortcuts', () => {
+ it('enables drawing shortcuts only when doc editor and common drawing focus are both active', () => {
+ expect(whenDocDrawingFocused(createContext({
+ [FOCUSING_DOC]: true,
+ [FOCUSING_UNIVER_EDITOR]: true,
+ [FOCUSING_COMMON_DRAWINGS]: true,
+ }) as never)).toBe(true);
+
+ expect(whenDocDrawingFocused(createContext({
+ [FOCUSING_DOC]: true,
+ [FOCUSING_UNIVER_EDITOR]: true,
+ [FOCUSING_COMMON_DRAWINGS]: false,
+ }) as never)).toBe(false);
+ });
+
+ it('binds arrow keys to one-pixel drawing move commands', () => {
+ expect([
+ MoveDrawingDownShortcutItem,
+ MoveDrawingUpShortcutItem,
+ MoveDrawingLeftShortcutItem,
+ MoveDrawingRightShortcutItem,
+ ]).toEqual([
+ expect.objectContaining({
+ id: MoveDocDrawingsCommand.id,
+ binding: KeyCode.ARROW_DOWN,
+ staticParameters: { direction: Direction.DOWN },
+ priority: 100,
+ }),
+ expect.objectContaining({
+ id: MoveDocDrawingsCommand.id,
+ binding: KeyCode.ARROW_UP,
+ staticParameters: { direction: Direction.UP },
+ priority: 100,
+ }),
+ expect.objectContaining({
+ id: MoveDocDrawingsCommand.id,
+ binding: KeyCode.ARROW_LEFT,
+ staticParameters: { direction: Direction.LEFT },
+ priority: 100,
+ }),
+ expect.objectContaining({
+ id: MoveDocDrawingsCommand.id,
+ binding: KeyCode.ARROW_RIGHT,
+ staticParameters: { direction: Direction.RIGHT },
+ priority: 100,
+ }),
+ ]);
+ });
+
+ it('binds delete and backspace to drawing deletion with the same focus guard', () => {
+ expect(DeleteDrawingsShortcutItem).toEqual(expect.objectContaining({
+ id: DeleteDocDrawingsCommand.id,
+ binding: KeyCode.DELETE,
+ mac: KeyCode.BACKSPACE,
+ preconditions: whenDocDrawingFocused,
+ }));
+ });
+});
diff --git a/packages/docs-drawing-ui/src/views/__tests__/DocPrintingFloatDom.spec.tsx b/packages/docs-drawing-ui/src/views/__tests__/DocPrintingFloatDom.spec.tsx
new file mode 100644
index 0000000000..f4cc36ad05
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/__tests__/DocPrintingFloatDom.spec.tsx
@@ -0,0 +1,169 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData } from '@univerjs/core';
+import type { IDocFloatDom } from '@univerjs/docs-drawing';
+import type { IBoundRectNoAngle, Scene } from '@univerjs/engine-render';
+import { ComponentManager } from '@univerjs/ui';
+import { act } from 'react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createDocUiTestBed } from '../../__tests__/create-doc-ui-test-bed';
+import { mountDocPrintingFloatDom } from '../DocPrintingFloatDom';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'doc-printing-float-dom-doc';
+const PRINTING_COMPONENT_KEY = 'printing-visible-content';
+
+class TestScene {
+ constructor(
+ private readonly _scroll = { x: 0, y: 0 },
+ private readonly _scale = { x: 1, y: 1 }
+ ) {
+ }
+
+ getViewport() {
+ return {
+ viewportScrollX: this._scroll.x,
+ viewportScrollY: this._scroll.y,
+ };
+ }
+
+ getAncestorScale() {
+ return {
+ scaleX: this._scale.x,
+ scaleY: this._scale.y,
+ };
+ }
+}
+
+function PrintingVisibleContent(props: { data?: { label?: string } }) {
+ return <span>{props.data?.label}</span>;
+}
+
+function createDocData(): IDocumentData {
+ return {
+ id: UNIT_ID,
+ body: {
+ dataStream: '\r\n',
+ },
+ documentStyle: {
+ pageSize: {
+ width: 200,
+ height: 100,
+ },
+ marginTop: 0,
+ marginBottom: 0,
+ marginRight: 0,
+ marginLeft: 0,
+ },
+ };
+}
+
+function createFloatDom(drawingId: string, label: string, bound: IBoundRectNoAngle): IDocFloatDom {
+ return {
+ drawingId,
+ unitId: UNIT_ID,
+ componentKey: PRINTING_COMPONENT_KEY,
+ transform: {
+ left: bound.left,
+ top: bound.top,
+ width: bound.right - bound.left,
+ height: bound.bottom - bound.top,
+ },
+ data: { label },
+ } as unknown as IDocFloatDom;
+}
+
+describe('DocPrintingFloatDom', () => {
+ let root: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createDocUiTestBed> | undefined;
+ let disposePrinting: (() => void) | undefined;
+
+ afterEach(() => {
+ act(() => {
+ disposePrinting?.();
+ });
+ root?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ currentTestBed = undefined;
+ disposePrinting = undefined;
+ });
+
+ it('prints only floating DOM content whose transformed bounds intersect the page bound', () => {
+ currentTestBed = createDocUiTestBed(createDocData(), [
+ [ComponentManager],
+ ]);
+ currentTestBed.injector.get(ComponentManager).register(PRINTING_COMPONENT_KEY, PrintingVisibleContent);
+
+ root = document.createElement('div');
+ document.body.appendChild(root);
+
+ act(() => {
+ disposePrinting = mountDocPrintingFloatDom({
+ floatDomInfos: [
+ createFloatDom('inside-image', 'Inside printable page', { left: 20, top: 10, right: 70, bottom: 40 }),
+ createFloatDom('outside-image', 'Outside printable page', { left: 240, top: 10, right: 300, bottom: 40 }),
+ ],
+ scene: new TestScene() as unknown as Scene,
+ skeleton: {} as never,
+ unitId: UNIT_ID,
+ offset: { x: 0, y: 0 },
+ bound: { left: 0, top: 0, right: 200, bottom: 100 },
+ }, root!, currentTestBed!.injector);
+ });
+
+ expect(root.textContent).toContain('Inside printable page');
+ expect(root.textContent).not.toContain('Outside printable page');
+
+ act(() => {
+ disposePrinting?.();
+ disposePrinting = undefined;
+ });
+
+ expect(root.textContent).toBe('');
+ });
+
+ it('prints floating DOM content based on viewport scroll and ancestor scale', () => {
+ currentTestBed = createDocUiTestBed(createDocData(), [
+ [ComponentManager],
+ ]);
+ currentTestBed.injector.get(ComponentManager).register(PRINTING_COMPONENT_KEY, PrintingVisibleContent);
+
+ root = document.createElement('div');
+ document.body.appendChild(root);
+
+ act(() => {
+ disposePrinting = mountDocPrintingFloatDom({
+ floatDomInfos: [
+ createFloatDom('visible-after-scroll', 'Visible after scroll and zoom', { left: 110, top: 60, right: 130, bottom: 80 }),
+ createFloatDom('before-scroll', 'Before scrolled viewport', { left: 0, top: 60, right: 20, bottom: 80 }),
+ createFloatDom('below-scaled-page', 'Below scaled page', { left: 120, top: 140, right: 150, bottom: 170 }),
+ ],
+ scene: new TestScene({ x: 100, y: 50 }, { x: 2, y: 1.5 }) as unknown as Scene,
+ skeleton: {} as never,
+ unitId: UNIT_ID,
+ offset: { x: 0, y: 0 },
+ bound: { left: 0, top: 0, right: 200, bottom: 100 },
+ }, root!, currentTestBed!.injector);
+ });
+
+ expect(root.textContent).toContain('Visible after scroll and zoom');
+ expect(root.textContent).not.toContain('Before scrolled viewport');
+ expect(root.textContent).not.toContain('Below scaled page');
+ });
+});
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
index f259715590..120aef7381 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
@@ -274,6 +274,33 @@ function inputByLabelText(text: string) {
return label?.querySelector('input') as HTMLInputElement;
}
+function setInputValue(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+async function selectPositionRelativeFrom(container: HTMLDivElement, selectIndex: number, label: string) {
+ const select = Array.from(container.querySelectorAll('[data-u-comp="select"]'))[selectIndex] as HTMLElement | undefined;
+
+ expect(select).toBeDefined();
+
+ await act(async () => {
+ select!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const option = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((button) => button.textContent === label) as HTMLElement | undefined;
+
+ expect(option).toBeDefined();
+
+ await act(async () => {
+ option!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
describe('DocDrawingPosition', () => {
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -315,4 +342,107 @@ describe('DocDrawingPosition', () => {
},
});
});
+
+ it('persists horizontal absolute position on the focused drawing', async () => {
+ currentTestBed = createPositionTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ const horizontalPositionInput = Array.from(container.querySelectorAll('input'))[0];
+
+ await act(async () => {
+ setInputValue(horizontalPositionInput, '36.5');
+ await Promise.resolve();
+ });
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ docTransform: {
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.PAGE,
+ posOffset: 36.5,
+ },
+ },
+ });
+ });
+
+ it('keeps the image visually fixed when horizontal positioning changes from page to margin', async () => {
+ currentTestBed = createPositionTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ await selectPositionRelativeFrom(container, 0, 'Margin');
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ docTransform: {
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.MARGIN,
+ posOffset: -90,
+ },
+ },
+ });
+ });
+
+ it('keeps the image visually fixed when vertical positioning changes from paragraph to line', async () => {
+ currentTestBed = createPositionTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ await selectPositionRelativeFrom(container, 1, 'Line');
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ docTransform: {
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.LINE,
+ posOffset: -12,
+ },
+ },
+ });
+ });
+
+ it('persists vertical absolute position on the focused drawing', async () => {
+ currentTestBed = createPositionTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ const verticalPositionInput = Array.from(container.querySelectorAll('input'))[1];
+
+ await act(async () => {
+ setInputValue(verticalPositionInput, '18.5');
+ await Promise.resolve();
+ });
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ docTransform: {
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,
+ posOffset: 18.5,
+ },
+ },
+ });
+ });
+
+ it('hides the position controls when doc drawing focus is cleared', async () => {
+ currentTestBed = createPositionTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ expect(container.firstElementChild?.classList.contains('univer-hidden')).toBe(false);
+
+ await act(async () => {
+ currentTestBed!.get(IDrawingManagerService).focusDrawing([]);
+ await Promise.resolve();
+ });
+
+ expect(container.firstElementChild?.classList.contains('univer-hidden')).toBe(true);
+ });
});
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx
index 2b1622590b..6a13f93063 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx
@@ -321,6 +321,66 @@ describe('DocDrawingTextWrap', () => {
});
});
+ it('persists in-front-of-text wrapping on the focused drawing', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ await act(async () => {
+ inputByLabelText('In front of text').click();
+ await Promise.resolve();
+ });
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ layoutType: PositionedObjectLayoutType.WRAP_NONE,
+ behindDoc: BooleanNumber.FALSE,
+ docTransform: {
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.PAGE,
+ posOffset: 24,
+ },
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PAGE,
+ posOffset: 114,
+ },
+ },
+ });
+ });
+
+ it('preserves wrap metadata when switching to top-and-bottom text flow', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ await act(async () => {
+ inputByLabelText('Top and Bottom').click();
+ await Promise.resolve();
+ });
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ layoutType: PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,
+ wrapText: WrapTextType.BOTH_SIDES,
+ distT: 1,
+ distL: 2,
+ distB: 3,
+ distR: 4,
+ docTransform: {
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.PAGE,
+ posOffset: 24,
+ },
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PAGE,
+ posOffset: 114,
+ },
+ },
+ });
+ });
+
it('persists left distance from text on the focused drawing', async () => {
currentTestBed = createPanelTestBed();
container = document.createElement('div');
@@ -360,4 +420,21 @@ describe('DocDrawingTextWrap', () => {
wrapText: WrapTextType.RIGHT,
});
});
+
+ it('hides the text wrapping controls when doc drawing focus is cleared', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ expect(container.firstElementChild?.classList.contains('univer-hidden')).toBe(false);
+
+ await act(async () => {
+ currentTestBed!.get(IDrawingManagerService).focusDrawing([]);
+ await Promise.resolve();
+ });
+
+ expect(container.firstElementChild?.classList.contains('univer-hidden')).toBe(true);
+ });
});
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.spec.ts
new file mode 100644
index 0000000000..938a268ec3
--- /dev/null
+++ b/packages/docs-ui/src/controllers/__tests__/doc-header-footer.controller.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 { DocumentFlavor } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { DocumentEditArea, Path, Rect } from '@univerjs/engine-render';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CloseHeaderFooterCommand } from '../../commands/commands/doc-header-footer.command';
+import { TextBubbleShape } from '../../views/header-footer/text-bubble';
+import { DocHeaderFooterController } from '../doc-header-footer.controller';
+
+const neoGetDocObjectMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../../basics/component-tools', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../basics/component-tools')>();
+
+ return {
+ ...actual,
+ neoGetDocObject: neoGetDocObjectMock,
+ };
+});
+
+function createCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ translate: vi.fn(),
+ } as any;
+}
+
+function createController(options: {
+ editArea?: DocumentEditArea;
+ documentFlavor?: DocumentFlavor;
+ editor?: boolean;
+} = {}) {
+ const pageRender$ = new Subject<any>();
+ const commandHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
+ const document = {
+ pageRender$,
+ onDblclick$: {
+ subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })),
+ },
+ getOffsetConfig: vi.fn(() => ({ documentTransform: { clone: vi.fn() } })),
+ };
+ const scene = {
+ getViewports: vi.fn(() => []),
+ };
+ neoGetDocObjectMock.mockReturnValue({ document, scene });
+ const unit = {
+ getSnapshot: vi.fn(() => ({
+ documentStyle: {
+ documentFlavor: options.documentFlavor ?? DocumentFlavor.TRADITIONAL,
+ },
+ })),
+ };
+ const viewModel = {
+ getEditArea: vi.fn(() => options.editArea ?? DocumentEditArea.BODY),
+ };
+ const controller = new DocHeaderFooterController(
+ {
+ unitId: 'doc-1',
+ unit,
+ mainComponent: document,
+ } as never,
+ {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ executeCommand: vi.fn(),
+ } as never,
+ {
+ isEditor: vi.fn(() => options.editor ?? false),
+ getEditor: vi.fn(() => null),
+ } as never,
+ {
+ getCurrentTypeOfUnit$: vi.fn(() => new BehaviorSubject({ getUnitId: () => 'doc-1' })),
+ getUniverDocInstance: vi.fn(() => unit),
+ } as never,
+ {
+ getRenderById: vi.fn(() => ({ mainComponent: document })),
+ } as never,
+ {
+ getViewModel: vi.fn(() => viewModel),
+ } as never,
+ {
+ setSegment: vi.fn(),
+ setSegmentPage: vi.fn(),
+ setCursorManually: vi.fn(),
+ } as never,
+ {
+ t: vi.fn((key: string) => key),
+ } as never
+ );
+
+ return { controller, pageRender$, commandHandlers, document };
+}
+
+describe('DocHeaderFooterController', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ neoGetDocObjectMock.mockReset();
+ });
+
+ it('closes header/footer editing after rich text changes in modern document mode', () => {
+ const { controller, commandHandlers } = createController({
+ editArea: DocumentEditArea.HEADER,
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+
+ commandHandlers[0]({ id: RichTextEditingMutation.id });
+
+ expect((controller as any)._commandService.executeCommand).toHaveBeenCalledWith(CloseHeaderFooterCommand.id, {
+ unitId: 'doc-1',
+ });
+
+ controller.dispose();
+ });
+
+ it('covers header and footer areas while editing the document body', () => {
+ const { controller, pageRender$ } = createController({ editArea: DocumentEditArea.BODY });
+ const rectSpy = vi.spyOn(Rect, 'drawWith').mockImplementation(() => undefined);
+ const pathSpy = vi.spyOn(Path, 'drawWith').mockImplementation(() => undefined);
+ const textSpy = vi.spyOn(TextBubbleShape, 'drawWith').mockImplementation(() => undefined);
+ const ctx = createCtx();
+
+ pageRender$.next({
+ ctx,
+ pageLeft: 12,
+ pageTop: 24,
+ page: {
+ pageWidth: 200,
+ pageHeight: 300,
+ marginTop: 30,
+ marginBottom: 40,
+ },
+ });
+
+ expect(ctx.translate).toHaveBeenCalledWith(11.5, 23.5);
+ expect(rectSpy).toHaveBeenCalledTimes(2);
+ expect(rectSpy.mock.calls[0][1]).toMatchObject({ width: 200, height: 30, fill: 'rgba(255, 255, 255, 0.5)' });
+ expect(rectSpy.mock.calls[1][1]).toMatchObject({ width: 200, height: 40, fill: 'rgba(255, 255, 255, 0.5)' });
+ expect(pathSpy).not.toHaveBeenCalled();
+ expect(textSpy).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('covers the body and draws header/footer guides while editing header or footer', () => {
+ const { controller, pageRender$ } = createController({ editArea: DocumentEditArea.HEADER });
+ const rectSpy = vi.spyOn(Rect, 'drawWith').mockImplementation(() => undefined);
+ const pathSpy = vi.spyOn(Path, 'drawWith').mockImplementation(() => undefined);
+ const textSpy = vi.spyOn(TextBubbleShape, 'drawWith').mockImplementation(() => undefined);
+ const ctx = createCtx();
+
+ pageRender$.next({
+ ctx,
+ pageLeft: 0,
+ pageTop: 0,
+ page: {
+ pageWidth: 200,
+ pageHeight: 300,
+ marginTop: 30,
+ marginBottom: 40,
+ },
+ });
+
+ expect(rectSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({
+ top: 30,
+ width: 200,
+ height: 230,
+ }));
+ expect(pathSpy).toHaveBeenCalledTimes(2);
+ expect(textSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({ text: 'docs-ui.headerFooter.header' }));
+ expect(textSpy).toHaveBeenCalledWith(ctx, expect.objectContaining({ text: 'docs-ui.headerFooter.footer' }));
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/controllers/components.controller.ts b/packages/docs-ui/src/controllers/components.controller.ts
index 68121638cd..8e037508bd 100644
--- a/packages/docs-ui/src/controllers/components.controller.ts
+++ b/packages/docs-ui/src/controllers/components.controller.ts
@@ -15,15 +15,98 @@
*/
import { Disposable, Inject } from '@univerjs/core';
-import { AddImageIcon, AlignTextBothIcon, BoldIcon, CopyDoubleIcon, CutIcon, DeleteColumnDoubleIcon, DeleteIcon, DeleteRowDoubleIcon, DocSettingIcon, FontColorDoubleIcon, GridIcon, H1Icon, H2Icon, H3Icon, H4Icon, H5Icon, HeaderFooterIcon, HorizontallyIcon, InsertDoubleIcon, InsertRowAboveDoubleIcon, InsertRowBelowDoubleIcon, ItalicIcon, KeyboardIcon, LeftInsertColumnDoubleIcon, LeftJustifyingIcon, MenuIcon, MoreLeftIcon, MoreRightIcon, NoColorDoubleIcon, OrderIcon, PaintBucketDoubleIcon, PasteSpecialDoubleIcon, ReduceDoubleIcon, ReduceIcon, RightInsertColumnDoubleIcon, RightJustifyingIcon, ShapeIcon, StrikethroughIcon, SubscriptIcon, SuperscriptIcon, TextTypeIcon, TodoListDoubleIcon, UnderlineIcon, UnorderIcon } from '@univerjs/icons';
+import {
+ AddImageIcon,
+ AlignTextBothIcon,
+ BoldIcon,
+ CopyDoubleIcon,
+ CutIcon,
+ DeleteColumnDoubleIcon,
+ DeleteIcon,
+ DeleteRowDoubleIcon,
+ DocSettingIcon,
+ FontColorDoubleIcon,
+ GridIcon,
+ H1Icon,
+ H2Icon,
+ H3Icon,
+ H4Icon,
+ H5Icon,
+ HeaderFooterIcon,
+ HorizontallyIcon,
+ InsertDoubleIcon,
+ InsertRowAboveDoubleIcon,
+ InsertRowBelowDoubleIcon,
+ ItalicIcon,
+ KeyboardIcon,
+ LeftInsertColumnDoubleIcon,
+ LeftJustifyingIcon,
+ MenuIcon,
+ MoreLeftIcon,
+ MoreRightIcon,
+ NoColorDoubleIcon,
+ OrderIcon,
+ PaintBucketDoubleIcon,
+ PasteSpecialDoubleIcon,
+ ReduceDoubleIcon,
+ ReduceIcon,
+ RightInsertColumnDoubleIcon,
+ RightJustifyingIcon,
+ ShapeIcon,
+ StrikethroughIcon,
+ SubscriptIcon,
+ SuperscriptIcon,
+ TextTypeIcon,
+ TodoListDoubleIcon,
+ UnderlineIcon,
+ UnorderIcon,
+} from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../views/header-footer/panel/component-name';
import { DocHeaderFooterPanel } from '../views/header-footer/panel/DocHeaderFooterPanel';
-import { DefaultTextColorIcon, DocParagraphBackgroundColorSwatchIcon0, DocParagraphBackgroundColorSwatchIcon1, DocParagraphBackgroundColorSwatchIcon10, DocParagraphBackgroundColorSwatchIcon11, DocParagraphBackgroundColorSwatchIcon12, DocParagraphBackgroundColorSwatchIcon13, DocParagraphBackgroundColorSwatchIcon14, DocParagraphBackgroundColorSwatchIcon15, DocParagraphBackgroundColorSwatchIcon2, DocParagraphBackgroundColorSwatchIcon3, DocParagraphBackgroundColorSwatchIcon4, DocParagraphBackgroundColorSwatchIcon5, DocParagraphBackgroundColorSwatchIcon6, DocParagraphBackgroundColorSwatchIcon7, DocParagraphBackgroundColorSwatchIcon8, DocParagraphBackgroundColorSwatchIcon9, DocParagraphTextColorSwatchIcon0, DocParagraphTextColorSwatchIcon1, DocParagraphTextColorSwatchIcon2, DocParagraphTextColorSwatchIcon3, DocParagraphTextColorSwatchIcon4, DocParagraphTextColorSwatchIcon5, DocParagraphTextColorSwatchIcon6, HeaderTextColorIcon, SubtitleTypeIcon, TitleTypeIcon } from '../views/Icon';
-import { BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker, ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker } from '../views/list-type-picker/index';
+import {
+ DefaultTextColorIcon,
+ DocParagraphBackgroundColorSwatchIcon0,
+ DocParagraphBackgroundColorSwatchIcon1,
+ DocParagraphBackgroundColorSwatchIcon10,
+ DocParagraphBackgroundColorSwatchIcon11,
+ DocParagraphBackgroundColorSwatchIcon12,
+ DocParagraphBackgroundColorSwatchIcon13,
+ DocParagraphBackgroundColorSwatchIcon14,
+ DocParagraphBackgroundColorSwatchIcon15,
+ DocParagraphBackgroundColorSwatchIcon2,
+ DocParagraphBackgroundColorSwatchIcon3,
+ DocParagraphBackgroundColorSwatchIcon4,
+ DocParagraphBackgroundColorSwatchIcon5,
+ DocParagraphBackgroundColorSwatchIcon6,
+ DocParagraphBackgroundColorSwatchIcon7,
+ DocParagraphBackgroundColorSwatchIcon8,
+ DocParagraphBackgroundColorSwatchIcon9,
+ DocParagraphTextColorSwatchIcon0,
+ DocParagraphTextColorSwatchIcon1,
+ DocParagraphTextColorSwatchIcon2,
+ DocParagraphTextColorSwatchIcon3,
+ DocParagraphTextColorSwatchIcon4,
+ DocParagraphTextColorSwatchIcon5,
+ DocParagraphTextColorSwatchIcon6,
+ HeaderTextColorIcon,
+ SubtitleTypeIcon,
+ TitleTypeIcon,
+} from '../views/Icon';
+import {
+ BULLET_LIST_TYPE_COMPONENT,
+ BulletListTypePicker,
+ ORDER_LIST_TYPE_COMPONENT,
+ OrderListTypePicker,
+} from '../views/list-type-picker/index';
import { PAGE_SETTING_COMPONENT_ID, PageSettings } from '../views/PageSettings';
import { ParagraphSettingIndex } from '../views/paragraph-setting/index';
-import { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, ParagraphMenu, TableBlockMenu } from '../views/ParagraphMenu';
+import {
+ DOC_PARAGRAPH_MENU_COMPONENT_KEY,
+ DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,
+ ParagraphMenu,
+ TableBlockMenu,
+} from '../views/ParagraphMenu';
import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../views/table/create/component-name';
import { DocCreateTableConfirm } from '../views/table/create/TableCreate';
@@ -37,20 +120,8 @@ export class ComponentsController extends Disposable {
super();
this._registerComponents();
- this._registerComponents2();
this._registerParts();
this._registerIcons();
- this._registerComponents3();
- }
-
- private _registerComponents(): void {
- if (!this._componentManager.get(COMPONENT_DOC_HEADER_FOOTER_PANEL)) {
- this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_HEADER_FOOTER_PANEL, DocHeaderFooterPanel));
- }
- }
-
- private _registerComponents2(): void {
- this.disposeWithMe(this._componentManager.register(paragraphSettingIndexKey, ParagraphSettingIndex));
}
private _registerParts(): void {
@@ -134,7 +205,12 @@ export class ComponentsController extends Disposable {
}));
}
- private _registerComponents3(): void {
+ private _registerComponents(): void {
+ if (!this._componentManager.get(COMPONENT_DOC_HEADER_FOOTER_PANEL)) {
+ this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_HEADER_FOOTER_PANEL, DocHeaderFooterPanel));
+ }
+
+ this.disposeWithMe(this._componentManager.register(paragraphSettingIndexKey, ParagraphSettingIndex));
([
[BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker],
[ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker],
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-checklist.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-checklist.render-controller.spec.ts
new file mode 100644
index 0000000000..c476b4b47e
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-checklist.render-controller.spec.ts
@@ -0,0 +1,67 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CURSOR_TYPE } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { ToggleCheckListCommand } from '../../../commands/commands/list.command';
+import { DocChecklistRenderController } from '../doc-checklist.render-controller';
+
+describe('DocChecklistRenderController', () => {
+ it('toggles the clicked checklist paragraph with current text ranges', () => {
+ const clickBullets$ = new Subject<any>();
+ const controller = new DocChecklistRenderController(
+ { mainComponent: { setCursor: vi.fn() } } as never,
+ {} as never,
+ { executeCommand: vi.fn() } as never,
+ { clickBullets$, hoverBullet$: new Subject() } as never,
+ { getTextRanges: vi.fn(() => [{ startOffset: 3, endOffset: 5 }]) } as never
+ );
+
+ clickBullets$.next({
+ paragraph: { startIndex: 12 },
+ segmentId: 'header-1',
+ });
+
+ expect((controller as any)._commandService.executeCommand).toHaveBeenCalledWith(ToggleCheckListCommand.id, {
+ index: 12,
+ segmentId: 'header-1',
+ textRanges: [{ startOffset: 3, endOffset: 5 }],
+ });
+
+ controller.dispose();
+ });
+
+ it('switches the document cursor between pointer and text when hovering checklist bullets', () => {
+ const hoverBullet$ = new Subject<any>();
+ const setCursor = vi.fn();
+ const controller = new DocChecklistRenderController(
+ { mainComponent: { setCursor } } as never,
+ {} as never,
+ { executeCommand: vi.fn() } as never,
+ { clickBullets$: new Subject(), hoverBullet$ } as never,
+ { getTextRanges: vi.fn(() => []) } as never
+ );
+
+ hoverBullet$.next({ paragraph: { startIndex: 1 } });
+ hoverBullet$.next(null);
+
+ expect(setCursor).toHaveBeenNthCalledWith(1, CURSOR_TYPE.POINTER);
+ expect(setCursor).toHaveBeenNthCalledWith(2, CURSOR_TYPE.TEXT);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.spec.ts
new file mode 100644
index 0000000000..db18ce6082
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.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 { EDITOR_ACTIVATED, FOCUSING_DOC } from '@univerjs/core';
+import { HTML_CLIPBOARD_MIME_TYPE, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { DOC_INTERNAL_FRAGMENT_MIME } from '../../../services/clipboard/internal-fragment';
+import { DocClipboardController } from '../doc-clipboard.controller';
+
+function createClipboardEvent(options: {
+ html?: string;
+ internalJson?: string;
+ text?: string;
+ items?: Array<{ type: string; getAsFile: () => File | null }>;
+}) {
+ const data = new Map([
+ [HTML_CLIPBOARD_MIME_TYPE, options.html ?? ''],
+ [DOC_INTERNAL_FRAGMENT_MIME, options.internalJson ?? ''],
+ [PLAIN_TEXT_CLIPBOARD_MIME_TYPE, options.text ?? ''],
+ ]);
+
+ return {
+ preventDefault: vi.fn(),
+ clipboardData: {
+ getData: vi.fn((type: string) => data.get(type) ?? ''),
+ items: options.items ?? [],
+ },
+ };
+}
+
+function createController(options?: { focusingDoc?: boolean; editorActivated?: boolean; editorExists?: boolean }) {
+ const onPaste$ = new Subject<any>();
+ const legacyPaste = vi.fn();
+ const controller = new DocClipboardController(
+ { unitId: 'doc-1' } as never,
+ {} as never,
+ { legacyPaste } as never,
+ { onPaste$ } as never,
+ {
+ getContextValue: vi.fn((key: string) => {
+ if (key === FOCUSING_DOC) return options?.focusingDoc ?? true;
+ if (key === EDITOR_ACTIVATED) return options?.editorActivated ?? false;
+ return false;
+ }),
+ } as never,
+ { getEditor: vi.fn(() => options?.editorExists ? {} : null) } as never
+ );
+
+ return { controller, onPaste$, legacyPaste };
+}
+
+describe('DocClipboardController', () => {
+ it('prevents the native paste and forwards html, internal json, text and image files to legacy paste', () => {
+ const imageFile = new File(['image'], 'image.png', { type: 'image/png' });
+ const { controller, onPaste$, legacyPaste } = createController();
+ const event = createClipboardEvent({
+ html: '<p>Hello</p>',
+ internalJson: '{"body":true}',
+ text: 'Hello',
+ items: [
+ { type: 'image/png', getAsFile: () => imageFile },
+ { type: 'text/plain', getAsFile: () => null },
+ ],
+ });
+
+ onPaste$.next({ event });
+
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(legacyPaste).toHaveBeenCalledWith({
+ html: '<p>Hello</p>',
+ internalJson: '{"body":true}',
+ text: 'Hello',
+ files: [imageFile],
+ });
+
+ controller.dispose();
+ });
+
+ it('drops pasted table html while editing and ignores paste events outside docs or editors', () => {
+ const editing = createController({ editorExists: true });
+ const tableEvent = createClipboardEvent({ html: '<table><tr><td>A</td></tr></table>', text: 'A' });
+
+ editing.onPaste$.next({ event: tableEvent });
+
+ expect(editing.legacyPaste).toHaveBeenCalledWith(expect.objectContaining({
+ html: '',
+ text: 'A',
+ }));
+ editing.controller.dispose();
+
+ const inactive = createController({ focusingDoc: false, editorActivated: false });
+ const inactiveEvent = createClipboardEvent({ text: 'Ignored' });
+
+ inactive.onPaste$.next({ event: inactiveEvent });
+
+ expect(inactiveEvent.preventDefault).not.toHaveBeenCalled();
+ expect(inactive.legacyPaste).not.toHaveBeenCalled();
+ inactive.controller.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.spec.ts
new file mode 100644
index 0000000000..42324f700e
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.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 { DocumentBlockRangeType, UniverInstanceType } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { ContextMenuPosition } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { DocContextMenuRenderController } from '../doc-contextmenu.render-controller';
+
+function createEventSubject() {
+ const subscribers = new Set<(evt: any) => void>();
+
+ return {
+ subscribeEvent: vi.fn((handler: (evt: any) => void) => {
+ subscribers.add(handler);
+ const unsubscribe = vi.fn(() => subscribers.delete(handler));
+ return { dispose: unsubscribe, unsubscribe };
+ }),
+ emit: (evt: any) => subscribers.forEach((handler) => handler(evt)),
+ };
+}
+
+function createController(options?: {
+ pointerOnBullet?: boolean;
+ textRanges?: Array<{ startOffset: number; endOffset: number }>;
+ blockRanges?: Array<{ startIndex: number; endIndex: number; blockType: DocumentBlockRangeType }>;
+ menuVisible?: boolean;
+}) {
+ const onPointerDown$ = createEventSubject();
+ let commandHandler: ((command: { id: string }) => void) | undefined;
+ const contextMenuService = {
+ visible: options?.menuVisible ?? false,
+ triggerContextMenu: vi.fn(),
+ hideContextMenu: vi.fn(),
+ };
+ const controller = new DocContextMenuRenderController(
+ {
+ unitId: 'doc-1',
+ mainComponent: { onPointerDown$ },
+ } as never,
+ contextMenuService as never,
+ {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ { isPointerOnNonChecklistBullet: vi.fn(() => options?.pointerOnBullet ?? false) } as never,
+ { getTextRanges: vi.fn(() => options?.textRanges ?? []) } as never,
+ {
+ getCurrentUnitOfType: vi.fn((type) => type === UniverInstanceType.UNIVER_DOC
+ ? { getBody: () => ({ blockRanges: options?.blockRanges ?? [] }) }
+ : null),
+ } as never
+ );
+
+ return { controller, onPointerDown$, contextMenuService, commandHandler: () => commandHandler };
+}
+
+describe('DocContextMenuRenderController', () => {
+ it('opens the main-area context menu on right click when the selection is normal document text', () => {
+ const { controller, onPointerDown$, contextMenuService } = createController();
+ const event = { button: 2, offsetX: 10, offsetY: 20 };
+
+ onPointerDown$.emit(event);
+
+ expect(contextMenuService.triggerContextMenu).toHaveBeenCalledWith(event, ContextMenuPosition.MAIN_AREA);
+ controller.dispose();
+ });
+
+ it('does not open context menu for checklist bullets or selections inside code blocks', () => {
+ const bullet = createController({ pointerOnBullet: true });
+ bullet.onPointerDown$.emit({ button: 2, offsetX: 10, offsetY: 20 });
+ expect(bullet.contextMenuService.triggerContextMenu).not.toHaveBeenCalled();
+ bullet.controller.dispose();
+
+ const codeBlock = createController({
+ textRanges: [{ startOffset: 5, endOffset: 8 }],
+ blockRanges: [{ startIndex: 1, endIndex: 10, blockType: DocumentBlockRangeType.CODE }],
+ });
+ codeBlock.onPointerDown$.emit({ button: 2, offsetX: 10, offsetY: 20 });
+ expect(codeBlock.contextMenuService.triggerContextMenu).not.toHaveBeenCalled();
+ codeBlock.controller.dispose();
+ });
+
+ it('hides an open context menu after document text is edited', () => {
+ const { controller, contextMenuService, commandHandler } = createController({ menuVisible: true });
+
+ commandHandler()?.({ id: RichTextEditingMutation.id });
+
+ expect(contextMenuService.hideContextMenu).toHaveBeenCalled();
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts
new file mode 100644
index 0000000000..5d8d7fd21e
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-editor-bridge.controller.spec.ts
@@ -0,0 +1,162 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DocEditorBridgeController } from '../doc-editor-bridge.controller';
+
+function createController(options: { cancelResize?: boolean; sheetEditor?: boolean; focusEditorId?: string | null } = {}) {
+ const blur$ = new Subject<void>();
+ const onBlur$ = new Subject<void>();
+ const commandHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
+ const scene = { transformByState: vi.fn() };
+ const mainComponent = { resize: vi.fn() };
+ const editor = {
+ getEditorId: vi.fn(() => 'editor-1'),
+ cancelDefaultResizeListener: options.cancelResize ?? false,
+ render: { scene, mainComponent },
+ getBoundingClientRect: vi.fn(() => ({ width: 120, height: 80 })),
+ params: { scrollBar: false },
+ isSheetEditor: vi.fn(() => options.sheetEditor ?? false),
+ };
+ const editorService = {
+ getAllEditor: vi.fn(() => [editor]),
+ getEditor: vi.fn(() => editor),
+ isSheetEditor: vi.fn((unitId: string) => unitId === 'sheet-editor'),
+ blur$,
+ blur: vi.fn(),
+ getFocusEditor: vi.fn(() => options.focusEditorId ? { getEditorId: () => options.focusEditorId } : null),
+ };
+ const skeleton = {
+ calculate: vi.fn(),
+ getActualSize: vi.fn(() => ({ actualWidth: 150, actualHeight: 90 })),
+ };
+ const canvasEle = document.createElement('canvas');
+ const controller = new DocEditorBridgeController(
+ { unitId: 'editor-1' } as never,
+ {
+ getUniverDocInstance: vi.fn(() => ({
+ getSnapshot: () => ({
+ documentStyle: {
+ marginTop: 10,
+ marginBottom: 20,
+ marginLeft: 5,
+ marginRight: 15,
+ },
+ }),
+ })),
+ getCurrentTypeOfUnit$: vi.fn(() => new BehaviorSubject({ getUnitId: () => 'sheet-1' })),
+ } as never,
+ editorService as never,
+ {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ {
+ blur: vi.fn(),
+ onBlur$,
+ } as never,
+ {
+ getSkeleton: vi.fn(() => skeleton),
+ } as never,
+ {
+ getRenderById: vi.fn(() => ({
+ engine: {
+ getCanvas: () => ({
+ getCanvasEle: () => canvasEle,
+ }),
+ },
+ })),
+ } as never
+ );
+
+ return {
+ controller,
+ editor,
+ scene,
+ mainComponent,
+ skeleton,
+ editorService,
+ blur$,
+ onBlur$,
+ commandHandlers,
+ canvasEle,
+ };
+}
+
+describe('DocEditorBridgeController', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('resizes editor scene and main component from skeleton content plus document margins', () => {
+ const { controller, scene, mainComponent, skeleton } = createController();
+
+ expect(skeleton.calculate).toHaveBeenCalled();
+ expect(scene.transformByState).toHaveBeenCalledWith({ width: 170, height: 120 });
+ expect(mainComponent.resize).toHaveBeenCalledWith(170, 120);
+
+ controller.dispose();
+ });
+
+ it('refreshes editor size after rich text edits for the same text editor', () => {
+ const { controller, scene, commandHandlers } = createController();
+ scene.transformByState.mockClear();
+
+ commandHandlers[0]({ id: RichTextEditingMutation.id, params: { unitId: 'other-editor' } });
+ commandHandlers[0]({ id: RichTextEditingMutation.id, params: { unitId: 'sheet-editor' } });
+ commandHandlers[0]({ id: RichTextEditingMutation.id, params: { unitId: 'editor-1' } });
+
+ expect(scene.transformByState).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+
+ it('bridges blur state and keeps formula helper mouse events from stealing focus', () => {
+ const { controller, editorService, blur$, onBlur$, canvasEle } = createController();
+ const windowStop = vi.fn();
+ const canvasStop = vi.fn();
+ const formulaHelp = document.createElement('div');
+ formulaHelp.className = 'univer-formula-help';
+ document.body.appendChild(formulaHelp);
+
+ blur$.next();
+ onBlur$.next();
+ formulaHelp.dispatchEvent(Object.assign(new MouseEvent('mousedown', { bubbles: true }), { stopPropagation: windowStop }));
+ canvasEle.dispatchEvent(Object.assign(new MouseEvent('mousedown', { bubbles: true }), {
+ stopPropagation: canvasStop,
+ }));
+
+ expect(editorService.blur).toHaveBeenCalled();
+ expect(windowStop).toHaveBeenCalled();
+ expect(canvasStop).toHaveBeenCalled();
+
+ document.body.removeChild(formulaHelp);
+ controller.dispose();
+ });
+
+ it('skips default resize when editor opts out', () => {
+ const { controller, scene, mainComponent } = createController({ cancelResize: true });
+
+ expect(scene.transformByState).not.toHaveBeenCalled();
+ expect(mainComponent.resize).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
new file mode 100644
index 0000000000..a109526382
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
@@ -0,0 +1,239 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CURSOR_TYPE, DocumentEditArea } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { DocSelectionRenderController } from '../doc-selection-render.controller';
+
+const neoGetDocObjectMock = vi.hoisted(() => vi.fn());
+const findFirstCursorOffsetMock = vi.hoisted(() => vi.fn(() => 3));
+
+vi.mock('../../../basics/component-tools', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../basics/component-tools')>();
+
+ return {
+ ...actual,
+ neoGetDocObject: neoGetDocObjectMock,
+ };
+});
+
+vi.mock('../../../basics/selection', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../basics/selection')>();
+
+ return {
+ ...actual,
+ findFirstCursorOffset: findFirstCursorOffsetMock,
+ };
+});
+
+function createEventSubject() {
+ const handlers = new Set<(evt: any, state?: any) => void>();
+
+ return {
+ subscribeEvent: vi.fn((handler: (evt: any, state?: any) => void) => {
+ handlers.add(handler);
+ return { dispose: vi.fn(() => handlers.delete(handler)) };
+ }),
+ emit: (evt: any, state?: any) => handlers.forEach((handler) => handler(evt, state)),
+ };
+}
+
+function createController(options: { readonly?: boolean; hasEditor?: boolean } = {}) {
+ const refreshSelection$ = new Subject<any>();
+ const textSelectionInner$ = new Subject<any>();
+ const currentSkeleton$ = new Subject<any>();
+ const commandHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
+ const documentTransform = {
+ clone: vi.fn(() => ({
+ invert: vi.fn(() => ({
+ applyPoint: vi.fn(() => ({ x: 10, y: 20 })),
+ })),
+ })),
+ };
+ const document = {
+ cursor: CURSOR_TYPE.DEFAULT,
+ onPointerEnter$: createEventSubject(),
+ onPointerLeave$: createEventSubject(),
+ onPointerDown$: createEventSubject(),
+ onDblclick$: createEventSubject(),
+ onTripleClick$: createEventSubject(),
+ getOffsetConfig: vi.fn(() => ({
+ documentTransform,
+ pageLayoutType: 0,
+ pageMarginLeft: 12,
+ pageMarginTop: 16,
+ })),
+ };
+ const scene = {
+ resetCursor: vi.fn(),
+ getViewports: vi.fn(() => [{
+ transformVector2SceneCoord: vi.fn(() => ({ x: 1, y: 2 })),
+ }]),
+ };
+ neoGetDocObjectMock.mockReturnValue({ document, scene });
+ const skeleton = {
+ findEditAreaByCoord: vi.fn(() => ({ editArea: DocumentEditArea.HEADER })),
+ };
+ const viewModel = {
+ getEditArea: vi.fn(() => DocumentEditArea.FOOTER),
+ setEditArea: vi.fn(),
+ };
+ const docSelectionRenderService = {
+ removeAllRanges: vi.fn(),
+ addDocRanges: vi.fn(),
+ textSelectionInner$,
+ focus: vi.fn(),
+ __onPointDown: vi.fn(),
+ __handleDblClick: vi.fn(),
+ __handleTripleClick: vi.fn(),
+ setCursorManually: vi.fn(),
+ isOnPointerEvent: false,
+ };
+ const docSelectionManagerService = {
+ refreshSelection$,
+ __replaceTextRangesWithNoRefresh: vi.fn(),
+ __getCurrentSelection: vi.fn(() => ({ unitId: 'doc-1' })),
+ refreshSelection: vi.fn(),
+ replaceDocRanges: vi.fn(),
+ };
+ const editor = options.hasEditor
+ ? { isReadOnly: vi.fn(() => options.readonly ?? false) }
+ : null;
+ const editorService = {
+ getEditor: vi.fn(() => editor),
+ focus: vi.fn(),
+ getFocusId: vi.fn(() => null),
+ };
+ const controller = new DocSelectionRenderController(
+ {
+ unitId: 'doc-1',
+ unit: { getSnapshot: vi.fn(() => ({ body: { dataStream: 'abc\r\n' } })) },
+ } as never,
+ {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ editorService as never,
+ {
+ getCurrentUnitOfType: vi.fn(() => ({ getUnitId: () => 'other-doc' })),
+ setCurrentUnitForType: vi.fn(),
+ } as never,
+ docSelectionRenderService as never,
+ {
+ getSkeleton: vi.fn(() => skeleton),
+ getViewModel: vi.fn(() => viewModel),
+ currentSkeleton$,
+ } as never,
+ docSelectionManagerService as never
+ );
+
+ return {
+ controller,
+ document,
+ scene,
+ skeleton,
+ viewModel,
+ refreshSelection$,
+ textSelectionInner$,
+ currentSkeleton$,
+ commandHandlers,
+ docSelectionRenderService,
+ docSelectionManagerService,
+ editorService,
+ };
+}
+
+describe('DocSelectionRenderController', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ neoGetDocObjectMock.mockReset();
+ findFirstCursorOffsetMock.mockClear();
+ });
+
+ it('syncs selection manager refreshes and inner render selections', () => {
+ const { controller, refreshSelection$, textSelectionInner$, docSelectionRenderService, docSelectionManagerService } = createController();
+ const docRanges = [{ startOffset: 1, endOffset: 2 }];
+
+ refreshSelection$.next({ unitId: 'other-doc', docRanges });
+ refreshSelection$.next({ unitId: 'doc-1', docRanges, isEditing: true, options: { segmentId: 'header' } });
+ textSelectionInner$.next([{ startOffset: 3, endOffset: 4 }]);
+
+ expect(docSelectionRenderService.removeAllRanges).toHaveBeenCalledTimes(1);
+ expect(docSelectionRenderService.addDocRanges).toHaveBeenCalledWith(docRanges, true, { segmentId: 'header' });
+ expect(docSelectionManagerService.__replaceTextRangesWithNoRefresh).toHaveBeenCalledWith(
+ [{ startOffset: 3, endOffset: 4 }],
+ { unitId: 'doc-1', subUnitId: 'doc-1' }
+ );
+
+ controller.dispose();
+ });
+
+ it('initializes the visible document selection when skeleton becomes available and refreshes on zoom', () => {
+ const { controller, currentSkeleton$, commandHandlers, docSelectionRenderService, docSelectionManagerService } = createController();
+
+ currentSkeleton$.next({ id: 'skeleton' });
+ commandHandlers[0]({ id: SetDocZoomRatioOperation.id, params: { unitId: 'other-doc' } });
+ commandHandlers[0]({ id: SetDocZoomRatioOperation.id, params: { unitId: 'doc-1' } });
+
+ expect(docSelectionRenderService.focus).toHaveBeenCalled();
+ expect(docSelectionManagerService.replaceDocRanges).toHaveBeenCalledWith(
+ [{ startOffset: 3, endOffset: 3 }],
+ { unitId: 'doc-1', subUnitId: 'doc-1' },
+ false
+ );
+ expect(docSelectionManagerService.refreshSelection).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+
+ it('maps document pointer gestures to selection rendering and editor focus', () => {
+ vi.useFakeTimers();
+ const {
+ controller,
+ document,
+ scene,
+ viewModel,
+ docSelectionRenderService,
+ editorService,
+ } = createController({ hasEditor: true });
+ const stopPropagation = vi.fn();
+
+ document.onPointerEnter$.emit({});
+ expect(document.cursor).toBe(CURSOR_TYPE.TEXT);
+ document.onPointerLeave$.emit({});
+ expect(document.cursor).toBe(CURSOR_TYPE.DEFAULT);
+ expect(scene.resetCursor).toHaveBeenCalled();
+
+ document.onPointerDown$.emit({ offsetX: 11, offsetY: 22, button: 0 }, { stopPropagation });
+ vi.runOnlyPendingTimers();
+ document.onDblclick$.emit({ offsetX: 11, offsetY: 22 });
+ document.onTripleClick$.emit({ offsetX: 11, offsetY: 22 });
+
+ expect(viewModel.setEditArea).toHaveBeenCalledWith(DocumentEditArea.HEADER);
+ expect(docSelectionRenderService.__onPointDown).toHaveBeenCalled();
+ expect(editorService.focus).toHaveBeenCalledWith('doc-1');
+ expect(stopPropagation).toHaveBeenCalled();
+ expect(docSelectionRenderService.__handleDblClick).toHaveBeenCalled();
+ expect(docSelectionRenderService.__handleTripleClick).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
similarity index 100%
rename from packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts
rename to packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
diff --git a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
similarity index 100%
rename from packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts
rename to packages/docs-ui/src/services/clipboard/__tests__/html-and-udm-convert.spec.ts
diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/__test__/convertor.spec.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/convertor.spec.ts
similarity index 100%
rename from packages/docs-ui/src/services/clipboard/udm-to-html/__test__/convertor.spec.ts
rename to packages/docs-ui/src/services/clipboard/udm-to-html/__tests__/convertor.spec.ts
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx
index a2a5120472..4b1f8042cb 100644
--- a/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx
+++ b/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx
@@ -14,10 +14,19 @@
* limitations under the License.
*/
-import type { ICommand, ICommandInfo, IDrawingParam } from '@univerjs/core';
+import type { ICommand, ICommandInfo, IDocumentData, IDrawingParam } from '@univerjs/core';
import type { ReactElement } from 'react';
import type { Root } from 'react-dom/client';
-import { CommandType, DrawingTypeEnum, ICommandService, LocaleType, Univer } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CommandType,
+ DrawingTypeEnum,
+ ICommandService,
+ LocaleType,
+ PositionedObjectLayoutType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
@@ -33,6 +42,8 @@ const subUnitId = 'drawing-command-subunit';
const drawingId = 'image-1';
const wrappingStyleCommandId = 'doc.command.update-doc-drawing-wrapping-style';
const editCommandId = 'drawing.command.open-image-setting';
+const cropCommandId = 'drawing.command.crop-image';
+const deleteCommandId = 'drawing.command.delete-image';
function createDrawing(id: string): IDrawingParam {
return {
@@ -50,6 +61,40 @@ function createDrawing(id: string): IDrawingParam {
};
}
+function createDocData(layoutType: PositionedObjectLayoutType, behindDoc = BooleanNumber.FALSE): IDocumentData {
+ return {
+ id: unitId,
+ body: {
+ dataStream: '\b\r\n',
+ customBlocks: [{
+ startIndex: 0,
+ blockId: drawingId,
+ }],
+ },
+ drawings: {
+ [drawingId]: {
+ drawingId,
+ unitId,
+ subUnitId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ layoutType,
+ behindDoc,
+ } as never,
+ },
+ drawingsOrder: [drawingId],
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
function createOperation(id: string): ICommand {
return {
id,
@@ -111,6 +156,8 @@ describe('drawing command behavior', () => {
commandService.registerCommand(SetDrawingAlignOperation);
commandService.registerCommand(createOperation(wrappingStyleCommandId));
commandService.registerCommand(createOperation(editCommandId));
+ commandService.registerCommand(createOperation(cropCommandId));
+ commandService.registerCommand(createOperation(deleteCommandId));
executedCommands = [];
commandService.onCommandExecuted((command) => executedCommands.push(command));
});
@@ -182,6 +229,45 @@ describe('drawing command behavior', () => {
}]);
});
+ it('loads the current doc image wrapping style before changing it from the floating toolbar', async () => {
+ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData(PositionedObjectLayoutType.WRAP_NONE, BooleanNumber.TRUE));
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImagePopupMenu
+ popup={{
+ extraProps: {
+ variant: 'doc-floating-toolbar',
+ unitId,
+ subUnitId,
+ drawingId,
+ menuItems: [],
+ },
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(document.querySelector('[data-u-comp="doc-image-floating-toolbar"] button')!);
+ const behindTextOption = findByText<HTMLButtonElement>('button', 'drawing-ui.image-text-wrap.behindText');
+
+ expect(behindTextOption.className).toContain('univer-bg-primary-50');
+
+ clickElement(findByText('button', 'drawing-ui.image-text-wrap.inFrontText'));
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([{
+ id: wrappingStyleCommandId,
+ type: CommandType.OPERATION,
+ params: {
+ unitId,
+ subUnitId,
+ drawings: [{ unitId, subUnitId, drawingId }],
+ wrappingStyle: 'inFrontOfText',
+ },
+ }]);
+ });
+
it('executes edit command and hides the doc image floating toolbar', async () => {
const editParams = { unitId, subUnitId, drawingId, source: 'toolbar' };
const rendered = renderWithRediContext(
@@ -217,4 +303,143 @@ describe('drawing command behavior', () => {
}]);
expect(document.querySelector('[data-u-comp="doc-image-floating-toolbar"]')).toBeNull();
});
+
+ it('keeps disabled doc image toolbar actions inert without hiding the toolbar', async () => {
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImagePopupMenu
+ popup={{
+ extraProps: {
+ variant: 'doc-floating-toolbar',
+ unitId,
+ subUnitId,
+ drawingId,
+ menuItems: [
+ {
+ label: 'drawing-ui.image-popup.edit',
+ index: 0,
+ commandId: editCommandId,
+ commandParams: { unitId, subUnitId, drawingId, source: 'toolbar' },
+ disable: true,
+ },
+ {
+ label: 'drawing-ui.image-popup.crop',
+ index: 1,
+ commandId: 'drawing.command.crop-image',
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: true,
+ },
+ {
+ label: 'drawing-ui.image-popup.delete',
+ index: 2,
+ commandId: 'drawing.command.delete-image',
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: true,
+ },
+ ],
+ },
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ const toolbarButtons = Array.from(document.querySelectorAll<HTMLButtonElement>('[data-u-comp="doc-image-floating-toolbar"] button'));
+ const actionButtons = toolbarButtons.slice(1);
+ expect(actionButtons.map((button) => button.disabled)).toEqual([true, true, true]);
+
+ actionButtons.forEach(clickElement);
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([]);
+ expect(document.querySelector('[data-u-comp="doc-image-floating-toolbar"]')).not.toBeNull();
+ });
+
+ it('executes crop and delete commands from the doc image floating toolbar', async () => {
+ const cropParams = { unitId, subUnitId, drawingId, source: 'toolbar-crop' };
+ const deleteParams = { unitId, subUnitId, drawingId, source: 'toolbar-delete' };
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImagePopupMenu
+ popup={{
+ extraProps: {
+ variant: 'doc-floating-toolbar',
+ unitId,
+ subUnitId,
+ drawingId,
+ menuItems: [
+ {
+ label: 'drawing-ui.image-popup.crop',
+ index: 1,
+ commandId: cropCommandId,
+ commandParams: cropParams,
+ disable: false,
+ },
+ {
+ label: 'drawing-ui.image-popup.delete',
+ index: 2,
+ commandId: deleteCommandId,
+ commandParams: deleteParams,
+ disable: false,
+ },
+ ],
+ },
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ const toolbarButtons = document.querySelectorAll('[data-u-comp="doc-image-floating-toolbar"] button');
+ clickElement(toolbarButtons[2]);
+ clickElement(toolbarButtons[3]);
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([
+ {
+ id: cropCommandId,
+ type: CommandType.OPERATION,
+ params: cropParams,
+ },
+ {
+ id: deleteCommandId,
+ type: CommandType.OPERATION,
+ params: deleteParams,
+ },
+ ]);
+ expect(document.querySelector('[data-u-comp="doc-image-floating-toolbar"]')).not.toBeNull();
+ });
+
+ it('executes a selected sheet image popup menu item and closes the menu', async () => {
+ const editParams = { unitId, subUnitId, drawingId, source: 'sheet-popup' };
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImagePopupMenu
+ popup={{
+ extraProps: {
+ menuItems: [{
+ label: 'drawing-ui.image-popup.edit',
+ index: 0,
+ commandId: editCommandId,
+ commandParams: editParams,
+ disable: false,
+ }],
+ },
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(container.firstElementChild!.firstElementChild!);
+ clickElement(findByText('[role="menuitem"]', 'drawing-ui.image-popup.edit'));
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([{
+ id: editCommandId,
+ type: CommandType.OPERATION,
+ params: editParams,
+ }]);
+ expect(document.querySelector('[role="menuitem"]')).toBeNull();
+ });
});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx
new file mode 100644
index 0000000000..ce6e04da87
--- /dev/null
+++ b/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx
@@ -0,0 +1,288 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDrawingParam } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import { DrawingTypeEnum, LocaleType, Univer } from '@univerjs/core';
+import { DrawingManagerService, getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Subject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DrawingImageClipService } from '../../services/drawing-image-clip.service';
+import { DrawingCommonPanel } from '../panel/DrawingCommonPanel';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const unitId = 'drawing-common-panel-unit';
+const subUnitId = 'drawing-common-panel-subunit';
+
+class TestTransformer {
+ readonly clearControl$ = new Subject<boolean>();
+ readonly changeStart$ = new Subject<{ objects: Map<string, { oKey: string }> }>();
+ readonly changing$ = new Subject<{ objects: Map<string, { oKey: string }> }>();
+ readonly changeEnd$ = new Subject<{ objects: Map<string, { oKey: string }> }>();
+ keepRatio = true;
+
+ refreshControls() {
+ return {
+ changeNotification: () => undefined,
+ };
+ }
+}
+
+class TestScene {
+ ancestorLeft = 0;
+ ancestorTop = 0;
+
+ constructor(private readonly _transformer: TestTransformer) {}
+
+ getEngine() {
+ return {
+ activeScene: {
+ width: 500,
+ height: 400,
+ },
+ };
+ }
+
+ getTransformerByCreate() {
+ return this._transformer;
+ }
+}
+
+class TestRenderManagerService {
+ readonly transformer = new TestTransformer();
+ readonly scene = new TestScene(this.transformer);
+
+ getRenderById() {
+ return {
+ scene: this.scene,
+ };
+ }
+}
+
+function createDrawing(drawingId: string, left: number): IDrawingParam {
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: {
+ left,
+ top: 20,
+ width: 100,
+ height: 50,
+ angle: 0,
+ },
+ };
+}
+
+function renderWithRediContext(injector: ReturnType<Univer['__getInjector']>, drawings: IDrawingParam[]) {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <DrawingCommonPanel drawings={drawings} />
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, root };
+}
+
+function textIsAvailable(container: HTMLElement, text: string) {
+ const element = Array.from(container.querySelectorAll<HTMLElement>('button,div,span'))
+ .find((item) => item.textContent === text);
+
+ if (!element) {
+ return false;
+ }
+
+ let current: HTMLElement | null = element;
+ while (current && current !== container) {
+ if (current.classList.contains('univer-hidden')) {
+ return false;
+ }
+
+ current = current.parentElement;
+ }
+
+ return true;
+}
+
+describe('DrawingCommonPanel behavior', () => {
+ let univer: Univer;
+ let drawingManagerService: IDrawingManagerService;
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ univer = new Univer({ locales: { [LocaleType.ZH_CN]: {} } });
+ const injector = univer.__getInjector();
+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IconManager]);
+ injector.add([ComponentManager]);
+ injector.add([DrawingImageClipService]);
+
+ drawingManagerService = injector.get(IDrawingManagerService);
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ univer.dispose();
+ });
+
+ it('starts in multi-select mode when multiple drawings are already focused', () => {
+ const drawings = [createDrawing('image-1', 10), createDrawing('image-2', 140)];
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ 'image-1': drawings[0],
+ 'image-2': drawings[1],
+ },
+ order: ['image-1', 'image-2'],
+ },
+ });
+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));
+
+ const rendered = renderWithRediContext(univer.__getInjector(), drawings);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.align.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.arrange.title')).toBe(true);
+ });
+
+ it('switches from single-image controls to multi-select controls when drawing focus changes', () => {
+ const drawings = [createDrawing('image-1', 10), createDrawing('image-2', 140)];
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ 'image-1': drawings[0],
+ 'image-2': drawings[1],
+ },
+ order: ['image-1', 'image-2'],
+ },
+ });
+ drawingManagerService.focusDrawing([{ unitId, subUnitId, drawingId: 'image-1' }]);
+
+ const rendered = renderWithRediContext(univer.__getInjector(), [drawings[0]]);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.align.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.arrange.title')).toBe(true);
+
+ act(() => {
+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));
+ });
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.align.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.arrange.title')).toBe(true);
+ });
+
+ it('switches from multi-select controls to single-image controls when the transformer starts editing one drawing', () => {
+ const drawings = [createDrawing('image-1', 10), createDrawing('image-2', 140)];
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ 'image-1': drawings[0],
+ 'image-2': drawings[1],
+ },
+ order: ['image-1', 'image-2'],
+ },
+ });
+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));
+
+ const rendered = renderWithRediContext(univer.__getInjector(), drawings);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.align.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(false);
+
+ const oKey = getDrawingShapeKeyByDrawingSearch({
+ unitId,
+ subUnitId,
+ drawingId: 'image-1',
+ });
+
+ act(() => {
+ (univer.__getInjector().get(IRenderManagerService) as unknown as TestRenderManagerService)
+ .transformer
+ .changeStart$
+ .next({ objects: new Map([[oKey, { oKey }]]) });
+ });
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.align.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.arrange.title')).toBe(true);
+ });
+
+ it('returns to the empty panel when the active transformer clears its controls', () => {
+ const drawing = createDrawing('image-1', 10);
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ 'image-1': drawing,
+ },
+ order: ['image-1'],
+ },
+ });
+ drawingManagerService.focusDrawing([{ unitId, subUnitId, drawingId: 'image-1' }]);
+
+ const rendered = renderWithRediContext(univer.__getInjector(), [drawing]);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.null')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.arrange.title')).toBe(true);
+
+ act(() => {
+ (univer.__getInjector().get(IRenderManagerService) as unknown as TestRenderManagerService)
+ .transformer
+ .clearControl$
+ .next(true);
+ });
+
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.null')).toBe(true);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.transform.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.crop.title')).toBe(false);
+ expect(textIsAvailable(container, 'drawing-ui.image-panel.arrange.title')).toBe(false);
+ });
+});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.spec.tsx
index 8b82d02d10..f4f4492dad 100644
--- a/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.spec.tsx
+++ b/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.spec.tsx
@@ -19,7 +19,7 @@ import type { IDrawingGroupUpdateParam } from '@univerjs/drawing';
import type { ReactElement } from 'react';
import type { Root } from 'react-dom/client';
import { DrawingTypeEnum, ICommandService, LocaleType, Univer } from '@univerjs/core';
-import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';
+import { DrawingManagerService, getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
import { IconManager, RediContext } from '@univerjs/ui';
import { act } from 'react';
@@ -107,6 +107,26 @@ function findButtonByText(text: string): HTMLButtonElement {
return button;
}
+function buttonIsAvailable(text: string): boolean {
+ const button = Array.from(document.querySelectorAll<HTMLButtonElement>('button'))
+ .find((item) => item.textContent?.includes(text));
+
+ if (!button) {
+ return false;
+ }
+
+ let current: HTMLElement | null = button;
+ while (current && current !== document.body) {
+ if (current.classList.contains('univer-hidden')) {
+ return false;
+ }
+
+ current = current.parentElement;
+ }
+
+ return true;
+}
+
function renderWithRediContext(injector: ReturnType<Univer['__getInjector']>, element: ReactElement) {
const container = document.createElement('div');
document.body.appendChild(container);
@@ -225,4 +245,41 @@ describe('DrawingGroup behavior', () => {
{ drawingId: 'image-2', groupId: undefined },
]);
});
+
+ it('shows only the group action when the transformer selects multiple ungrouped drawings', () => {
+ const drawings = [createDrawing('image-1', 0), createDrawing('image-2', 30)];
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ 'image-1': drawings[0],
+ 'image-2': drawings[1],
+ },
+ order: ['image-1', 'image-2'],
+ },
+ });
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <DrawingGroup hasGroup drawings={drawings} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ const firstKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId: 'image-1' });
+ const secondKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId: 'image-2' });
+
+ act(() => {
+ (univer.__getInjector().get(IRenderManagerService) as unknown as TestRenderManagerService)
+ .changeStart$
+ .next({
+ objects: new Map([
+ [firstKey, { oKey: firstKey, left: 0, top: 10, width: 20, height: 30, angle: 0 }],
+ [secondKey, { oKey: secondKey, left: 30, top: 10, width: 20, height: 30, angle: 0 }],
+ ]),
+ });
+ });
+
+ expect(buttonIsAvailable('drawing-ui.image-panel.group.group')).toBe(true);
+ expect(buttonIsAvailable('drawing-ui.image-panel.group.unGroup')).toBe(false);
+ });
});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
index 2537580110..fcc6e04b72 100644
--- a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
+++ b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
@@ -25,7 +25,11 @@ import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SetDrawingArrangeOperation } from '../../commands/operations/drawing-arrange.operation';
-import { AutoImageCropOperation, CropType } from '../../commands/operations/image-crop.operation';
+import {
+ AutoImageCropOperation,
+ CloseImageCropOperation,
+ CropType,
+} from '../../commands/operations/image-crop.operation';
import { DrawingImageClipService } from '../../services/drawing-image-clip.service';
import { DrawingArrange } from '../panel/DrawingArrange';
import { ImageCropper } from '../panel/ImageCropper';
@@ -108,6 +112,7 @@ describe('drawing panel actions', () => {
commandService = injector.get(ICommandService);
commandService.registerCommand(SetDrawingArrangeOperation);
commandService.registerCommand(AutoImageCropOperation);
+ commandService.registerCommand(CloseImageCropOperation);
drawingManagerService = injector.get(IDrawingManagerService);
});
@@ -143,6 +148,45 @@ describe('drawing panel actions', () => {
}]);
});
+ it('uses the latest focused drawings when arranging after selection changes', () => {
+ const originalDrawing = createDrawing('image-1', 0);
+ const focusedDrawing = createDrawing('image-2', 30);
+ const orderUpdates: IDrawingOrderUpdateParam[] = [];
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ [originalDrawing.drawingId]: originalDrawing,
+ [focusedDrawing.drawingId]: focusedDrawing,
+ },
+ order: [originalDrawing.drawingId, focusedDrawing.drawingId],
+ },
+ });
+ drawingManagerService.featurePluginOrderUpdate$.subscribe((update) => orderUpdates.push(update));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <DrawingArrange arrangeShow drawings={[originalDrawing]} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => {
+ drawingManagerService.focusDrawing([{
+ unitId,
+ subUnitId,
+ drawingId: focusedDrawing.drawingId,
+ }]);
+ });
+ clickElement(findActionByText('drawing-ui.image-panel.arrange.forward'));
+
+ expect(orderUpdates).toEqual([{
+ unitId,
+ subUnitId,
+ drawingIds: [focusedDrawing.drawingId],
+ arrangeType: ArrangeTypeEnum.forward,
+ }]);
+ });
+
it('starts image cropping with the current crop mode', async () => {
const executedCommands: ICommandInfo[] = [];
commandService.onCommandExecuted((command) => executedCommands.push(command));
@@ -165,4 +209,88 @@ describe('drawing panel actions', () => {
},
}]);
});
+
+ it('reapplies image cropping when the crop mode changes while cropping', async () => {
+ const executedCommands: ICommandInfo[] = [];
+ commandService.onCommandExecuted((command) => executedCommands.push(command));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImageCropper cropperShow drawings={[createDrawing('image-1', 0)]} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(findActionByText('drawing-ui.image-panel.crop.start'));
+ await flushPendingCommands();
+
+ await act(async () => {
+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const squareCropOption = findActionByText('1:1');
+
+ await act(async () => {
+ squareCropOption.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(executedCommands).toEqual([
+ {
+ id: AutoImageCropOperation.id,
+ type: AutoImageCropOperation.type,
+ params: {
+ cropType: CropType.FREE,
+ },
+ },
+ {
+ id: AutoImageCropOperation.id,
+ type: AutoImageCropOperation.type,
+ params: {
+ cropType: CropType.R1_1,
+ },
+ },
+ ]);
+ });
+
+ it('does not reapply image cropping after manual crop close when the crop mode changes', async () => {
+ const executedCommands: ICommandInfo[] = [];
+ commandService.onCommandExecuted((command) => executedCommands.push(command));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImageCropper cropperShow drawings={[createDrawing('image-1', 0)]} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(findActionByText('drawing-ui.image-panel.crop.start'));
+ await flushPendingCommands();
+
+ await act(async () => {
+ await commandService.executeCommand(CloseImageCropOperation.id);
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ findActionByText('16:9').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(executedCommands.filter((command) => command.id === AutoImageCropOperation.id)).toEqual([
+ {
+ id: AutoImageCropOperation.id,
+ type: AutoImageCropOperation.type,
+ params: {
+ cropType: CropType.FREE,
+ },
+ },
+ ]);
+ });
});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingTransformBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingTransformBehavior.spec.tsx
new file mode 100644
index 0000000000..f6b3ce3282
--- /dev/null
+++ b/packages/drawing-ui/src/views/__tests__/DrawingTransformBehavior.spec.tsx
@@ -0,0 +1,312 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDrawingParam } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import { DrawingTypeEnum, LocaleType, Univer } from '@univerjs/core';
+import { DrawingManagerService, getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Subject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DrawingTransform } from '../panel/DrawingTransform';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const unitId = 'drawing-transform-unit';
+const subUnitId = 'drawing-transform-subunit';
+
+interface ITransformObject {
+ oKey: string;
+ left?: number;
+ top?: number;
+ width?: number;
+ height?: number;
+ angle?: number;
+}
+
+class TestTransformer {
+ readonly changeStart$ = new Subject<{ objects: Map<string, ITransformObject> }>();
+ readonly changing$ = new Subject<{ objects: Map<string, ITransformObject> }>();
+ readonly changeEnd$ = new Subject<{ objects: Map<string, ITransformObject> }>();
+ keepRatio = true;
+ refreshCount = 0;
+ notificationCount = 0;
+
+ refreshControls() {
+ this.refreshCount += 1;
+
+ return {
+ changeNotification: () => {
+ this.notificationCount += 1;
+ },
+ };
+ }
+}
+
+class TestScene {
+ ancestorLeft = 0;
+ ancestorTop = 0;
+
+ constructor(private readonly _transformer: TestTransformer) {}
+
+ getEngine() {
+ return {
+ activeScene: {
+ width: 500,
+ height: 400,
+ },
+ };
+ }
+
+ getTransformerByCreate() {
+ return this._transformer;
+ }
+}
+
+class TestRenderManagerService {
+ readonly transformer = new TestTransformer();
+ readonly scene = new TestScene(this.transformer);
+
+ getRenderById() {
+ return {
+ scene: this.scene,
+ };
+ }
+}
+
+function createDrawing(drawingId: string): IDrawingParam {
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: {
+ left: 10,
+ top: 20,
+ width: 100,
+ height: 50,
+ angle: 0,
+ },
+ };
+}
+
+function renderWithRediContext(injector: ReturnType<Univer['__getInjector']>, drawing: IDrawingParam) {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <DrawingTransform transformShow drawings={[drawing]} />
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, root };
+}
+
+function inputInField(container: HTMLElement, text: string) {
+ const label = Array.from(container.querySelectorAll('span'))
+ .find((span) => span.textContent === text);
+ return label?.parentElement?.querySelector('input') as HTMLInputElement;
+}
+
+function checkboxInField(container: HTMLElement, text: string) {
+ const label = Array.from(container.querySelectorAll('span'))
+ .find((span) => span.textContent === text);
+ return label?.parentElement?.querySelector('input[type="checkbox"]') as HTMLInputElement;
+}
+
+function setInputValue(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+function inputNumberValue(container: HTMLElement, text: string) {
+ return Number(inputInField(container, text).value);
+}
+
+async function waitForDebouncedInput() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 350));
+ });
+}
+
+describe('DrawingTransform behavior', () => {
+ let univer: Univer;
+ let drawingManagerService: IDrawingManagerService;
+ let renderManagerService: TestRenderManagerService;
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ univer = new Univer({ locales: { [LocaleType.ZH_CN]: {} } });
+ const injector = univer.__getInjector();
+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+
+ drawingManagerService = injector.get(IDrawingManagerService);
+ renderManagerService = injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ univer.dispose();
+ });
+
+ it('resizes the focused drawing proportionally while aspect ratio is locked', async () => {
+ const drawing = createDrawing('image-1');
+ const updates: IDrawingParam[][] = [];
+ drawingManagerService.featurePluginUpdate$.subscribe((update) => updates.push(update));
+
+ const rendered = renderWithRediContext(univer.__getInjector(), drawing);
+ root = rendered.root;
+ container = rendered.container;
+
+ setInputValue(inputInField(container, 'drawing-ui.image-panel.transform.width'), '120');
+ await waitForDebouncedInput();
+
+ expect(updates).toEqual([[
+ {
+ unitId,
+ subUnitId,
+ drawingId: 'image-1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: {
+ width: 120,
+ height: 60,
+ },
+ },
+ ]]);
+ expect(renderManagerService.transformer.refreshCount).toBe(1);
+ expect(renderManagerService.transformer.notificationCount).toBe(1);
+ });
+
+ it('resizes only the edited dimension after aspect ratio is unlocked', async () => {
+ const drawing = createDrawing('image-1');
+ const updates: IDrawingParam[][] = [];
+ drawingManagerService.featurePluginUpdate$.subscribe((update) => updates.push(update));
+
+ const rendered = renderWithRediContext(univer.__getInjector(), drawing);
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => {
+ checkboxInField(container!, 'drawing-ui.image-panel.transform.lock').click();
+ });
+
+ expect(renderManagerService.transformer.keepRatio).toBe(false);
+
+ setInputValue(inputInField(container, 'drawing-ui.image-panel.transform.width'), '120');
+ await waitForDebouncedInput();
+
+ expect(updates).toEqual([[
+ {
+ unitId,
+ subUnitId,
+ drawingId: 'image-1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: {
+ width: 120,
+ },
+ },
+ ]]);
+ expect(renderManagerService.transformer.refreshCount).toBe(1);
+ expect(renderManagerService.transformer.notificationCount).toBe(1);
+ });
+
+ it('emits the requested rotation for the focused drawing', () => {
+ const drawing = createDrawing('image-1');
+ const updates: IDrawingParam[][] = [];
+ drawingManagerService.featurePluginUpdate$.subscribe((update) => updates.push(update));
+
+ const rendered = renderWithRediContext(univer.__getInjector(), drawing);
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => {
+ setInputValue(inputInField(container!, 'drawing-ui.image-panel.transform.rotate'), '45');
+ });
+
+ expect(updates).toEqual([[
+ {
+ unitId,
+ subUnitId,
+ drawingId: 'image-1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: {
+ angle: 45,
+ },
+ },
+ ]]);
+ expect(renderManagerService.transformer.refreshCount).toBe(1);
+ expect(renderManagerService.transformer.notificationCount).toBe(1);
+ });
+
+ it('syncs transform fields from canvas transformer updates', () => {
+ const drawing = createDrawing('image-1');
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ [drawing.drawingId]: drawing,
+ },
+ order: [drawing.drawingId],
+ },
+ });
+
+ const rendered = renderWithRediContext(univer.__getInjector(), drawing);
+ root = rendered.root;
+ container = rendered.container;
+
+ const oKey = getDrawingShapeKeyByDrawingSearch({
+ unitId,
+ subUnitId,
+ drawingId: drawing.drawingId,
+ });
+
+ act(() => {
+ renderManagerService.transformer.changeEnd$.next({
+ objects: new Map([[
+ oKey,
+ {
+ oKey,
+ left: 44,
+ top: 66,
+ width: 180,
+ height: 90,
+ angle: 15,
+ },
+ ]]),
+ });
+ });
+
+ expect(inputNumberValue(container, 'drawing-ui.image-panel.transform.width')).toBe(180);
+ expect(inputNumberValue(container, 'drawing-ui.image-panel.transform.height')).toBe(90);
+ expect(inputNumberValue(container, 'drawing-ui.image-panel.transform.x')).toBe(44);
+ expect(inputNumberValue(container, 'drawing-ui.image-panel.transform.y')).toBe(66);
+ expect(inputNumberValue(container, 'drawing-ui.image-panel.transform.rotate')).toBe(15);
+ });
+});
diff --git a/packages/drawing-ui/src/views/__tests__/ImageCropperObjectBehavior.spec.ts b/packages/drawing-ui/src/views/__tests__/ImageCropperObjectBehavior.spec.ts
new file mode 100644
index 0000000000..84cf632317
--- /dev/null
+++ b/packages/drawing-ui/src/views/__tests__/ImageCropperObjectBehavior.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 { Vector2 } from '@univerjs/engine-render';
+import { describe, expect, it } from 'vitest';
+import { ImageCropperObject } from '../crop/image-cropper-object';
+
+describe('ImageCropperObject behavior', () => {
+ it('treats the crop frame as draggable while leaving the image center untouched', () => {
+ const cropper = new ImageCropperObject('cropper', {
+ applyTransform: {
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 80,
+ angle: 0,
+ },
+ dragPadding: 10,
+ });
+
+ expect(cropper.isHit(Vector2.FromArray([5, 5]))).toBe(true);
+ expect(cropper.isHit(Vector2.FromArray([50, 40]))).toBe(false);
+ expect(cropper.isHit(Vector2.FromArray([120, 40]))).toBe(false);
+ });
+
+ it('positions the crop frame from the source rectangle and refreshes when the crop changes', () => {
+ const cropper = new ImageCropperObject('cropper', {
+ applyTransform: {
+ left: 10,
+ top: 20,
+ width: 120,
+ height: 80,
+ angle: 15,
+ },
+ srcRect: {
+ left: 5,
+ top: 10,
+ right: 15,
+ bottom: 20,
+ },
+ });
+
+ expect(cropper.getState()).toMatchObject({
+ left: 15,
+ top: 30,
+ width: 100,
+ height: 50,
+ angle: 15,
+ });
+
+ cropper.refreshSrcRect({
+ left: 0,
+ top: 5,
+ right: 30,
+ bottom: 10,
+ }, {
+ left: 10,
+ top: 20,
+ width: 120,
+ height: 80,
+ angle: 45,
+ });
+
+ expect(cropper.getState()).toMatchObject({
+ left: 10,
+ top: 25,
+ width: 90,
+ height: 65,
+ angle: 45,
+ });
+ });
+});
diff --git a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
index ad88a18b6b..52ec9407af 100644
--- a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
+++ b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
@@ -37,6 +37,36 @@ export interface IDrawingCommonPanelProps {
hasGroup?: boolean;
}
+function getPanelShowState(drawings: IDrawingParam[]) {
+ if (drawings.length === 0) {
+ return {
+ arrangeShow: false,
+ transformShow: false,
+ alignShow: false,
+ cropperShow: false,
+ nullShow: true,
+ };
+ }
+
+ if (drawings.length === 1) {
+ return {
+ arrangeShow: true,
+ transformShow: true,
+ alignShow: false,
+ cropperShow: true,
+ nullShow: false,
+ };
+ }
+
+ return {
+ arrangeShow: true,
+ transformShow: false,
+ alignShow: true,
+ cropperShow: false,
+ nullShow: false,
+ };
+}
+
export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {
const drawingManagerService = useDependency(IDrawingManagerService);
const renderManagerService = useDependency(IRenderManagerService);
@@ -59,11 +89,13 @@ export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {
}
const transformer = scene.getTransformerByCreate();
- const [arrangeShow, setArrangeShow] = useState(true);
- const [transformShow, setTransformShow] = useState(true);
- const [alignShow, setAlignShow] = useState(false);
- const [cropperShow, setCropperShow] = useState(true);
- const [nullShow, setNullShow] = useState(false);
+ const initialShowState = getPanelShowState(drawings);
+
+ const [arrangeShow, setArrangeShow] = useState(initialShowState.arrangeShow);
+ const [transformShow, setTransformShow] = useState(initialShowState.transformShow);
+ const [alignShow, setAlignShow] = useState(initialShowState.alignShow);
+ const [cropperShow, setCropperShow] = useState(initialShowState.cropperShow);
+ const [nullShow, setNullShow] = useState(initialShowState.nullShow);
// const [groupShow, setGroupShow] = useState(false);
useEffect(() => {
diff --git a/packages/engine-formula/src/basics/__tests__/dirty.spec.ts b/packages/engine-formula/src/basics/__tests__/dirty.spec.ts
new file mode 100644
index 0000000000..4534094d66
--- /dev/null
+++ b/packages/engine-formula/src/basics/__tests__/dirty.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IUnitRange } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { isInDirtyRange } from '../dirty';
+
+describe('dirty range matching', () => {
+ const dirtyRanges: IUnitRange[] = [
+ {
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ range: {
+ startRow: 2,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 3,
+ },
+ },
+ {
+ unitId: 'unit-1',
+ sheetId: 'sheet-2',
+ range: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ },
+ },
+ ];
+
+ it('matches cells inside the edited range including boundary cells', () => {
+ expect(isInDirtyRange(dirtyRanges, 'unit-1', 'sheet-1', 2, 1)).toBe(true);
+ expect(isInDirtyRange(dirtyRanges, 'unit-1', 'sheet-1', 3, 2)).toBe(true);
+ expect(isInDirtyRange(dirtyRanges, 'unit-1', 'sheet-1', 4, 3)).toBe(true);
+ });
+
+ it('does not match cells outside the range or from another sheet/workbook', () => {
+ expect(isInDirtyRange(dirtyRanges, 'unit-1', 'sheet-1', 1, 1)).toBe(false);
+ expect(isInDirtyRange(dirtyRanges, 'unit-1', 'sheet-1', 4, 4)).toBe(false);
+ expect(isInDirtyRange(dirtyRanges, 'unit-1', 'sheet-2', 3, 2)).toBe(false);
+ expect(isInDirtyRange(dirtyRanges, 'unit-2', 'sheet-1', 3, 2)).toBe(false);
+ });
+});
diff --git a/packages/engine-formula/src/controllers/__tests__/computing-status.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/computing-status.controller.spec.ts
new file mode 100644
index 0000000000..6d07a2ad2f
--- /dev/null
+++ b/packages/engine-formula/src/controllers/__tests__/computing-status.controller.spec.ts
@@ -0,0 +1,102 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { describe, expect, it } from 'vitest';
+import { SetFormulaCalculationNotificationMutation } from '../../commands/mutations/set-formula-calculation.mutation';
+import { FormulaExecuteStageType } from '../../services/runtime.service';
+import { ComputingStatusReporterController } from '../computing-status.controller';
+
+interface ICommandServiceMock {
+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };
+ emit: (id: string, params?: unknown) => void;
+}
+
+function createCommandServiceMock(): ICommandServiceMock {
+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();
+ return {
+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {
+ callbacks.add(callback);
+ return {
+ dispose: () => callbacks.delete(callback),
+ };
+ },
+ emit: (id: string, params?: unknown) => {
+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));
+ },
+ };
+}
+
+describe('ComputingStatusReporterController', () => {
+ it('reports formula calculation progress and completion to the global computing status service', () => {
+ const commandService = createCommandServiceMock();
+ const registeredSubjects: Array<{ getValue: () => boolean; next: (value: boolean) => void; isStopped: boolean }> = [];
+ const globalComputingStatusService = {
+ pushComputingStatusSubject: (subject: { getValue: () => boolean; next: (value: boolean) => void; isStopped: boolean }) => {
+ registeredSubjects.push(subject);
+ return {
+ dispose: () => {
+ const index = registeredSubjects.indexOf(subject);
+ if (index !== -1) {
+ registeredSubjects.splice(index, 1);
+ }
+ },
+ };
+ },
+ };
+
+ const controller = new ComputingStatusReporterController(commandService as never, globalComputingStatusService as never);
+
+ expect(registeredSubjects).toHaveLength(1);
+ expect(registeredSubjects[0].getValue()).toBe(true);
+
+ commandService.emit(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,
+ },
+ });
+ expect(registeredSubjects[0].getValue()).toBe(false);
+
+ commandService.emit(SetFormulaCalculationNotificationMutation.id, {
+ stageInfo: {
+ stage: FormulaExecuteStageType.CALCULATION_COMPLETED,
+ },
+ });
+ expect(registeredSubjects[0].getValue()).toBe(true);
+
+ controller.dispose();
+ expect(registeredSubjects).toHaveLength(0);
+ });
+
+ it('ignores unrelated commands and notifications without stage info', () => {
+ const commandService = createCommandServiceMock();
+ const registeredSubjects: Array<{ getValue: () => boolean; next: (value: boolean) => void; isStopped: boolean }> = [];
+ const globalComputingStatusService = {
+ pushComputingStatusSubject: (subject: { getValue: () => boolean; next: (value: boolean) => void; isStopped: boolean }) => {
+ registeredSubjects.push(subject);
+ return { dispose: () => undefined };
+ },
+ };
+
+ // eslint-disable-next-line no-new
+ new ComputingStatusReporterController(commandService as never, globalComputingStatusService as never);
+
+ commandService.emit('unrelated.command', {});
+ commandService.emit(SetFormulaCalculationNotificationMutation.id, {});
+
+ expect(registeredSubjects[0].getValue()).toBe(true);
+ });
+});
diff --git a/packages/engine-formula/src/controllers/__tests__/set-feature-calculation.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/set-feature-calculation.controller.spec.ts
new file mode 100644
index 0000000000..692afec4b9
--- /dev/null
+++ b/packages/engine-formula/src/controllers/__tests__/set-feature-calculation.controller.spec.ts
@@ -0,0 +1,102 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { describe, expect, it, vi } from 'vitest';
+import { RemoveFeatureCalculationMutation, SetFeatureCalculationMutation } from '../../commands/mutations/set-feature-calculation.mutation';
+import { SetFeatureCalculationController } from '../set-feature-calculation.controller';
+
+interface ICommandServiceMock {
+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };
+ emit: (id: string, params?: unknown) => void;
+}
+
+function createCommandServiceMock(): ICommandServiceMock {
+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();
+ return {
+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {
+ callbacks.add(callback);
+ return {
+ dispose: () => callbacks.delete(callback),
+ };
+ },
+ emit: (id: string, params?: unknown) => {
+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));
+ },
+ };
+}
+
+describe('SetFeatureCalculationController', () => {
+ it('registers and removes feature calculation executors from command payloads', () => {
+ const commandService = createCommandServiceMock();
+ const featureCalculationManagerService = {
+ register: vi.fn(),
+ remove: vi.fn(),
+ };
+
+ // eslint-disable-next-line no-new
+ new SetFeatureCalculationController(commandService as never, featureCalculationManagerService as never);
+
+ const calculationParam = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ dependencyRanges: [
+ {
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ range: {
+ startRow: 1,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ },
+ },
+ ],
+ getDirtyData: vi.fn(),
+ };
+
+ commandService.emit(SetFeatureCalculationMutation.id, {
+ featureId: 'feature-1',
+ calculationParam,
+ });
+ expect(featureCalculationManagerService.register).toHaveBeenCalledWith('unit-1', 'sheet-1', 'feature-1', calculationParam);
+
+ commandService.emit(RemoveFeatureCalculationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ featureIds: ['feature-1'],
+ });
+ expect(featureCalculationManagerService.remove).toHaveBeenCalledWith('unit-1', 'sheet-1', ['feature-1']);
+ });
+
+ it('ignores null params and unrelated commands', () => {
+ const commandService = createCommandServiceMock();
+ const featureCalculationManagerService = {
+ register: vi.fn(),
+ remove: vi.fn(),
+ };
+
+ // eslint-disable-next-line no-new
+ new SetFeatureCalculationController(commandService as never, featureCalculationManagerService as never);
+
+ commandService.emit(SetFeatureCalculationMutation.id, null);
+ commandService.emit(RemoveFeatureCalculationMutation.id, null);
+ commandService.emit('unknown.command', {});
+
+ expect(featureCalculationManagerService.register).not.toHaveBeenCalled();
+ expect(featureCalculationManagerService.remove).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
index 705d8dd107..d61134969b 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
@@ -188,5 +188,63 @@ describe('Test dependency', () => {
expect(tree2.refOffsetX).toEqual(0);
expect(tree2.refOffsetY).toEqual(2);
});
+
+ it('should generate virtual dependency trees for shared formulas with offsets', async () => {
+ formulaCurrentConfigService.load({
+ formulaData: {
+ [testUnitId]: {
+ [testSheetId]: {
+ 0: {
+ 1: {
+ f: '=A1',
+ si: 'shared-formula-1',
+ },
+ },
+ 1: {
+ 1: {
+ f: '=A1',
+ si: 'shared-formula-1',
+ x: 0,
+ y: 1,
+ },
+ },
+ 2: {
+ 1: {
+ f: '=A1',
+ si: 'shared-formula-1',
+ x: 0,
+ y: 2,
+ },
+ },
+ },
+ },
+ },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: true,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ excludedCell: {},
+ allUnitData: {
+ [testUnitId]: testSheetData,
+ },
+ });
+
+ const treeList = await formulaDependencyGenerator.generate();
+ const realTree = treeList.find((tree): tree is FormulaDependencyTree => tree instanceof FormulaDependencyTree && tree.row === 0 && tree.column === 1);
+ const virtualTrees = treeList.filter((tree): tree is FormulaDependencyTreeVirtual => !(tree instanceof FormulaDependencyTree));
+
+ expect(realTree?.formula).toBe('=A1');
+ expect(virtualTrees).toHaveLength(2);
+ expect(virtualTrees
+ .map((tree) => [tree.refTree, tree.refOffsetX, tree.refOffsetY])
+ .sort((a, b) => Number(a[2]) - Number(b[2]))).toEqual([
+ [realTree, 0, 1],
+ [realTree, 0, 2],
+ ]);
+ });
});
});
diff --git a/packages/engine-formula/src/functions/logical/bycol/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/bycol/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/logical/bycol/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/logical/bycol/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/logical/byrow/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/byrow/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/logical/byrow/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/logical/byrow/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/logical/makearray/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/makearray/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/logical/makearray/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/logical/makearray/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/logical/map/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/map/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/logical/map/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/logical/map/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/logical/reduce/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/reduce/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/logical/reduce/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/logical/reduce/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/logical/scan/__test__/index.spec.ts b/packages/engine-formula/src/functions/logical/scan/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/logical/scan/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/logical/scan/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/lookup/filter/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/filter/__tests__/index.spec.ts
index 44cb878c6c..0bb1baefd2 100644
--- a/packages/engine-formula/src/functions/lookup/filter/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/filter/__tests__/index.spec.ts
@@ -16,9 +16,9 @@
import { describe, expect, it } from 'vitest';
import { ErrorType } from '../../../../basics/error-type';
-import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
+import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
-import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
import { getObjectValue } from '../../../util';
import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
import { Filter } from '../index';
@@ -77,5 +77,38 @@ describe('Test filter function', () => {
['empty3'],
]);
});
+
+ it('filters columns when include is a single row', async () => {
+ const array = ArrayValueObject.create('{1,2,3;4,5,6}');
+ const include = ArrayValueObject.create('{true,false,1}');
+
+ const resultObject = testFunction.calculate(array, include);
+
+ expect(getObjectValue(resultObject)).toStrictEqual([
+ [1, 3],
+ [4, 6],
+ ]);
+ });
+
+ it('supports scalar array and string-number include values', async () => {
+ expect(getObjectValue(testFunction.calculate(NumberValueObject.create(42), StringValueObject.create('1')))).toBe(42);
+ expect(getObjectValue(testFunction.calculate(NumberValueObject.create(42), StringValueObject.create('0'), StringValueObject.create('empty')))).toBe('empty');
+ });
+
+ it('returns include conversion errors before building a filtered result', async () => {
+ const array = ArrayValueObject.create('{1,2,3;4,5,6}');
+ const includeWithError = ArrayValueObject.create({
+ calculateValueList: transformToValueObject([[1], [ErrorType.NA]]),
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+
+ expect(getObjectValue(testFunction.calculate(array, ArrayValueObject.create('{"test",1,1}')))).toBe(ErrorType.VALUE);
+ expect(getObjectValue(testFunction.calculate(array, includeWithError))).toBe(ErrorType.NA);
+ });
});
});
diff --git a/packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/lookup/index/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts b/packages/engine-formula/src/functions/lookup/indirect/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/lookup/indirect/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/meta/cube/__tests__/index.spec.ts b/packages/engine-formula/src/functions/meta/cube/__tests__/index.spec.ts
new file mode 100644
index 0000000000..9f00e58866
--- /dev/null
+++ b/packages/engine-formula/src/functions/meta/cube/__tests__/index.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 { describe, expect, it } from 'vitest';
+import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
+import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { CubeValueObject } from '../../../../engine/value-object/cube-value-object';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { getObjectValue } from '../../../util';
+import { FUNCTION_NAMES_META } from '../../function-names';
+import { Cube } from '../index';
+
+describe('Cube function', () => {
+ const testFunction = new Cube(FUNCTION_NAMES_META.CUBE);
+
+ it('combines multiple array references into a cube value object', () => {
+ const first = ArrayValueObject.create('{1,2;3,4}');
+ const second = ArrayValueObject.create('{5;6}');
+
+ const result = testFunction.calculate(first, second);
+
+ expect(result.isCube()).toBe(true);
+ expect(result).toBeInstanceOf(CubeValueObject);
+ expect((result as CubeValueObject).getCubeCount()).toBe(2);
+ expect((result as CubeValueObject).getCubeValues()).toEqual([first, second]);
+ });
+
+ it('propagates input errors before validating array arguments', () => {
+ const result = testFunction.calculate(ErrorValueObject.create(ErrorType.NAME), NumberValueObject.create(1));
+
+ expect(getObjectValue(result)).toBe(ErrorType.NAME);
+ });
+
+ it('rejects scalar values because cube aggregation requires array inputs', () => {
+ const result = testFunction.calculate(ArrayValueObject.create('{1,2}'), NumberValueObject.create(1));
+
+ expect(getObjectValue(result)).toBe(ErrorType.VALUE);
+ });
+});
diff --git a/packages/engine-formula/src/functions/text/arraytotext/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/arraytotext/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/arraytotext/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/arraytotext/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/asc/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/asc/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/asc/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/asc/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/bahttext/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/bahttext/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/bahttext/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/bahttext/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/char/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/char/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/char/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/char/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/clean/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/clean/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/clean/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/clean/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/code/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/code/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/code/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/code/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/dbcs/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/dbcs/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/dbcs/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/dbcs/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/dollar/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/dollar/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/dollar/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/dollar/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/exact/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/exact/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/exact/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/exact/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/find/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/find/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/find/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/find/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/findb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/findb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/findb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/findb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/fixed/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/fixed/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/fixed/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/fixed/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/left/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/left/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/left/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/left/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/leftb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/leftb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/leftb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/leftb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/len/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/len/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/len/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/len/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/lenb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/lenb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/lenb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/lenb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/lower/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/lower/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/lower/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/lower/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/mid/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/mid/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/mid/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/mid/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/midb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/midb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/midb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/midb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/numberstring/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/numberstring/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/numberstring/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/numberstring/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/numbervalue/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/numbervalue/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/numbervalue/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/numbervalue/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/proper/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/proper/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/proper/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/proper/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/regexextract/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/regexextract/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/regexextract/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/regexextract/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/regexmatch/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/regexmatch/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/regexmatch/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/regexmatch/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/regexreplace/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/regexreplace/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/regexreplace/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/regexreplace/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/replace/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/replace/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/replace/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/replace/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/replaceb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/replaceb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/replaceb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/replaceb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/rept/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/rept/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/rept/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/rept/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/right/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/right/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/right/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/right/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/rightb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/rightb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/rightb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/rightb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/search/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/search/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/search/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/search/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/searchb/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/searchb/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/searchb/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/searchb/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/substitute/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/substitute/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/substitute/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/substitute/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/t/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/t/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/t/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/t/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/text/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/text/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/text/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/text/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/textafter/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/textafter/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/textafter/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/textafter/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/textbefore/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/textbefore/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/textbefore/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/textbefore/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/textjoin/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/textjoin/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/textjoin/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/textjoin/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/textsplit/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/textsplit/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/textsplit/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/textsplit/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/trim/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/trim/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/trim/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/trim/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/unichar/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/unichar/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/unichar/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/unichar/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/unicode/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/unicode/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/unicode/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/unicode/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/upper/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/upper/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/upper/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/upper/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/value/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/value/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/value/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/value/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/functions/text/valuetotext/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/valuetotext/__tests__/index.spec.ts
similarity index 100%
rename from packages/engine-formula/src/functions/text/valuetotext/__test__/index.spec.ts
rename to packages/engine-formula/src/functions/text/valuetotext/__tests__/index.spec.ts
diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
index 435d516b97..191f098d68 100644
--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
@@ -14,8 +14,17 @@
* limitations under the License.
*/
-import type { ICellData, Injector, IWorkbookData, Nullable, Univer } from '@univerjs/core';
-import { LocaleType, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';
+import type { IBaseSnapshot, ICellData, Injector, IWorkbookData, Nullable, Univer } from '@univerjs/core';
+import {
+ BaseDataModel,
+ BooleanNumber,
+ CellValueType,
+ IUniverInstanceService,
+ LocaleType,
+ ObjectMatrix,
+ RANGE_TYPE,
+ UniverInstanceType,
+} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { FormulaDataModel, initSheetFormulaData } from '../formula-data.model';
import { createCommandTestBed } from './create-command-test-bed';
@@ -65,6 +74,10 @@ const TEST_WORKBOOK_DATA_EXTRA: IWorkbookData = {
sheet1: {
id: 'sheet1',
name: 'Sheet1',
+ rowCount: 5,
+ rowData: {
+ 2: { hd: BooleanNumber.TRUE },
+ },
cellData: {
0: {
0: { f: '=A1' },
@@ -87,6 +100,118 @@ const TEST_WORKBOOK_DATA_EXTRA: IWorkbookData = {
styles: {},
};
+const TEST_BASE_DATA: Partial<IBaseSnapshot> = {
+ id: 'base-test',
+ name: 'Base',
+ schemaVersion: 1,
+ tableOrder: ['table-main', 'tableOther', 'table-deleted'],
+ createdAt: 0,
+ updatedAt: 0,
+ tables: {
+ 'table-main': {
+ id: 'table-main',
+ name: 'Sales',
+ primaryFieldId: 'name',
+ fieldOrder: ['name', 'amount', 'qty', 'tags', 'link', 'attachment', 'total', 'deleted-formula'],
+ fields: {
+ name: { id: 'name', name: 'Name', type: 'text', config: {} },
+ amount: { id: 'amount', name: 'Amount', type: 'number', config: {} },
+ qty: { id: 'qty', name: 'Qty', type: 'number', config: {} },
+ tags: { id: 'tags', name: 'Tags', type: 'text', config: {} },
+ link: { id: 'link', name: 'Link', type: 'link', config: {} },
+ attachment: { id: 'attachment', name: 'Files', type: 'attachment', config: {} },
+ total: {
+ id: 'total',
+ name: 'Total',
+ type: 'formula',
+ config: {
+ formula: '=SUM({Amount}, [Qty], tableOther[External])',
+ },
+ },
+ 'deleted-formula': {
+ id: 'deleted-formula',
+ name: 'Deleted Formula',
+ type: 'formula',
+ deleted: true,
+ config: { formula: '=1' },
+ },
+ },
+ records: {
+ 'record-1': {
+ id: 'record-1',
+ orderKey: 'a',
+ createdAt: 0,
+ updatedAt: 0,
+ values: {
+ name: 'Order 1',
+ amount: 10,
+ qty: 2,
+ tags: ['paid', 'online'],
+ link: { text: 'Invoice', url: 'https://example.com/invoice' },
+ attachment: ['file-1'],
+ },
+ },
+ 'record-deleted': {
+ id: 'record-deleted',
+ orderKey: 'b',
+ createdAt: 0,
+ updatedAt: 0,
+ deleted: true,
+ values: {
+ amount: 999,
+ },
+ },
+ },
+ recordOrder: ['record-1', 'record-deleted'],
+ views: {},
+ viewOrder: [],
+ },
+ tableOther: {
+ id: 'tableOther',
+ name: 'Sales',
+ primaryFieldId: 'external',
+ fieldOrder: ['external'],
+ fields: {
+ external: { id: 'external', name: 'External', type: 'number', config: {} },
+ },
+ records: {
+ 'record-2': {
+ id: 'record-2',
+ orderKey: 'a',
+ createdAt: 0,
+ updatedAt: 0,
+ values: { external: 8 },
+ },
+ },
+ recordOrder: ['record-2'],
+ views: {},
+ viewOrder: [],
+ },
+ 'table-deleted': {
+ id: 'table-deleted',
+ name: 'Deleted',
+ deleted: true,
+ primaryFieldId: 'name',
+ fieldOrder: ['name'],
+ fields: {
+ name: { id: 'name', name: 'Name', type: 'formula', config: { formula: '=1' } },
+ },
+ records: {
+ 'record-3': {
+ id: 'record-3',
+ orderKey: 'a',
+ createdAt: 0,
+ updatedAt: 0,
+ values: {},
+ },
+ },
+ recordOrder: ['record-3'],
+ views: {},
+ viewOrder: [],
+ },
+ },
+};
+
describe('Test formula data model', () => {
describe('formulaDataModel function', () => {
let univer: Univer;
@@ -581,6 +706,45 @@ describe('Test formula data model', () => {
const sheetFormulaData = formulaDataModel.getSheetFormulaData('test', 'sheet1');
expect(sheetFormulaData?.[0]?.[0]?.f).toBe('=A1');
});
+
+ it('should expose manually hidden sheet rows for subtotal-style formulas', () => {
+ expect(formulaDataModel.getHiddenRowsFiltered()).toEqual({
+ test: {
+ sheet1: {
+ 2: { hd: BooleanNumber.TRUE },
+ },
+ },
+ });
+ });
+
+ it('should build formula and runtime data for base tables with live records and fields only', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);
+ univer.createUnit(UniverInstanceType.UNIVER_BASE, TEST_BASE_DATA);
+
+ const formulaData = formulaDataModel.getFormulaData();
+ expect(formulaData['base-test']?.['table-deleted']).toBeUndefined();
+ expect(formulaData['base-test']?.['table-main']).toEqual({
+ 0: {
+ 6: {
+ f: '=SUM(table-main[[#This Row],[Amount]], table-main[[#This Row],[Qty]], tableOther[[#This Row],[External]])',
+ si: 'total',
+ },
+ },
+ });
+
+ const calculateData = formulaDataModel.getCalculateData();
+ const tableData = calculateData.allUnitData['base-test']?.['table-main'];
+
+ expect(calculateData.unitSheetNameMap['base-test']?.Sales).toBe('tableOther');
+ expect(tableData?.rowCount).toBe(1);
+ expect(tableData?.columnCount).toBe(7);
+ expect(tableData?.cellData.getValue(0, 0)).toEqual({ v: 'Order 1', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 1)).toEqual({ v: 10, t: CellValueType.NUMBER });
+ expect(tableData?.cellData.getValue(0, 3)).toEqual({ v: 'paid, online', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 4)).toEqual({ v: 'Invoice', t: CellValueType.STRING });
+ expect(tableData?.cellData.getValue(0, 5)).toEqual({ v: '', t: CellValueType.STRING });
+ });
});
});
diff --git a/packages/engine-render/src/__tests__/canvas.spec.ts b/packages/engine-render/src/__tests__/canvas.spec.ts
new file mode 100644
index 0000000000..45d6dfa185
--- /dev/null
+++ b/packages/engine-render/src/__tests__/canvas.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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { Canvas, CanvasRenderMode, HitCanvas, SceneCanvas } from '../canvas';
+
+describe('canvas wrapper', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('initializes rendering and printing contexts with sizing and ids', () => {
+ const canvas = new Canvas({
+ id: 'ignored-by-constructor',
+ width: 120,
+ height: 80,
+ pixelRatio: 2,
+ colorService: { getRenderColor: (color: string) => color } as any,
+ });
+
+ canvas.setId('render-canvas');
+ expect(canvas.getCanvasEle().id).toBe('render-canvas');
+ expect(canvas.getCanvasEle().dataset.uComp).toBe('render-canvas');
+ expect(canvas.getCanvasEle().tabIndex).toBe(1);
+ expect(canvas.getPixelRatio()).toBe(2);
+ expect(canvas.getWidth()).toBe(120);
+ expect(canvas.getHeight()).toBe(80);
+ expect(canvas.getCanvasEle().width).toBe(240);
+ expect(canvas.getCanvasEle().style.width).toBe('120px');
+
+ canvas.setPixelRatio(0.5);
+ expect(canvas.getPixelRatio()).toBe(1);
+
+ canvas.clear();
+ canvas.dispose();
+ expect(canvas.getCanvasEle()).toBeNull();
+
+ const printing = new Canvas({ mode: CanvasRenderMode.Printing, width: 20, height: 10 });
+ expect(printing.getContext().__mode).toBe('printing');
+ printing.dispose();
+ });
+
+ it('keeps zero-sized canvases from changing pixel ratio and supports scene/hit subclasses', () => {
+ const canvas = new Canvas();
+ canvas.setPixelRatio(3);
+ expect(canvas.getPixelRatio()).toBeGreaterThan(0);
+
+ const sceneCanvas = new SceneCanvas({ width: 30, height: 40, pixelRatio: 2 });
+ expect(sceneCanvas.getWidth()).toBe(30);
+ expect(sceneCanvas.getHeight()).toBe(40);
+
+ const hitCanvas = new HitCanvas({ width: 10, height: 20, pixelRatio: 2 });
+ expect(hitCanvas.hitCanvas).toBe(true);
+ expect(hitCanvas.getWidth()).toBe(10);
+
+ canvas.dispose();
+ sceneCanvas.dispose();
+ hitCanvas.dispose();
+ });
+
+ it('falls back when exporting data URLs fails', () => {
+ const canvas = new Canvas({ width: 10, height: 10 });
+ const nativeCanvas = canvas.getCanvasEle();
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const toDataURL = vi.fn()
+ .mockImplementationOnce(() => {
+ throw new Error('typed export failed');
+ })
+ .mockReturnValueOnce('data:image/png;base64,fallback');
+ nativeCanvas.toDataURL = toDataURL;
+
+ expect(canvas.toDataURL('image/jpeg', 0.8)).toBe('data:image/png;base64,fallback');
+
+ toDataURL
+ .mockImplementationOnce(() => {
+ throw new Error('typed export failed');
+ })
+ .mockImplementationOnce(() => {
+ throw new Error('fallback failed');
+ });
+ expect(canvas.toDataURL('image/jpeg', 0.8)).toBe('');
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Unable to get data URL. fallback failed'));
+
+ canvas.dispose();
+ });
+});
diff --git a/packages/engine-render/src/__tests__/context-proxy.spec.ts b/packages/engine-render/src/__tests__/context-proxy.spec.ts
new file mode 100644
index 0000000000..5bbbc64ac7
--- /dev/null
+++ b/packages/engine-render/src/__tests__/context-proxy.spec.ts
@@ -0,0 +1,142 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { UniverRenderingContext2D } from '../context';
+
+function createNativeContext() {
+ const canvas = document.createElement('canvas');
+ const ctx = {
+ canvas,
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ fillStyle: '#000000',
+ strokeStyle: '#000000',
+ filter: 'none',
+ imageSmoothingEnabled: true,
+ imageSmoothingQuality: 'low',
+ lineCap: 'butt',
+ lineDashOffset: 0,
+ lineJoin: 'miter',
+ lineWidth: 1,
+ miterLimit: 10,
+ shadowBlur: 0,
+ shadowColor: '#000000',
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ direction: 'inherit',
+ font: '10px serif',
+ fontKerning: 'auto',
+ fontStretch: 'condensed',
+ fontVariantCaps: 'small-caps',
+ letterSpacing: '1px',
+ textRendering: 'optimizeLegibility',
+ wordSpacing: '2px',
+ textAlign: 'start',
+ textBaseline: 'alphabetic',
+ getTransform: vi.fn(() => ({ a: 2, b: 0, c: 0, d: 4, e: 0, f: 0 })),
+ resetTransform: vi.fn(),
+ reset: vi.fn(),
+ createConicGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
+ createLinearGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
+ createPattern: vi.fn(() => ({})),
+ createRadialGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
+ fillText: vi.fn(),
+ measureText: vi.fn(() => ({ width: 42 })),
+ stroke: vi.fn(),
+ setLineDash: undefined,
+ getLineDash: vi.fn(() => []),
+ setTransform: vi.fn(),
+ } as any;
+
+ return ctx as CanvasRenderingContext2D;
+}
+
+describe('context proxy branches', () => {
+ it('reads proxied state and helper factories from the native context', () => {
+ const nativeCtx = createNativeContext() as any;
+ const renderCtx = new UniverRenderingContext2D(nativeCtx);
+
+ expect(renderCtx.globalAlpha).toBe(1);
+ expect(renderCtx.globalCompositeOperation).toBe('source-over');
+ expect(renderCtx.fillStyle).toBe('#000000');
+ expect(renderCtx.strokeStyle).toBe('#000000');
+ expect(renderCtx.filter).toBe('none');
+ expect(renderCtx.imageSmoothingEnabled).toBe(true);
+ expect(renderCtx.imageSmoothingQuality).toBe('low');
+ expect(renderCtx.lineCap).toBe('butt');
+ expect(renderCtx.lineDashOffset).toBe(0);
+ expect(renderCtx.lineJoin).toBe('miter');
+ expect(renderCtx.lineWidth).toBe(1);
+ expect(renderCtx.miterLimit).toBe(10);
+ expect(renderCtx.shadowBlur).toBe(0);
+ expect(renderCtx.shadowColor).toBe('#000000');
+ expect(renderCtx.shadowOffsetX).toBe(0);
+ expect(renderCtx.shadowOffsetY).toBe(0);
+ expect(renderCtx.direction).toBe('inherit');
+ expect(renderCtx.font).toBe('10px serif');
+ nativeCtx.font = '12px serif';
+ expect(renderCtx.font).toBe('10px serif');
+ renderCtx.font = '14px serif';
+ expect(renderCtx.font).toBe('14px serif');
+ expect(renderCtx.fontKerning).toBe('auto');
+ expect(renderCtx.fontStretch).toBe('condensed');
+ expect(renderCtx.fontVariantCaps).toBe('small-caps');
+ expect(renderCtx.letterSpacing).toBe('1px');
+ expect(renderCtx.textRendering).toBe('optimizeLegibility');
+ expect(renderCtx.wordSpacing).toBe('2px');
+ expect(renderCtx.textAlign).toBe('start');
+ expect(renderCtx.textBaseline).toBe('alphabetic');
+
+ renderCtx.fontStretch = 'expanded' as any;
+ renderCtx.fontVariantCaps = 'all-small-caps' as any;
+ renderCtx.letterSpacing = '3px';
+ renderCtx.textRendering = 'geometricPrecision' as any;
+ renderCtx.wordSpacing = '4px';
+ expect(nativeCtx.fontStretch).toBe('expanded');
+ expect(nativeCtx.fontVariantCaps).toBe('all-small-caps');
+ expect(nativeCtx.letterSpacing).toBe('3px');
+ expect(nativeCtx.textRendering).toBe('geometricPrecision');
+ expect(nativeCtx.wordSpacing).toBe('4px');
+
+ expect(renderCtx.getScale()).toEqual({ scaleX: 2, scaleY: 4 });
+ expect(renderCtx.createConicGradient(0, 1, 2)).toBeTruthy();
+ expect(renderCtx.createLinearGradient(0, 0, 1, 1)).toBeTruthy();
+ expect(renderCtx.createPattern(document.createElement('canvas'), 'repeat')).toBeTruthy();
+ expect(renderCtx.createRadialGradient(0, 0, 1, 2, 2, 3)).toBeTruthy();
+ expect(renderCtx.measureText('abc')).toEqual({ width: 42 });
+
+ renderCtx.resetTransform();
+ renderCtx.reset();
+ renderCtx.fillText('with width', 1, 2, 3);
+ renderCtx.fillTextPrecision('without width', 1, 2);
+ renderCtx.stroke(new Path2D());
+ expect(nativeCtx.resetTransform).toHaveBeenCalled();
+ expect(nativeCtx.reset).toHaveBeenCalled();
+ expect(nativeCtx.fillText).toHaveBeenCalledWith('with width', 1, 2, 3);
+ expect(nativeCtx.stroke).toHaveBeenCalledWith(expect.any(Path2D));
+ });
+
+ it('uses webkit line dash fallback when standard dash APIs are missing', () => {
+ const nativeCtx = createNativeContext() as any;
+ nativeCtx.webkitLineDash = [];
+ const renderCtx = new UniverRenderingContext2D(nativeCtx as CanvasRenderingContext2D);
+
+ renderCtx.setLineDash([3, 2]);
+
+ expect(nativeCtx.webkitLineDash).toEqual([3, 2]);
+ });
+});
diff --git a/packages/engine-render/src/__tests__/layer.spec.ts b/packages/engine-render/src/__tests__/layer.spec.ts
new file mode 100644
index 0000000000..247cba8c95
--- /dev/null
+++ b/packages/engine-render/src/__tests__/layer.spec.ts
@@ -0,0 +1,175 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { IViewportInfo } from '../basics/vector2';
+import { describe, expect, it, vi } from 'vitest';
+import { BaseObject } from '../base-object';
+import { RENDER_CLASS_TYPE } from '../basics/const';
+import { Layer } from '../layer';
+
+class TestObject extends BaseObject {
+ constructor(id: string, zIndex = 1) {
+ super(id);
+ this.zIndex = zIndex;
+ }
+
+ override render(_ctx: any, _bounds?: IViewportInfo) {
+ return this;
+ }
+}
+
+class TestGroup extends TestObject {
+ constructor(id: string, private readonly _children: BaseObject[]) {
+ super(id, 100);
+ }
+
+ override get classType() {
+ return RENDER_CLASS_TYPE.GROUP;
+ }
+
+ override getObjects() {
+ return this._children;
+ }
+}
+
+function createScene() {
+ let transformCallback: (() => void) | undefined;
+ const sceneViewer = {
+ classType: RENDER_CLASS_TYPE.SCENE_VIEWER,
+ makeDirty: vi.fn(),
+ };
+ const viewport = {
+ shouldIntoRender: vi.fn(() => true),
+ render: vi.fn(),
+ };
+ const engine = {
+ width: 160,
+ height: 90,
+ canvasColorService: undefined,
+ onTransformChange$: {
+ subscribeEvent: vi.fn((callback: () => void) => {
+ transformCallback = callback;
+ return { dispose: vi.fn() };
+ }),
+ },
+ };
+ const scene = {
+ getParent: vi.fn(() => sceneViewer),
+ getEngine: vi.fn(() => engine),
+ getObject: vi.fn(() => null),
+ setObjectBehavior: vi.fn(),
+ getViewports: vi.fn(() => [viewport]),
+ __viewport: viewport,
+ __sceneViewer: sceneViewer,
+ __resizeCache: () => transformCallback?.(),
+ };
+
+ return scene as any;
+}
+
+function createCtx() {
+ const transform = document.createElement('canvas').getContext('2d')!.getTransform();
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ setTransform: vi.fn(),
+ getTransform: vi.fn(() => transform),
+ drawImage: vi.fn(),
+ } as any;
+}
+
+describe('layer', () => {
+ it('adds, orders, filters and removes regular objects', () => {
+ const scene = createScene();
+ const visible = new TestObject('visible', 2);
+ const hidden = new TestObject('hidden', 1);
+ const eventless = new TestObject('eventless', 3);
+ hidden.hide();
+ eventless.evented = false;
+
+ const layer = new Layer(scene, [visible, hidden, eventless], 4);
+
+ expect(layer.scene).toBe(scene);
+ expect(layer.zIndex).toBe(4);
+ expect(layer.getObjectsByOrder().map((object) => object.oKey)).toEqual(['visible', 'eventless']);
+ expect(layer.getObjectsByOrderForPick().map((object) => object.oKey)).toEqual(['visible']);
+ expect(scene.setObjectBehavior).toHaveBeenCalledTimes(3);
+ expect(scene.__sceneViewer.makeDirty).toHaveBeenCalledWith(true);
+
+ layer.removeObject(visible);
+ expect(layer.getObjects().map((object) => object.oKey)).not.toContain('visible');
+ layer.removeObject('hidden');
+ expect(layer.getObjects().map((object) => object.oKey)).not.toContain('hidden');
+ layer.removeObjects(['eventless']);
+ expect(layer.getObjects()).toEqual([]);
+
+ layer.dispose();
+ });
+
+ it('expands groups, renders through viewports and updates dirty state', async () => {
+ const scene = createScene();
+ const child = new TestObject('child', 1);
+ const duplicateChild = new TestObject('duplicate-child', 2);
+ scene.getObject = vi.fn((key: string) => key === 'duplicate-child' ? duplicateChild : null);
+ const group = new TestGroup('group', [child, duplicateChild]);
+ const layer = new Layer(scene, [], 1);
+
+ layer.addObject(group);
+ expect(layer.getObjects().map((object) => object.oKey)).toEqual(['child', 'group']);
+ expect(child.layer).toBe(layer);
+ expect(group.layer).toBe(layer);
+
+ layer.makeDirtyWithDebounce(true);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(layer.isDirty()).toBe(true);
+
+ const ctx = createCtx();
+ layer.render(ctx, true);
+ expect(ctx.save).toHaveBeenCalled();
+ expect(scene.__viewport.render).toHaveBeenCalledWith(ctx, [child, group], true);
+ expect(layer.isDirty()).toBe(false);
+
+ child.onTransformChange$.emitEvent({} as any);
+ expect(layer.isDirty()).toBe(true);
+
+ layer.clear();
+ expect(layer.getObjects()).toEqual([]);
+ layer.dispose();
+ });
+
+ it('uses cache canvas rendering, resizing and disposal paths', () => {
+ const scene = createScene();
+ const object = new TestObject('cached', 1);
+ const layer = new Layer(scene, [object], 1, true);
+ const ctx = createCtx();
+
+ expect(layer.isAllowCache()).toBe(true);
+ layer.render(ctx);
+ expect(ctx.drawImage).not.toHaveBeenCalled();
+
+ scene.__resizeCache();
+ layer.render(ctx);
+ expect(ctx.drawImage).toHaveBeenCalledWith(expect.any(HTMLCanvasElement), 0, 0, 160, 90);
+
+ layer.disableCache();
+ expect(layer.isAllowCache()).toBe(false);
+ layer.enableCache();
+ expect(layer.isAllowCache()).toBe(true);
+
+ layer.dispose();
+ expect(layer.getObjects()).toEqual([]);
+ });
+});
diff --git a/packages/engine-render/src/__tests__/scroll-timer.spec.ts b/packages/engine-render/src/__tests__/scroll-timer.spec.ts
new file mode 100644
index 0000000000..86bac2f645
--- /dev/null
+++ b/packages/engine-render/src/__tests__/scroll-timer.spec.ts
@@ -0,0 +1,101 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ScrollTimer, ScrollTimerType } from '../scroll-timer';
+
+function createViewport() {
+ return {
+ top: 10,
+ left: 20,
+ width: 100,
+ height: 80,
+ scrollByViewportDeltaVal: vi.fn(() => true),
+ transScroll2ViewportScrollValue: vi.fn((x: number, y: number) => ({ x: x * 2, y: y * 3 })),
+ };
+}
+
+describe('ScrollTimer', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('auto-scrolls the active viewport when the pointer moves near the right and bottom edges', () => {
+ const viewport = createViewport();
+ const scene = {
+ findViewportByPosToScene: vi.fn(() => viewport),
+ };
+ const timer = ScrollTimer.create(scene as never, ScrollTimerType.ALL, { t: 5, b: 10, l: 5, r: 15 });
+ const scrollFunction = vi.fn();
+
+ timer.scrolling(130, 95, scrollFunction);
+ timer.startScroll(130, 95);
+ timer.stopScroll();
+
+ expect(scene.findViewportByPosToScene).toHaveBeenCalled();
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: 25,
+ viewportScrollY: 15,
+ });
+ expect(viewport.transScroll2ViewportScrollValue).toHaveBeenCalledWith(25, 15);
+ expect(scrollFunction).toHaveBeenCalledWith(50, 45);
+ });
+
+ it('respects axis restrictions and explicit target viewport', () => {
+ const viewport = createViewport();
+ const scene = {
+ findViewportByPosToScene: vi.fn(),
+ };
+ const timer = ScrollTimer.create(scene as never, ScrollTimerType.Y, { t: 5, b: 10, l: 5, r: 15 });
+ const scrollFunction = vi.fn();
+
+ timer.scrolling(130, 95, scrollFunction);
+ timer.startScroll(130, 95, viewport);
+ timer.stopScroll();
+
+ expect(scene.findViewportByPosToScene).not.toHaveBeenCalled();
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: 0,
+ viewportScrollY: 15,
+ });
+ expect(scrollFunction).toHaveBeenCalledWith(0, 45);
+ expect(timer.getActiveViewport()).toBe(viewport);
+ expect(timer.offsetX).toBe(130);
+ expect(timer.offsetY).toBe(95);
+ });
+
+ it('does not invoke the scroll callback with movement when pointer stays inside the safe area', () => {
+ const viewport = createViewport();
+ const scene = {
+ findViewportByPosToScene: vi.fn(() => viewport),
+ };
+ const timer = new ScrollTimer(scene as never, ScrollTimerType.ALL, { t: 5, b: 10, l: 5, r: 15 });
+ const scrollFunction = vi.fn();
+
+ timer.scrolling(60, 50, scrollFunction);
+ timer.startScroll(60, 50);
+ timer.stopScroll();
+ timer.dispose();
+
+ expect(viewport.scrollByViewportDeltaVal).not.toHaveBeenCalled();
+ expect(scrollFunction).toHaveBeenCalledWith(0, 0);
+ expect(timer.getScene()).toBe(scene);
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/path2.spec.ts b/packages/engine-render/src/basics/__tests__/path2.spec.ts
new file mode 100644
index 0000000000..7e24ab9c94
--- /dev/null
+++ b/packages/engine-render/src/basics/__tests__/path2.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 { describe, expect, it } from 'vitest';
+import { Path2 } from '../path2';
+import { Vector2 } from '../vector2';
+
+describe('Path2', () => {
+ it('returns undefined when either path has no drawable segment', () => {
+ expect(new Path2([]).intersection([new Vector2(0, 0), new Vector2(1, 1)])).toBeUndefined();
+ expect(new Path2([new Vector2(0, 0), new Vector2(1, 1)]).intersection([])).toBeUndefined();
+ });
+
+ it('finds intersections between the source path and the provided contrast path', () => {
+ const path = new Path2([
+ new Vector2(0, 0),
+ new Vector2(10, 10),
+ new Vector2(20, 0),
+ ]);
+
+ const intersections = path.intersection([
+ new Vector2(0, 10),
+ new Vector2(10, 0),
+ new Vector2(20, 10),
+ ]);
+
+ expect(intersections).toHaveLength(2);
+ expect(intersections?.[0].x).toBeCloseTo(5);
+ expect(intersections?.[0].y).toBeCloseTo(5);
+ expect(intersections?.[1].x).toBeCloseTo(15);
+ expect(intersections?.[1].y).toBeCloseTo(5);
+ });
+
+ it('does not report parallel or touching-only segments as intersections', () => {
+ const path = new Path2([new Vector2(0, 0), new Vector2(10, 0)]);
+
+ expect(path.intersection([new Vector2(0, 2), new Vector2(10, 2)])).toEqual([]);
+ expect(path.intersection([new Vector2(10, 0), new Vector2(10, 10)])).toEqual([]);
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/performance-monitor.spec.ts b/packages/engine-render/src/basics/__tests__/performance-monitor.spec.ts
new file mode 100644
index 0000000000..131b713c08
--- /dev/null
+++ b/packages/engine-render/src/basics/__tests__/performance-monitor.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 { PerformanceMonitor, RollingAverage } from '../performance-monitor';
+
+describe('performance monitor', () => {
+ it('samples frame timing, fps and reset/disable lifecycle', () => {
+ const monitor = new PerformanceMonitor(3);
+
+ monitor.endFrame(0);
+ monitor.endFrame(16);
+ monitor.endFrame(33);
+ monitor.endFrame(50);
+ monitor.sampleFrame(1050);
+
+ expect(monitor.instantaneousFrameTime).toBeGreaterThan(0);
+ expect(monitor.instantaneousFPS).toBeGreaterThan(0);
+ expect(monitor.averageFrameTime).toBeGreaterThan(0);
+ expect(monitor.averageFrameTimeVariance).not.toBeNaN();
+ expect(monitor.averageFPS).toBeGreaterThan(0);
+ expect(monitor.isSaturated).toBe(true);
+ expect(monitor.isEnabled).toBe(true);
+
+ monitor.disable();
+ monitor.sampleFrame(1100);
+ expect(monitor.isEnabled).toBe(false);
+
+ monitor.enable();
+ monitor.endFrame(1200);
+ monitor.reset();
+ expect(monitor.instantaneousFrameTime).toBe(0);
+ expect(monitor.isSaturated).toBe(false);
+
+ monitor.dispose();
+ });
+
+ it('uses performance.now when available and Date.now as fallback', () => {
+ const monitor = new PerformanceMonitor();
+ const performanceNow = vi.spyOn(performance, 'now').mockReturnValue(123);
+
+ expect(monitor.now()).toBe(123);
+ performanceNow.mockRestore();
+
+ const originalPerformance = globalThis.performance;
+ const dateNow = vi.spyOn(Date, 'now').mockReturnValue(456);
+ try {
+ Object.defineProperty(globalThis, 'performance', {
+ configurable: true,
+ value: undefined,
+ });
+ expect(monitor.now()).toBe(456);
+ } finally {
+ Object.defineProperty(globalThis, 'performance', {
+ configurable: true,
+ value: originalPerformance,
+ });
+ dateNow.mockRestore();
+ }
+ });
+
+ it('computes rolling history, saturation and wraparound variance', () => {
+ const average = new RollingAverage(3);
+
+ expect(average.history(0)).toBe(0);
+ average.addFrameTime(10);
+ average.calcAverageFrameTime();
+ average.addFrameTime(20);
+ average.calcAverageFrameTime();
+ average.addFrameTime(30);
+ average.calcAverageFrameTime();
+ average.addFrameTime(40);
+ average.calcAverageFrameTime();
+
+ expect(average.isSaturated()).toBe(true);
+ expect(average.history(0)).toBe(40);
+ expect(average.history(1)).toBe(30);
+ expect(average.history(3)).toBe(0);
+ expect(average.averageFrameTime).not.toBeNaN();
+ expect(average.variance).not.toBeNaN();
+
+ average.reset();
+ expect(average.history(0)).toBe(0);
+ expect(average.averageFrameTime).toBeCloseTo(16.67, 2);
+ expect(average.variance).toBe(0);
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/quick-event.spec.ts b/packages/engine-render/src/basics/__tests__/quick-event.spec.ts
new file mode 100644
index 0000000000..a9d4f438e6
--- /dev/null
+++ b/packages/engine-render/src/basics/__tests__/quick-event.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 { describe, expect, it, vi } from 'vitest';
+import { attachObjectHover } from '../quick-event';
+
+function createEventSubject() {
+ let listener: ((evt: unknown) => void) | undefined;
+ return {
+ subscribeEvent: vi.fn((callback: (evt: unknown) => void) => {
+ listener = callback;
+ }),
+ emit: (evt: unknown) => listener?.(evt),
+ };
+}
+
+describe('quick event helpers', () => {
+ it('binds pointer enter and leave events to hover callbacks with the target object', () => {
+ const enter = createEventSubject();
+ const leave = createEventSubject();
+ const object = {
+ onPointerEnter$: enter,
+ onPointerLeave$: leave,
+ };
+ const hoverIn = vi.fn();
+ const hoverOut = vi.fn();
+
+ attachObjectHover(object as never, hoverIn, hoverOut);
+
+ const enterEvent = { offsetX: 10, offsetY: 20 };
+ const leaveEvent = { offsetX: 30, offsetY: 40 };
+ enter.emit(enterEvent);
+ leave.emit(leaveEvent);
+
+ expect(enter.subscribeEvent).toHaveBeenCalledTimes(1);
+ expect(leave.subscribeEvent).toHaveBeenCalledTimes(1);
+ expect(hoverIn).toHaveBeenCalledWith(object, enterEvent);
+ expect(hoverOut).toHaveBeenCalledWith(object, leaveEvent);
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/viewport-subtract.spec.ts b/packages/engine-render/src/basics/__tests__/viewport-subtract.spec.ts
new file mode 100644
index 0000000000..4fbfc74acf
--- /dev/null
+++ b/packages/engine-render/src/basics/__tests__/viewport-subtract.spec.ts
@@ -0,0 +1,48 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { subtractViewportRange } from '../viewport-subtract';
+
+describe('subtractViewportRange', () => {
+ it('returns the original viewport when the ranges do not overlap', () => {
+ const range = { startRow: 0, endRow: 10, startColumn: 0, endColumn: 8 };
+
+ expect(subtractViewportRange(range, { startRow: 10, endRow: 12, startColumn: 0, endColumn: 8 })).toEqual([range]);
+ expect(subtractViewportRange(range, { startRow: 0, endRow: 10, startColumn: 8, endColumn: 12 })).toEqual([range]);
+ });
+
+ it('splits the visible viewport around a frozen pane overlap', () => {
+ const ranges = subtractViewportRange(
+ { startRow: 0, endRow: 10, startColumn: 0, endColumn: 10 },
+ { startRow: 2, endRow: 8, startColumn: 3, endColumn: 7 }
+ );
+
+ expect(ranges).toEqual([
+ { startRow: 0, startColumn: 0, endRow: 2, endColumn: 10 },
+ { startRow: 8, startColumn: 0, endRow: 10, endColumn: 10 },
+ { startRow: 2, startColumn: 0, endRow: 8, endColumn: 3 },
+ { startRow: 2, startColumn: 7, endRow: 8, endColumn: 10 },
+ ]);
+ });
+
+ it('returns an empty list when the second range fully covers the first range', () => {
+ expect(subtractViewportRange(
+ { startRow: 2, endRow: 8, startColumn: 3, endColumn: 7 },
+ { startRow: 0, endRow: 10, startColumn: 0, endColumn: 10 }
+ )).toEqual([]);
+ });
+});
diff --git a/packages/engine-render/src/basics/path2.ts b/packages/engine-render/src/basics/path2.ts
index 401395da7a..1eed8037e8 100644
--- a/packages/engine-render/src/basics/path2.ts
+++ b/packages/engine-render/src/basics/path2.ts
@@ -41,8 +41,8 @@ export class Path2 {
const from = this._lines[o - 1];
const to = this._lines[o];
for (let n = 1; n < lines.length; n++) {
- const contrastFrom = this._lines[o - 1];
- const contrastTo = this._lines[o];
+ const contrastFrom = lines[n - 1];
+ const contrastTo = lines[n];
const point = this._intersection(
{
diff --git a/packages/engine-render/src/components/__tests__/extension.spec.ts b/packages/engine-render/src/components/__tests__/extension.spec.ts
new file mode 100644
index 0000000000..ac756c9d47
--- /dev/null
+++ b/packages/engine-render/src/components/__tests__/extension.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 { IScale } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { ComponentExtension } from '../extension';
+
+class TestExtension extends ComponentExtension<unknown, string, unknown> {
+ constructor() {
+ super();
+ this.uKey = 'test-extension';
+ this.type = 'test';
+ }
+
+ getParentScale(parentScale: IScale) {
+ return this._getScale(parentScale);
+ }
+}
+
+describe('ComponentExtension', () => {
+ it('uses the larger parent scale for extension rendering math', () => {
+ const extension = new TestExtension();
+
+ expect(extension.getParentScale({ scaleX: 1.25, scaleY: 2 })).toBe(2);
+ expect(extension.getParentScale({})).toBe(1);
+ });
+
+ it('clears transient render offsets and parent links on dispose', () => {
+ const extension = new TestExtension();
+ extension.parent = {} as never;
+ extension.extensionOffset = {
+ renderConfig: {},
+ };
+
+ extension.dispose();
+
+ expect(extension.parent).toBeNull();
+ expect(extension.extensionOffset).toEqual({});
+ });
+});
diff --git a/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts b/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts
new file mode 100644
index 0000000000..bb31ea9ed7
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/doc-background.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 type { IDocumentSkeletonPage } from '../../../basics/i-document-skeleton-cached';
+import { DocumentFlavor } from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { PageLayoutType } from '../../../basics/i-document-skeleton-cached';
+import { Path, Rect } from '../../../shape';
+import { DocBackground } from '../doc-background';
+
+function createCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ translate: vi.fn(),
+ } as any;
+}
+
+function createPage(overrides: Partial<IDocumentSkeletonPage> = {}) {
+ return {
+ width: 200,
+ height: 120,
+ pageWidth: 200,
+ pageHeight: 120,
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 16,
+ marginBottom: 16,
+ originMarginTop: 16,
+ originMarginBottom: 16,
+ sections: [],
+ ...overrides,
+ } as IDocumentSkeletonPage;
+}
+
+function createSkeleton(pages: IDocumentSkeletonPage[], documentFlavor = DocumentFlavor.TRADITIONAL) {
+ return {
+ getSkeletonData: () => ({ pages }),
+ getViewModel: () => ({
+ getDataModel: () => ({
+ getSnapshot: () => ({
+ documentStyle: {
+ documentFlavor,
+ },
+ }),
+ }),
+ }),
+ } as any;
+}
+
+describe('DocBackground', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('positions multiple traditional pages horizontally and draws their margin identifiers', () => {
+ const background = DocBackground.create(
+ 'horizontal-background',
+ createSkeleton([createPage(), createPage({ pageWidth: 180, pageHeight: 100 })]),
+ {
+ pageLayoutType: PageLayoutType.HORIZONTAL,
+ pageMarginLeft: 24,
+ pageMarginTop: 18,
+ backgroundFillColor: '#eeeeee',
+ pageFillColor: '#ffffff',
+ pageStrokeColor: '#999999',
+ marginStrokeColor: '#3366ff',
+ }
+ );
+ background.resize(500, 240);
+ const ctx = createCtx();
+ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});
+ const pathDraw = vi.spyOn(Path, 'drawWith').mockImplementation(() => {});
+
+ background.draw(ctx);
+
+ expect(rectDraw).toHaveBeenCalledTimes(3);
+ expect(rectDraw.mock.calls[0][1]).toMatchObject({ width: 500, height: 240, fill: '#eeeeee' });
+ expect(rectDraw.mock.calls[1][1]).toMatchObject({ width: 200, height: 120, fill: '#ffffff', stroke: '#999999' });
+ expect(rectDraw.mock.calls[2][1]).toMatchObject({ width: 180, height: 100, fill: '#ffffff', stroke: '#999999' });
+ expect(ctx.translate).toHaveBeenNthCalledWith(1, 0, 0);
+ expect(ctx.translate).toHaveBeenNthCalledWith(2, -0.5, -0.5);
+ expect(ctx.translate).toHaveBeenNthCalledWith(3, 223.5, -0.5);
+ expect(pathDraw).toHaveBeenCalledTimes(2);
+ const firstMarginPath = pathDraw.mock.calls[0]?.[1] as any;
+ expect(firstMarginPath).toMatchObject({ stroke: '#3366ff', strokeWidth: 1.5 });
+ expect(firstMarginPath.dataArray[0].points).toEqual([5, 16]);
+
+ background.dispose();
+ });
+
+ it('updates fill colors for the next draw and skips unchanged empty viewport paints', () => {
+ const background = new DocBackground(
+ 'modern-background',
+ createSkeleton([createPage()], DocumentFlavor.MODERN),
+ {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 24,
+ pageMarginTop: 18,
+ }
+ );
+ background.resize(320, 180);
+ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});
+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});
+
+ background.setFillColors('#111111', '#222222', '#333333', '#444444');
+ background.draw(createCtx());
+ expect(rectDraw).toHaveBeenCalledTimes(1);
+ expect(rectDraw.mock.calls[0][1]).toMatchObject({ width: 320, height: 180, fill: '#111111' });
+
+ rectDraw.mockClear();
+ background.setFillColors('#111111', '#222222', '#333333', '#444444');
+ background.draw(createCtx(), {
+ viewBound: { left: 10, top: 20, right: 10, bottom: 120 },
+ } as any);
+ expect(rectDraw).not.toHaveBeenCalled();
+
+ background.dispose();
+ });
+});
diff --git a/packages/engine-render/src/components/docs/__tests__/doc-component.spec.ts b/packages/engine-render/src/components/docs/__tests__/doc-component.spec.ts
new file mode 100644
index 0000000000..a243bb6aed
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/doc-component.spec.ts
@@ -0,0 +1,104 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { IViewportInfo } from '../../../basics/vector2';
+import type { UniverRenderingContext } from '../../../context';
+import { describe, expect, it, vi } from 'vitest';
+import { RENDER_CLASS_TYPE } from '../../../basics/const';
+import { PageLayoutType } from '../../../basics/i-document-skeleton-cached';
+import { DocComponent } from '../doc-component';
+
+class TestDocComponent extends DocComponent {
+ readonly drawCalls: Array<{ ctx: UniverRenderingContext; bounds?: Partial<IViewportInfo> }> = [];
+
+ protected override _draw(ctx: UniverRenderingContext, bounds?: Partial<IViewportInfo>): void {
+ this.drawCalls.push({ ctx, bounds });
+ }
+}
+
+function createCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ transform: vi.fn(),
+ } as any;
+}
+
+function createPage() {
+ return {
+ pageWidth: 100,
+ pageHeight: 80,
+ marginLeft: 10,
+ marginRight: 10,
+ marginTop: 8,
+ marginBottom: 8,
+ } as any;
+}
+
+describe('DocComponent', () => {
+ it('uses default document layout config when no config is provided', () => {
+ const component = new TestDocComponent('doc-component');
+
+ expect(component.pageMarginLeft).toBe(17);
+ expect(component.pageMarginTop).toBe(14);
+ expect(component.pageLayoutType).toBe(PageLayoutType.VERTICAL);
+ expect(component.getSkeleton()).toBeUndefined();
+ });
+
+ it('renders only when a skeleton is attached and the component is visible', () => {
+ const component = new TestDocComponent('doc-component');
+ const ctx = createCtx();
+
+ component.render(ctx);
+ expect(ctx.save).not.toHaveBeenCalled();
+
+ component.setSkeleton({} as any);
+ component.render(ctx, { viewBound: { left: 0, top: 0, right: 100, bottom: 100 } } as IViewportInfo);
+ expect(ctx.save).toHaveBeenCalledTimes(1);
+ expect(ctx.transform).toHaveBeenCalledTimes(1);
+ expect(ctx.restore).toHaveBeenCalledTimes(1);
+ expect(component.drawCalls).toHaveLength(1);
+
+ component.hide();
+ component.render(ctx);
+ expect(component.drawCalls).toHaveLength(1);
+ });
+
+ it('uses scene ancestor scale and skips pages outside the viewport', () => {
+ const component = new TestDocComponent('doc-component', {} as any, {
+ pageMarginLeft: 24,
+ pageMarginTop: 18,
+ pageLayoutType: PageLayoutType.HORIZONTAL,
+ });
+ component.parent = {
+ classType: RENDER_CLASS_TYPE.SCENE,
+ scaleX: 2,
+ scaleY: 3,
+ ancestorScaleX: 1.25,
+ ancestorScaleY: 1.5,
+ } as any;
+ const bounds = { viewBound: { left: 200, top: 200, right: 300, bottom: 300 } } as IViewportInfo;
+
+ expect(component.pageMarginLeft).toBe(24);
+ expect(component.pageMarginTop).toBe(18);
+ expect(component.pageLayoutType).toBe(PageLayoutType.HORIZONTAL);
+ expect(component.getParentScale()).toEqual({ scaleX: 1.25, scaleY: 1.5 });
+ expect(component.isSkipByDiffBounds(createPage(), 0, 0, bounds)).toBe(true);
+ expect(component.isSkipByDiffBounds(createPage(), 220, 220, bounds)).toBe(false);
+ expect(component.isSkipByDiffBounds({ ...createPage(), pageWidth: Number.POSITIVE_INFINITY }, 220, 400, bounds)).toBe(false);
+ expect(component.isSkipByDiffBounds({ ...createPage(), pageHeight: Number.POSITIVE_INFINITY }, 400, 220, bounds)).toBe(false);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/background.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/background.spec.ts
new file mode 100644
index 0000000000..d9a2f1a27f
--- /dev/null
+++ b/packages/engine-render/src/components/docs/extensions/__tests__/background.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 { describe, expect, it, vi } from 'vitest';
+import { Vector2 } from '../../../../basics/vector2';
+import { Background } from '../background';
+
+function createCtx() {
+ return {
+ fillRect: vi.fn(),
+ fillStyle: '',
+ } as any;
+}
+
+function createGlyph(overrides: Record<string, unknown> = {}) {
+ return {
+ content: 'A',
+ width: 24,
+ ts: {
+ bg: { rgb: '#ff0000' },
+ },
+ parent: {
+ parent: {
+ contentHeight: 12,
+ },
+ },
+ ...overrides,
+ } as any;
+}
+
+describe('docs background extension', () => {
+ it('draws span background using the span start point and line height', () => {
+ const extension = new Background();
+ extension.extensionOffset = {
+ spanStartPoint: Vector2.create(10, 20),
+ } as any;
+ const ctx = createCtx();
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph());
+
+ expect(ctx.fillStyle).toBe('#ff0000');
+ expect(ctx.fillRect).toHaveBeenCalledWith(9.5, 21, 25, 14);
+ });
+
+ it('skips spans without layout line, background color or visible content', () => {
+ const extension = new Background();
+ const ctx = createCtx();
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph({ parent: null }));
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph({ ts: {} }));
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph({ content: '\r' }));
+
+ expect(ctx.fillRect).not.toHaveBeenCalled();
+ });
+
+ it('clears cached color state', () => {
+ const extension = new Background() as any;
+ extension._preBackgroundColor = '#fff';
+
+ extension.clearCache();
+
+ expect(extension._preBackgroundColor).toBe('');
+ });
+});
diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/border.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/border.spec.ts
new file mode 100644
index 0000000000..27aefbd62c
--- /dev/null
+++ b/packages/engine-render/src/components/docs/extensions/__tests__/border.spec.ts
@@ -0,0 +1,113 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BorderStyleTypes } from '@univerjs/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { BORDER_TYPE } from '../../../../basics/const';
+import { Vector2 } from '../../../../basics/vector2';
+import { Border } from '../border';
+
+const drawLineByBorderTypeMock = vi.fn((..._args: any[]) => undefined);
+const getLineWidthMock = vi.fn((..._args: any[]) => 2);
+const setLineTypeMock = vi.fn((..._args: any[]) => undefined);
+
+vi.mock('../../../../basics/draw', () => ({
+ drawLineByBorderType: (...args: any[]) => drawLineByBorderTypeMock(...args),
+ getLineWidth: (...args: any[]) => getLineWidthMock(...args),
+ setLineType: (...args: any[]) => setLineTypeMock(...args),
+}));
+
+function createCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ translateWithPrecisionRatio: vi.fn(),
+ setLineWidthByPrecision: vi.fn(),
+ getScale: vi.fn(() => ({ scaleX: 2, scaleY: 2 })),
+ strokeStyle: '',
+ } as any;
+}
+
+function createGlyph(borderData?: any) {
+ return {
+ ts: borderData ? { bd: borderData } : undefined,
+ left: 0,
+ width: 40,
+ parent: {
+ parent: {
+ asc: 12,
+ lineHeight: 24,
+ },
+ },
+ } as any;
+}
+
+describe('docs border extension', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns early without line, text style or border data', () => {
+ const extension = new Border();
+ const ctx = createCtx();
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, { ts: { bd: {} } } as any);
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph());
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, { ...createGlyph(), ts: {} } as any);
+
+ expect(ctx.save).not.toHaveBeenCalled();
+ });
+
+ it('draws each span border and reuses cached line style/color until cleared', () => {
+ const extension = new Border();
+ extension.extensionOffset = { spanStartPoint: Vector2.create(5, 7) } as any;
+ const ctx = createCtx();
+ const borderData = {
+ t: { s: BorderStyleTypes.THIN, cl: { rgb: '#111111' } },
+ b: { s: BorderStyleTypes.THIN, cl: { rgb: '#111111' } },
+ l: { s: BorderStyleTypes.DASHED, cl: { rgb: '#222222' } },
+ r: { s: BorderStyleTypes.DASHED },
+ };
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph(borderData));
+
+ expect(ctx.save).toHaveBeenCalledTimes(1);
+ expect(ctx.translateWithPrecisionRatio).toHaveBeenCalled();
+ expect(drawLineByBorderTypeMock).toHaveBeenCalledTimes(4);
+ expect(drawLineByBorderTypeMock).toHaveBeenCalledWith(
+ ctx,
+ BORDER_TYPE.TOP,
+ 0.25,
+ expect.objectContaining({
+ startX: 5,
+ startY: 7,
+ endX: 45,
+ endY: 31,
+ })
+ );
+ expect(setLineTypeMock).toHaveBeenCalledTimes(2);
+ expect(ctx.setLineWidthByPrecision).toHaveBeenCalledWith(2);
+ expect(ctx.strokeStyle).toBe('rgb(0,0,0)');
+
+ extension.clearCache();
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, createGlyph({
+ t: { s: BorderStyleTypes.THIN, cl: { rgb: '#333333' } },
+ }));
+
+ expect(setLineTypeMock).toHaveBeenCalledTimes(3);
+ expect(ctx.restore).toHaveBeenCalledTimes(2);
+ });
+});
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
index 431fdee6f0..b869af9cbf 100644
--- 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
@@ -31,6 +31,12 @@ type MockRenderContext = UniverRenderingContext & {
fillText: ReturnType<typeof vi.fn>;
translate: ReturnType<typeof vi.fn>;
rotate: ReturnType<typeof vi.fn>;
+ createLinearGradient: ReturnType<typeof vi.fn>;
+ createRadialGradient: ReturnType<typeof vi.fn>;
+ createPattern: ReturnType<typeof vi.fn>;
+ _context: {
+ createConicGradient: ReturnType<typeof vi.fn>;
+ };
};
type GlyphOverrides = Omit<Partial<IDocumentSkeletonGlyph>, 'bBox' | 'parent'> & {
@@ -41,6 +47,9 @@ type GlyphOverrides = Omit<Partial<IDocumentSkeletonGlyph>, 'bBox' | 'parent'> &
const DEFAULT_SCALE: IScale = { scaleX: 1, scaleY: 1 };
function createContext(): MockRenderContext {
+ const gradient = {
+ addColorStop: vi.fn(),
+ };
return {
fillStyle: '',
font: '10px Arial',
@@ -49,6 +58,12 @@ function createContext(): MockRenderContext {
fillText: vi.fn(),
translate: vi.fn(),
rotate: vi.fn(),
+ createLinearGradient: vi.fn(() => gradient),
+ createRadialGradient: vi.fn(() => gradient),
+ createPattern: vi.fn(() => ({ setTransform: vi.fn() })),
+ _context: {
+ createConicGradient: vi.fn(() => gradient),
+ },
} as unknown as MockRenderContext;
}
@@ -206,4 +221,173 @@ describe('docs font and baseline extension', () => {
extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', { parent: null }));
expect(TestContext.fillText).not.toHaveBeenCalled();
});
+
+ it('renders solid and gradient text fills with normalized colors', () => {
+ const extension = new FontAndBaseLine() as any;
+ const TestContext = createContext();
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(10, 24),
+ spanStartPoint: Vector2.create(10, 24),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 0,
+ centerAngle: 0,
+ },
+ } as IExtensionConfig;
+
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('S', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#000000' },
+ textFill: {
+ type: 'solid',
+ color: '#abc',
+ opacity: 0.5,
+ },
+ } as any,
+ }));
+ expect(TestContext.fillStyle).toBe('rgba(170, 187, 204, 0.5)');
+
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('L', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: {
+ type: 'gradient',
+ color: '#123456',
+ opacity: 0.5,
+ gradient: {
+ type: 'linear',
+ angle: 45,
+ stops: [
+ { offset: 0, color: '#000000', opacity: 1 },
+ { offset: 100, color: '#ffffff', opacity: 0.5 },
+ ],
+ },
+ },
+ } as any,
+ }));
+ expect(TestContext.createLinearGradient).toHaveBeenCalled();
+
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('R', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: {
+ type: 'gradient',
+ color: '#123456',
+ gradient: { type: 'radial' },
+ },
+ } as any,
+ }));
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('D', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: {
+ type: 'gradient',
+ color: '#123456',
+ gradient: { type: 'diamond' },
+ },
+ } as any,
+ }));
+ expect(TestContext.createRadialGradient).toHaveBeenCalledTimes(2);
+
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: {
+ type: 'gradient',
+ color: '#123456',
+ gradient: { type: 'angular', angle: 180 },
+ },
+ } as any,
+ }));
+ expect(TestContext._context.createConicGradient).toHaveBeenCalled();
+
+ expect(extension._normalizeGradientStops(undefined, '#010203')).toEqual([
+ { color: '#010203', offset: 0, opacity: undefined },
+ { color: '#ffffff', offset: 1, opacity: undefined },
+ ]);
+ expect(extension._colorWithOpacity('#123456', 0.25)).toBe('rgba(18, 52, 86, 0.25)');
+ expect(extension._colorWithOpacity('rgb(1,2,3)', 0.25)).toBe('rgb(1,2,3)');
+ expect(extension._clamp(2, 0, 1)).toBe(1);
+ });
+
+ it('renders picture text fills from cached images and ignores unsupported fill cases', () => {
+ const extension = new FontAndBaseLine() as any;
+ const TestContext = createContext();
+ const image = document.createElement('canvas') as HTMLCanvasElement & {
+ complete: boolean;
+ naturalWidth: number;
+ naturalHeight: number;
+ };
+ image.width = 4;
+ image.height = 4;
+ image.complete = true;
+ image.naturalWidth = 4;
+ image.naturalHeight = 4;
+ extension._textFillImageCache.set('cached-image', image);
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(10, 24),
+ spanStartPoint: Vector2.create(10, 24),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 0,
+ centerAngle: 0,
+ },
+ } as IExtensionConfig;
+
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('P', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: {
+ type: 'picture',
+ picture: {
+ source: 'cached-image',
+ mode: 'tile',
+ scaleX: 0.5,
+ scaleY: 0.5,
+ offsetX: 1,
+ offsetY: 1,
+ opacity: 0.75,
+ },
+ },
+ } as any,
+ }));
+ expect(TestContext.createPattern).toHaveBeenCalled();
+
+ TestContext.fillText.mockClear();
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('N', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: { type: 'none' },
+ } as any,
+ }));
+ expect(TestContext.fillText).not.toHaveBeenCalled();
+
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(10, 24),
+ spanStartPoint: Vector2.create(10, 24),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 90,
+ centerAngle: 90,
+ },
+ } as IExtensionConfig;
+ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('V', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ textFill: {
+ type: 'solid',
+ color: '#ff0000',
+ },
+ } as any,
+ }));
+ expect(TestContext.fillText).toHaveBeenCalled();
+ });
});
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
index 8be220a061..94bbd4c34b 100644
--- 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
@@ -15,9 +15,9 @@
*/
import type { IParagraphConfig } from '../../../../../../basics/interfaces';
-import { BooleanNumber, GridType, SpacingRule } from '@univerjs/core';
+import { BooleanNumber, DataStreamTreeTokenType, GridType, SpacingRule } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import { getLineHeightMetrics, layoutParagraph } from '../layout-ruler';
+import { getLineHeightMetrics, layoutParagraph, updateInlineDrawingPosition } from '../layout-ruler';
import { lineBreaking } from '../linebreaking';
import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
@@ -159,4 +159,213 @@ describe('layout-ruler', () => {
expect(getLineBoxHeight(metrics)).toBeCloseTo(23.4, 4);
});
+
+ it('splits an oversized word slice in a narrow paragraph divide', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('oversized', {
+ documentStyle: {
+ pageSize: { width: 80, height: 120 },
+ marginLeft: 10,
+ marginRight: 10,
+ marginTop: 10,
+ marginBottom: 10,
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const glyphs = shapedTextList[0].glyphs.map((glyph) => ({ ...glyph, width: 36 }));
+
+ const result = layoutParagraph(
+ ctx,
+ glyphs,
+ [curPage],
+ sectionBreakConfig,
+ { paragraphIndex: paragraphNode.endIndex, paragraphStyle: {} } as unknown as IParagraphConfig,
+ true
+ );
+
+ const lines = result.flatMap((page) => page.sections.flatMap((section) => section.columns.flatMap((column) => column.lines)));
+ expect(lines.length).toBeGreaterThan(1);
+ });
+
+ it('keeps overflowing paragraph break and trailing spaces on the current line', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('word', {
+ documentStyle: {
+ pageSize: { width: 76, height: 120 },
+ marginLeft: 10,
+ marginRight: 10,
+ marginTop: 10,
+ marginBottom: 10,
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const paragraphConfig = { paragraphIndex: paragraphNode.endIndex, paragraphStyle: {} } as unknown as IParagraphConfig;
+ const firstGlyph = { ...shapedTextList[0].glyphs[0], width: 50 } as any;
+ const spaceGlyph = {
+ ...firstGlyph,
+ content: DataStreamTreeTokenType.SPACE,
+ width: 20,
+ st: firstGlyph.ed + 1,
+ ed: firstGlyph.ed + 1,
+ };
+ const paragraphGlyph = {
+ ...firstGlyph,
+ content: DataStreamTreeTokenType.PARAGRAPH,
+ width: 20,
+ st: firstGlyph.ed + 2,
+ ed: firstGlyph.ed + 2,
+ };
+
+ const firstLayout = layoutParagraph(ctx, [firstGlyph], [curPage], sectionBreakConfig, paragraphConfig, true);
+ const withSpace = layoutParagraph(ctx, [spaceGlyph], firstLayout, sectionBreakConfig, paragraphConfig, false);
+ const withParagraphBreak = layoutParagraph(ctx, [paragraphGlyph], withSpace, sectionBreakConfig, paragraphConfig, false);
+
+ const glyphContents = withParagraphBreak.flatMap((page) => page.sections.flatMap(
+ (section) => section.columns.flatMap(
+ (column) => column.lines.flatMap(
+ (line) => line.divides.flatMap((divide) => divide.glyphGroup.map((glyph) => glyph.content))
+ )
+ )
+ ));
+ expect(glyphContents).toContain(firstGlyph.content);
+ expect(glyphContents).toContain(DataStreamTreeTokenType.SPACE);
+ });
+
+ it('opens new pages when narrow document content exceeds the current column height', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed(
+ 'First Second Third Fourth Fifth Sixth Seventh Eighth',
+ {
+ documentStyle: {
+ pageSize: { width: 80, height: 42 },
+ marginLeft: 8,
+ marginRight: 8,
+ marginTop: 8,
+ marginBottom: 8,
+ },
+ }
+ );
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const paragraphConfig = { paragraphIndex: paragraphNode.endIndex, paragraphStyle: {} } as unknown as IParagraphConfig;
+ const baseGlyph = { ...shapedTextList[0].glyphs[0], width: 48 } as any;
+ let result = [curPage];
+
+ for (let i = 0; i < 8; i++) {
+ result = layoutParagraph(
+ ctx,
+ [{ ...baseGlyph, st: i, ed: i, content: String(i) } as any],
+ result,
+ sectionBreakConfig,
+ paragraphConfig,
+ i === 0
+ );
+ }
+
+ expect(result.length).toBeGreaterThan(1);
+ });
+
+ it('preserves a usable divide width when paragraph indentation consumes the column', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Indented', {
+ documentStyle: {
+ pageSize: { width: 80, height: 120 },
+ marginLeft: 10,
+ marginRight: 10,
+ marginTop: 10,
+ marginBottom: 10,
+ },
+ body: {
+ dataStream: 'Indented\r\n',
+ textRuns: [{ st: 0, ed: 10, ts: {} }],
+ paragraphs: [{
+ startIndex: 8,
+ paragraphStyle: {
+ indentStart: { v: 60 },
+ indentEnd: { v: 60 },
+ },
+ }],
+ sectionBreaks: [{ startIndex: 9 }],
+ },
+ });
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+
+ const result = layoutParagraph(
+ ctx,
+ shapedTextList[0].glyphs,
+ [curPage],
+ sectionBreakConfig,
+ {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {
+ indentStart: { v: 60 },
+ indentEnd: { v: 60 },
+ },
+ } as unknown as IParagraphConfig,
+ true
+ );
+
+ const divide = result[0].sections[0].columns[0].lines[0].divides[0];
+ expect(divide.width).toBeGreaterThan(0);
+ });
+
+ it('positions inline custom block drawings relative to their glyph box', () => {
+ const drawing = {
+ drawingId: 'image-1',
+ drawingOrigin: {
+ docTransform: {
+ size: { width: 30, height: 20 },
+ angle: 15,
+ },
+ },
+ } as any;
+ const page = {
+ skeDrawings: new Map([['old-image', { drawingId: 'old-image' }]]),
+ } as any;
+ const section = {
+ columns: [],
+ parent: page,
+ } as any;
+ const column = {
+ left: 40,
+ lines: [],
+ parent: section,
+ } as any;
+ const line = {
+ top: 100,
+ lineHeight: 24,
+ marginBottom: 4,
+ paragraphStart: true,
+ parent: column,
+ divides: [{
+ left: 10,
+ paddingLeft: 2,
+ glyphGroup: [{
+ streamType: DataStreamTreeTokenType.CUSTOM_BLOCK,
+ width: 50,
+ left: 8,
+ bBox: { ba: 9, bd: 3 },
+ drawingId: 'image-1',
+ }, {
+ streamType: DataStreamTreeTokenType.CUSTOM_BLOCK,
+ width: 20,
+ left: 70,
+ bBox: { ba: 5, bd: 5 },
+ }],
+ }],
+ } as any;
+ section.columns = [column];
+ column.lines = [line];
+
+ updateInlineDrawingPosition(line, new Map([['image-1', drawing]]), 80);
+
+ expect(page.skeDrawings.get('old-image')).toEqual({ drawingId: 'old-image' });
+ expect(page.skeDrawings.get('image-1')).toMatchObject({
+ aLeft: 30,
+ aTop: 104,
+ width: 30,
+ height: 20,
+ angle: 15,
+ isPageBreak: false,
+ lineTop: 100,
+ columnLeft: 40,
+ blockAnchorTop: 80,
+ lineHeight: 24,
+ });
+ });
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
index e654115d70..c539a0ecdb 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts
@@ -22,6 +22,59 @@ import { shaping } from '../shaping';
import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';
describe('line-adjustment', () => {
+ function createGlyph(content: string, width: number, overrides: Record<string, unknown> = {}) {
+ return {
+ content,
+ width,
+ left: 0,
+ xOffset: 0,
+ isJustifiable: content === ' ',
+ adjustability: {
+ stretchability: content === ' ' ? [0, 3] : [0, 0],
+ shrinkability: content === ' ' ? [0, 2] : [0, 0],
+ },
+ bBox: {
+ width,
+ },
+ ...overrides,
+ } as any;
+ }
+
+ function createPagesWithLine(divide: any, horizontalAlign: HorizontalAlign) {
+ const line = {
+ paragraphIndex: 0,
+ divides: [divide],
+ } as any;
+ const column = {
+ lines: [line],
+ };
+ const section = {
+ columns: [column],
+ };
+ const page = {
+ sections: [section],
+ };
+
+ divide.parent = line;
+ line.parent = column;
+
+ return {
+ pages: [page] as any[],
+ viewModel: {
+ getParagraph: () => ({
+ startIndex: 0,
+ paragraphStyle: {
+ horizontalAlign,
+ },
+ }),
+ } as any,
+ paragraphNode: {
+ endIndex: 1,
+ } as any,
+ sectionBreakConfig: {} as any,
+ };
+ }
+
it('adjusts lines after layout', () => {
const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hello world');
const shapedTextList = shaping(ctx, paragraphNode.content!, viewModel, paragraphNode, sectionBreakConfig);
@@ -106,4 +159,70 @@ describe('line-adjustment', () => {
expect(() => lineAdjustment(pages, viewModel, paragraphNode, sectionBreakConfig)).not.toThrow();
});
+
+ it('sets center and right padding from actual glyph group width', () => {
+ const centerDivide = {
+ width: 100,
+ isFull: false,
+ paddingLeft: 0,
+ glyphGroup: [createGlyph('A', 20), createGlyph('B', 30)],
+ } as any;
+ const center = createPagesWithLine(centerDivide, HorizontalAlign.CENTER);
+
+ lineAdjustment(center.pages, center.viewModel, center.paragraphNode, center.sectionBreakConfig);
+ expect(centerDivide.glyphGroupWidth).toBe(50);
+ expect(centerDivide.paddingLeft).toBe(25);
+
+ const rightDivide = {
+ width: 100,
+ isFull: false,
+ paddingLeft: 0,
+ glyphGroup: [createGlyph('A', 20), createGlyph('B', 30)],
+ } as any;
+ const right = createPagesWithLine(rightDivide, HorizontalAlign.RIGHT);
+
+ lineAdjustment(right.pages, right.viewModel, right.paragraphNode, right.sectionBreakConfig);
+ expect(rightDivide.glyphGroupWidth).toBe(50);
+ expect(rightDivide.paddingLeft).toBe(50);
+ });
+
+ it('expands justifiable spaces to fill a full justified divide', () => {
+ const space = createGlyph(' ', 5);
+ const divide = {
+ width: 40,
+ isFull: true,
+ paddingLeft: 0,
+ glyphGroup: [createGlyph('A', 10), space, createGlyph('B', 10)],
+ } as any;
+ const context = createPagesWithLine(divide, HorizontalAlign.JUSTIFIED);
+
+ lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);
+
+ expect(space.width).toBe(20);
+ expect(divide.glyphGroupWidth).toBe(40);
+ expect(divide.paddingLeft).toBe(0);
+ });
+
+ it('restores extra CJK spacing for a full line ending in CJK text', () => {
+ const cjkGlyph = createGlyph('中', 20, {
+ xOffset: 5,
+ bBox: { width: 10 },
+ adjustability: {
+ stretchability: [0, 0],
+ shrinkability: [0, 7],
+ },
+ });
+ const divide = {
+ width: 100,
+ isFull: true,
+ paddingLeft: 0,
+ glyphGroup: [createGlyph('A', 10), cjkGlyph],
+ };
+ const context = createPagesWithLine(divide, HorizontalAlign.UNSPECIFIED);
+
+ lineAdjustment(context.pages, context.viewModel, context.paragraphNode, context.sectionBreakConfig);
+
+ expect(cjkGlyph.width).toBe(15);
+ expect(cjkGlyph.adjustability.shrinkability[1]).toBe(0);
+ });
});
diff --git a/packages/engine-render/src/components/docs/layout/hyphenation/__tests__/hypen.spec.ts b/packages/engine-render/src/components/docs/layout/hyphenation/__tests__/hypen.spec.ts
index 24cb6bacc3..0416d01ff6 100644
--- a/packages/engine-render/src/components/docs/layout/hyphenation/__tests__/hypen.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/hyphenation/__tests__/hypen.spec.ts
@@ -18,9 +18,25 @@ import type { Nullable } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Hyphen } from '../hyphen';
import { Lang } from '../lang';
+import { PATTERN_LOADERS } from '../pattern-loaders.gen';
describe('test hyphenation', () => {
let hyphen: Nullable<Hyphen> = null;
+ const PATTERN_LOADER_CHUNK_SIZE = 8;
+ const patternLoaderChunks = Object.entries(PATTERN_LOADERS).reduce<Array<Array<[string, () => Promise<unknown>]>>>(
+ (chunks, entry) => {
+ const lastChunk = chunks[chunks.length - 1];
+ if (!lastChunk || lastChunk.length >= PATTERN_LOADER_CHUNK_SIZE) {
+ chunks.push([entry]);
+ } else {
+ lastChunk.push(entry);
+ }
+
+ return chunks;
+ },
+ []
+ );
+
beforeEach(() => {
hyphen = new Hyphen();
});
@@ -42,6 +58,27 @@ describe('test hyphenation', () => {
expect(hyphen?.hasPattern(Lang.Af)).toBe(true);
});
+
+ it('registers generated hyphenation pattern loaders and loads representative modules', async () => {
+ const supportedLangs = Object.values(Lang).filter((lang) => lang !== Lang.UNKNOWN);
+ const entries = Object.entries(PATTERN_LOADERS);
+
+ expect(entries).toHaveLength(supportedLangs.length);
+ expect(supportedLangs.every((lang) => typeof PATTERN_LOADERS[lang] === 'function')).toBe(true);
+
+ const patterns = await Promise.all([
+ PATTERN_LOADERS[Lang.Af]?.(),
+ PATTERN_LOADERS[Lang.EnGb]?.(),
+ PATTERN_LOADERS[Lang.ZhLatnPinyin]?.(),
+ ]);
+ expect(patterns.every((pattern) => pattern != null)).toBe(true);
+ });
+
+ it.each(patternLoaderChunks.map((entries) => [entries]))('loads generated hyphenation pattern modules %#', async (entries) => {
+ const patterns = await Promise.all(entries.map(([, loader]) => loader()));
+
+ expect(patterns.every((pattern) => pattern != null)).toBe(true);
+ });
});
describe('test basic use of hyphen', () => {
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/column.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/column.spec.ts
new file mode 100644
index 0000000000..9e54a51476
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/column.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 { ColumnSeparatorType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { createSkeletonColumn } from '../column';
+
+describe('column model', () => {
+ const columnProperties = [
+ { width: 120, paddingEnd: 20 },
+ { width: 80, paddingEnd: 16 },
+ { width: 160, paddingEnd: 0 },
+ ];
+
+ it('creates the first column at the section origin with its trailing gap', () => {
+ const column = createSkeletonColumn(
+ 0,
+ columnProperties,
+ ColumnSeparatorType.BETWEEN_EACH_COLUMN,
+ 500
+ );
+
+ expect(column).toMatchObject({
+ left: 0,
+ width: 120,
+ spaceWidth: 20,
+ separator: ColumnSeparatorType.BETWEEN_EACH_COLUMN,
+ height: 0,
+ isFull: false,
+ drawingLRIds: [],
+ lines: [],
+ });
+ });
+
+ it('accumulates previous column widths and removes gap from the last column', () => {
+ const middleColumn = createSkeletonColumn(1, columnProperties, ColumnSeparatorType.NONE, 500);
+ const lastColumn = createSkeletonColumn(2, columnProperties, ColumnSeparatorType.NONE, 500);
+
+ expect(middleColumn.left).toBe(140);
+ expect(middleColumn.width).toBe(80);
+ expect(middleColumn.spaceWidth).toBe(16);
+
+ expect(lastColumn.left).toBe(236);
+ expect(lastColumn.width).toBe(160);
+ expect(lastColumn.spaceWidth).toBe(0);
+ });
+
+ it('keeps infinite width for single-column unconstrained sections', () => {
+ const column = createSkeletonColumn(0, [{ width: 0, paddingEnd: 0 }], ColumnSeparatorType.NONE);
+
+ expect(column.left).toBe(0);
+ expect(column.width).toBe(Number.POSITIVE_INFINITY);
+ expect(column.spaceWidth).toBe(0);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/model/column.ts b/packages/engine-render/src/components/docs/layout/model/column.ts
index 1197e36ef3..0a45f35bef 100644
--- a/packages/engine-render/src/components/docs/layout/model/column.ts
+++ b/packages/engine-render/src/components/docs/layout/model/column.ts
@@ -50,21 +50,28 @@ function _calculateColumnSize(
let colWidth = 0;
let spaceWidth = 0;
let left = 0;
- for (let i = 0; i <= columnIndex; i++) {
+ for (let i = 0; i < columnIndex; i++) {
const { width, paddingEnd } = columnProperties[i];
- if (i === columnProperties.length - 1) {
- colWidth = pageWidth === Number.POSITIVE_INFINITY ? pageWidth - colWidth : width;
+ left += width + paddingEnd;
+ }
+
+ const { width, paddingEnd } = columnProperties[columnIndex];
+ if (columnIndex === columnProperties.length - 1) {
+ if (pageWidth === Number.POSITIVE_INFINITY) {
+ colWidth = pageWidth;
spaceWidth = 0;
} else {
- spaceWidth = paddingEnd;
colWidth = width;
- left += colWidth + spaceWidth;
+ spaceWidth = 0;
}
+ } else {
+ colWidth = width;
+ spaceWidth = paddingEnd;
}
return {
width: colWidth,
spaceWidth,
- left: left - colWidth - spaceWidth,
+ left,
};
}
diff --git a/packages/engine-render/src/components/docs/layout/style/__tests__/custom-decoration.spec.ts b/packages/engine-render/src/components/docs/layout/style/__tests__/custom-decoration.spec.ts
new file mode 100644
index 0000000000..6b6dc165de
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/style/__tests__/custom-decoration.spec.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BooleanNumber, CustomDecorationType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getCustomDecorationStyle } from '../custom-decoration';
+
+describe('custom decoration style', () => {
+ it('renders active comments with bottom border and highlight background', () => {
+ expect(getCustomDecorationStyle({ type: CustomDecorationType.COMMENT, active: true } as never)).toEqual({
+ bbl: {
+ s: BooleanNumber.TRUE,
+ cl: { rgb: '#fcdf7e' },
+ c: BooleanNumber.FALSE,
+ },
+ bg: { rgb: '#faedc2' },
+ });
+ });
+
+ it('keeps the comment bottom border when the comment is inactive', () => {
+ expect(getCustomDecorationStyle({ type: CustomDecorationType.COMMENT, active: false } as never)).toEqual({
+ bbl: {
+ s: BooleanNumber.TRUE,
+ cl: { rgb: '#fcdf7e' },
+ c: BooleanNumber.FALSE,
+ },
+ });
+ });
+
+ it('does not style deleted decorations as active comments', () => {
+ expect(getCustomDecorationStyle({ type: CustomDecorationType.DELETED } as never)).toBeNull();
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.spec.ts b/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.spec.ts
new file mode 100644
index 0000000000..3bc610793a
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/style/__tests__/custom-range.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 { BooleanNumber, CustomRangeType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getCustomRangeStyle } from '../custom-range';
+
+describe('custom range style', () => {
+ it('renders active hyperlink-like ranges as blue underlined text', () => {
+ expect(getCustomRangeStyle({ rangeType: CustomRangeType.HYPERLINK } as never)).toEqual({
+ ul: { s: BooleanNumber.TRUE },
+ cl: { rgb: '#274fee' },
+ });
+ expect(getCustomRangeStyle({ rangeType: CustomRangeType.MENTION, active: true } as never)).toEqual({
+ ul: { s: BooleanNumber.TRUE },
+ cl: { rgb: '#274fee' },
+ });
+ });
+
+ it('keeps the link color but drops underline for inactive custom ranges', () => {
+ expect(getCustomRangeStyle({ rangeType: CustomRangeType.CUSTOM, active: false } as never)).toEqual({
+ cl: { rgb: '#274fee' },
+ });
+ });
+
+ it('does not style unsupported custom range types', () => {
+ expect(getCustomRangeStyle({ rangeType: CustomRangeType.COMMENT } as never)).toBeNull();
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet-component.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet-component.spec.ts
new file mode 100644
index 0000000000..1f9c5c922d
--- /dev/null
+++ b/packages/engine-render/src/components/sheets/__tests__/sheet-component.spec.ts
@@ -0,0 +1,97 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Nullable } from '@univerjs/core';
+import type { IViewportInfo, Vector2 } from '../../../basics/vector2';
+import type { UniverRenderingContext } from '../../../context';
+import type { SpreadsheetSkeleton } from '../sheet.render-skeleton';
+import { describe, expect, it, vi } from 'vitest';
+import { RENDER_CLASS_TYPE } from '../../../basics/const';
+import { SheetComponent } from '../sheet-component';
+
+class TestSheetComponent extends SheetComponent {
+ readonly drawCalls: Array<{ ctx: UniverRenderingContext; bounds?: IViewportInfo }> = [];
+
+ getDocuments() {
+ return null;
+ }
+
+ getNoMergeCellPositionByIndex(): Nullable<{ startY: number; startX: number; endX: number; endY: number }> {
+ return null;
+ }
+
+ getSelectionBounding(): Nullable<{ startRow: number; startColumn: number; endRow: number; endColumn: number }> {
+ return null;
+ }
+
+ protected override _draw(ctx: UniverRenderingContext, bounds?: IViewportInfo): void {
+ this.drawCalls.push({ ctx, bounds });
+ }
+}
+
+function createCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ } as unknown as UniverRenderingContext;
+}
+
+describe('SheetComponent', () => {
+ it('renders visible sheet components inside a canvas save and restore pair', () => {
+ const component = new TestSheetComponent('sheet-component');
+ const ctx = createCtx();
+ const bounds = { viewBound: { left: 0, top: 0, right: 100, bottom: 80 } } as IViewportInfo;
+
+ component.render(ctx, bounds);
+
+ expect(ctx.save).toHaveBeenCalledTimes(1);
+ expect(ctx.restore).toHaveBeenCalledTimes(1);
+ expect(component.drawCalls).toEqual([{ ctx, bounds }]);
+ });
+
+ it('updates the skeleton and syncs the scene transformer offset', () => {
+ const component = new TestSheetComponent('sheet-component');
+ const scene = { updateTransformerZero: vi.fn() };
+ vi.spyOn(component as any, 'getScene').mockReturnValue(scene);
+ const skeleton = {
+ rowHeaderWidth: 46,
+ columnHeaderHeight: 28,
+ } as SpreadsheetSkeleton;
+
+ component.updateSkeleton(skeleton);
+
+ expect(component.getSkeleton()).toBe(skeleton);
+ expect(scene.updateTransformerZero).toHaveBeenCalledWith(46, 28);
+ });
+
+ it('uses viewer ancestor scale for hit testing helpers and clears skeleton on dispose', () => {
+ const component = new TestSheetComponent('sheet-component', { rowHeaderWidth: 1, columnHeaderHeight: 1 } as SpreadsheetSkeleton);
+ component.parent = {
+ classType: RENDER_CLASS_TYPE.SCENE_VIEWER,
+ scaleX: 2,
+ scaleY: 3,
+ ancestorScaleX: 1.25,
+ ancestorScaleY: 1.5,
+ removeObject: vi.fn(),
+ } as any;
+
+ expect(component.getParentScale()).toEqual({ scaleX: 1.25, scaleY: 1.5 });
+ expect(component.getScrollXYByRelativeCoords({} as Vector2)).toEqual({ x: 0, y: 0 });
+
+ component.dispose();
+ expect(component.getSkeleton()).toBeNull();
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet-header-util.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet-header-util.spec.ts
new file mode 100644
index 0000000000..ab26424a51
--- /dev/null
+++ b/packages/engine-render/src/components/sheets/__tests__/sheet-header-util.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 { IWorkbookData, Workbook } from '@univerjs/core';
+import type { IBoundRectNoAngle, IViewportInfo } from '../../../basics/vector2';
+import {
+ CellValueType,
+ HorizontalAlign,
+ ILogService,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ Univer,
+ UniverInstanceType,
+ VerticalAlign,
+ 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 { SpreadsheetColumnHeader } from '../column-header';
+import { SHEET_VIEWPORT_KEY } from '../interfaces';
+import { SpreadsheetRowHeader } from '../row-header';
+import { SpreadsheetSkeleton } from '../sheet.render-skeleton';
+import { createDocumentModelWithStyle, extractOtherStyle, getFontFormat } from '../util';
+import '../extensions/column-header-layout';
+import '../extensions/row-header-layout';
+
+function workbookDataFactory(): IWorkbookData {
+ return {
+ id: 'header-workbook',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'header-workbook',
+ sheetOrder: ['sheet-1'],
+ styles: {},
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Sheet-1',
+ rowCount: 12,
+ columnCount: 8,
+ defaultColumnWidth: 64,
+ defaultRowHeight: 24,
+ rowHeader: { width: 42 },
+ columnHeader: { height: 28 },
+ },
+ },
+ };
+}
+
+function createBound(left: number, top: number, right: number, bottom: number): IBoundRectNoAngle {
+ return { left, top, right, bottom };
+}
+
+function createViewportInfo(scene: Scene, cacheCanvas: Canvas): IViewportInfo {
+ const viewBound = createBound(0, 0, 320, 180);
+ const cacheBound = createBound(0, 0, 360, 220);
+ const viewPortPosition = createBound(0, 0, 320, 180);
+
+ 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: 8,
+ bufferEdgeY: 8,
+ };
+}
+
+function createCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ moveToByPrecision: vi.fn(),
+ lineToByPrecision: vi.fn(),
+ stroke: vi.fn(),
+ clip: vi.fn(),
+ rectByPrecision: vi.fn(),
+ fillRectByPrecision: vi.fn(),
+ setLineWidthByPrecision: vi.fn(),
+ translateWithPrecision: vi.fn(),
+ translateWithPrecisionRatio: vi.fn(),
+ fillText: vi.fn(),
+ fillStyle: '',
+ strokeStyle: '',
+ textAlign: 'center',
+ textBaseline: 'middle',
+ font: '',
+ } as any;
+}
+
+describe('spreadsheet headers and cell document helpers', () => {
+ let univer: Univer;
+ let workbook: Workbook;
+ let skeleton: SpreadsheetSkeleton;
+ let engine: Engine;
+ let scene: Scene;
+ let viewport: Viewport;
+ let cacheCanvas: Canvas;
+ let restoreEnv: () => void;
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ restoreEnv = setupRenderTestEnv().restore;
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookDataFactory());
+ get(IUniverInstanceService).focusUnit('header-workbook');
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ skeleton = injector.createInstance(SpreadsheetSkeleton, workbook.getActiveSheet()!, workbook.getStyles()).calculate() as SpreadsheetSkeleton;
+
+ container = document.createElement('div');
+ container.style.width = '480px';
+ container.style.height = '320px';
+ document.body.appendChild(container);
+ engine = new Engine('header-engine', { elementWidth: 480, elementHeight: 320, dpr: 1 });
+ engine.mount(container, false);
+ scene = new Scene('header-scene', engine);
+ scene.transformByState({ width: 1000, height: 800, scaleX: 1, scaleY: 1 });
+ viewport = new Viewport(MAIN_VIEW_PORT_KEY, scene, {
+ left: 0,
+ top: 0,
+ width: 320,
+ height: 180,
+ active: true,
+ allowCache: true,
+ bufferEdgeX: 8,
+ bufferEdgeY: 8,
+ });
+ cacheCanvas = new Canvas({ width: 360, height: 220, pixelRatio: 1 });
+ skeleton.setScene(scene);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ cacheCanvas?.dispose();
+ viewport?.dispose();
+ scene?.dispose();
+ engine?.dispose();
+ univer?.dispose();
+ restoreEnv?.();
+ container?.remove();
+ });
+
+ it('draws column and row headers from a DI-created spreadsheet skeleton', () => {
+ const bounds = createViewportInfo(scene, cacheCanvas);
+ const columnHeader = new SpreadsheetColumnHeader('column-header', skeleton);
+ const rowHeader = new SpreadsheetRowHeader('row-header', skeleton);
+ const ctx = createCtx();
+ scene.addObject(columnHeader, 1);
+ scene.addObject(rowHeader, 1);
+
+ columnHeader.setCustomHeader({
+ columnsCfg: {
+ 0: { text: 'SKU', backgroundColor: '#f4f6f8', textAlign: 'left' },
+ },
+ headerStyle: { fontColor: '#123456' },
+ }, 'sheet-1');
+ rowHeader.setCustomHeader({
+ rowsCfg: {
+ 0: { text: 'Top', backgroundColor: '#eef2ff', textAlign: 'right' },
+ },
+ headerStyle: { borderColor: '#8899aa' },
+ }, 'sheet-1');
+
+ columnHeader.draw(ctx, bounds);
+ rowHeader.draw(ctx, bounds);
+
+ expect(ctx.translateWithPrecision).toHaveBeenCalledWith(42, 0);
+ expect(ctx.translateWithPrecision).toHaveBeenCalledWith(0, 28);
+ expect(ctx.fillText).toHaveBeenCalled();
+ expect(columnHeader.isHit(Vector2.FromArray([50, 10]))).toBe(true);
+ expect(columnHeader.isHit(Vector2.FromArray([10, 10]))).toBe(false);
+ expect(rowHeader.isHit(Vector2.FromArray([10, 40]))).toBe(true);
+ expect(rowHeader.isHit(Vector2.FromArray([50, 10]))).toBe(false);
+ expect(() => columnHeader.getDocuments()).toThrow('Method not implemented.');
+ expect(() => rowHeader.getDocuments()).toThrow('Method not implemented.');
+
+ columnHeader.dispose();
+ rowHeader.dispose();
+ });
+
+ it('builds a sheet cell document model with render style metadata', () => {
+ const documentModel = createDocumentModelWithStyle('Revenue', { fs: 14, bl: 1, cl: { rgb: '#223344' } }, {
+ horizontalAlign: HorizontalAlign.RIGHT,
+ verticalAlign: VerticalAlign.MIDDLE,
+ wrapStrategy: WrapStrategy.WRAP,
+ cellValueType: CellValueType.STRING,
+ paddingData: { t: 3, r: 4, b: 5, l: 6 },
+ });
+
+ const snapshot = documentModel.getSnapshot();
+ expect(snapshot.body?.dataStream).toBe('Revenue\r\n');
+ expect(snapshot.body?.textRuns?.[0].ts).toMatchObject({ fs: 14, bl: 1 });
+ expect(snapshot.documentStyle).toMatchObject({
+ marginTop: 3,
+ marginRight: 4,
+ marginBottom: 5,
+ marginLeft: 6,
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.RIGHT,
+ verticalAlign: VerticalAlign.MIDDLE,
+ wrapStrategy: WrapStrategy.WRAP,
+ cellValueType: CellValueType.STRING,
+ },
+ });
+ });
+
+ it('extracts non-font cell style and font format for sheet text rendering', () => {
+ const style = {
+ ff: 'Arial',
+ fs: 12,
+ bl: 1,
+ it: 1,
+ ul: { s: 1 },
+ st: { s: 1 },
+ ol: { s: 1 },
+ cl: { rgb: '#112233' },
+ ht: HorizontalAlign.CENTER,
+ vt: VerticalAlign.BOTTOM,
+ tb: WrapStrategy.CLIP,
+ pd: { t: 1, r: 2, b: 3, l: 4 },
+ tr: { a: 45 },
+ } as any;
+
+ expect(extractOtherStyle(style)).toEqual({
+ textRotation: { a: 45 },
+ textDirection: undefined,
+ horizontalAlign: HorizontalAlign.CENTER,
+ verticalAlign: VerticalAlign.BOTTOM,
+ wrapStrategy: WrapStrategy.CLIP,
+ paddingData: { t: 1, r: 2, b: 3, l: 4 },
+ });
+ expect(extractOtherStyle(null)).toEqual({});
+
+ expect(getFontFormat(style)).toMatchObject({
+ ff: 'Arial',
+ fs: 12,
+ bl: 1,
+ it: 1,
+ cl: { rgb: '#112233' },
+ });
+ expect(getFontFormat(undefined)).toEqual({});
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/custom.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/custom.spec.ts
new file mode 100644
index 0000000000..d04c72f007
--- /dev/null
+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/custom.spec.ts
@@ -0,0 +1,135 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Custom } from '../custom';
+
+function createCtx() {
+ return { save: vi.fn(), restore: vi.fn() } as any;
+}
+
+function createCellWithCoord(row: number, col: number, overrides?: Partial<any>) {
+ return {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: { startRow: row, endRow: row, startColumn: col, endColumn: col },
+ ...overrides,
+ };
+}
+
+function createSkeleton(options: { cells: Map<string, any>; primary?: (row: number, col: number) => any }) {
+ const worksheet = {
+ unitId: 'unit-1',
+ getSheetId: vi.fn(() => 'sheet-1'),
+ getRowVisible: vi.fn(() => true),
+ getColVisible: vi.fn(() => true),
+ getCell: vi.fn((row: number, col: number) => options.cells.get(`${row},${col}`)),
+ };
+
+ return {
+ worksheet,
+ rowColumnSegment: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ getCellWithCoordByIndex: vi.fn((row: number, col: number) => (
+ options.primary?.(row, col) ?? createCellWithCoord(row, col)
+ )),
+ getStyles: vi.fn(() => ({
+ getStyleByCell: vi.fn((cell) => ({ fs: cell?.fs ?? 10 })),
+ })),
+ } as any;
+}
+
+describe('custom sheet extension', () => {
+ it('returns early when worksheet is missing', () => {
+ const extension = new Custom();
+ const ctx = createCtx();
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, { worksheet: null } as any, undefined);
+
+ expect(ctx.save).not.toHaveBeenCalled();
+ });
+
+ it('draws custom renderers in sorted order with real cell render info', () => {
+ const extension = new Custom();
+ const ctx = createCtx();
+ const first = { zIndex: 20, drawWith: vi.fn() };
+ const second = { zIndex: 10, drawWith: vi.fn() };
+ const cells = new Map<string, any>([
+ ['0,0', { v: 'custom', customRender: [first, second], fs: 12 }],
+ ['0,1', { v: 'plain' }],
+ ]);
+ const skeleton = createSkeleton({ cells });
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, skeleton, [
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 },
+ ]);
+
+ expect(ctx.save).toHaveBeenCalledTimes(1);
+ expect(ctx.restore).toHaveBeenCalledTimes(1);
+ expect(second.drawWith).toHaveBeenCalledBefore(first.drawWith);
+ expect(second.drawWith).toHaveBeenCalledWith(
+ ctx,
+ expect.objectContaining({
+ data: cells.get('0,0'),
+ style: { fs: 12 },
+ primaryWithCoord: expect.objectContaining({ startRow: 0, startColumn: 0 }),
+ subUnitId: 'sheet-1',
+ row: 0,
+ col: 0,
+ worksheet: skeleton.worksheet,
+ unitId: 'unit-1',
+ }),
+ skeleton,
+ extension.parent
+ );
+ });
+
+ it('uses the main merged cell renderer once and respects out-of-diff rows', () => {
+ const extension = new Custom();
+ const ctx = createCtx();
+ const drawWith = vi.fn();
+ const cells = new Map<string, any>([
+ ['1,0', { customRender: [{ zIndex: 1, drawWith }] }],
+ ['1,1', { customRender: [{ zIndex: 1, drawWith: vi.fn() }] }],
+ ]);
+ const mergeInfo = { startRow: 1, endRow: 1, startColumn: 0, endColumn: 1 };
+ const skeleton = createSkeleton({
+ cells,
+ primary: (row, col) => row === 1 && (col === 0 || col === 1)
+ ? createCellWithCoord(row, col, {
+ isMerged: col === 1,
+ isMergedMainCell: col === 0,
+ mergeInfo,
+ })
+ : createCellWithCoord(row, col),
+ });
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, skeleton, [
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 },
+ ]);
+ expect(drawWith).not.toHaveBeenCalled();
+
+ extension.draw(ctx, { scaleX: 1, scaleY: 1 }, skeleton, [
+ { startRow: 1, endRow: 1, startColumn: 0, endColumn: 1 },
+ ]);
+
+ expect(drawWith).toHaveBeenCalledTimes(1);
+ expect(skeleton.getCellWithCoordByIndex).toHaveBeenCalledWith(1, 0, false);
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/sheet-extension.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/sheet-extension.spec.ts
new file mode 100644
index 0000000000..fbf7ccfb59
--- /dev/null
+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/sheet-extension.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 { describe, expect, it } from 'vitest';
+import { SHEET_EXTENSION_TYPE, SheetExtension } from '../sheet-extension';
+
+describe('sheet extension range helpers', () => {
+ it('checks cell, row and column diff intersections', () => {
+ const extension = new SheetExtension();
+ const diffRanges = [
+ { startRow: 2, endRow: 4, startColumn: 3, endColumn: 5 },
+ ];
+
+ expect(extension.type).toBe(SHEET_EXTENSION_TYPE.GRID);
+ expect(extension.isRenderDiffRangesByCell({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 })).toBe(true);
+ expect(extension.isRenderDiffRangesByCell({ startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 }, diffRanges)).toBe(true);
+ expect(extension.isRenderDiffRangesByCell({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }, diffRanges)).toBe(false);
+
+ expect(extension.isRenderDiffRangesByColumn(0, 1)).toBe(true);
+ expect(extension.isRenderDiffRangesByColumn(4, 6, diffRanges)).toBe(true);
+ expect(extension.isRenderDiffRangesByColumn(0, 1, diffRanges)).toBe(false);
+
+ expect(extension.isRenderDiffRangesByRow(0, 1)).toBe(true);
+ expect(extension.isRenderDiffRangesByRow(4, 6, diffRanges)).toBe(true);
+ expect(extension.isRenderDiffRangesByRow(0, 1, diffRanges)).toBe(false);
+ });
+
+ it('checks whether row ranges overlap the current view ranges', () => {
+ const extension = new SheetExtension();
+ const viewRanges = [
+ { startRow: 5, endRow: 8, startColumn: 0, endColumn: 2 },
+ ];
+
+ expect(extension.isRowInRanges(1, 2)).toBe(true);
+ expect(extension.isRowInRanges(5, 5, viewRanges)).toBe(true);
+ expect(extension.isRowInRanges(8, 10, viewRanges)).toBe(true);
+ expect(extension.isRowInRanges(4, 9, viewRanges)).toBe(true);
+ expect(extension.isRowInRanges(1, 4, viewRanges)).toBe(false);
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/watermark/__tests__/watermark-layer.spec.ts b/packages/engine-render/src/components/sheets/watermark/__tests__/watermark-layer.spec.ts
new file mode 100644
index 0000000000..0a33ea8cbd
--- /dev/null
+++ b/packages/engine-render/src/components/sheets/watermark/__tests__/watermark-layer.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 { beforeEach, describe, expect, it, vi } from 'vitest';
+import { IWatermarkTypeEnum } from '../type';
+import { WatermarkLayer } from '../watermark-layer';
+
+const renderWatermarkMock = vi.fn();
+
+vi.mock('../util', () => ({
+ renderWatermark: (...args: unknown[]) => renderWatermarkMock(...args),
+}));
+
+function createScene() {
+ return {
+ getViewports: vi.fn(() => []),
+ getParent: vi.fn(() => ({ classType: 'test-parent' })),
+ getEngine: vi.fn(() => null),
+ };
+}
+
+function createCtx(id = 'main') {
+ return {
+ getId: vi.fn(() => id),
+ save: vi.fn(),
+ restore: vi.fn(),
+ } as any;
+}
+
+describe('WatermarkLayer', () => {
+ beforeEach(() => {
+ renderWatermarkMock.mockClear();
+ });
+
+ it('renders configured text watermark with the latest user info', () => {
+ const layer = new WatermarkLayer(createScene() as never);
+ const config = {
+ type: IWatermarkTypeEnum.Text,
+ config: {
+ text: {
+ x: 1,
+ y: 2,
+ repeat: false,
+ spacingX: 0,
+ spacingY: 0,
+ rotate: 0,
+ opacity: 1,
+ content: 'confidential',
+ fontSize: 12,
+ color: '#000',
+ bold: false,
+ italic: false,
+ direction: 'inherit' as const,
+ },
+ },
+ };
+ const user = { name: 'Alice' };
+ const ctx = createCtx();
+
+ layer.updateConfig(config, user as never);
+ layer.render(ctx);
+
+ expect(renderWatermarkMock).toHaveBeenCalledWith(ctx, config, undefined, user);
+ });
+
+ it('creates an image element for image watermark config before rendering', () => {
+ const layer = new WatermarkLayer(createScene() as never);
+ const config = {
+ type: IWatermarkTypeEnum.Image,
+ config: {
+ image: {
+ x: 0,
+ y: 0,
+ repeat: false,
+ spacingX: 0,
+ spacingY: 0,
+ rotate: 0,
+ opacity: 1,
+ url: 'https://example.com/watermark.png',
+ width: 80,
+ height: 40,
+ maintainAspectRatio: true,
+ originRatio: 2,
+ },
+ },
+ };
+ const ctx = createCtx();
+
+ layer.updateConfig(config);
+ layer.render(ctx);
+
+ const image = renderWatermarkMock.mock.calls[0][2] as HTMLImageElement;
+ expect(image).toBeInstanceOf(Image);
+ expect(image.src).toContain('https://example.com/watermark.png');
+ });
+
+ it('does not render watermark without config or a valid rendering context id', () => {
+ const layer = new WatermarkLayer(createScene() as never);
+
+ layer.render(createCtx(''));
+ expect(renderWatermarkMock).not.toHaveBeenCalled();
+
+ layer.updateConfig({
+ type: IWatermarkTypeEnum.Text,
+ config: {
+ text: {
+ x: 0,
+ y: 0,
+ repeat: false,
+ spacingX: 0,
+ spacingY: 0,
+ rotate: 0,
+ opacity: 1,
+ content: 'draft',
+ fontSize: 12,
+ color: '#000',
+ bold: false,
+ italic: false,
+ direction: 'inherit',
+ },
+ },
+ });
+ layer.render(createCtx(''));
+
+ expect(renderWatermarkMock).not.toHaveBeenCalled();
+ });
+});
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
index 6e55f151b2..bcd988b37b 100644
--- a/packages/engine-render/src/render-manager/__tests__/render-unit.spec.ts
+++ b/packages/engine-render/src/render-manager/__tests__/render-unit.spec.ts
@@ -39,7 +39,7 @@ class RenderModuleB extends Disposable implements IRenderModule {
}
}
-function createRenderUnit() {
+function createRenderUnit(createUnitOptions?: any) {
const parentInjector = new Injector();
const unit = {
getUnitId: () => 'unit-1',
@@ -51,6 +51,7 @@ function createRenderUnit() {
scene: {} as any,
isMainScene: true,
unit,
+ createUnitOptions,
});
return renderUnit;
@@ -98,4 +99,39 @@ describe('render unit', () => {
renderUnit.dispose();
expect(renderUnit.components.size).toBe(0);
});
+
+ it('exposes mutable render context state for scene lifecycle coordination', () => {
+ const renderUnit = createRenderUnit({ makeCurrent: false });
+ const states: boolean[] = [];
+ const sub = renderUnit.activated$.subscribe((v) => states.push(v));
+ const nextEngine = { name: 'engine-2' } as any;
+ const nextScene = { name: 'scene-2' } as any;
+ const component = { key: 'main-component' } as any;
+
+ expect(states).toEqual([false]);
+ expect(renderUnit.isMainScene).toBe(true);
+
+ renderUnit.activate();
+ renderUnit.isMainScene = false;
+ renderUnit.engine = nextEngine;
+ renderUnit.scene = nextScene;
+ renderUnit.mainComponent = component;
+ renderUnit.components.set('selection', component);
+
+ const context = renderUnit.getRenderContext();
+ expect(states).toEqual([false, true]);
+ expect(renderUnit.isMainScene).toBe(false);
+ expect(context.isMainScene).toBe(false);
+ expect(renderUnit.engine).toBe(nextEngine);
+ expect(context.engine).toBe(nextEngine);
+ expect(renderUnit.scene).toBe(nextScene);
+ expect(context.scene).toBe(nextScene);
+ expect(renderUnit.mainComponent).toBe(component);
+ expect(context.components.get('selection')).toBe(component);
+ expect(context.unitId).toBe('unit-1');
+
+ sub.unsubscribe();
+ renderUnit.dispose();
+ expect(renderUnit.isDisposed()).toBe(true);
+ });
});
diff --git a/packages/engine-render/src/shape/__tests__/basic-shapes-extra.spec.ts b/packages/engine-render/src/shape/__tests__/basic-shapes-extra.spec.ts
new file mode 100644
index 0000000000..eae1062cf1
--- /dev/null
+++ b/packages/engine-render/src/shape/__tests__/basic-shapes-extra.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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { ObjectType } from '../../base-object';
+import { getOffsetRectForDom, transformBoundingCoord } from '../../basics/position';
+import { Vector2 } from '../../basics/vector2';
+import { CustomObject } from '../../custom/custom-object';
+import { CheckboxShape } from '../checkbox';
+import { Circle } from '../circle';
+import { ListItem } from '../dropdown-item';
+import { Rect } from '../rect';
+
+function createShapeCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ transform: vi.fn(),
+ translate: vi.fn(),
+ scale: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ arc: vi.fn(),
+ rect: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ setLineDash: vi.fn(),
+ fillStyle: '#fff',
+ strokeStyle: '#000',
+ lineWidth: 1,
+ lineCap: 'round',
+ lineJoin: 'round',
+ lineDashOffset: 0,
+ miterLimit: 10,
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ shadowColor: '',
+ shadowBlur: 0,
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ } as any;
+}
+
+describe('basic shape and position helpers', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('draws and serializes circle state while keeping resize square', () => {
+ const circle = new Circle('circle-1', {
+ left: 8,
+ top: 12,
+ radius: 18,
+ fill: '#00aaff',
+ stroke: '#003355',
+ strokeWidth: 2,
+ strokeDashArray: [3, 2],
+ });
+ const ctx = createShapeCtx();
+
+ expect(circle.radius).toBe(18);
+ expect(circle.width).toBe(36);
+ expect(circle.height).toBe(36);
+
+ Circle.drawWith(ctx, circle);
+ expect(ctx.setLineDash).toHaveBeenCalledWith([3, 2]);
+ expect(ctx.arc).toHaveBeenCalledWith(18, 18, 18, 0, Math.PI * 2, false);
+ expect(ctx.fill).toHaveBeenCalled();
+ expect(ctx.stroke).toHaveBeenCalled();
+ circle.render(ctx);
+ expect(ctx.transform).toHaveBeenCalled();
+
+ circle.transformByState({ width: 30, height: 60 });
+ expect(circle.radius).toBe(15);
+ expect(circle.width).toBe(30);
+ expect(circle.height).toBe(30);
+ expect(circle.objectType).toBe(ObjectType.CIRCLE);
+ expect(circle.toJson()).toMatchObject({ radius: 15 });
+ });
+
+ it('draws checked and unchecked checkbox graphics with scaled business dimensions', () => {
+ const checked = new CheckboxShape('check-1', {
+ left: 4,
+ top: 6,
+ width: 24,
+ height: 20,
+ fill: '#2f56ef',
+ checked: true,
+ });
+ const checkedCtx = createShapeCtx();
+
+ CheckboxShape.drawWith(checkedCtx, checked);
+ expect(checked.checked).toBe(true);
+ expect(checkedCtx.translate).toHaveBeenCalledWith(4, 6);
+ expect(checkedCtx.scale).toHaveBeenCalledWith(1.5, 1.25);
+ expect(checkedCtx.fill).toHaveBeenCalledWith(expect.any(Path2D), 'evenodd');
+ checked.render(checkedCtx);
+ expect(checkedCtx.transform).toHaveBeenCalled();
+ expect(checked.toJson()).toMatchObject({ checked: true });
+
+ const unchecked = new CheckboxShape('check-2', {
+ width: 16,
+ height: 16,
+ checked: false,
+ });
+ const uncheckedCtx = createShapeCtx();
+ CheckboxShape.drawWith(uncheckedCtx, unchecked);
+ expect(unchecked.checked).toBe(false);
+ expect(uncheckedCtx.fill).toHaveBeenCalledWith(expect.any(Path2D), 'evenodd');
+ expect(unchecked.toJson()).not.toHaveProperty('checked');
+ });
+
+ it('draws a plain rect using its business bounds', () => {
+ const ctx = createShapeCtx();
+
+ Rect.drawWith(ctx, {
+ width: 80,
+ height: 32,
+ fill: '#ffffff',
+ });
+
+ expect(ctx.save).toHaveBeenCalled();
+ expect(ctx.rect).toHaveBeenCalledWith(0, 0, 80, 32);
+ expect(ctx.arc).not.toHaveBeenCalled();
+ expect(ctx.fill).toHaveBeenCalled();
+ expect(ctx.restore).toHaveBeenCalled();
+ });
+
+ it('draws a rounded visual rect centered in the interaction bounds', () => {
+ const rect = new Rect('rect-visual', {
+ width: 80,
+ height: 40,
+ radius: 12,
+ visualWidth: 60,
+ visualHeight: 20,
+ fill: '#ddeeff',
+ stroke: '#225588',
+ strokeWidth: 2,
+ strokeDashArray: [4, 2],
+ paintFirst: 'stroke',
+ });
+ const ctx = createShapeCtx();
+
+ expect(rect.radius).toBe(12);
+ expect(rect.visualWidth).toBe(60);
+ expect(rect.visualHeight).toBe(20);
+
+ rect.setOpacity(0.4);
+ rect.setObjectType(ObjectType.SHAPE);
+ expect(rect.opacity).toBe(0.4);
+ expect(rect.objectType).toBe(ObjectType.SHAPE);
+
+ Rect.drawWith(ctx, {
+ width: rect.width,
+ height: rect.height,
+ radius: rect.radius,
+ visualWidth: rect.visualWidth ?? undefined,
+ visualHeight: rect.visualHeight ?? undefined,
+ fill: rect.fill,
+ stroke: rect.stroke,
+ strokeWidth: rect.strokeWidth,
+ strokeDashArray: rect.strokeDashArray,
+ paintFirst: rect.paintFirst,
+ });
+
+ expect(ctx.setLineDash).toHaveBeenCalledWith([4, 2]);
+ expect(ctx.translate).toHaveBeenCalledWith(0, 10);
+ expect(ctx.translate).toHaveBeenCalledWith(10, 0);
+ expect(ctx.moveTo).toHaveBeenCalledWith(10, 0);
+ expect(ctx.lineTo).toHaveBeenCalledWith(50, 0);
+ expect(ctx.arc).toHaveBeenCalledTimes(4);
+ expect(ctx.arc).toHaveBeenNthCalledWith(1, 50, 10, 10, (Math.PI * 3) / 2, 0, false);
+ expect(ctx.arc).toHaveBeenNthCalledWith(4, 10, 10, 10, Math.PI, (Math.PI * 3) / 2, false);
+ expect(ctx.stroke.mock.invocationCallOrder[0]).toBeLessThan(ctx.fill.mock.invocationCallOrder[0]);
+ expect(rect.toJson()).toMatchObject({
+ width: 80,
+ height: 40,
+ radius: 12,
+ strokeDashArray: [4, 2],
+ });
+ });
+
+ it('keeps list item drawing isolated from the surrounding canvas state', () => {
+ const ctx = createShapeCtx();
+
+ ListItem.drawWith(ctx, {
+ text: 1,
+ fontString: '12px Arial',
+ fontFamily: 'Arial',
+ fontSize: '12',
+ } as any);
+
+ expect(ctx.save).toHaveBeenCalledBefore(ctx.restore);
+ expect(ctx.restore).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders a custom object callback only when visible and in viewport', () => {
+ const render = vi.fn();
+ const hit = vi.fn((coord: Vector2) => coord.x === 5 && coord.y === 6);
+ const object = new CustomObject('custom-1', render, hit);
+ object.transformByState({ left: 10, top: 12, width: 40, height: 30 });
+ const ctx = createShapeCtx();
+
+ object.render(ctx, { viewBound: { left: 0, top: 0, right: 120, bottom: 80 } } as any);
+ expect(ctx.transform).toHaveBeenCalled();
+ expect(render).toHaveBeenCalledWith(ctx);
+ expect(object.isHit(Vector2.FromArray([5, 6]))).toBe(true);
+ expect(hit).toHaveBeenCalled();
+ expect(object.toJson()).toMatchObject({ width: 40, height: 30, left: 10, top: 12 });
+
+ const beforeCalls = render.mock.calls.length;
+ object.render(ctx, { viewBound: { left: 200, top: 200, right: 260, bottom: 260 } } as any);
+ expect(render).toHaveBeenCalledTimes(beforeCalls);
+
+ object.hide();
+ object.render(ctx);
+ expect(render).toHaveBeenCalledTimes(beforeCalls);
+
+ const defaultObject = new CustomObject('custom-default');
+ defaultObject.transformByState({ width: 12, height: 14 });
+ defaultObject.render(ctx);
+ expect(ctx.save).toHaveBeenCalled();
+ });
+
+ it('computes DOM offsets and transforms world bounds into object coordinates', () => {
+ Object.defineProperty(window, 'pageYOffset', { value: 30, configurable: true });
+ Object.defineProperty(window, 'pageXOffset', { value: 40, configurable: true });
+ Object.defineProperty(document.documentElement, 'clientTop', { value: 2, configurable: true });
+ Object.defineProperty(document.documentElement, 'clientLeft', { value: 4, configurable: true });
+
+ const element = document.createElement('div');
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
+ top: 10,
+ left: 20,
+ right: 70,
+ bottom: 50,
+ width: 50,
+ height: 40,
+ x: 20,
+ y: 10,
+ toJSON: () => ({}),
+ });
+
+ expect(getOffsetRectForDom(element)).toEqual({
+ top: 38,
+ left: 56,
+ });
+
+ const rect = new Rect('rect-1', {
+ left: 10,
+ top: 20,
+ width: 100,
+ height: 50,
+ });
+ const transformed = transformBoundingCoord(rect, {
+ tl: Vector2.FromArray([10, 20]),
+ tr: Vector2.FromArray([60, 20]),
+ bl: Vector2.FromArray([10, 70]),
+ br: Vector2.FromArray([60, 70]),
+ dx: 50,
+ dy: 50,
+ });
+
+ expect(transformed).toEqual({
+ minX: 0,
+ maxX: 50,
+ minY: 0,
+ maxY: 50,
+ });
+ });
+});
diff --git a/packages/engine-render/src/shape/__tests__/image-branches.spec.ts b/packages/engine-render/src/shape/__tests__/image-branches.spec.ts
new file mode 100644
index 0000000000..6d26ed0cb5
--- /dev/null
+++ b/packages/engine-render/src/shape/__tests__/image-branches.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 { describe, expect, it, vi } from 'vitest';
+import { Image } from '../image';
+
+function createNativeImage(width = 120, height = 80) {
+ const img = document.createElement('img');
+ Object.defineProperty(img, 'width', { value: width, configurable: true });
+ Object.defineProperty(img, 'height', { value: height, configurable: true });
+ Object.defineProperty(img, 'complete', { value: true, configurable: true });
+ return img;
+}
+
+function createCtxMock() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ rect: vi.fn(),
+ clip: vi.fn(),
+ drawImage: vi.fn(),
+ transform: vi.fn(),
+ translate: vi.fn(),
+ globalAlpha: 1,
+ } as any;
+}
+
+describe('image branch coverage', () => {
+ it('supports missing native image, geometry setters and image load fallback branches', () => {
+ const success = vi.fn();
+ const image = new Image('img4', {
+ url: 'https://example.com/ok.png',
+ left: 0,
+ top: 0,
+ width: 80,
+ height: 40,
+ success,
+ });
+ vi.spyOn(image, 'getEngine').mockReturnValue({ activeScene: { onFileLoaded$: { emitEvent: vi.fn() } } } as any);
+ image.getNative()!.onload!(new Event('load'));
+ expect(success).toHaveBeenCalled();
+
+ image.getNative()!.onerror!(new Event('error'));
+ expect(image.getNative()!.src).toContain('data:image/svg+xml;base64');
+
+ image.setClipService(null);
+ expect(image.getClipService()).toBeNull();
+ image.setPrstGeom('ellipse');
+ image.setPrstGeomAdjValues({ adj: 1 });
+ expect(image.prstGeom).toBe('ellipse');
+ expect(image.prstGeomAdjValues).toEqual({ adj: 1 });
+
+ const noNative = new Image('img5', {
+ left: 3,
+ top: 4,
+ width: 30,
+ height: 20,
+ });
+ expect(noNative.getNativeSize()).toEqual({ width: 30, height: 20 });
+ noNative.resetSize();
+ noNative.changeSource('https://example.com/later.png');
+ noNative.getNative()!.onload!(new Event('load'));
+ expect(noNative.getNative()).toBeTruthy();
+ noNative.openRenderByCropper();
+ expect(noNative.calculateTransformWithSrcRect()).toEqual({
+ left: 3,
+ top: 4,
+ width: 30,
+ height: 20,
+ angle: 0,
+ });
+ });
+
+ it('clips preset geometry and handles render visibility and bounds branches', () => {
+ const image = new Image('img6', {
+ image: createNativeImage(100, 60),
+ left: 10,
+ top: 20,
+ width: 100,
+ height: 60,
+ srcRect: { left: 10, top: 5, right: 20, bottom: 15 },
+ });
+ image.setPrstGeom('roundRect');
+ image.setPrstGeomAdjValues({ r: 2 });
+ image.setClipService({
+ applyShapeClip: vi.fn(() => ({ left: -60, top: -40, width: 130, height: 90 })),
+ } as any);
+
+ const ctx = createCtxMock();
+ image.render(ctx, { viewBound: { left: 0, top: 0, right: 200, bottom: 200 } } as any);
+ expect(ctx.translate).toHaveBeenCalledWith(-50, -30);
+ expect(ctx.drawImage).toHaveBeenCalledWith(expect.any(HTMLImageElement), -73, -47.5, 169, 120);
+
+ const clipWithoutBounds = new Image('img7', {
+ image: createNativeImage(20, 20),
+ left: 0,
+ top: 0,
+ width: 20,
+ height: 20,
+ });
+ clipWithoutBounds.setPrstGeom('custom');
+ clipWithoutBounds.setClipService({ applyShapeClip: vi.fn(() => null) } as any);
+ const noBoundsCtx = createCtxMock();
+ clipWithoutBounds.render(noBoundsCtx);
+ expect(noBoundsCtx.drawImage).toHaveBeenCalledWith(expect.any(HTMLImageElement), -10, -10, 20, 20);
+
+ image.hide();
+ expect(image.render(createCtxMock())).toBe(image);
+
+ image.show();
+ expect(image.render(createCtxMock(), { viewBound: { left: 500, top: 500, right: 600, bottom: 600 } } as any)).toBe(image);
+ });
+});
diff --git a/packages/engine-render/src/shape/__tests__/scroll-bar.spec.ts b/packages/engine-render/src/shape/__tests__/scroll-bar.spec.ts
new file mode 100644
index 0000000000..97b4b31c59
--- /dev/null
+++ b/packages/engine-render/src/shape/__tests__/scroll-bar.spec.ts
@@ -0,0 +1,191 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Engine } from '../../engine';
+import { MAIN_VIEW_PORT_KEY, Scene } from '../../scene';
+import { Viewport } from '../../viewport';
+import { ScrollBar } from '../scroll-bar';
+
+function createRenderContext() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ transform: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ rect: vi.fn(),
+ roundRect: vi.fn(),
+ setLineDash: vi.fn(),
+ translate: vi.fn(),
+ scale: vi.fn(),
+ rotate: vi.fn(),
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 0,
+ globalAlpha: 1,
+ } as any;
+}
+
+describe('ScrollBar', () => {
+ let restoreEnv: () => void;
+ let container: HTMLDivElement;
+ let engine: Engine;
+ let scene: Scene;
+ let viewport: Viewport;
+
+ beforeEach(() => {
+ restoreEnv = setupRenderTestEnv().restore;
+ container = document.createElement('div');
+ container.style.width = '400px';
+ container.style.height = '260px';
+ document.body.appendChild(container);
+
+ engine = new Engine('scrollbar-engine', { elementWidth: 400, elementHeight: 260, dpr: 1 });
+ engine.mount(container, false);
+ scene = new Scene('scrollbar-scene', engine);
+ scene.transformByState({ width: 1000, height: 800, scaleX: 1, scaleY: 1 });
+ viewport = new Viewport(MAIN_VIEW_PORT_KEY, scene, {
+ left: 0,
+ top: 0,
+ width: 160,
+ height: 120,
+ active: true,
+ allowCache: true,
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ viewport?.dispose();
+ scene?.dispose();
+ engine?.dispose();
+ restoreEnv?.();
+ container?.remove();
+ });
+
+ it('resizes visible thumbs, maps scroll ratios and renders both axes', () => {
+ const scrollBar = new ScrollBar(viewport, {
+ mainScene: scene,
+ barSize: 12,
+ barBorder: 2,
+ thumbMargin: 2,
+ minThumbSizeH: 20,
+ minThumbSizeV: 18,
+ });
+ const ctx = createRenderContext();
+
+ scrollBar.resize(160, 120, 640, 480);
+ viewport.scrollToBarPos({ x: 12, y: 10 });
+ scrollBar.render(ctx, 4, 6);
+
+ expect(scrollBar.hasHorizonThumb()).toBe(true);
+ expect(scrollBar.hasVerticalThumb()).toBe(true);
+ expect(scrollBar.limitX).toBeGreaterThan(0);
+ expect(scrollBar.limitY).toBeGreaterThan(0);
+ expect(scrollBar.ratioScrollX).toBeGreaterThan(0);
+ expect(scrollBar.ratioScrollY).toBeGreaterThan(0);
+ expect(scrollBar.scrollHorizonThumbThickness).toBe(8);
+ expect(scrollBar.scrollVerticalThumbThickness).toBe(8);
+ expect(ctx.transform).toHaveBeenCalled();
+ expect(ctx.restore).toHaveBeenCalled();
+
+ scrollBar.dispose();
+ expect(viewport.getScrollBar()).toBeNull();
+ });
+
+ it('hides thumbs when content fits inside the viewport', () => {
+ const scrollBar = ScrollBar.attachTo(viewport, {
+ enableHorizontal: true,
+ enableVertical: true,
+ });
+
+ scrollBar.resize(160, 120, 100, 80);
+
+ expect(scrollBar.hasHorizonThumb()).toBe(false);
+ expect(scrollBar.hasVerticalThumb()).toBe(false);
+ expect(scrollBar.limitX).toBe(0);
+ expect(scrollBar.limitY).toBe(0);
+
+ scrollBar.dispose();
+ });
+
+ it('uses track clicks and thumb dragging to update viewport scroll', () => {
+ const scrollBar = new ScrollBar(viewport, { mainScene: scene });
+ const scrollToBarPos = vi.spyOn(viewport, 'scrollToBarPos');
+ const scrollByBarDeltaValue = vi.spyOn(viewport, 'scrollByBarDeltaValue');
+ const setCapture = vi.spyOn(engine, 'setCapture').mockImplementation(() => {});
+
+ scrollBar.resize(160, 120, 640, 480);
+ scrollBar.horizonScrollTrack!.onPointerDown$.emitEvent({ offsetX: 80, offsetY: 115 } as any);
+ scrollBar.verticalScrollTrack!.onPointerDown$.emitEvent({ offsetX: 155, offsetY: 70 } as any);
+
+ scrollBar.horizonThumbRect!.onPointerEnter$.emitEvent({} as any);
+ scrollBar.horizonThumbRect!.onPointerDown$.emitEvent({ offsetX: 20, offsetY: 112 } as any);
+ scene.onPointerMove$.emitEvent({ offsetX: 36, offsetY: 112 } as any);
+ scene.onPointerUp$.emitEvent({ offsetX: 36, offsetY: 112 } as any);
+ scrollBar.horizonThumbRect!.onPointerLeave$.emitEvent({} as any);
+
+ scrollBar.verticalThumbRect!.onPointerEnter$.emitEvent({} as any);
+ scrollBar.verticalThumbRect!.onPointerDown$.emitEvent({ offsetX: 154, offsetY: 24 } as any);
+ scene.onPointerMove$.emitEvent({ offsetX: 154, offsetY: 48 } as any);
+ scene.onPointerUp$.emitEvent({ offsetX: 154, offsetY: 48 } as any);
+ scrollBar.verticalThumbRect!.onPointerLeave$.emitEvent({} as any);
+
+ expect(scrollToBarPos).toHaveBeenCalledWith({ x: expect.any(Number) });
+ expect(scrollToBarPos).toHaveBeenCalledWith({ y: expect.any(Number) });
+ expect(scrollByBarDeltaValue).toHaveBeenCalledWith({ x: 16 });
+ expect(scrollByBarDeltaValue).toHaveBeenCalledWith({ y: 24 });
+ expect(setCapture).toHaveBeenCalled();
+
+ scrollBar.dispose();
+ });
+
+ it('supports single-axis scrollbars and no-op resize guards', () => {
+ const horizontalOnly = new ScrollBar(viewport, {
+ enableHorizontal: true,
+ enableVertical: false,
+ barSize: 10,
+ });
+
+ horizontalOnly.resize();
+ expect(horizontalOnly.verticalThumbRect).toBeUndefined();
+ expect(horizontalOnly.placeholderBarRect).toBeUndefined();
+ expect(horizontalOnly.enableVertical).toBe(false);
+ expect(horizontalOnly.ratioScrollY).toBe(1);
+
+ horizontalOnly.resize(120, 80, 400, 80);
+ expect(horizontalOnly.hasHorizonThumb()).toBe(true);
+ horizontalOnly.dispose();
+
+ const verticalOnly = new ScrollBar(viewport, {
+ enableHorizontal: false,
+ enableVertical: true,
+ });
+ verticalOnly.resize(120, 80, 80, 400);
+ expect(verticalOnly.horizonThumbRect).toBeUndefined();
+ expect(verticalOnly.enableHorizontal).toBe(false);
+ expect(verticalOnly.ratioScrollX).toBe(1);
+ expect(verticalOnly.hasVerticalThumb()).toBe(true);
+ verticalOnly.dispose();
+ });
+});
diff --git a/packages/network/src/facade/__tests__/f-network.spec.ts b/packages/network/src/facade/__tests__/f-network.spec.ts
index f9ccb574f8..565c35805e 100644
--- a/packages/network/src/facade/__tests__/f-network.spec.ts
+++ b/packages/network/src/facade/__tests__/f-network.spec.ts
@@ -27,7 +27,7 @@ import {
} from '@univerjs/network';
import { firstValueFrom } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { MockHTTPImplementation } from '../../services/http/__testing__/http-testing-utils';
+import { MockHTTPImplementation } from '../../services/http/__tests__/http-testing-utils';
import '@univerjs/network/facade';
class FakeWebSocket {
diff --git a/packages/network/src/services/http/__testing__/headers.spec.ts b/packages/network/src/services/http/__tests__/headers.spec.ts
similarity index 100%
rename from packages/network/src/services/http/__testing__/headers.spec.ts
rename to packages/network/src/services/http/__tests__/headers.spec.ts
diff --git a/packages/network/src/services/http/__testing__/http-params.spec.ts b/packages/network/src/services/http/__tests__/http-params.spec.ts
similarity index 100%
rename from packages/network/src/services/http/__testing__/http-params.spec.ts
rename to packages/network/src/services/http/__tests__/http-params.spec.ts
diff --git a/packages/network/src/services/http/__testing__/http-testing-utils.ts b/packages/network/src/services/http/__tests__/http-testing-utils.ts
similarity index 100%
rename from packages/network/src/services/http/__testing__/http-testing-utils.ts
rename to packages/network/src/services/http/__tests__/http-testing-utils.ts
diff --git a/packages/network/src/services/http/__testing__/http.service.spec.ts b/packages/network/src/services/http/__tests__/http.service.spec.ts
similarity index 100%
rename from packages/network/src/services/http/__testing__/http.service.spec.ts
rename to packages/network/src/services/http/__tests__/http.service.spec.ts
diff --git a/packages/network/src/services/http/__testing__/request.spec.ts b/packages/network/src/services/http/__tests__/request.spec.ts
similarity index 100%
rename from packages/network/src/services/http/__testing__/request.spec.ts
rename to packages/network/src/services/http/__tests__/request.spec.ts
diff --git a/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.ts
index 8ac074a485..0f23f38841 100644
--- a/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/auth-interceptor.spec.ts
@@ -15,9 +15,9 @@
*/
import type { Injector } from '@univerjs/core';
-import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import type { MockHTTPImplementation } from '../../__tests__/http-testing-utils';
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
-import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
+import { createHTTPTestBed } from '../../__tests__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
diff --git a/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
index d846fc7ef0..9e36cc3cdf 100644
--- a/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
@@ -15,9 +15,9 @@
*/
import type { Injector } from '@univerjs/core';
-import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import type { MockHTTPImplementation } from '../../__tests__/http-testing-utils';
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
-import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
+import { createHTTPTestBed } from '../../__tests__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
diff --git a/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
index d1e5957390..7f1b15f3ba 100644
--- a/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
@@ -15,9 +15,9 @@
*/
import type { Injector } from '@univerjs/core';
-import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import type { MockHTTPImplementation } from '../../__tests__/http-testing-utils';
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
-import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
+import { createHTTPTestBed } from '../../__tests__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
diff --git a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
index e2551bbb6d..f2b60d533a 100644
--- a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
@@ -15,10 +15,10 @@
*/
import type { Injector } from '@univerjs/core';
-import type { MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import type { MockHTTPImplementation } from '../../__tests__/http-testing-utils';
import { awaitTime } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { createHTTPTestBed } from '../../__testing__/http-testing-utils';
+import { createHTTPTestBed } from '../../__tests__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.permission.controller.spec.ts b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.permission.controller.spec.ts
new file mode 100644
index 0000000000..9698fc33a8
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.permission.controller.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 { AddCfCommand } from '@univerjs/sheets-conditional-formatting';
+import { describe, expect, it, vi } from 'vitest';
+import { ConditionalFormattingPermissionController } from '../cf.permission.controller';
+
+describe('ConditionalFormattingPermissionController', () => {
+ it('blocks adding conditional formatting when target ranges cannot edit cell style', () => {
+ let beforeCommandHandler: ((command: { id: string; params?: unknown }) => void) | undefined;
+ const permissionCheck = {
+ permissionCheckWithRanges: vi.fn(() => false),
+ blockExecuteWithoutPermission: vi.fn(),
+ };
+ const controller = new ConditionalFormattingPermissionController(
+ { t: (key: string) => key } as never,
+ {
+ beforeCommandExecuted: vi.fn((handler) => {
+ beforeCommandHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ permissionCheck as never
+ );
+ const ranges = [{ startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 }];
+
+ beforeCommandHandler?.({
+ id: AddCfCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rule: { ranges },
+ },
+ });
+
+ expect(permissionCheck.permissionCheckWithRanges).toHaveBeenCalledWith(expect.objectContaining({
+ workbookTypes: expect.any(Array),
+ worksheetTypes: expect.any(Array),
+ rangeTypes: expect.any(Array),
+ }), ranges, 'unit-1', 'sheet-1');
+ expect(permissionCheck.blockExecuteWithoutPermission).toHaveBeenCalledWith('sheets-conditional-formatting-ui.permission.dialog.setStyleErr');
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.render.controller.spec.ts b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.render.controller.spec.ts
new file mode 100644
index 0000000000..ae26effe89
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.render.controller.spec.ts
@@ -0,0 +1,111 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { INTERCEPTOR_POINT } from '@univerjs/sheets';
+import { DEFAULT_PADDING, DEFAULT_WIDTH } from '@univerjs/sheets-conditional-formatting';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SheetsCfRenderController } from '../cf.render.controller';
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+function createController() {
+ let interceptor: any;
+ const ruleChange$ = new Subject<any>();
+ const markDirty$ = new Subject<any>();
+ const reCalculate = vi.fn();
+ const makeDirty = vi.fn();
+ const controller = new SheetsCfRenderController(
+ {
+ intercept: vi.fn((point, config) => {
+ expect(point).toBe(INTERCEPTOR_POINT.CELL_CONTENT);
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ {
+ composeStyle: vi.fn(() => ({
+ style: { bg: { rgb: '#00ff00' } },
+ isShowValue: false,
+ dataBar: { color: '#00f' },
+ iconSet: { icon: 'arrow-up' },
+ })),
+ } as never,
+ {
+ getCurrentUnitOfType: vi.fn(() => ({
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ })),
+ } as never,
+ {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => ({ reCalculate })),
+ mainComponent: { makeDirty },
+ })),
+ } as never,
+ { markDirty$ } as never,
+ { $ruleChange: ruleChange$ } as never
+ );
+
+ return { controller, interceptor: () => interceptor, ruleChange$, markDirty$, reCalculate, makeDirty };
+}
+
+describe('SheetsCfRenderController', () => {
+ it('composes conditional-formatting style, data bar and icon set into rendered cell data', () => {
+ const { controller, interceptor } = createController();
+ const rawCell = { v: 10, s: 'style-1' };
+
+ const result = interceptor().handler(rawCell, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 2,
+ rawData: rawCell,
+ workbook: {
+ getStyles: vi.fn(() => ({
+ get: vi.fn(() => ({ fs: 12 })),
+ })),
+ },
+ }, (cell: unknown) => cell);
+
+ expect(result).not.toBe(rawCell);
+ expect(result.s).toEqual({ fs: 12, bg: { rgb: '#00ff00' } });
+ expect(result.fontRenderExtension).toEqual({
+ isSkip: true,
+ leftOffset: DEFAULT_PADDING + DEFAULT_WIDTH,
+ });
+ expect(result.dataBar).toEqual({ color: '#00f' });
+ expect(result.iconSet).toEqual({ icon: 'arrow-up' });
+
+ controller.dispose();
+ });
+
+ it('marks the active sheet skeleton dirty when conditional formatting changes affect it', async () => {
+ vi.useFakeTimers();
+ const { controller, ruleChange$, markDirty$, reCalculate, makeDirty } = createController();
+
+ ruleChange$.next({ unitId: 'unit-1', subUnitId: 'sheet-1' });
+ markDirty$.next({ unitId: 'other-unit', subUnitId: 'sheet-1' });
+ await vi.advanceTimersByTimeAsync(20);
+
+ expect(reCalculate).toHaveBeenCalled();
+ expect(makeDirty).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx
new file mode 100644
index 0000000000..91c09eead5
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx
@@ -0,0 +1,465 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRange } from '@univerjs/core';
+import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
+import type { Root } from 'react-dom/client';
+import { BooleanNumber, createIdentifier, LocaleService, LocaleType } from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { AddCfCommand, CFNumberOperator, CFRuleType, CFSubRuleType, SetCfCommand } from '@univerjs/sheets-conditional-formatting';
+import { IMarkSelectionService } from '@univerjs/sheets-ui';
+import { IShortcutService, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createCfUiTestBed } from '../../__tests__/create-cf-ui-test-bed';
+import { ConditionalFormattingI18nController } from '../../controllers/cf.i18n.controller';
+import { ConditionFormattingPanel } from '../ConditionFormattingPanel';
+import { RuleEdit } from '../panel/RuleEdit';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const ACTIVE_RANGE: IRange = {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+};
+
+const IEditorService = createIdentifier<TestEditorService>('univer.editor.service');
+const IDescriptionService = createIdentifier<TestDescriptionService>('formula.description-service');
+
+class TestEditorService {
+ register() {
+ return { dispose() {} };
+ }
+
+ getEditor() {
+ return undefined;
+ }
+
+ getFocusId() {
+ return undefined;
+ }
+
+ focus(): void {}
+
+ blur(): void {}
+}
+
+class TestRenderManagerService {
+ getRenderById() {
+ return undefined;
+ }
+}
+
+class TestShortcutService {
+ registerShortcut() {
+ return { dispose() {} };
+ }
+}
+
+class TestMarkSelectionService {
+ addShape() {
+ return 'shape-id';
+ }
+
+ removeShape(): void {}
+}
+
+class TestDescriptionService {
+ hasDefinedNameDescription() {
+ return false;
+ }
+}
+
+function createNumberHighlightRule(cfId: string, value: number): IConditionFormattingRule {
+ return {
+ cfId,
+ ranges: [ACTIVE_RANGE],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value,
+ style: {
+ bl: BooleanNumber.TRUE,
+ },
+ },
+ };
+}
+
+function createPanelTestBed() {
+ const testBed = createCfUiTestBed();
+ testBed.injector.add([ConditionalFormattingI18nController]);
+ testBed.injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ testBed.injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ testBed.injector.add([IShortcutService, { useClass: TestShortcutService as never }]);
+ testBed.injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService as never }]);
+ testBed.injector.add([IDescriptionService, { useClass: TestDescriptionService as never }]);
+ testBed.injector.add([LexerTreeBuilder]);
+ testBed.commandService.registerCommand(AddCfCommand);
+ testBed.commandService.registerCommand(SetCfCommand);
+ testBed.commandService.registerCommand(SetWorksheetActiveOperation);
+ testBed.get(LocaleService).load({
+ [LocaleType.ZH_CN]: {
+ 'sheets-conditional-formatting-ui': {
+ panel: {
+ managerRuleSelect: 'Show {0}',
+ workSheet: 'Worksheet',
+ selectedRange: 'Selected range',
+ createRule: 'Create rule',
+ clear: 'Clear rules',
+ range: 'Range',
+ styleType: 'Style type',
+ styleRule: 'Style rule',
+ submit: 'Submit',
+ cancel: 'Cancel',
+ },
+ operator: {
+ containsText: 'Contains text',
+ notContainsText: 'Does not contain text',
+ beginsWith: 'Begins with',
+ endsWith: 'Ends with',
+ equal: 'Equals',
+ notEqual: 'Does not equal',
+ containsBlanks: 'Contains blanks',
+ notContainsBlanks: 'Does not contain blanks',
+ containsErrors: 'Contains errors',
+ notContainsErrors: 'Does not contain errors',
+ between: 'Between',
+ notBetween: 'Not between',
+ greaterThan: 'Greater than',
+ greaterThanOrEqual: 'Greater than or equal',
+ lessThan: 'Less than',
+ lessThanOrEqual: 'Less than or equal',
+ },
+ subRuleType: {
+ text: 'Text',
+ number: 'Number',
+ timePeriod: 'Date',
+ duplicateValues: 'Duplicate values',
+ uniqueValues: 'Unique values',
+ },
+ ruleType: {
+ highlightCell: 'Highlight cell',
+ },
+ preview: {
+ describe: {
+ greaterThan: 'Greater than {0}',
+ containsText: 'Contains {0}',
+ },
+ },
+ errorMessage: {
+ notBlank: 'Required',
+ rangeError: 'Select a range',
+ },
+ },
+ },
+ });
+ testBed.setSelection(ACTIVE_RANGE);
+
+ return testBed;
+}
+
+function writeInput(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+function clickButton(container: HTMLElement, text: string) {
+ const button = Array.from(container.querySelectorAll('button'))
+ .find((item) => item.textContent === text) as HTMLButtonElement | undefined;
+ if (!button) {
+ throw new Error(`Button was not rendered: ${text}`);
+ }
+ button.click();
+}
+
+describe('ConditionFormattingPanel and RuleEdit', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createPanelTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('adds a text highlight rule to the active selection from the rule editor', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ let cancelRequests = 0;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleEdit
+ onCancel={() => {
+ cancelRequests += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const textInput = container.querySelector('input[type="text"]') as HTMLInputElement;
+
+ await act(async () => {
+ writeInput(textInput, 'overdue');
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ clickButton(container!, 'Submit');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([
+ expect.objectContaining({
+ ranges: [expect.objectContaining(ACTIVE_RANGE)],
+ stopIfTrue: false,
+ rule: expect.objectContaining({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ value: 'overdue',
+ }),
+ }),
+ ]);
+ expect(cancelRequests).toBe(1);
+ });
+
+ it('keeps the rule editor open and does not add a rule when the required condition input is empty', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ let cancelRequests = 0;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleEdit
+ onCancel={() => {
+ cancelRequests += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ clickButton(container!, 'Submit');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId) ?? []).toEqual([]);
+ expect(cancelRequests).toBe(0);
+ expect(container.textContent).toContain('Style rule');
+ });
+
+ it('saves changes to an existing number highlight rule without replacing its identity', async () => {
+ currentTestBed = createPanelTestBed();
+ const originalRule = {
+ ...createNumberHighlightRule('cf-active', 10),
+ stopIfTrue: true,
+ };
+ await currentTestBed.commandService.executeCommand(AddCfCommand.id, {
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ rule: originalRule,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ let cancelRequests = 0;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleEdit
+ rule={originalRule}
+ onCancel={() => {
+ cancelRequests += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const numberInput = Array.from(container.querySelectorAll('input'))
+ .find((input) => input.value === '10') as HTMLInputElement | undefined;
+ if (!numberInput) {
+ throw new Error('Number condition input was not rendered');
+ }
+
+ await act(async () => {
+ writeInput(numberInput, '25');
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ clickButton(container!, 'Submit');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([
+ expect.objectContaining({
+ cfId: 'cf-active',
+ ranges: [expect.objectContaining(ACTIVE_RANGE)],
+ stopIfTrue: true,
+ rule: expect.objectContaining({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value: 25,
+ }),
+ }),
+ ]);
+ expect(cancelRequests).toBe(1);
+ });
+
+ it('opens the clicked worksheet rule for editing and returns to the manager without changing it', async () => {
+ currentTestBed = createPanelTestBed();
+ await currentTestBed.commandService.executeCommand(AddCfCommand.id, {
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ rule: createNumberHighlightRule('cf-active', 10),
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <ConditionFormattingPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const rangeText = Array.from(container.querySelectorAll('div'))
+ .find((element) => element.textContent === 'A1');
+ const ruleRow = rangeText?.parentElement?.parentElement as HTMLElement | undefined;
+ if (!ruleRow) {
+ throw new Error('Worksheet rule row was not rendered');
+ }
+
+ await act(async () => {
+ ruleRow.click();
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('Range');
+ expect(container.textContent).toContain('Style type');
+
+ await act(async () => {
+ clickButton(container!, 'Cancel');
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('Show');
+ expect(container.textContent).toContain('A1');
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([
+ expect.objectContaining({
+ cfId: 'cf-active',
+ rule: expect.objectContaining({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ value: 10,
+ }),
+ }),
+ ]);
+ });
+
+ it('cancels rule editing on worksheet activation without saving in-progress changes', async () => {
+ currentTestBed = createPanelTestBed();
+ const originalRule = createNumberHighlightRule('cf-active', 10);
+ await currentTestBed.commandService.executeCommand(AddCfCommand.id, {
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ rule: originalRule,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ let cancelRequests = 0;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleEdit
+ rule={originalRule}
+ onCancel={() => {
+ cancelRequests += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const numberInput = Array.from(container.querySelectorAll('input'))
+ .find((input) => input.value === '10') as HTMLInputElement | undefined;
+ if (!numberInput) {
+ throw new Error('Number condition input was not rendered');
+ }
+
+ await act(async () => {
+ writeInput(numberInput, '99');
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await currentTestBed!.commandService.executeCommand(SetWorksheetActiveOperation.id, {
+ unitId: currentTestBed!.unitId,
+ subUnitId: currentTestBed!.subUnitId,
+ });
+ await Promise.resolve();
+ });
+
+ expect(cancelRequests).toBe(1);
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([
+ expect.objectContaining({
+ cfId: 'cf-active',
+ rule: expect.objectContaining({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ value: 10,
+ }),
+ }),
+ ]);
+ });
+});
diff --git a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx
index 002a40a4b1..d3d141afa8 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx
@@ -109,4 +109,46 @@ describe('ConditionalStyleEditor', () => {
},
});
});
+
+ it('emits background color changes when a user picks a fill preset color', async () => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ let latestStyle: IHighlightCell['style'] | undefined;
+
+ await act(async () => {
+ root!.render(
+ <ConditionalStyleEditor
+ onChange={(style) => {
+ latestStyle = style;
+ }}
+ />
+ );
+ await Promise.resolve();
+ });
+
+ const styleControls = Array.from(container.firstElementChild!.children) as HTMLElement[];
+
+ await act(async () => {
+ styleControls[5].click();
+ await Promise.resolve();
+ });
+
+ const firstPresetColor = document.querySelector('[data-u-comp="color-picker-presets"] button') as HTMLButtonElement;
+
+ if (!firstPresetColor) {
+ throw new Error('Preset colors were not rendered');
+ }
+
+ await act(async () => {
+ firstPresetColor.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(latestStyle).toMatchObject({
+ bg: {
+ rgb: '#ffffff',
+ },
+ });
+ });
});
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx
index 1b098ad2ff..3686f5272a 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx
@@ -17,8 +17,16 @@
import type { IRange } from '@univerjs/core';
import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
import type { Root } from 'react-dom/client';
-import { BooleanNumber, LocaleService, LocaleType } from '@univerjs/core';
-import { AddCfCommand, CFNumberOperator, CFRuleType, CFSubRuleType, DeleteCfCommand } from '@univerjs/sheets-conditional-formatting';
+import { BooleanNumber, LocaleService, LocaleType, RANGE_TYPE } from '@univerjs/core';
+import { SetSelectionsOperation } from '@univerjs/sheets';
+import {
+ AddCfCommand,
+ CFNumberOperator,
+ CFRuleType,
+ CFSubRuleType,
+ DeleteCfCommand,
+ MoveCfCommand,
+} from '@univerjs/sheets-conditional-formatting';
import { IMarkSelectionService } from '@univerjs/sheets-ui';
import { RediContext } from '@univerjs/ui';
import { act } from 'react';
@@ -78,6 +86,8 @@ async function createRuleListTestBed() {
testBed.injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService as never }]);
testBed.commandService.registerCommand(AddCfCommand);
testBed.commandService.registerCommand(DeleteCfCommand);
+ testBed.commandService.registerCommand(MoveCfCommand);
+ testBed.commandService.registerCommand(SetSelectionsOperation);
testBed.get(LocaleService).load({
[LocaleType.ZH_CN]: {
sheets: {
@@ -233,7 +243,7 @@ describe('RuleList', () => {
expect(container.textContent).not.toContain('A1');
});
- it('deletes only the clicked conditional formatting rule', async () => {
+ it('refreshes selected-range rules when the active sheet selection changes', async () => {
currentTestBed = await createRuleListTestBed();
container = document.createElement('div');
document.body.appendChild(container);
@@ -248,6 +258,60 @@ describe('RuleList', () => {
await Promise.resolve();
});
+ await act(async () => {
+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const selectedRangeOption = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((button) => button.textContent === 'Selected range');
+
+ expect(selectedRangeOption).toBeDefined();
+
+ await act(async () => {
+ selectedRangeOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('A1');
+ expect(container.textContent).not.toContain('F6');
+
+ await act(async () => {
+ await currentTestBed!.commandService.executeCommand(SetSelectionsOperation.id, {
+ unitId: currentTestBed!.unitId,
+ subUnitId: currentTestBed!.subUnitId,
+ selections: [{
+ range: {
+ ...FAR_RANGE,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: null,
+ style: null,
+ }],
+ });
+ await new Promise((resolve) => setTimeout(resolve, 32));
+ });
+
+ expect(container.textContent).not.toContain('A1');
+ expect(container.textContent).toContain('F6');
+ });
+
+ it('deletes only the clicked conditional formatting rule', async () => {
+ currentTestBed = await createRuleListTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const openedRuleIds: string[] = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleList onClick={(rule) => openedRuleIds.push(rule.cfId)} onCreate={() => undefined} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
const activeRangeText = Array.from(container.querySelectorAll('div'))
.find((element) => element.textContent === 'A1');
const activeRuleRow = activeRangeText?.parentElement?.parentElement as HTMLElement | undefined;
@@ -264,11 +328,52 @@ describe('RuleList', () => {
const remainingRules = currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId);
+ expect(openedRuleIds).toEqual([]);
expect(remainingRules?.map((rule) => rule.cfId)).toEqual(['cf-far']);
expect(container.textContent).not.toContain('A1');
expect(container.textContent).toContain('F6');
});
+ it('opens the clicked conditional formatting rule for editing without changing worksheet rules', async () => {
+ currentTestBed = await createRuleListTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const openedRuleIds: string[] = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleList onClick={(rule) => openedRuleIds.push(rule.cfId)} onCreate={() => undefined} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const activeRangeText = Array.from(container.querySelectorAll('div'))
+ .find((element) => element.textContent === 'A1');
+ const activeRuleRow = activeRangeText?.parentElement?.parentElement as HTMLElement | undefined;
+ const ruleIdsBeforeOpen = currentTestBed.ruleModel
+ .getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)
+ ?.map((rule) => rule.cfId);
+
+ if (!activeRuleRow) {
+ throw new Error('Rule row was not rendered');
+ }
+
+ await act(async () => {
+ activeRuleRow.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(openedRuleIds).toEqual(['cf-active']);
+ expect(
+ currentTestBed.ruleModel
+ .getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)
+ ?.map((rule) => rule.cfId)
+ ).toEqual(ruleIdsBeforeOpen);
+ });
+
it('clears all worksheet conditional formatting rules in worksheet mode', async () => {
currentTestBed = await createRuleListTestBed();
container = document.createElement('div');
@@ -300,4 +405,113 @@ describe('RuleList', () => {
expect(container.textContent).not.toContain('A1');
expect(container.textContent).not.toContain('F6');
});
+
+ it('starts the create-rule flow from the toolbar without changing existing worksheet rules', async () => {
+ currentTestBed = await createRuleListTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ let createRequests = 0;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleList
+ onClick={() => undefined}
+ onCreate={() => {
+ createRequests += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const createRuleButton = container.querySelectorAll('a')[0];
+ const ruleIdsBeforeCreate = currentTestBed.ruleModel
+ .getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)
+ ?.map((rule) => rule.cfId);
+
+ await act(async () => {
+ createRuleButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(createRequests).toBe(1);
+ expect(
+ currentTestBed.ruleModel
+ .getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)
+ ?.map((rule) => rule.cfId)
+ ).toEqual(ruleIdsBeforeCreate);
+ });
+
+ it('moves a dragged worksheet rule after the drop target rule', async () => {
+ currentTestBed = await createRuleListTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleList onClick={() => undefined} onCreate={() => undefined} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const ruleRows = Array.from(container.querySelectorAll<HTMLElement>('[data-draggable-list-item-id]'));
+ const firstRuleRow = ruleRows[0];
+ const secondRuleRow = ruleRows[1];
+ const dragHandle = firstRuleRow?.querySelector<HTMLElement>('.draggableHandle');
+
+ if (!firstRuleRow || !secondRuleRow || !dragHandle) {
+ throw new Error('Rule drag controls were not rendered');
+ }
+
+ expect(
+ currentTestBed.ruleModel
+ .getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)
+ ?.map((rule) => rule.cfId)
+ ).toEqual(['cf-far', 'cf-active']);
+
+ Object.defineProperty(firstRuleRow, 'setPointerCapture', {
+ configurable: true,
+ value() {},
+ });
+
+ const elementFromPoint = document.elementFromPoint;
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: () => secondRuleRow,
+ });
+
+ try {
+ await act(async () => {
+ dragHandle.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 1, clientY: 1, pointerId: 7 }));
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ window.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, clientX: 1, clientY: 80, pointerId: 7 }));
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ window.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, clientX: 1, clientY: 80, pointerId: 7 }));
+ await Promise.resolve();
+ });
+ } finally {
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: elementFromPoint,
+ });
+ }
+
+ expect(
+ currentTestBed.ruleModel
+ .getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)
+ ?.map((rule) => rule.cfId)
+ ).toEqual(['cf-active', 'cf-far']);
+ });
});
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx
index 1198bf80c7..f11b3224da 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx
@@ -15,11 +15,17 @@
*/
import type { Workbook } from '@univerjs/core';
-import type { IAverageHighlightCell, IConditionalFormattingRuleConfig, IHighlightCell, IRankHighlightCell } from '@univerjs/sheets-conditional-formatting';
+import type {
+ IAverageHighlightCell,
+ IConditionalFormattingRuleConfig,
+ IHighlightCell,
+ IRankHighlightCell,
+} from '@univerjs/sheets-conditional-formatting';
import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';
import type { IStyleEditorProps } from './type';
import { IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { borderClassName, clsx } from '@univerjs/design';
+import { LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';
import { CFRuleType, CFSubRuleType } from '@univerjs/sheets-conditional-formatting';
import { FormulaEditor } from '@univerjs/sheets-formula-ui';
import { useDependency, useSidebarClick } from '@univerjs/ui';
@@ -31,6 +37,7 @@ import { previewClassName } from './styles';
export const FormulaStyleEditor = (props: IStyleEditorProps) => {
const { onChange, interceptorManager } = props;
const localeService = useDependency(LocaleService);
+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);
const univerInstanceService = useDependency(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getActiveSheet();
@@ -60,6 +67,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
subType: CFSubRuleType.formula,
};
};
+
useEffect(() => {
const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().submit, {
handler() {
@@ -72,7 +80,11 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
useEffect(() => {
const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().beforeSubmit, {
handler: (v, _c, next) => {
- if (formulaError || formula.length === 1 || !formula.startsWith('=')) {
+ const isFormulaValid = formula.length > 1
+ && formula.startsWith(operatorToken.EQUALS)
+ && lexerTreeBuilder.checkIfAddBracket(formula) === 0;
+
+ if (formulaError || !isFormulaValid) {
setFormulaError(localeService.t('sheets-conditional-formatting-ui.errorMessage.formulaError'));
return false;
}
@@ -80,7 +92,13 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
},
});
return dispose as () => void;
- }, [formulaError, formula]);
+ }, [
+ formulaError,
+ formula,
+ interceptorManager,
+ lexerTreeBuilder,
+ localeService,
+ ]);
const _onChange = (config: {
formula: string;
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsx
index 7ff6ef3130..52ec1cb9d1 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsx
@@ -16,22 +16,28 @@
import type { IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditional-formatting';
import type { Root } from 'react-dom/client';
-import { InterceptorManager, LocaleService, LocaleType } from '@univerjs/core';
+import { createIdentifier, InterceptorManager, LocaleService, LocaleType } from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { IRefSelectionsService } from '@univerjs/sheets';
import {
CFNumberOperator,
CFRuleType,
CFSubRuleType,
CFTextOperator,
+ CFTimePeriodOperator,
CFValueType,
IIconSetType,
} from '@univerjs/sheets-conditional-formatting';
-import { ILayoutService, RediContext } from '@univerjs/ui';
+import { IContextMenuService, ILayoutService, IShortcutService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
+import { Subject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { createCfUiTestBed } from '../../../../__tests__/create-cf-ui-test-bed';
import { ColorScaleStyleEditor } from '../ColorScale';
import { DataBarStyleEditor } from '../DataBar';
+import { FormulaStyleEditor } from '../Formula';
import { HighlightCellStyleEditor } from '../HighlightCell';
import { IconSet } from '../IconSet';
import { RankStyleEditor } from '../Rank';
@@ -39,18 +45,89 @@ import { beforeSubmit, submit } from '../type';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const IEditorService = createIdentifier<TestEditorService>('univer.editor.service');
+const IDescriptionService = createIdentifier<TestDescriptionService>('formula.description-service');
+
class TestLayoutService {
readonly rootContainerElement = document.body;
}
+class TestEditorService {
+ register() {
+ return { dispose() {} };
+ }
+
+ getEditor() {
+ return undefined;
+ }
+
+ getFocusId() {
+ return undefined;
+ }
+
+ focus(): void {}
+
+ blur(): void {}
+}
+
+class TestRenderManagerService {
+ getRenderById() {
+ return undefined;
+ }
+}
+
+class TestDocSelectionManagerService {
+ readonly textSelection$ = new Subject();
+}
+
+class TestDescriptionService {
+ hasDefinedNameDescription() {
+ return false;
+ }
+}
+
+class TestRefSelectionsService {
+ setSelections(): void {}
+
+ clear(): void {}
+}
+
+class TestShortcutService {
+ registerShortcut() {
+ return { dispose() {} };
+ }
+}
+
+class TestContextMenuService {
+ disable(): void {}
+
+ enable(): void {}
+}
+
function createEditorTestBed() {
const testBed = createCfUiTestBed();
testBed.injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
+ testBed.injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ testBed.injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ testBed.injector.add([IDescriptionService, { useClass: TestDescriptionService as never }]);
+ testBed.injector.add([IRefSelectionsService, { useClass: TestRefSelectionsService as never }]);
+ testBed.injector.add([IShortcutService, { useClass: TestShortcutService as never }]);
+ testBed.injector.add([IContextMenuService, { useClass: TestContextMenuService as never }]);
+ testBed.injector.add([LexerTreeBuilder]);
testBed.get(LocaleService).load({ [LocaleType.ZH_CN]: {} });
return testBed;
}
+async function createFormulaEditorTestBed() {
+ const testBed = createEditorTestBed();
+ const docsSelectionServiceUrl = new URL('../docs/src/services/doc-selection-manager.service.ts', `file://${process.cwd()}/`).href;
+ const { DocSelectionManagerService } = await import(/* @vite-ignore */ docsSelectionServiceUrl);
+ testBed.injector.add([DocSelectionManagerService, { useClass: TestDocSelectionManagerService as never }]);
+
+ return testBed;
+}
+
function createRuleInterceptorManager() {
return new InterceptorManager({ beforeSubmit, submit });
}
@@ -65,6 +142,22 @@ function inputText(input: HTMLInputElement, value: string) {
input.dispatchEvent(new Event('input', { bubbles: true }));
}
+async function selectOption(selectIndex: number, optionText: string) {
+ const select = Array.from(document.querySelectorAll<HTMLElement>('[data-u-comp="select"]'))[selectIndex];
+ select.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ select.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+
+ const option = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"], [role="menuitemradio"]'))
+ .find((item) => item.textContent?.includes(optionText));
+
+ if (!option) {
+ throw new Error(`Rule editor option ${optionText} was not rendered`);
+ }
+
+ option.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
describe('conditional formatting rule editors', () => {
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -165,6 +258,51 @@ describe('conditional formatting rule editors', () => {
});
});
+ it('preserves an existing bottom percent rank rule when reopening the editor', async () => {
+ currentTestBed = createEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RankStyleEditor
+ interceptorManager={interceptorManager}
+ rule={{
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.rank,
+ isBottom: true,
+ isPercent: true,
+ value: 15,
+ style: {
+ cl: {
+ rgb: '#c00000',
+ },
+ },
+ }}
+ onChange={() => undefined}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(submitRule(interceptorManager)).toMatchObject({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.rank,
+ isBottom: true,
+ isPercent: true,
+ value: 15,
+ style: {
+ cl: {
+ rgb: '#c00000',
+ },
+ },
+ });
+ });
+
it('submits data bar rule configuration with min/max value types and visibility', async () => {
currentTestBed = createEditorTestBed();
container = document.createElement('div');
@@ -195,6 +333,49 @@ describe('conditional formatting rule editors', () => {
});
});
+ it('preserves custom colors, gradient fill, thresholds, and hidden cell values when reopening a data bar rule', async () => {
+ currentTestBed = createEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <DataBarStyleEditor
+ interceptorManager={interceptorManager}
+ rule={{
+ type: CFRuleType.dataBar,
+ isShowValue: false,
+ config: {
+ min: { type: CFValueType.percent, value: 15 },
+ max: { type: CFValueType.percentile, value: 85 },
+ isGradient: true,
+ positiveColor: '#63be7b',
+ nativeColor: '#f8696b',
+ },
+ }}
+ onChange={() => undefined}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(submitRule(interceptorManager)).toMatchObject({
+ type: CFRuleType.dataBar,
+ isShowValue: false,
+ config: {
+ min: { type: CFValueType.percent, value: 15 },
+ max: { type: CFValueType.percentile, value: 85 },
+ isGradient: true,
+ positiveColor: '#63be7b',
+ nativeColor: '#f8696b',
+ },
+ });
+ });
+
it('submits a two-point color scale when the median value type is disabled', async () => {
currentTestBed = createEditorTestBed();
container = document.createElement('div');
@@ -223,6 +404,67 @@ describe('conditional formatting rule editors', () => {
});
});
+ it('preserves an existing three-point color scale rule when reopening the editor', async () => {
+ currentTestBed = createEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <ColorScaleStyleEditor
+ interceptorManager={interceptorManager}
+ rule={{
+ type: CFRuleType.colorScale,
+ config: [
+ {
+ index: 0,
+ color: '#63be7b',
+ value: { type: CFValueType.min },
+ },
+ {
+ index: 1,
+ color: '#ffeb84',
+ value: { type: CFValueType.percentile, value: 50 },
+ },
+ {
+ index: 2,
+ color: '#f8696b',
+ value: { type: CFValueType.max },
+ },
+ ],
+ }}
+ onChange={() => undefined}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(submitRule(interceptorManager)).toMatchObject({
+ type: CFRuleType.colorScale,
+ config: [
+ {
+ index: 0,
+ color: '#63be7b',
+ value: { type: CFValueType.min },
+ },
+ {
+ index: 1,
+ color: '#ffeb84',
+ value: { type: CFValueType.percentile, value: 50 },
+ },
+ {
+ index: 2,
+ color: '#f8696b',
+ value: { type: CFValueType.max },
+ },
+ ],
+ });
+ });
+
it('submits a valid default icon set rule with visible cell values', async () => {
currentTestBed = createEditorTestBed();
container = document.createElement('div');
@@ -353,6 +595,166 @@ describe('conditional formatting rule editors', () => {
});
});
+ it('preserves an existing time period highlight rule without requiring an input value', async () => {
+ currentTestBed = createEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <HighlightCellStyleEditor
+ interceptorManager={interceptorManager}
+ rule={{
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.timePeriod,
+ operator: CFTimePeriodOperator.last7Days,
+ style: {
+ bg: {
+ rgb: '#fff2cc',
+ },
+ },
+ }}
+ onChange={() => undefined}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(true);
+ expect(submitRule(interceptorManager)).toMatchObject({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.timePeriod,
+ operator: CFTimePeriodOperator.last7Days,
+ style: {
+ bg: {
+ rgb: '#fff2cc',
+ },
+ },
+ });
+ });
+
+ it('submits a duplicate-values highlight rule after switching the condition type', async () => {
+ currentTestBed = createEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+ let lastRule: unknown;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <HighlightCellStyleEditor
+ interceptorManager={interceptorManager}
+ onChange={(rule) => {
+ lastRule = rule;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await selectOption(0, 'duplicateValues');
+ await Promise.resolve();
+ });
+
+ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(true);
+ expect(submitRule(interceptorManager)).toMatchObject({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.duplicateValues,
+ });
+ expect(lastRule).toMatchObject({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.duplicateValues,
+ });
+ });
+
+ it('preserves an existing formula highlight rule and validates it through beforeSubmit', async () => {
+ currentTestBed = await createFormulaEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <FormulaStyleEditor
+ interceptorManager={interceptorManager}
+ rule={{
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.formula,
+ value: '=MOD(ROW(),2)=0',
+ style: {
+ bg: {
+ rgb: '#ddebf7',
+ },
+ cl: {
+ rgb: '#1f4e79',
+ },
+ },
+ }}
+ onChange={() => undefined}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(true);
+ expect(submitRule(interceptorManager)).toMatchObject({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.formula,
+ value: '=MOD(ROW(),2)=0',
+ style: {
+ bg: {
+ rgb: '#ddebf7',
+ },
+ cl: {
+ rgb: '#1f4e79',
+ },
+ },
+ });
+ });
+
+ it('blocks submitting a reopened formula highlight rule with an invalid formula', async () => {
+ currentTestBed = await createFormulaEditorTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const interceptorManager = createRuleInterceptorManager();
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <FormulaStyleEditor
+ interceptorManager={interceptorManager}
+ rule={{
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.formula,
+ value: '=SUM(',
+ style: {
+ bg: {
+ rgb: '#fce4d6',
+ },
+ },
+ }}
+ onChange={() => undefined}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(false);
+ });
+
it('preserves an existing icon set rule with hidden cell values', async () => {
currentTestBed = createEditorTestBed();
container = document.createElement('div');
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/base-calculate.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/base-calculate.spec.ts
similarity index 100%
rename from packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/base-calculate.spec.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/base-calculate.spec.ts
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.color.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.color.spec.ts
similarity index 100%
rename from packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.color.spec.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.color.spec.ts
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.databar.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.databar.spec.ts
similarity index 100%
rename from packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.databar.spec.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.databar.spec.ts
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.highlight.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.highlight.spec.ts
similarity index 100%
rename from packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.highlight.spec.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.highlight.spec.ts
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/test.util.ts
similarity index 100%
rename from packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/test.util.ts
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.spec.ts
new file mode 100644
index 0000000000..89be5d6317
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.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 { IConditionFormattingRule } from '../../type';
+import { BooleanNumber, CellValueType, ColorKit, ObjectMatrix } from '@univerjs/core';
+import { FormulaResultStatus } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { CFNumberOperator, CFRuleType, CFSubRuleType, CFValueType } from '../../../base/const';
+import {
+ compareWithNumber,
+ filterRange,
+ getCacheStyleMatrix,
+ getCellValue,
+ getColorScaleFromValue,
+ getMaxInFormulaResult,
+ getOppositeOperator,
+ getValueByType,
+ isFloatsEqual,
+ isNullable,
+ serialTimeToTimestamp,
+ toYMD_1900,
+} from '../utils';
+
+describe('conditional formatting calculate utilities', () => {
+ it('normalizes cell values used by conditional formatting rules', () => {
+ expect(isFloatsEqual(1, 1 + Number.EPSILON / 2)).toBe(true);
+ expect(isNullable(null)).toBe(true);
+ expect(isNullable(undefined)).toBe(true);
+ expect(isNullable(' ')).toBe(true);
+ expect(getCellValue()).toBeNull();
+ expect(getCellValue({ t: CellValueType.BOOLEAN, v: BooleanNumber.TRUE })).toBe('TRUE');
+ expect(getCellValue({ t: CellValueType.BOOLEAN, v: BooleanNumber.FALSE })).toBe('FALSE');
+ expect(getCellValue({ v: '', p: { body: { dataStream: 'rich\r\n' } } as any })).toBe('rich');
+ expect(getCellValue({ v: 'plain' })).toBe('plain');
+ });
+
+ it('converts spreadsheet serial dates and filters ranges to sheet bounds', () => {
+ expect(toYMD_1900(0)).toEqual([1900, 1, 0]);
+ expect(toYMD_1900(60)).toEqual([1900, 2, 29]);
+ expect(toYMD_1900(59)).toEqual([1900, 2, 28]);
+ expect(Number.isFinite(serialTimeToTimestamp(44927.5))).toBe(true);
+
+ expect(filterRange([
+ { startRow: 0, startColumn: 0, endRow: 10, endColumn: 10 },
+ { startRow: 100, startColumn: 0, endRow: 101, endColumn: 1 },
+ ], 5, 6)).toEqual([
+ { startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 },
+ ]);
+ });
+
+ it('calculates threshold values from matrices for data bars, color scales and icon sets', () => {
+ const matrix = new ObjectMatrix<number>();
+ matrix.setValue(0, 0, 2);
+ matrix.setValue(0, 1, 6);
+ matrix.setValue(0, 2, 10);
+ const context = {
+ cfId: 'cf-1',
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ accessor: {
+ get() {
+ throw new Error('formula service is not used by this test');
+ },
+ },
+ } as any;
+
+ expect(getValueByType({ type: CFValueType.max }, matrix, context)).toEqual({
+ status: FormulaResultStatus.SUCCESS,
+ result: 10,
+ });
+ expect(getValueByType({ type: CFValueType.min }, matrix, context)).toEqual({
+ status: FormulaResultStatus.SUCCESS,
+ result: 2,
+ });
+ expect(getValueByType({ type: CFValueType.percent, value: 50 }, matrix, context)).toEqual({
+ status: FormulaResultStatus.SUCCESS,
+ result: 6,
+ });
+ expect(getValueByType({ type: CFValueType.percentile, value: 50 }, matrix, context)).toEqual({
+ status: FormulaResultStatus.SUCCESS,
+ result: 6,
+ });
+ expect(getValueByType({ type: CFValueType.num, value: 'bad-number' }, matrix, context)).toEqual({
+ status: FormulaResultStatus.SUCCESS,
+ result: 0,
+ });
+ });
+
+ it('compares numbers and derives opposite operators for icon range bands', () => {
+ expect(compareWithNumber({ operator: CFNumberOperator.between, value: [10, 1] }, 5)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.notBetween, value: [1, 10] }, 12)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.equal, value: 3 }, 3)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.notEqual, value: 3 }, 4)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.greaterThan, value: 3 }, 4)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.greaterThanOrEqual, value: 3 }, 3)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.lessThan, value: 3 }, 2)).toBe(true);
+ expect(compareWithNumber({ operator: CFNumberOperator.lessThanOrEqual, value: 3 }, 3)).toBe(true);
+ expect(compareWithNumber({ operator: 'unknown' as CFNumberOperator, value: 3 }, 3)).toBe(false);
+ expect(getOppositeOperator(CFNumberOperator.greaterThan)).toBe(CFNumberOperator.lessThanOrEqual);
+ expect(getOppositeOperator(CFNumberOperator.greaterThanOrEqual)).toBe(CFNumberOperator.lessThan);
+ expect(getOppositeOperator(CFNumberOperator.lessThan)).toBe(CFNumberOperator.greaterThanOrEqual);
+ expect(getOppositeOperator(CFNumberOperator.lessThanOrEqual)).toBe(CFNumberOperator.greaterThan);
+ expect(getOppositeOperator(CFNumberOperator.equal)).toBe(CFNumberOperator.equal);
+ });
+
+ it('interpolates colors, reads cached style results, and computes formula result maxima', () => {
+ expect(getColorScaleFromValue([
+ { value: 0, color: new ColorKit('#000000') },
+ { value: 10, color: new ColorKit('#ffffff') },
+ ], -1)).toBe('rgb(0,0,0)');
+ expect(getColorScaleFromValue([
+ { value: 0, color: new ColorKit('#000000') },
+ { value: 10, color: new ColorKit('#ffffff') },
+ ], 5)).toBe('rgb(128,128,128)');
+ expect(getColorScaleFromValue([
+ { value: 0, color: new ColorKit('#000000') },
+ { value: 10, color: new ColorKit('#ffffff') },
+ ], 20)).toBe('rgb(255,255,255)');
+
+ const rule: IConditionFormattingRule = {
+ cfId: 'cf-1',
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.equal,
+ style: {},
+ },
+ } as any;
+ const matrix = getCacheStyleMatrix<string>('unit', 'sheet', rule, {
+ accessor: {
+ get() {
+ return {
+ getCellCfs(_unitId: string, _subUnitId: string, row: number, col: number) {
+ return row === 0 && col === 0
+ ? [{ cfId: 'cf-1', result: 'hit' }, { cfId: 'cf-2', result: 'miss' }]
+ : undefined;
+ },
+ };
+ },
+ },
+ } as any);
+ expect(matrix.getValue(0, 0)).toBe('hit');
+ expect(matrix.getValue(1, 1)).toBeUndefined();
+ expect(getMaxInFormulaResult({ 0: { 0: 1, 1: '9' } })).toBe(9);
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/render/__tests__/conditional-formatting-render.spec.ts b/packages/sheets-conditional-formatting/src/render/__tests__/conditional-formatting-render.spec.ts
new file mode 100644
index 0000000000..bc0ef61454
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/render/__tests__/conditional-formatting-render.spec.ts
@@ -0,0 +1,214 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { IIconSetType } from '../../models/icon-map';
+import { DataBar } from '../data-bar.render';
+import { ConditionalFormattingIcon } from '../icon.render';
+
+function createCtx() {
+ const gradient = { addColorStop: vi.fn() };
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ arcTo: vi.fn(),
+ closePath: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ drawImage: vi.fn(),
+ createLinearGradient: vi.fn(() => gradient),
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 0,
+ gradient,
+ } as any;
+}
+
+function createCellBounds(row: number, col: number, overrides?: Record<string, unknown>) {
+ const startX = col * 80;
+ const startY = row * 24;
+ return {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ startX,
+ endX: startX + 80,
+ startY,
+ endY: startY + 24,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ startX,
+ endX: startX + 80,
+ startY,
+ endY: startY + 24,
+ },
+ ...overrides,
+ };
+}
+
+function createSkeleton(cells: Record<string, unknown>, hiddenRows = new Set<number>(), hiddenCols = new Set<number>()) {
+ return {
+ rowColumnSegment: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 },
+ worksheet: {
+ getRowVisible: (row: number) => !hiddenRows.has(row),
+ getColVisible: (col: number) => !hiddenCols.has(col),
+ getCell: (row: number, col: number) => cells[`${row},${col}`],
+ },
+ getCellWithCoordByIndex: (row: number, col: number) => createCellBounds(row, col),
+ } as any;
+}
+
+describe('conditional formatting render extensions', () => {
+ it('draws data bars for positive and negative cell values in visible cells', () => {
+ const ctx = createCtx();
+ const skeleton = createSkeleton({
+ '0,0': {
+ dataBar: {
+ color: '#2f56ef',
+ value: 75,
+ startPoint: 25,
+ isGradient: false,
+ isShowValue: true,
+ },
+ },
+ '0,1': {
+ dataBar: {
+ color: '#f45531',
+ value: -50,
+ startPoint: 60,
+ isGradient: true,
+ isShowValue: true,
+ },
+ },
+ '1,0': {
+ dataBar: {
+ color: '#111111',
+ value: 100,
+ startPoint: 0,
+ isGradient: false,
+ isShowValue: true,
+ },
+ },
+ }, new Set([1]));
+
+ new DataBar().draw(ctx, { scaleX: 1, scaleY: 1 }, skeleton, [
+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ ]);
+
+ expect(ctx.save).toHaveBeenCalled();
+ expect(ctx.fill).toHaveBeenCalledTimes(2);
+ expect(ctx.createLinearGradient).toHaveBeenCalledTimes(1);
+ expect(ctx.gradient.addColorStop).toHaveBeenCalledWith(0, 'rgb(255 255 255)');
+ expect(ctx.gradient.addColorStop).toHaveBeenCalledWith(1, '#f45531');
+ expect(ctx.stroke).toHaveBeenCalledTimes(1);
+ expect(ctx.restore).toHaveBeenCalled();
+ });
+
+ it('skips data bar drawing when worksheet is missing or bar dimensions collapse', () => {
+ const ctx = createCtx();
+ const dataBar = new DataBar();
+ expect(dataBar.draw(ctx, { scaleX: 1, scaleY: 1 }, { worksheet: undefined } as any, [])).toBe(false);
+
+ (dataBar as any)._drawRectWithRoundedCorner(ctx, 0, 0, 0, 10, true, true, true, true);
+ (dataBar as any)._drawRectWithRoundedCorner(ctx, 0, 0, 10, 0, true, true, true, true);
+ expect(ctx.beginPath).not.toHaveBeenCalled();
+ });
+
+ it('draws configured conditional-formatting icons and skips unavailable icons', () => {
+ const ctx = createCtx();
+ const icon = new ConditionalFormattingIcon();
+ const nativeImage = document.createElement('img');
+ (icon as any)._imageMap.set(`${IIconSetType.threeArrows}_0`, nativeImage);
+
+ const skeleton = createSkeleton({
+ '0,0': {
+ iconSet: {
+ iconType: IIconSetType.threeArrows,
+ iconId: '0',
+ isShowValue: true,
+ },
+ },
+ '0,1': {
+ iconSet: {
+ iconType: IIconSetType.empty,
+ iconId: '0',
+ isShowValue: true,
+ },
+ },
+ '0,2': {
+ iconSet: {
+ iconType: IIconSetType.threeArrows,
+ iconId: '99',
+ isShowValue: true,
+ },
+ },
+ });
+
+ icon.draw(ctx, { scaleX: 1, scaleY: 1 }, skeleton, [
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 },
+ ]);
+
+ expect(ctx.drawImage).toHaveBeenCalledTimes(1);
+ expect(ctx.drawImage).toHaveBeenCalledWith(nativeImage, 2, 4.5, 15, 15);
+ });
+
+ it('skips icon drawing for missing worksheet and cells too small for the icon', () => {
+ const ctx = createCtx();
+ const icon = new ConditionalFormattingIcon();
+ const nativeImage = document.createElement('img');
+ (icon as any)._imageMap.set(`${IIconSetType.threeArrows}_0`, nativeImage);
+
+ expect(icon.draw(ctx, { scaleX: 1, scaleY: 1 }, { worksheet: undefined } as any, [])).toBe(false);
+
+ const skeleton = createSkeleton({
+ '0,0': {
+ iconSet: {
+ iconType: IIconSetType.threeArrows,
+ iconId: '0',
+ isShowValue: true,
+ },
+ },
+ });
+ skeleton.getCellWithCoordByIndex = () => createCellBounds(0, 0, {
+ endX: 10,
+ endY: 10,
+ mergeInfo: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ endX: 10,
+ startY: 0,
+ endY: 10,
+ },
+ }) as any;
+
+ icon.draw(ctx, { scaleX: 1, scaleY: 1 }, skeleton, [
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ ]);
+ expect(ctx.drawImage).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/utils/__test__/anchor.spec.ts b/packages/sheets-conditional-formatting/src/utils/__tests__/anchor.spec.ts
similarity index 100%
rename from packages/sheets-conditional-formatting/src/utils/__test__/anchor.spec.ts
rename to packages/sheets-conditional-formatting/src/utils/__tests__/anchor.spec.ts
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts
new file mode 100644
index 0000000000..67c8d631ac
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-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 { DataValidationStatus, DataValidationType } from '@univerjs/core';
+import { INTERCEPTOR_POINT } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsDataValidationRenderController } from '../dv-render.controller';
+
+describe('SheetsDataValidationRenderController', () => {
+ it('adds invalid markers, dropdown canvas renderer and list-cell layout behavior through the cell interceptor', () => {
+ let interceptor: any;
+ const canvasRender = {
+ calcCellAutoHeight: vi.fn(() => 36),
+ calcCellAutoWidth: vi.fn(() => 120),
+ };
+ const skeleton = {
+ worksheet: { getMergedCell: vi.fn(() => null) },
+ getStyles: vi.fn(() => ({ getStyleByCell: vi.fn(() => ({ fs: 11 })) })),
+ getCellWithCoordByIndex: vi.fn(() => ({ startX: 10, startY: 20 })),
+ };
+ const controller = new SheetsDataValidationRenderController(
+ { executeCommand: vi.fn() } as never,
+ { mergeMenu: vi.fn() } as never,
+ {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => ({
+ getSkeletonParam: vi.fn(() => ({ skeleton })),
+ })),
+ })),
+ } as never,
+ { getUniverSheetInstance: vi.fn() } as never,
+ { getUndoRedoParamsOfAutoHeight: vi.fn(() => ({ redos: [] })) } as never,
+ { activeDropdown: null, hideDropdown: vi.fn(), showDropdown: vi.fn() } as never,
+ {
+ getRuleIdByLocation: vi.fn(() => 'rule-1'),
+ getRuleById: vi.fn(() => ({ uid: 'rule-1', type: DataValidationType.LIST })),
+ ruleChange$: new Subject(),
+ } as never,
+ {
+ getValidatorItem: vi.fn(() => ({
+ canvasRender,
+ dropdownType: 'list',
+ skipDefaultFontRender: vi.fn(() => true),
+ getExtraStyle: vi.fn(() => ({ bg: { rgb: '#fff3cd' } })),
+ })),
+ } as never,
+ {
+ intercept: vi.fn((point, config) => {
+ expect(point).toBe(INTERCEPTOR_POINT.CELL_CONTENT);
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ { getValue: vi.fn(() => DataValidationStatus.INVALID) } as never
+ );
+ const rawCell = { v: 'bad', markers: { bl: { size: 1 } }, coverable: true };
+ const workbook = { getStyles: vi.fn(() => ({ get: vi.fn(() => ({ fs: 10 })) })) };
+ const worksheet = { getMergedCell: vi.fn(() => null) };
+
+ const result = interceptor.handler(rawCell, {
+ row: 1,
+ col: 2,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rawData: rawCell,
+ workbook,
+ worksheet,
+ }, (cell: unknown) => cell);
+
+ expect(result).not.toBe(rawCell);
+ expect(result.markers).toEqual(expect.objectContaining({
+ bl: { size: 1 },
+ tr: { size: 6, color: '#fe4b4b' },
+ }));
+ expect(result.customRender).toContain(canvasRender);
+ expect(result.fontRenderExtension.isSkip).toBe(true);
+ expect(result.interceptorStyle).toEqual({ bg: { rgb: '#fff3cd' } });
+ expect(result.coverable).toBe(false);
+ expect(result.interceptorAutoHeight()).toBe(36);
+ expect(result.interceptorAutoWidth()).toBe(120);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.behavior.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx
similarity index 58%
rename from packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.behavior.spec.tsx
rename to packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx
index f004b6c6f9..f8e7e186ca 100644
--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.behavior.spec.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx
@@ -27,6 +27,9 @@ import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { Root } from 'react-dom/client';
import {
createIdentifier,
+ DataValidationErrorStyle,
+ DataValidationOperator,
+ DataValidationRenderMode,
DataValidationType,
ICommandService,
ILogService,
@@ -62,6 +65,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import {
RangeProtectionRuleModel,
RefRangeService,
+ serializeListOptions,
SheetInterceptorService,
SheetSkeletonService,
SheetsSelectionsService,
@@ -71,14 +75,20 @@ import {
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
import {
+ CheckboxValidator,
DataValidationCacheService,
DataValidationCustomFormulaService,
+ DataValidationFormulaController,
DataValidationFormulaService,
DataValidationListCacheService,
DateValidator,
+ ListMultipleValidator,
+ ListValidator,
+ RemoveSheetDataValidationCommand,
SheetDataValidationModel,
SheetsDataValidationValidatorService,
UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
UpdateSheetDataValidationSettingCommand,
} from '@univerjs/sheets-data-validation';
import { IMarkSelectionService } from '@univerjs/sheets-ui';
@@ -100,6 +110,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
import { DataValidationDetail } from '../DataValidationDetail';
import { DateShowTimeOption } from '../DateShowTimeOption';
+import { BASE_FORMULA_INPUT_NAME, FORMULA_INPUTS, LIST_FORMULA_INPUT_NAME } from '../formula-input';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -207,6 +218,18 @@ class TestRangeEditor {
this._change$.next();
}
+ replaceText(text: string) {
+ this._data = {
+ ...this._data,
+ body: {
+ ...this._data.body,
+ dataStream: `${text}\r\n`,
+ textRuns: [],
+ },
+ };
+ this._change$.next();
+ }
+
getDocumentDataModel() {
return {
change$: this._change$.asObservable(),
@@ -335,6 +358,27 @@ function createDateRule(uid = 'rule-date'): ISheetDataValidationRule {
};
}
+function createDateBetweenRule(uid = 'rule-date-between'): ISheetDataValidationRule {
+ return {
+ ...createDateRule(uid),
+ operator: DataValidationOperator.BETWEEN,
+ formula1: '2024-01-01',
+ formula2: '2024-01-31',
+ };
+}
+
+function createListRule(uid = 'rule-list'): ISheetDataValidationRule {
+ return {
+ uid,
+ type: DataValidationType.LIST,
+ ranges: [FIRST_RANGE],
+ formula1: serializeListOptions(['Pending', 'Approved']),
+ formula2: '#FDCECE,#DEF6A2',
+ renderMode: DataValidationRenderMode.CUSTOM,
+ allowBlank: true,
+ };
+}
+
function createDetailTestBed(rule: ISheetDataValidationRule) {
const univer = new Univer();
const injector = univer.__getInjector();
@@ -377,6 +421,7 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {
[DataValidationListCacheService],
[DataValidationFormulaService],
[DataValidationCustomFormulaService],
+ [DataValidationFormulaController],
[RegisterOtherFormulaService],
[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
[ISheetRowFilteredService, { useClass: SheetRowFilteredService }],
@@ -395,15 +440,33 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {
injector.get(LocaleService).load({
[LocaleType.EN_US]: {
'sheets-data-validation': {
+ checkbox: {
+ title: 'Checkbox',
+ },
date: {
title: 'Date',
},
+ list: {
+ title: 'Dropdown',
+ },
+ listMultiple: {
+ title: 'Dropdown multiple',
+ },
validFail: {
date: 'Enter a valid date',
+ list: 'Please input options',
+ listIntersects: 'The selected range cannot intersect the rule range',
+ listInvalid: 'Enter a valid range formula',
number: 'Enter a valid number',
},
},
'sheets-data-validation-ui': {
+ list: {
+ add: 'Add item',
+ customOptions: 'Custom options',
+ options: 'Options',
+ refOptions: 'From range',
+ },
operators: {
legal: 'Is valid',
},
@@ -440,16 +503,29 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {
const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
injector.get(ILogService).setLogLevel(LogLevel.SILENT);
injector.get(ComponentManager).register(DateShowTimeOption.componentKey, DateShowTimeOption);
+ FORMULA_INPUTS.forEach(([key, component]) => {
+ injector.get(ComponentManager).register(key, component);
+ });
const commandService = injector.get(ICommandService);
commandService.registerCommand(UpdateSheetDataValidationSettingCommand);
commandService.registerCommand(UpdateSheetDataValidationOptionsCommand);
+ commandService.registerCommand(UpdateSheetDataValidationRangeCommand);
+ commandService.registerCommand(RemoveSheetDataValidationCommand);
const localeService = injector.get(LocaleService);
const validatorRegistry = injector.get(DataValidatorRegistryService);
const dateValidator = new DateValidator(localeService, injector);
+ dateValidator.formulaInput = BASE_FORMULA_INPUT_NAME;
dateValidator.optionsInput = DateShowTimeOption.componentKey;
validatorRegistry.register(dateValidator);
+ validatorRegistry.register(injector.createInstance(CheckboxValidator));
+ const listValidator = injector.createInstance(ListValidator);
+ listValidator.formulaInput = LIST_FORMULA_INPUT_NAME;
+ const listMultipleValidator = injector.createInstance(ListMultipleValidator);
+ listMultipleValidator.formulaInput = LIST_FORMULA_INPUT_NAME;
+ validatorRegistry.register(listValidator);
+ validatorRegistry.register(listMultipleValidator);
const sheetDataValidationModel = injector.get(SheetDataValidationModel);
commandService.syncExecuteCommand(AddDataValidationMutation.id, {
@@ -487,13 +563,31 @@ async function renderDetail(root: Root, testBed: ReturnType<typeof createDetailT
});
}
-async function clickElement(element: HTMLElement) {
+async function clickElement(element: Element) {
await act(async () => {
element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
await Promise.resolve();
});
}
+async function openSelect(element: HTMLElement) {
+ await act(async () => {
+ const PointerEventCtor = window.PointerEvent ?? MouseEvent;
+ element.dispatchEvent(new PointerEventCtor('pointerdown', { bubbles: true, button: 0 }));
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+async function changeInputValue(input: HTMLInputElement, value: string) {
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
async function waitForDebounce() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 1100));
@@ -506,6 +600,11 @@ function findElementByText(container: HTMLElement, text: string) {
.sort((a, b) => (a.textContent?.length ?? 0) - (b.textContent?.length ?? 0))[0];
}
+function findButtonByText(container: HTMLElement, text: string) {
+ return Array.from(container.querySelectorAll<HTMLButtonElement>('button'))
+ .find((element) => element.textContent?.includes(text))!;
+}
+
describe('DataValidationDetail rule editing', () => {
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -558,4 +657,171 @@ describe('DataValidationDetail rule editing', () => {
showTime: true,
});
});
+
+ it('persists both date bounds when editing a between-rule formula', async () => {
+ currentTestBed = createDetailTestBed(createDateBetweenRule());
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ const inputs = Array.from(container.querySelectorAll<HTMLInputElement>('[data-u-comp="input"] input'));
+
+ await changeInputValue(inputs[0], '2024-02-01');
+ await waitForDebounce();
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toMatchObject({
+ operator: DataValidationOperator.BETWEEN,
+ formula1: '2024-02-01',
+ formula2: '2024-01-31',
+ });
+
+ await changeInputValue(inputs[1], '2024-02-29');
+ await waitForDebounce();
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toMatchObject({
+ operator: DataValidationOperator.BETWEEN,
+ formula1: '2024-02-01',
+ formula2: '2024-02-29',
+ });
+ });
+
+ it('updates the active rule range after confirming a new apply-to range', async () => {
+ currentTestBed = createDetailTestBed(createDateRule('rule-date-range-selector'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ const selectRangeIcon = container.querySelector<SVGElement>('svg')!;
+ await clickElement(selectRangeIcon);
+
+ const rangeInput = document.body.querySelector<HTMLInputElement>('[data-u-comp="input"] input')!;
+ await changeInputValue(rangeInput, 'B3:C4');
+ await clickElement(findButtonByText(document.body, 'rangeSelector.confirm'));
+ await waitForDebounce();
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)?.ranges).toEqual([{
+ startRow: 2,
+ endRow: 3,
+ startColumn: 1,
+ endColumn: 2,
+ }]);
+ });
+
+ it('clears date bounds and operator when switching the rule to checkbox validation', async () => {
+ currentTestBed = createDetailTestBed(createDateBetweenRule('rule-date-to-checkbox'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ await openSelect(container.querySelectorAll<HTMLElement>('[data-u-comp="select"]')[0]);
+ const options = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"], [role="menuitemradio"]'));
+ const checkboxOption = options.find((item) => item.textContent?.includes('sheets-data-validation.checkbox.title'))!;
+
+ await clickElement(checkboxOption);
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toMatchObject({
+ type: DataValidationType.CHECKBOX,
+ operator: undefined,
+ formula1: undefined,
+ formula2: undefined,
+ });
+ });
+
+ it('preserves dropdown choices and colors when switching a list rule to multi-select', async () => {
+ currentTestBed = createDetailTestBed(createListRule('rule-list-to-multiple'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ await openSelect(container.querySelectorAll<HTMLElement>('[data-u-comp="select"]')[0]);
+ const options = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"], [role="menuitemradio"]'));
+ const multipleListOption = options.find((item) => item.textContent?.includes('sheets-data-validation.listMultiple.title'))!;
+
+ await clickElement(multipleListOption);
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toMatchObject({
+ type: DataValidationType.LIST_MULTIPLE,
+ formula1: serializeListOptions(['Pending', 'Approved']),
+ formula2: '#FDCECE,#DEF6A2',
+ renderMode: DataValidationRenderMode.CUSTOM,
+ });
+ });
+
+ it('removes stale date bound inputs after changing validation type to checkbox', async () => {
+ currentTestBed = createDetailTestBed(createDateBetweenRule('rule-date-editor-to-checkbox'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ const dateInputs = Array.from(container.querySelectorAll<HTMLInputElement>('[data-u-comp="input"] input'));
+
+ expect(dateInputs.map((input) => input.value)).toEqual(['2024-01-01', '2024-01-31']);
+
+ await openSelect(container.querySelectorAll<HTMLElement>('[data-u-comp="select"]')[0]);
+ const options = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"], [role="menuitemradio"]'));
+ const checkboxOption = options.find((item) => item.textContent?.includes('sheets-data-validation.checkbox.title'))!;
+
+ await clickElement(checkboxOption);
+
+ expect(Array.from(container.querySelectorAll<HTMLInputElement>('[data-u-comp="input"] input')).map((input) => input.value)).toEqual([]);
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toMatchObject({
+ type: DataValidationType.CHECKBOX,
+ operator: undefined,
+ formula1: undefined,
+ formula2: undefined,
+ });
+ });
+
+ it('keeps the switched checkbox rule while saving panel options after a type change', async () => {
+ currentTestBed = createDetailTestBed(createDateBetweenRule('rule-date-checkbox-options'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ await openSelect(container.querySelectorAll<HTMLElement>('[data-u-comp="select"]')[0]);
+ const options = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"], [role="menuitemradio"]'));
+ const checkboxOption = options.find((item) => item.textContent?.includes('sheets-data-validation.checkbox.title'))!;
+
+ await clickElement(checkboxOption);
+ await clickElement(findElementByText(container, 'panel.options'));
+ await clickElement(container.querySelectorAll<HTMLInputElement>('[data-u-comp="radio"] input')[1]);
+ await waitForDebounce();
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toMatchObject({
+ type: DataValidationType.CHECKBOX,
+ operator: undefined,
+ formula1: undefined,
+ formula2: undefined,
+ errorStyle: DataValidationErrorStyle.STOP,
+ });
+ });
+
+ it('removes the active rule and closes the detail panel from the remove action', async () => {
+ currentTestBed = createDetailTestBed(createDateRule('rule-date-remove'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeDefined();
+
+ await clickElement(findButtonByText(container, 'panel.removeRule'));
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeUndefined();
+ expect(currentTestBed.panelService.activeRule).toBe(null);
+ expect(container.querySelector('[data-u-comp="data-validation-detail"]')).toBe(null);
+ });
});
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx
index a4f96686b4..2bdd2769a0 100644
--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx
@@ -69,6 +69,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import {
RangeProtectionRuleModel,
RefRangeService,
+ SetWorksheetActiveOperation,
SheetInterceptorService,
SheetSkeletonService,
SheetsSelectionsService,
@@ -454,6 +455,7 @@ function createItemTestBed(rule: ISheetDataValidationRule = createCheckboxRule()
commandService.registerCommand(AddSheetDataValidationCommand);
commandService.registerCommand(RemoveSheetAllDataValidationCommand);
commandService.registerCommand(RemoveSheetDataValidationCommand);
+ commandService.registerCommand(SetWorksheetActiveOperation);
const validatorRegistry = injector.get(DataValidatorRegistryService);
validatorRegistry.register(injector.createInstance(CheckboxValidator));
@@ -550,6 +552,29 @@ describe('DataValidationItem', () => {
expect(currentTestBed.markSelectionService.removed).toEqual(['shape-0', 'shape-1']);
});
+ it('clears highlighted rule ranges when the hovered item is unmounted', async () => {
+ currentTestBed = createItemTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ const item = renderItem(root, currentTestBed, () => undefined);
+
+ await enterItem(item);
+
+ expect(currentTestBed.markSelectionService.added.map((entry) => entry.selection.range)).toEqual([
+ FIRST_RANGE,
+ SECOND_RANGE,
+ ]);
+
+ act(() => {
+ root?.unmount();
+ });
+ root = undefined;
+
+ expect(currentTestBed.markSelectionService.removed).toEqual(['shape-0', 'shape-1']);
+ });
+
it('removes the hovered rule through the sheet data-validation command without selecting the item', async () => {
currentTestBed = createItemTestBed();
container = document.createElement('div');
@@ -829,6 +854,67 @@ describe('DataValidationPanel', () => {
expect(container.querySelector('[data-u-comp="data-validation-detail"]')).not.toBeNull();
});
+ it('keeps showing a cross-sheet active rule while its formula editor has focus', async () => {
+ currentTestBed = createItemTestBed();
+ currentTestBed.panelService.setActiveRule({
+ unitId: UNIT_ID,
+ subUnitId: OTHER_SUB_UNIT_ID,
+ rule: currentTestBed.rule,
+ });
+ currentTestBed.panelService.setFocusFormulaEditorActiveRuleSubUnitId(OTHER_SUB_UNIT_ID);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <DataValidationPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(container.querySelector('[data-u-comp="data-validation-detail"]')).not.toBeNull();
+ expect(currentTestBed.panelService.activeRule?.subUnitId).toBe(OTHER_SUB_UNIT_ID);
+ });
+
+ it('returns to the cross-sheet active rule sheet after the focused rule is accepted', async () => {
+ currentTestBed = createItemTestBed();
+ currentTestBed.panelService.setActiveRule({
+ unitId: UNIT_ID,
+ subUnitId: OTHER_SUB_UNIT_ID,
+ rule: currentTestBed.rule,
+ });
+ currentTestBed.panelService.setFocusFormulaEditorActiveRuleSubUnitId(OTHER_SUB_UNIT_ID);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <DataValidationPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(currentTestBed.workbook.getActiveSheet().getSheetId()).toBe(SUB_UNIT_ID);
+
+ const detail = container.querySelector('[data-u-comp="data-validation-detail"]') as HTMLElement;
+ const buttons = Array.from(detail.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];
+ const doneButton = buttons[buttons.length - 1];
+
+ await act(async () => {
+ doneButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(currentTestBed.workbook.getActiveSheet().getSheetId()).toBe(OTHER_SUB_UNIT_ID);
+ expect(currentTestBed.panelService.activeRule).toBeNull();
+ });
+
it('opens the selected rule in detail and returns to the list after the rule is accepted', async () => {
currentTestBed = createItemTestBed();
container = document.createElement('div');
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.spec.tsx
index 9432f93731..6a3ba7fb7d 100644
--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.spec.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.spec.tsx
@@ -15,12 +15,19 @@
*/
import type { IDataValidationRuleOptions } from '@univerjs/core';
-import { DataValidationErrorStyle, LocaleService, LocaleType, Univer } from '@univerjs/core';
+import {
+ DataValidationErrorStyle,
+ DataValidationRenderMode,
+ LocaleService,
+ LocaleType,
+ Univer,
+} from '@univerjs/core';
import { ComponentManager, RediContext } from '@univerjs/ui';
import { act, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it } from 'vitest';
import { DataValidationOptions } from '../DataValidationOptions';
+import { ListRenderModeInput } from '../ListRenderModeInput';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -40,6 +47,12 @@ function createOptionsTestBed() {
showInfo: 'Show message',
showWarning: 'Show warning',
},
+ renderMode: {
+ arrow: 'Arrow',
+ chip: 'Chip',
+ label: 'Display style',
+ text: 'Text',
+ },
},
},
});
@@ -53,6 +66,7 @@ function createOptionsTestBed() {
function OptionsHarness(props: {
initialValue: IDataValidationRuleOptions;
changes: IDataValidationRuleOptions[];
+ extraComponent?: string;
}) {
const [value, setValue] = useState(props.initialValue);
@@ -63,6 +77,7 @@ function OptionsHarness(props: {
props.changes.push(nextValue);
setValue(nextValue);
}}
+ extraComponent={props.extraComponent}
/>
);
}
@@ -147,4 +162,85 @@ describe('DataValidationOptions', () => {
error: 'Only choose approved values',
});
});
+
+ it('keeps a custom error message while message display is toggled off and back on', async () => {
+ currentTestBed = createOptionsTestBed();
+ const changes: IDataValidationRuleOptions[] = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <OptionsHarness
+ initialValue={{
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: true,
+ error: 'Keep this instruction',
+ }}
+ changes={changes}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await clickElement(container.firstElementChild as HTMLElement);
+ const showMessageCheckbox = container.querySelector<HTMLInputElement>('[data-u-comp="checkbox"] input')!;
+
+ await clickElement(showMessageCheckbox);
+
+ expect(changes.at(-1)).toEqual({
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: false,
+ error: 'Keep this instruction',
+ });
+
+ await clickElement(showMessageCheckbox);
+
+ expect(changes.at(-1)).toEqual({
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: true,
+ error: 'Keep this instruction',
+ });
+ expect(container.querySelector<HTMLInputElement>('[data-u-comp="input"] input')?.value).toBe('Keep this instruction');
+ });
+
+ it('saves list render mode changes from the registered extra options component', async () => {
+ currentTestBed = createOptionsTestBed();
+ currentTestBed.injector
+ .get(ComponentManager)
+ .register(ListRenderModeInput.componentKey, ListRenderModeInput);
+ const changes: IDataValidationRuleOptions[] = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <OptionsHarness
+ initialValue={{
+ errorStyle: DataValidationErrorStyle.WARNING,
+ renderMode: DataValidationRenderMode.CUSTOM,
+ showErrorMessage: false,
+ }}
+ changes={changes}
+ extraComponent={ListRenderModeInput.componentKey}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await clickElement(container.firstElementChild as HTMLElement);
+ await clickElement(container.querySelectorAll<HTMLInputElement>('[data-u-comp="radio"] input')[1]);
+
+ expect(changes.at(-1)).toEqual({
+ errorStyle: DataValidationErrorStyle.WARNING,
+ renderMode: DataValidationRenderMode.ARROW,
+ showErrorMessage: false,
+ });
+ });
});
diff --git a/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/formula-input.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/formula-input.spec.tsx
new file mode 100644
index 0000000000..78706a3fa5
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/formula-input.spec.tsx
@@ -0,0 +1,199 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IFormulaValue } from '@univerjs/data-validation';
+import type { FormulaInputType } from '../interface';
+import { LocaleService, LocaleType, Univer } from '@univerjs/core';
+import { RediContext } from '@univerjs/ui';
+import { act, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { BaseFormulaInput } from '../BaseFormulaInput';
+import { CheckboxFormulaInput } from '../CheckboxFormulaInput';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function createFormulaInputTestBed() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'sheets-data-validation-ui': {
+ checkbox: {
+ checked: 'Checked',
+ tips: 'Use custom cell values',
+ unchecked: 'Unchecked',
+ },
+ panel: {
+ formulaAnd: 'and',
+ formulaPlaceholder: 'Enter a formula',
+ valuePlaceholder: 'Enter a value',
+ },
+ },
+ },
+ });
+
+ return {
+ injector,
+ univer,
+ };
+}
+
+function FormulaInputHarness(props: {
+ Component: FormulaInputType;
+ changes: IFormulaValue[];
+ initialValue: IFormulaValue;
+ isTwoFormula?: boolean;
+}) {
+ const [value, setValue] = useState(props.initialValue);
+
+ return (
+ <props.Component
+ isTwoFormula={props.isTwoFormula}
+ value={value}
+ onChange={(nextValue) => {
+ if (!nextValue) {
+ return;
+ }
+
+ props.changes.push(nextValue);
+ setValue(nextValue);
+ }}
+ ruleId="rule-formula"
+ subUnitId="sheet-1"
+ unitId="unit-1"
+ />
+ );
+}
+
+async function changeInputValue(input: HTMLInputElement, value: string) {
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+async function clickElement(element: HTMLElement) {
+ await act(async () => {
+ element.click();
+ await Promise.resolve();
+ });
+}
+
+describe('formula input behaviors', () => {
+ let root: ReturnType<typeof createRoot> | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createFormulaInputTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('keeps the other bound when editing a two-bound formula rule', async () => {
+ currentTestBed = createFormulaInputTestBed();
+ const changes: IFormulaValue[] = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <FormulaInputHarness
+ Component={BaseFormulaInput}
+ changes={changes}
+ initialValue={{ formula1: '10', formula2: '20' }}
+ isTwoFormula
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const inputs = container.querySelectorAll<HTMLInputElement>('[data-u-comp="input"] input');
+
+ await changeInputValue(inputs[0], '15');
+ expect(changes.at(-1)).toEqual({ formula1: '15', formula2: '20' });
+
+ await changeInputValue(inputs[1], '25');
+ expect(changes.at(-1)).toEqual({ formula1: '15', formula2: '25' });
+ });
+
+ it('clears custom checkbox values when default boolean cell values are restored', async () => {
+ currentTestBed = createFormulaInputTestBed();
+ const changes: IFormulaValue[] = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <FormulaInputHarness
+ Component={CheckboxFormulaInput}
+ changes={changes}
+ initialValue={{ formula1: 'DONE', formula2: 'TODO' }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await clickElement(container.querySelector<HTMLInputElement>('[data-u-comp="checkbox"] input')!);
+
+ expect(changes.at(-1)).toEqual({ formula1: undefined, formula2: undefined });
+ expect(container.querySelectorAll<HTMLInputElement>('[data-u-comp="input"] input')).toHaveLength(0);
+ });
+
+ it('keeps the paired checkbox value when editing one custom checkbox value', async () => {
+ currentTestBed = createFormulaInputTestBed();
+ const changes: IFormulaValue[] = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <FormulaInputHarness
+ Component={CheckboxFormulaInput}
+ changes={changes}
+ initialValue={{ formula1: 'DONE', formula2: 'TODO' }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const inputs = container.querySelectorAll<HTMLInputElement>('[data-u-comp="input"] input');
+
+ await changeInputValue(inputs[0], 'YES');
+ expect(changes.at(-1)).toEqual({ formula1: 'YES', formula2: 'TODO' });
+
+ await changeInputValue(inputs[1], 'NO');
+ expect(changes.at(-1)).toEqual({ formula1: 'YES', formula2: 'NO' });
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/list-formula-input.spec.ts b/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/list-formula-input.spec.ts
index eec97ad1e2..ced25016ac 100644
--- a/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/list-formula-input.spec.ts
+++ b/packages/sheets-data-validation-ui/src/views/components/formula-input/__tests__/list-formula-input.spec.ts
@@ -28,4 +28,16 @@ describe('ListFormulaInput', () => {
expect(deserializeListOptions(payload.formula1)).toEqual(['a,b', 'c']);
expect(payload.formula2).toBe('#ff0000,');
});
+
+ it('keeps colors aligned with the first non-empty occurrence of each custom option', () => {
+ const payload = buildCustomListFormulaPayload([
+ { label: '', color: '#ff0000' },
+ { label: 'Pending', color: '#ffffff' },
+ { label: 'Done', color: '#00ff00' },
+ { label: 'Pending', color: '#0000ff' },
+ ], '#ffffff');
+
+ expect(deserializeListOptions(payload.formula1)).toEqual(['Pending', 'Done']);
+ expect(payload.formula2).toBe(',#00ff00');
+ });
});
diff --git a/packages/sheets-data-validation-ui/src/views/validator-views/__tests__/validator-views.spec.ts b/packages/sheets-data-validation-ui/src/views/validator-views/__tests__/validator-views.spec.ts
new file mode 100644
index 0000000000..5a7026f80d
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/views/validator-views/__tests__/validator-views.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 type { IFormulaResult } from '@univerjs/data-validation';
+import { DataValidationType, ICommandService, Injector, IUniverInstanceService, LocaleService, ThemeService } from '@univerjs/core';
+import { DataValidatorDropdownType } from '@univerjs/data-validation';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { DataValidationFormulaService, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
+import { describe, expect, it } from 'vitest';
+import { DateShowTimeOption } from '../../components/DateShowTimeOption';
+import {
+ BASE_FORMULA_INPUT_NAME,
+ CHECKBOX_FORMULA_INPUT_NAME,
+ CUSTOM_FORMULA_INPUT_NAME,
+ LIST_FORMULA_INPUT_NAME,
+} from '../../components/formula-input';
+import { ListRenderModeInput } from '../../components/ListRenderModeInput';
+
+class TestPath2D {
+ constructor(_path?: string) {
+ // Path details are not used by these view choice tests.
+ }
+}
+
+Object.assign(globalThis, { Path2D: TestPath2D });
+
+class TestCommandService {}
+
+class TestUniverInstanceService {}
+
+class TestRenderManagerService {}
+
+class TestLocaleService {}
+
+class TestThemeService {
+ getColorFromTheme(): string {
+ return '#155eef';
+ }
+}
+
+class TestFormulaService {
+ getRuleFormulaResult(): Promise<IFormulaResult[] | undefined> {
+ return Promise.resolve(undefined);
+ }
+
+ getRuleFormulaResultSync(): IFormulaResult[] | undefined {
+ return undefined;
+ }
+}
+
+class TestSheetDataValidationModel {}
+
+function createValidatorViewInjector() {
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([SheetDataValidationModel, { useClass: TestSheetDataValidationModel as never }]);
+ injector.add([DataValidationFormulaService, { useClass: TestFormulaService as never }]);
+ injector.add([ThemeService, { useClass: TestThemeService as never }]);
+ return injector;
+}
+
+describe('sheet data validation view choices', () => {
+ it('uses list editors and dropdown renderers for list validation rules', async () => {
+ const { DropdownMultipleWidget } = await import('../../widgets/dropdown-multiple-widget');
+ const { DropdownWidget } = await import('../../widgets/dropdown-widget');
+ const { ListMultipleValidatorView } = await import('../list-multiple-view');
+ const { ListValidatorView } = await import('../list-validator-view');
+ const injector = createValidatorViewInjector();
+
+ const singleListView = injector.createInstance(ListValidatorView);
+ const multipleListView = injector.createInstance(ListMultipleValidatorView);
+
+ expect(singleListView.id).toBe(DataValidationType.LIST);
+ expect(singleListView.formulaInput).toBe(LIST_FORMULA_INPUT_NAME);
+ expect(singleListView.optionsInput).toBe(ListRenderModeInput.componentKey);
+ expect(singleListView.dropdownType).toBe(DataValidatorDropdownType.LIST);
+ expect(singleListView.canvasRender).toBeInstanceOf(DropdownWidget);
+
+ expect(multipleListView.id).toBe(DataValidationType.LIST_MULTIPLE);
+ expect(multipleListView.dropdownType).toBe(DataValidatorDropdownType.MULTIPLE_LIST);
+ expect(multipleListView.canvasRender).toBeInstanceOf(DropdownMultipleWidget);
+ });
+
+ it('uses specialized formula editors for checkbox, custom, date, and numeric validation rules', async () => {
+ const { CheckboxRender } = await import('../../widgets/checkbox-widget');
+ const { CheckboxValidatorView } = await import('../checkbox-validator-view');
+ const { CustomFormulaValidatorView } = await import('../custom-validator-view');
+ const { DateValidatorView } = await import('../date-validator-view');
+ const { DecimalValidatorView } = await import('../decimal-validator-view');
+ const { TextLengthValidatorView } = await import('../text-length-validator.view');
+ const { WholeValidatorView } = await import('../whole-validator-view');
+ const injector = createValidatorViewInjector();
+
+ const checkboxView = injector.createInstance(CheckboxValidatorView);
+ const customView = injector.createInstance(CustomFormulaValidatorView);
+ const dateView = injector.createInstance(DateValidatorView);
+ const decimalView = injector.createInstance(DecimalValidatorView);
+ const textLengthView = injector.createInstance(TextLengthValidatorView);
+ const wholeView = injector.createInstance(WholeValidatorView);
+
+ expect(checkboxView.id).toBe(DataValidationType.CHECKBOX);
+ expect(checkboxView.formulaInput).toBe(CHECKBOX_FORMULA_INPUT_NAME);
+ expect(checkboxView.canvasRender).toBeInstanceOf(CheckboxRender);
+
+ expect(customView.id).toBe(DataValidationType.CUSTOM);
+ expect(customView.formulaInput).toBe(CUSTOM_FORMULA_INPUT_NAME);
+
+ expect(dateView.id).toBe(DataValidationType.DATE);
+ expect(dateView.formulaInput).toBe(BASE_FORMULA_INPUT_NAME);
+ expect(dateView.optionsInput).toBe(DateShowTimeOption.componentKey);
+ expect(dateView.dropdownType).toBe(DataValidatorDropdownType.DATE);
+
+ expect(decimalView.formulaInput).toBe(BASE_FORMULA_INPUT_NAME);
+ expect(textLengthView.formulaInput).toBe(BASE_FORMULA_INPUT_NAME);
+ expect(wholeView.formulaInput).toBe(BASE_FORMULA_INPUT_NAME);
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/views/validator-views/date-validator-view.ts b/packages/sheets-data-validation-ui/src/views/validator-views/date-validator-view.ts
index 167bca8bc6..6f393c8086 100644
--- a/packages/sheets-data-validation-ui/src/views/validator-views/date-validator-view.ts
+++ b/packages/sheets-data-validation-ui/src/views/validator-views/date-validator-view.ts
@@ -17,7 +17,7 @@
import { DataValidationType } from '@univerjs/core';
import { DataValidatorDropdownType } from '@univerjs/data-validation';
import { DateShowTimeOption } from '../components/DateShowTimeOption';
-import { BASE_FORMULA_INPUT_NAME } from '../components/formula-input/formula-input';
+import { BASE_FORMULA_INPUT_NAME } from '../components/formula-input';
import { BaseSheetDataValidatorView } from './sheet-validator-view';
export class DateValidatorView extends BaseSheetDataValidatorView {
diff --git a/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts b/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts
index 0273ca447c..0f8f6851ea 100644
--- a/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts
+++ b/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts
@@ -17,7 +17,15 @@
import type { ICellRenderContext, IDataValidationRule } from '@univerjs/core';
import type { IFormulaResult } from '@univerjs/data-validation';
import type { ISetRangeValuesCommandParams } from '@univerjs/sheets';
-import { DataValidationType, ICommandService, Injector, IUniverInstanceService, LocaleService, ThemeService } from '@univerjs/core';
+import {
+ DataValidationRenderMode,
+ DataValidationType,
+ ICommandService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ ThemeService,
+} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { SetRangeValuesCommand } from '@univerjs/sheets';
import { DataValidationFormulaService, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
@@ -62,12 +70,14 @@ class TestThemeService {
}
class TestFormulaService {
+ results: { result: { v: string }[][][][] }[] | undefined;
+
getRuleFormulaResult(): Promise<IFormulaResult[] | undefined> {
- return Promise.resolve(undefined);
+ return Promise.resolve(this.results as IFormulaResult[] | undefined);
}
getRuleFormulaResultSync(): IFormulaResult[] | undefined {
- return undefined;
+ return this.results as IFormulaResult[] | undefined;
}
}
@@ -77,8 +87,31 @@ class TestCheckboxValidator {
}
}
+class TestListValidator {
+ id = DataValidationType.LIST;
+
+ skipDefaultFontRender(): boolean {
+ return true;
+ }
+
+ getListWithColorMap(): Record<string, string> {
+ return {
+ Done: '#34c759',
+ Hold: '#ffcc00',
+ };
+ }
+}
+
+class TestListMultipleValidator extends TestListValidator {
+ override id = DataValidationType.LIST_MULTIPLE;
+
+ parseCellValue(value: unknown): string[] {
+ return String(value || '').split(',').filter(Boolean);
+ }
+}
+
class TestSheetDataValidationModel {
- readonly rule: IDataValidationRule = {
+ rule: IDataValidationRule = {
uid: 'rule-checkbox',
type: DataValidationType.CHECKBOX,
ranges: [{ startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 }],
@@ -86,17 +119,56 @@ class TestSheetDataValidationModel {
formula2: 'TODO',
};
- readonly validator = new TestCheckboxValidator();
+ readonly checkboxValidator = new TestCheckboxValidator();
+ readonly listValidator = new TestListValidator();
+ readonly listMultipleValidator = new TestListMultipleValidator();
getRuleByLocation(): IDataValidationRule {
return this.rule;
}
- getValidator(): TestCheckboxValidator {
- return this.validator;
+ getValidator(type: DataValidationType) {
+ if (type === DataValidationType.LIST) {
+ return this.listValidator;
+ }
+
+ if (type === DataValidationType.LIST_MULTIPLE) {
+ return this.listMultipleValidator;
+ }
+
+ return this.checkboxValidator;
}
}
+class RecordingRenderContext {
+ readonly fillStyles: unknown[] = [];
+
+ private _fillStyle: unknown;
+
+ get fillStyle(): unknown {
+ return this._fillStyle;
+ }
+
+ set fillStyle(value: unknown) {
+ this._fillStyle = value;
+ this.fillStyles.push(value);
+ }
+
+ save(): void {}
+ restore(): void {}
+ translateWithPrecision(): void {}
+ translate(): void {}
+ beginPath(): void {}
+ rect(): void {}
+ clip(): void {}
+ fill(): void {}
+ closePath(): void {}
+ moveTo(): void {}
+ lineTo(): void {}
+ arc(): void {}
+ fillText(): void {}
+}
+
function createInjector(): Injector {
const injector = new Injector();
injector.add([ICommandService, { useClass: RecordingCommandService as never }]);
@@ -147,6 +219,26 @@ function getCommandService(injector: Injector): RecordingCommandService {
return injector.get(ICommandService) as unknown as RecordingCommandService;
}
+function getDataValidationModel(injector: Injector): TestSheetDataValidationModel {
+ return injector.get(SheetDataValidationModel) as unknown as TestSheetDataValidationModel;
+}
+
+function getFormulaService(injector: Injector): TestFormulaService {
+ return injector.get(DataValidationFormulaService) as unknown as TestFormulaService;
+}
+
+function createSkeleton() {
+ return {
+ rowHeaderWidth: 8,
+ columnHeaderHeight: 12,
+ };
+}
+
+function getRenderedDropdownInfo(widget: unknown) {
+ const map = (widget as { _dropdownInfoMap: Map<string, Map<string, { left: number; top: number; width: number; height: number }>> })._dropdownInfoMap;
+ return map.get('sheet-1')!.get('3.4')!;
+}
+
describe('data validation canvas widgets', () => {
it('opens the single-select dropdown for the clicked cell and ignores secondary clicks', async () => {
const injector = createInjector();
@@ -195,6 +287,79 @@ describe('data validation canvas widgets', () => {
]);
});
+ it('uses the rendered capsule bounds for single-select dropdown hit testing', async () => {
+ const injector = createInjector();
+ const model = getDataValidationModel(injector);
+ model.rule = {
+ ...model.rule,
+ type: DataValidationType.LIST,
+ renderMode: DataValidationRenderMode.CUSTOM,
+ };
+ const { DropdownWidget } = await import('../dropdown-widget');
+ const widget = injector.createInstance(DropdownWidget);
+ const ctx = new RecordingRenderContext();
+ const cellContext = createCellContext('Done');
+
+ widget.drawWith(ctx as never, cellContext, createSkeleton() as never);
+ const dropdownInfo = getRenderedDropdownInfo(widget);
+
+ expect(widget.isHit({ x: dropdownInfo.left + 1, y: dropdownInfo.top + 1 }, cellContext)).toBe(true);
+ expect(widget.isHit({ x: dropdownInfo.left - 1, y: dropdownInfo.top + 1 }, cellContext)).toBe(false);
+ expect(widget.isHit({ x: dropdownInfo.left + 1, y: dropdownInfo.top - 1 }, cellContext)).toBe(false);
+ });
+
+ it('limits arrow-mode single-select hit testing to the dropdown arrow region', async () => {
+ const injector = createInjector();
+ const model = getDataValidationModel(injector);
+ model.rule = {
+ ...model.rule,
+ type: DataValidationType.LIST,
+ renderMode: DataValidationRenderMode.ARROW,
+ };
+ const { DropdownWidget } = await import('../dropdown-widget');
+ const widget = injector.createInstance(DropdownWidget);
+ const ctx = new RecordingRenderContext();
+ const cellContext = createCellContext('Done');
+
+ widget.drawWith(ctx as never, cellContext, createSkeleton() as never);
+ const dropdownInfo = getRenderedDropdownInfo(widget);
+
+ expect(widget.isHit({ x: dropdownInfo.left + 1, y: dropdownInfo.top + 1 }, cellContext)).toBe(true);
+ expect(widget.isHit({ x: dropdownInfo.left - 10, y: dropdownInfo.top + 1 }, cellContext)).toBe(false);
+ });
+
+ it('applies list option colors while drawing multi-select dropdown capsules', async () => {
+ const injector = createInjector();
+ const model = getDataValidationModel(injector);
+ model.rule = {
+ ...model.rule,
+ type: DataValidationType.LIST_MULTIPLE,
+ };
+ const { DropdownMultipleWidget } = await import('../dropdown-multiple-widget');
+ const widget = injector.createInstance(DropdownMultipleWidget);
+ const ctx = new RecordingRenderContext();
+
+ widget.drawWith(ctx as never, createCellContext('Done,Hold'), createSkeleton() as never, {} as never);
+
+ expect(ctx.fillStyles).toContain('#34c759');
+ expect(ctx.fillStyles).toContain('#ffcc00');
+ });
+
+ it('calculates autofit dimensions for multi-select list capsules', async () => {
+ const injector = createInjector();
+ const model = getDataValidationModel(injector);
+ model.rule = {
+ ...model.rule,
+ type: DataValidationType.LIST_MULTIPLE,
+ };
+ const { DropdownMultipleWidget } = await import('../dropdown-multiple-widget');
+ const widget = injector.createInstance(DropdownMultipleWidget);
+ const cellContext = createCellContext('Done,Hold,Done,Hold,Done,Hold');
+
+ expect(widget.calcCellAutoHeight(cellContext)).toBe(12);
+ expect(widget.calcCellAutoWidth(cellContext)).toBe(94);
+ });
+
it('toggles checkbox cells from the checked formula value to the unchecked formula value', async () => {
const injector = createInjector();
const { CheckboxRender } = await import('../checkbox-widget');
@@ -220,4 +385,76 @@ describe('data validation canvas widgets', () => {
},
]);
});
+
+ it('toggles checkbox cells from the unchecked formula value to the checked formula value', async () => {
+ const injector = createInjector();
+ const { CheckboxRender } = await import('../checkbox-widget');
+ const widget = injector.createInstance(CheckboxRender);
+
+ await widget.onPointerDown(createCellContext('TODO'), { button: 0 } as never);
+
+ expect(getCommandService(injector).commands).toEqual([
+ {
+ id: SetRangeValuesCommand.id,
+ params: {
+ range: {
+ startColumn: 9,
+ endColumn: 9,
+ startRow: 8,
+ endRow: 8,
+ },
+ value: {
+ v: 'DONE',
+ p: null,
+ },
+ } satisfies ISetRangeValuesCommandParams,
+ },
+ ]);
+ });
+
+ it('writes the resolved unchecked value when a checked checkbox rule uses formulas', async () => {
+ const injector = createInjector();
+ const model = getDataValidationModel(injector);
+ model.rule = {
+ ...model.rule,
+ formula1: '=A1',
+ formula2: '=B1',
+ };
+ getFormulaService(injector).results = [
+ { result: [[[[{ v: 'DONE' }]]]] },
+ { result: [[[[{ v: 'TODO' }]]]] },
+ ];
+ const { CheckboxRender } = await import('../checkbox-widget');
+ const widget = injector.createInstance(CheckboxRender);
+
+ await widget.onPointerDown(createCellContext('DONE'), { button: 0 } as never);
+
+ expect(getCommandService(injector).commands).toEqual([
+ {
+ id: SetRangeValuesCommand.id,
+ params: {
+ range: {
+ startColumn: 9,
+ endColumn: 9,
+ startRow: 8,
+ endRow: 8,
+ },
+ value: {
+ v: 'TODO',
+ p: null,
+ },
+ } satisfies ISetRangeValuesCommandParams,
+ },
+ ]);
+ });
+
+ it('keeps checkbox cell values unchanged on secondary clicks', async () => {
+ const injector = createInjector();
+ const { CheckboxRender } = await import('../checkbox-widget');
+ const widget = injector.createInstance(CheckboxRender);
+
+ await widget.onPointerDown(createCellContext('TODO'), { button: 2 } as never);
+
+ expect(getCommandService(injector).commands).toEqual([]);
+ });
});
diff --git a/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.ts b/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.ts
index c68faa5931..032729a62b 100644
--- a/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.ts
+++ b/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.ts
@@ -14,12 +14,106 @@
* limitations under the License.
*/
-import type { ICellData } from '@univerjs/core';
+import type { ICellData, Injector, LocaleService } from '@univerjs/core';
+import {
+ CellValueType,
+ DataValidationRenderMode,
+ DataValidationType,
+ UniverInstanceType,
+ WrapStrategy,
+} from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
-import { describe, expect, it } from 'vitest';
-import { getRuleFormulaResultSet, isValidListFormula } from '../list-validator';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DataValidationFormulaService } from '../../services/dv-formula.service';
+import { DataValidationListCacheService } from '../../services/dv-list-cache.service';
+import { getRuleFormulaResultSet, isValidListFormula, ListValidator } from '../list-validator';
+import { getDataValidationCellValue, getSheetRangeValueSet, getTransformedFormula } from '../util';
+
+function createWorksheet() {
+ return {
+ getSheetId: () => 'sheet1',
+ getName: () => 'Sheet1',
+ getCellRaw: vi.fn((row: number, col: number) => {
+ const cells: Record<string, any> = {
+ '0,0': { v: 'Red' },
+ '0,1': { v: 'Green,Blue' },
+ '1,0': { v: '' },
+ '1,1': { v: 10 },
+ };
+ return cells[`${row},${col}`];
+ }),
+ };
+}
+
+function createContext() {
+ const worksheet = createWorksheet();
+ const workbook = {
+ getUnitId: () => 'unit1',
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: vi.fn((sheetId: string) => (sheetId === 'sheet1' ? worksheet : undefined)),
+ getSheetBySheetName: vi.fn((sheetName: string) => (sheetName === 'Sheet1' ? worksheet : undefined)),
+ };
+ const localeService = {
+ t: vi.fn((key: string) => key),
+ } as unknown as LocaleService;
+ const formulaService = {
+ getRuleFormulaResult: vi.fn(async () => ([{
+ result: [[[
+ [{ v: 'Blue' }, { v: 7, t: CellValueType.NUMBER, s: { n: { pattern: '0.00' } } }],
+ [{ v: null }, { v: 'Red' }],
+ ]]],
+ }])),
+ };
+ const listCacheService = {
+ getOrCompute: vi.fn(() => ({
+ list: ['Red', 'Green', 'Blue'],
+ listWithColor: [{ label: 'Red', color: '#ff0000' }, { label: 'Green', color: '#00ff00' }],
+ colorMap: { Red: '#ff0000', Green: '#00ff00' },
+ })),
+ };
+ const lexerTreeBuilder = new LexerTreeBuilder();
+ const univerInstanceService = {
+ getUnit: vi.fn(() => workbook),
+ getUniverSheetInstance: vi.fn(() => workbook),
+ getCurrentUnitOfType: vi.fn((type: UniverInstanceType) => (type === UniverInstanceType.UNIVER_SHEET ? workbook : undefined)),
+ };
+ const injector = {
+ get(token: unknown) {
+ if (token === DataValidationFormulaService) {
+ return formulaService;
+ }
+ if (token === DataValidationListCacheService) {
+ return listCacheService;
+ }
+ if (token === LexerTreeBuilder) {
+ return lexerTreeBuilder;
+ }
+ if (String(token) === 'univer.current') {
+ return univerInstanceService;
+ }
+
+ throw new Error(`Unknown token: ${String(token)}`);
+ },
+ } as unknown as Injector;
+
+ return {
+ worksheet,
+ workbook,
+ localeService,
+ formulaService,
+ listCacheService,
+ lexerTreeBuilder,
+ univerInstanceService,
+ injector,
+ validator: new ListValidator(localeService, injector),
+ };
+}
describe('list-validator helpers', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it('collects formatted values and skips empty cells', () => {
const result = getRuleFormulaResultSet([
[
@@ -60,4 +154,161 @@ describe('list-validator helpers', () => {
lexer.dispose();
});
+
+ it('validates list formulas and rejects self-intersecting reference lists', () => {
+ const { validator } = createContext();
+
+ expect(validator.validatorFormula({ formula1: '' } as any, 'unit1', 'sheet1')).toEqual({
+ success: false,
+ formula1: 'sheets-data-validation.validFail.list',
+ });
+ expect(validator.validatorFormula({ formula1: '=SUM(A1:A2)' } as any, 'unit1', 'sheet1')).toEqual({
+ success: false,
+ formula1: 'sheets-data-validation.validFail.listInvalid',
+ });
+ expect(validator.validatorFormula({
+ formula1: '=A1:A2',
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 1, endColumn: 0 }],
+ } as any, 'unit1', 'sheet1')).toEqual({
+ success: false,
+ formula1: 'sheets-data-validation.validFail.listIntersects',
+ });
+ expect(validator.validatorFormula({
+ formula1: '=Sheet2!A1:A2',
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 1, endColumn: 0 }],
+ } as any, 'unit1', 'sheet1')).toEqual({
+ success: true,
+ formula1: undefined,
+ });
+ });
+
+ it('applies list option colors and validates list/list-multiple selections', async () => {
+ const { validator, listCacheService } = createContext();
+ const rule = {
+ uid: 'rule-list',
+ type: DataValidationType.LIST,
+ renderMode: DataValidationRenderMode.ARROW,
+ formula1: 'Red,Green,Blue',
+ } as any;
+
+ expect(validator.skipDefaultFontRender(rule)).toBe(true);
+ expect(validator.skipDefaultFontRender({ ...rule, renderMode: DataValidationRenderMode.TEXT })).toBe(false);
+ expect(validator.getExtraStyle(rule, 'Red', { style: { tb: WrapStrategy.OVERFLOW } as any })).toEqual({
+ bg: { rgb: '#ff0000' },
+ tb: WrapStrategy.CLIP,
+ });
+ expect(validator.getExtraStyle({ ...rule, renderMode: undefined }, 'Missing', { style: {} as any })).toEqual({
+ tb: WrapStrategy.WRAP,
+ });
+ expect(validator.parseCellValue('Red,Green,Blue')).toEqual(['Red', 'Green', 'Blue']);
+
+ await expect(validator.isValidType(
+ { value: 'Green', unitId: 'unit1', subUnitId: 'sheet1' } as any,
+ {} as any,
+ rule
+ )).resolves.toBe(true);
+ await expect(validator.isValidType(
+ { value: 'Missing', unitId: 'unit1', subUnitId: 'sheet1' } as any,
+ {} as any,
+ rule
+ )).resolves.toBe(false);
+ await expect(validator.isValidType(
+ { value: 'Red,Blue', unitId: 'unit1', subUnitId: 'sheet1' } as any,
+ {} as any,
+ { ...rule, type: DataValidationType.LIST_MULTIPLE }
+ )).resolves.toBe(true);
+ await expect(validator.isValidType(
+ { value: undefined, unitId: 'unit1', subUnitId: 'sheet1' } as any,
+ {} as any,
+ rule
+ )).resolves.toBe(true);
+
+ expect(listCacheService.getOrCompute).toHaveBeenCalled();
+ });
+
+ it('reads cached and async list options for the active workbook', async () => {
+ const { validator, formulaService, listCacheService } = createContext();
+ const formulaRule = {
+ uid: 'formula-list',
+ type: DataValidationType.LIST,
+ formula1: '=Sheet1!A1:B2',
+ } as any;
+
+ expect(validator.getList(formulaRule, 'unit1', 'sheet1')).toEqual(['Red', 'Green', 'Blue']);
+ expect(validator.getListWithColor(formulaRule, 'unit1', 'sheet1')).toEqual([
+ { label: 'Red', color: '#ff0000' },
+ { label: 'Green', color: '#00ff00' },
+ ]);
+ expect(validator.getListWithColorMap(formulaRule, 'unit1', 'sheet1')).toEqual({
+ Red: '#ff0000',
+ Green: '#00ff00',
+ });
+ await expect(validator.getListAsync(formulaRule, 'unit1', 'sheet1')).resolves.toEqual(['Blue', '7.00', 'Red']);
+ await expect(validator.getListAsync({ ...formulaRule, formula1: 'A,B' }, 'unit1', 'sheet1')).resolves.toEqual(['A', 'B']);
+ await expect(validator.parseFormula(formulaRule, 'unit1', 'sheet1')).resolves.toEqual({
+ formula1: undefined,
+ formula2: undefined,
+ isFormulaValid: true,
+ });
+ expect(validator.generateRuleName()).toBe('sheets-data-validation.list.name');
+ expect(validator.generateRuleErrorMessage()).toBe('sheets-data-validation.list.error');
+ expect(formulaService.getRuleFormulaResult).toHaveBeenCalled();
+ expect(listCacheService.getOrCompute).toHaveBeenCalled();
+ });
+
+ it('returns empty lists when no workbook or worksheet can be resolved', async () => {
+ const context = createContext();
+ context.univerInstanceService.getUniverSheetInstance.mockReturnValueOnce(undefined as any);
+ context.univerInstanceService.getCurrentUnitOfType.mockReturnValueOnce(undefined as any);
+
+ expect(context.validator.getList({ formula1: 'A,B' } as any, 'missing', 'sheet1')).toEqual([]);
+ context.univerInstanceService.getUniverSheetInstance.mockReturnValue({
+ getSheetBySheetId: () => undefined,
+ getActiveSheet: () => undefined,
+ } as any);
+ context.univerInstanceService.getCurrentUnitOfType.mockReturnValue(undefined as any);
+ expect(context.validator.getListWithColor({ formula1: 'A,B' } as any, 'unit1', 'missing')).toEqual([]);
+ expect(context.validator.getListWithColorMap({ formula1: 'A,B' } as any, 'unit1', 'missing')).toEqual({});
+ await expect(context.validator.getListAsync({ formula1: 'A,B' } as any, 'unit1', 'missing')).resolves.toEqual([]);
+ });
+
+ it('extracts values from sheet ranges and single cells', () => {
+ const { univerInstanceService } = createContext();
+
+ expect(getSheetRangeValueSet({
+ unitId: 'unit1',
+ sheetName: 'Sheet1',
+ range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 },
+ }, univerInstanceService as any, 'unit1', 'sheet1')).toEqual(['Red', 'Green,Blue', '10']);
+
+ expect(getDataValidationCellValue(null)).toBe('');
+ expect(getDataValidationCellValue({ v: 12 })).toBe('12');
+ expect(getDataValidationCellValue({ v: true })).toBe('true');
+ });
+
+ it('offsets formula references relative to the validated cell position', () => {
+ const lexer = {
+ moveFormulaRefOffset: vi.fn((formula: string, col: number, row: number) => `${formula}:${col}:${row}`),
+ };
+
+ expect(getTransformedFormula(lexer as any, {
+ formula1: '=A1',
+ formula2: 'B',
+ ranges: [{ startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 }],
+ } as any, {
+ row: 5,
+ col: 7,
+ } as any)).toEqual({
+ transformedFormula1: '=A1:4:3',
+ transformedFormula2: 'B',
+ });
+ expect(lexer.moveFormulaRefOffset).toHaveBeenCalledWith('=A1', 4, 3, true);
+ });
+
+ it('collects legal formula results from mixed formula result cells', () => {
+ expect(getRuleFormulaResultSet([
+ [{ v: '#VALUE!' }, { v: 'OK' }],
+ [{ v: 3, s: { n: { pattern: '0.0' } } } as any],
+ ] as any)).toEqual(['OK', '3.0']);
+ });
});
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts
new file mode 100644
index 0000000000..227b2baaa1
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/drawing-context-menu.controller.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ContextMenuPosition } from '@univerjs/ui';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { DrawingContextMenuController } from '../drawing-context-menu.controller';
+
+function createController(options?: {
+ selectedObjects?: Map<string, { oKey: string }>;
+ drawingLookup?: (oKey: string) => unknown;
+ scene?: any;
+}) {
+ const changeEnd$ = new Subject<any>();
+ const transformer = {
+ changeEnd$,
+ getSelectedObjectMap: vi.fn(() => options?.selectedObjects ?? new Map([['shape-1', { oKey: 'shape-1' }]])),
+ };
+ const scene = options?.scene ?? {
+ getTransformerByCreate: vi.fn(() => transformer),
+ };
+ const contextMenuService = {
+ triggerContextMenu: vi.fn(),
+ };
+ const controller = new DrawingContextMenuController(
+ { getDrawingOKey: vi.fn(options?.drawingLookup ?? (() => ({ unitId: 'u1' }))) } as any,
+ contextMenuService as any,
+ { getRenderById: vi.fn(() => ({ scene })) } as any,
+ { getAllUnitsForType: vi.fn(() => [{ getUnitId: () => 'unit-1' }]) } as any
+ );
+
+ return { controller, changeEnd$, contextMenuService, transformer };
+}
+
+describe('DrawingContextMenuController', () => {
+ it('opens drawing context menu on right click when all selected objects belong to drawings', () => {
+ const { controller, changeEnd$, contextMenuService } = createController();
+ const event = { button: 2 };
+
+ changeEnd$.next({ event });
+
+ expect(contextMenuService.triggerContextMenu).toHaveBeenCalledWith(event, ContextMenuPosition.DRAWING);
+ controller.dispose();
+ });
+
+ it('ignores non-right-clicks, empty selections and non-drawing selected objects', () => {
+ const { controller, changeEnd$, contextMenuService, transformer } = createController({
+ selectedObjects: new Map(),
+ });
+
+ changeEnd$.next({ event: { button: 0 } });
+ changeEnd$.next({ event: { button: 2 } });
+ transformer.getSelectedObjectMap.mockReturnValue(new Map([['shape-1', { oKey: 'shape-1' }]]));
+ (controller as any)._drawingManagerService.getDrawingOKey = vi.fn(() => null);
+ changeEnd$.next({ event: { button: 2 } });
+
+ expect(contextMenuService.triggerContextMenu).not.toHaveBeenCalled();
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-cell-image-autofill.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-cell-image-autofill.controller.spec.ts
new file mode 100644
index 0000000000..3ead5ce18f
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-cell-image-autofill.controller.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { SheetCellImageAutofillController } from '../sheet-cell-image-autofill.controller';
+import { resizeImageByCell } from '../sheet-cell-image.controller';
+
+vi.mock('../sheet-cell-image.controller', () => ({
+ resizeImageByCell: vi.fn(),
+}));
+
+describe('SheetCellImageAutofillController', () => {
+ it('registers an autofill hook that resizes every pasted cell image by its target cell', () => {
+ let hook: any;
+ const disposable = { dispose: vi.fn() };
+ const autoFillService = {
+ addHook: vi.fn((registeredHook) => {
+ hook = registeredHook;
+ return disposable;
+ }),
+ };
+ const injector = { id: 'injector' };
+ const controller = new SheetCellImageAutofillController(autoFillService as any, injector as any);
+ const location = { unitId: 'unit-1', subUnitId: 'sheet-1' };
+ const cellA = { p: { drawingsOrder: ['a'] } };
+ const cellB = { p: { drawingsOrder: ['b'] } };
+
+ hook.onBeforeSubmit(location, 'down', 'copy', {
+ 2: {
+ 3: cellA,
+ 4: cellB,
+ },
+ });
+
+ expect(autoFillService.addHook).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'sheet-cell-image-autofill',
+ onBeforeSubmit: expect.any(Function),
+ }));
+ expect(resizeImageByCell).toHaveBeenCalledWith(injector, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ }, cellA);
+ expect(resizeImageByCell).toHaveBeenCalledWith(injector, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 4,
+ }, cellB);
+
+ controller.dispose();
+ expect(disposable.dispose).toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-cell-image.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-cell-image.controller.spec.ts
new file mode 100644
index 0000000000..530b1e72fe
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-cell-image.controller.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
+import { INTERCEPTOR_POINT } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetCellImageController } from '../sheet-cell-image.controller';
+
+describe('SheetCellImageController', () => {
+ it('reloads editor drawing data when the embedded editor opens and clears it when closed', () => {
+ let interceptor: any;
+ const visible$ = new Subject<{ visible: boolean }>();
+ const drawingManagerService = {
+ removeDrawingDataForUnit: vi.fn(),
+ initializeNotification: vi.fn(),
+ };
+ const docDrawingController = { loadDrawingDataForUnit: vi.fn() };
+ const controller = new SheetCellImageController(
+ {
+ intercept: vi.fn((point, config) => {
+ expect(point).toBe(INTERCEPTOR_POINT.CELL_CONTENT);
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ {} as never,
+ drawingManagerService as never,
+ docDrawingController as never,
+ { visible$ } as never
+ );
+
+ visible$.next({ visible: true });
+ expect(drawingManagerService.removeDrawingDataForUnit).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ expect(docDrawingController.loadDrawingDataForUnit).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ expect(drawingManagerService.initializeNotification).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+
+ visible$.next({ visible: false });
+ expect(drawingManagerService.removeDrawingDataForUnit).toHaveBeenCalledTimes(2);
+
+ const rawCell = {
+ p: {
+ body: { dataStream: 'image\r\n' },
+ drawingsOrder: ['drawing-1'],
+ },
+ };
+ const result = interceptor.handler(rawCell, {
+ rawData: rawCell,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 2,
+ }, (cell: unknown) => cell);
+
+ expect(result).not.toBe(rawCell);
+ expect(result.interceptorStyle.tr).toEqual({ a: 0 });
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.spec.ts
new file mode 100644
index 0000000000..fe1d9057f0
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-permission.controller.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 { ObjectType } from '@univerjs/engine-render';
+import { InsertSheetDrawingCommand, SetDrawingArrangeCommand } from '@univerjs/sheets-drawing';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetDrawingPermissionController } from '../sheet-drawing-permission.controller';
+
+function createController() {
+ let beforeCommandHandler: ((command: { id: string; params?: unknown }) => void) | undefined;
+ const viewPermission$ = new Subject<Array<{ value: boolean }>>();
+ const editPermission$ = new Subject<Array<{ value: boolean }>>();
+ const activeSheet$ = new BehaviorSubject({ getSheetId: () => 'sheet-1' });
+ const workbook = {
+ activeSheet$,
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => activeSheet$.value,
+ };
+ const workbook$ = new BehaviorSubject(workbook);
+ const drawingObject = { objectType: ObjectType.IMAGE, oKey: 'image-drawing-1' };
+ const unrelatedObject = { objectType: ObjectType.IMAGE, oKey: 'image-other' };
+ const transformer = { clearSelectedObjects: vi.fn() };
+ const scene = {
+ getAllObjectsByOrder: vi.fn(() => [drawingObject, unrelatedObject]),
+ getTransformerByCreate: vi.fn(() => transformer),
+ removeObject: vi.fn(),
+ attachTransformerTo: vi.fn(),
+ detachTransformerFrom: vi.fn(),
+ };
+ const sheetDrawingService = {
+ setDrawingVisible: vi.fn(),
+ setDrawingEditable: vi.fn(),
+ getDrawingData: vi.fn(() => ({
+ 'drawing-1': { drawingId: 'drawing-1' },
+ })),
+ addNotification: vi.fn(),
+ };
+ let composePermissionCall = 0;
+ const permissionService = {
+ composePermission: vi.fn(() => [{ value: true }]),
+ composePermission$: vi.fn(() => {
+ composePermissionCall += 1;
+ return composePermissionCall === 1 ? viewPermission$ : editPermission$;
+ }),
+ };
+ const sheetPermissionCheckController = {
+ permissionCheckWithoutRange: vi.fn(() => false),
+ blockExecuteWithoutPermission: vi.fn(),
+ };
+
+ const controller = new SheetDrawingPermissionController(
+ {
+ beforeCommandExecuted: vi.fn((handler) => {
+ beforeCommandHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ { t: (key: string) => key } as never,
+ { getRenderById: vi.fn(() => ({ scene })) } as never,
+ permissionService as never,
+ {
+ getCurrentTypeOfUnit$: vi.fn(() => workbook$),
+ getCurrentUnitOfType: vi.fn(() => workbook),
+ } as never,
+ { currentUser$: new BehaviorSubject({ userID: 'user-1' }) } as never,
+ sheetPermissionCheckController as never,
+ sheetDrawingService as never
+ );
+
+ return {
+ controller,
+ viewPermission$,
+ editPermission$,
+ scene,
+ transformer,
+ drawingObject,
+ unrelatedObject,
+ sheetDrawingService,
+ beforeCommandHandler: () => beforeCommandHandler,
+ sheetPermissionCheckController,
+ };
+}
+
+describe('SheetDrawingPermissionController', () => {
+ it('hides sheet drawings and removes rendered drawing objects when view permission is revoked', () => {
+ const { controller, viewPermission$, scene, transformer, drawingObject, unrelatedObject, sheetDrawingService } = createController();
+
+ viewPermission$.next([{ value: false }]);
+
+ expect(sheetDrawingService.setDrawingVisible).toHaveBeenLastCalledWith(false);
+ expect(scene.removeObject).toHaveBeenCalledWith(drawingObject);
+ expect(scene.removeObject).not.toHaveBeenCalledWith(unrelatedObject);
+ expect(transformer.clearSelectedObjects).toHaveBeenCalled();
+
+ viewPermission$.next([{ value: true }]);
+
+ expect(sheetDrawingService.setDrawingVisible).toHaveBeenLastCalledWith(true);
+ expect(sheetDrawingService.addNotification).toHaveBeenCalledWith([{ drawingId: 'drawing-1' }]);
+
+ controller.dispose();
+ });
+
+ it('detaches and reattaches transformers when edit permission changes, and blocks protected commands', () => {
+ const {
+ controller,
+ editPermission$,
+ scene,
+ transformer,
+ drawingObject,
+ sheetDrawingService,
+ beforeCommandHandler,
+ sheetPermissionCheckController,
+ } = createController();
+
+ editPermission$.next([{ value: false }]);
+
+ expect(sheetDrawingService.setDrawingEditable).toHaveBeenLastCalledWith(false);
+ expect(scene.detachTransformerFrom).toHaveBeenCalledWith(drawingObject);
+ expect(transformer.clearSelectedObjects).toHaveBeenCalled();
+
+ editPermission$.next([{ value: true }]);
+
+ expect(sheetDrawingService.setDrawingEditable).toHaveBeenLastCalledWith(true);
+ expect(scene.attachTransformerTo).toHaveBeenCalledWith(drawingObject);
+ expect(sheetDrawingService.addNotification).toHaveBeenCalledWith([{ drawingId: 'drawing-1' }]);
+
+ beforeCommandHandler()?.({
+ id: InsertSheetDrawingCommand.id,
+ params: {
+ drawings: [{ unitId: 'unit-1', subUnitId: 'sheet-1' }],
+ },
+ });
+ beforeCommandHandler()?.({
+ id: SetDrawingArrangeCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ },
+ });
+
+ expect(sheetPermissionCheckController.permissionCheckWithoutRange).toHaveBeenCalledTimes(2);
+ expect(sheetPermissionCheckController.blockExecuteWithoutPermission).toHaveBeenCalledWith('sheets-drawing-ui.permission.dialog.editErr');
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.ts
new file mode 100644
index 0000000000..7cf56c8916
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.ts
@@ -0,0 +1,187 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DrawingTypeEnum, PRINT_CHART_COMPONENT_KEY } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { mountPrintingFloatDom } from '../../views/PrintingFloatDom';
+import { SheetDrawingPrintingController } from '../sheet-drawing-printing.controller';
+
+vi.mock('../../views/PrintingFloatDom', () => ({
+ mountPrintingFloatDom: vi.fn(() => vi.fn()),
+}));
+
+function createController() {
+ const interceptors = new Map<string, any>();
+ const points = {
+ PRINTING_COMPONENT_COLLECT: 'PRINTING_COMPONENT_COLLECT',
+ PRINTING_RANGE: 'PRINTING_RANGE',
+ PRINTING_DOM_COLLECT: 'PRINTING_DOM_COLLECT',
+ };
+ const drawingData = {
+ 'unit-1': {
+ 'sheet-1': {
+ order: ['image-1', 'chart-1', 'dom-1', 'grouped-image'],
+ data: {
+ 'image-1': {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'image-1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: { left: 20, top: 30, width: 120, height: 60 },
+ },
+ 'chart-1': {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'chart-1',
+ drawingType: DrawingTypeEnum.DRAWING_CHART,
+ transform: { left: 40, top: 50, width: 120, height: 60 },
+ },
+ 'dom-1': {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'dom-1',
+ drawingType: DrawingTypeEnum.DRAWING_DOM,
+ componentKey: 'custom-dom',
+ transform: { left: 80, top: 90, width: 40, height: 20 },
+ },
+ 'grouped-image': {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'grouped-image',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ groupId: 'group-1',
+ transform: { left: -100, top: -100, width: 20, height: 20 },
+ },
+ },
+ },
+ },
+ };
+ const render = {
+ scene: { scaleX: 1, scaleY: 1 },
+ with: vi.fn(() => ({
+ getSkeletonParam: vi.fn(() => ({
+ skeleton: {
+ getCellIndexByOffset: vi.fn((x: number, y: number) => ({
+ row: Math.floor(y / 10),
+ column: Math.floor(x / 10),
+ })),
+ },
+ })),
+ })),
+ };
+ const controller = new SheetDrawingPrintingController(
+ {
+ getPrintComponent: vi.fn((key: string) => `${key}-print`),
+ interceptor: {
+ getInterceptPoints: vi.fn(() => points),
+ intercept: vi.fn((point, config) => {
+ interceptors.set(point, config);
+ return { dispose: vi.fn() };
+ }),
+ },
+ } as never,
+ { renderDrawing: vi.fn() } as never,
+ { getDrawingDataForUnit: vi.fn(() => drawingData['unit-1']) } as never,
+ { getRenderById: vi.fn(() => render) } as never,
+ {
+ get: vi.fn((key: string) => {
+ if (key === PRINT_CHART_COMPONENT_KEY) return 'ChartPrintingComponent';
+ return `${key}-Component`;
+ }),
+ } as never,
+ {} as never
+ );
+
+ return { controller, interceptors, points };
+}
+
+describe('SheetDrawingPrintingController', () => {
+ it('renders printable image drawings into the print scene while leaving chart/dom to float dom printing', () => {
+ const { controller, interceptors, points } = createController();
+ const scene = {};
+ const next = vi.fn(() => 'next-result');
+
+ const result = interceptors.get(points.PRINTING_COMPONENT_COLLECT).handler(null, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ scene,
+ }, next);
+
+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledTimes(2);
+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'image-1' }), scene);
+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'grouped-image' }), scene);
+ expect(result).toBe('next-result');
+
+ controller.dispose();
+ });
+
+ it('expands the printed range to include ungrouped drawing bounds', () => {
+ const { controller, interceptors, points } = createController();
+ const next = vi.fn((range) => range);
+
+ const range = interceptors.get(points.PRINTING_RANGE).handler(
+ { startRow: 4, endRow: 4, startColumn: 4, endColumn: 4 },
+ { unitId: 'unit-1', subUnitId: 'sheet-1' },
+ next
+ );
+
+ expect(range).toEqual({
+ startRow: 3,
+ endRow: 11,
+ startColumn: 2,
+ endColumn: 16,
+ });
+
+ controller.dispose();
+ });
+
+ it('mounts chart and dom float components for printing and registers cleanup', () => {
+ const { controller, interceptors, points } = createController();
+ const unmount = vi.fn();
+ vi.mocked(mountPrintingFloatDom).mockReturnValueOnce(unmount);
+ const add = vi.fn((dispose: () => void) => dispose());
+ const disposableCollection = { add };
+ const next = vi.fn((value) => value);
+
+ const result = interceptors.get(points.PRINTING_DOM_COLLECT).handler(disposableCollection, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ scene: 'scene',
+ skeleton: 'skeleton',
+ worksheet: 'worksheet',
+ root: 'root',
+ }, next);
+
+ expect(mountPrintingFloatDom).toHaveBeenCalledWith(
+ {
+ floatDomInfos: [
+ expect.objectContaining({ drawingId: 'chart-1', componentKey: 'ChartPrintingComponent' }),
+ expect.objectContaining({ drawingId: 'dom-1', componentKey: 'custom-dom-print-Component' }),
+ ],
+ scene: 'scene',
+ skeleton: 'skeleton',
+ worksheet: 'worksheet',
+ },
+ 'root',
+ expect.any(Object)
+ );
+ expect(add).toHaveBeenCalled();
+ expect(unmount).toHaveBeenCalled();
+ expect(result).toBe(disposableCollection);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-cell-image-hover.render-controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-cell-image-hover.render-controller.spec.ts
new file mode 100644
index 0000000000..6c7adf02db
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-cell-image-hover.render-controller.spec.ts
@@ -0,0 +1,111 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CURSOR_TYPE } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SheetCellImageHoverRenderController } from '../sheet-celll-image-hover.render-controller';
+
+function createController(selectionPrimary: Record<string, unknown>) {
+ const currentRichTextNoDistinct$ = new Subject<any>();
+ const currentClickedCell$ = new Subject<any>();
+ const scene = {
+ setCursor: vi.fn(),
+ resetCursor: vi.fn(),
+ };
+ const drawingRenderService = {
+ previewImage: vi.fn(),
+ };
+ const controller = new SheetCellImageHoverRenderController(
+ { unitId: 'unit-1', scene } as never,
+ { currentRichTextNoDistinct$, currentClickedCell$ } as never,
+ {
+ getWorkbookSelections: vi.fn(() => ({
+ getCurrentSelections: vi.fn(() => [{ primary: selectionPrimary }]),
+ })),
+ } as never,
+ drawingRenderService as never,
+ {
+ getCurrentSkeleton: vi.fn(() => ({
+ imageCacheMap: {
+ getImage: vi.fn(() => ({ src: 'blob:image', width: 120, height: 80 })),
+ },
+ })),
+ } as never
+ );
+
+ return {
+ controller,
+ currentRichTextNoDistinct$,
+ currentClickedCell$,
+ scene,
+ drawingRenderService,
+ };
+}
+
+describe('SheetCellImageHoverRenderController', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('sets zoom cursor for a cell image in the active primary selection and resets it when leaving', () => {
+ vi.useFakeTimers();
+ const { controller, currentRichTextNoDistinct$, scene } = createController({
+ actualRow: 2,
+ actualColumn: 3,
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 3,
+ isMerged: false,
+ isMergedMainCell: false,
+ });
+
+ currentRichTextNoDistinct$.next({ unitId: 'unit-1', row: 2, col: 3, drawing: { drawing: {} } });
+ expect(scene.setCursor).toHaveBeenCalledWith(CURSOR_TYPE.ZOOM_IN);
+
+ vi.advanceTimersByTime(34);
+ currentRichTextNoDistinct$.next({ unitId: 'unit-1', row: 4, col: 4, drawing: { drawing: {} } });
+ expect(scene.resetCursor).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('previews a clicked cell image and clears cursor state', () => {
+ const { controller, currentRichTextNoDistinct$, currentClickedCell$, scene, drawingRenderService } = createController({
+ actualRow: 1,
+ actualColumn: 1,
+ startRow: 1,
+ endRow: 3,
+ startColumn: 1,
+ endColumn: 3,
+ isMerged: true,
+ isMergedMainCell: false,
+ });
+ const drawingOrigin = {
+ imageSourceType: 'BASE64',
+ source: 'image-source',
+ };
+
+ currentRichTextNoDistinct$.next({ unitId: 'unit-1', row: 2, col: 2, drawing: { drawing: { drawingOrigin } } });
+ currentClickedCell$.next({ drawing: { drawing: { drawingOrigin } } });
+
+ expect(drawingRenderService.previewImage).toHaveBeenCalledWith('preview-cell-image', 'blob:image', 120, 80);
+ expect(scene.resetCursor).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.render-controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.render-controller.spec.ts
new file mode 100644
index 0000000000..81afc6b623
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.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 { drawingPositionToTransform } from '@univerjs/sheets-drawing';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsDrawingRenderController } from '../sheet-drawing.render-controller';
+
+vi.mock('@univerjs/sheets-drawing', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/sheets-drawing')>();
+
+ return {
+ ...actual,
+ drawingPositionToTransform: vi.fn(() => ({ left: 24, top: 36, width: 120, height: 80 })),
+ };
+});
+
+describe('SheetsDrawingRenderController', () => {
+ it('initializes sheet drawing data and materializes sheet transforms for render objects', () => {
+ const drawingWithSheetTransform = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'drawing-1',
+ sheetTransform: {
+ from: { row: 1, column: 2 },
+ to: { row: 3, column: 4 },
+ },
+ } as any;
+ const drawingWithoutSkeleton = {
+ unitId: 'unit-1',
+ subUnitId: 'missing-sheet',
+ drawingId: 'drawing-2',
+ sheetTransform: {
+ from: { row: 5, column: 6 },
+ to: { row: 7, column: 8 },
+ },
+ };
+ const drawingData = {
+ 'sheet-1': {
+ data: {
+ 'drawing-1': drawingWithSheetTransform,
+ 'drawing-3': { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-3' },
+ },
+ },
+ 'missing-sheet': {
+ data: {
+ 'drawing-2': drawingWithoutSkeleton,
+ },
+ },
+ };
+ const sheetDrawingService = {
+ initializeNotification: vi.fn(),
+ getDrawingDataForUnit: vi.fn(() => drawingData),
+ };
+ const drawingManagerService = {
+ registerDrawingData: vi.fn(),
+ initializeNotification: vi.fn(),
+ };
+ const skeletonParam = { skeleton: { id: 'skeleton-1' } };
+ const sheetSkeletonService = {
+ getSkeletonParam: vi.fn((unitId: string, subUnitId: string) => {
+ if (unitId === 'unit-1' && subUnitId === 'sheet-1') {
+ return skeletonParam;
+ }
+
+ return null;
+ }),
+ };
+
+ const controller = new SheetsDrawingRenderController(
+ { unitId: 'unit-1' } as never,
+ sheetDrawingService as never,
+ drawingManagerService as never,
+ sheetSkeletonService as never
+ );
+
+ expect(sheetDrawingService.initializeNotification).toHaveBeenCalledWith('unit-1');
+ expect(drawingPositionToTransform).toHaveBeenCalledWith(drawingWithSheetTransform.sheetTransform, skeletonParam);
+ expect(drawingWithSheetTransform.transform).toEqual({ left: 24, top: 36, width: 120, height: 80 });
+ expect(drawingWithoutSkeleton).not.toHaveProperty('transform');
+ expect(drawingManagerService.registerDrawingData).toHaveBeenCalledWith('unit-1', drawingData);
+ expect(drawingManagerService.initializeNotification).toHaveBeenCalledWith('unit-1');
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsx b/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsx
new file mode 100644
index 0000000000..3b48f308b5
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsx
@@ -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 { Worksheet } from '@univerjs/core';
+import type { Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';
+import type { IFloatDomData } from '@univerjs/sheets-drawing';
+import { DrawingTypeEnum } from '@univerjs/core';
+import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { ComponentManager } from '@univerjs/ui';
+import { act } from 'react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createSheetsDrawingUiTestBed } from '../../__tests__/create-sheets-drawing-ui-test-bed';
+import { mountPrintingFloatDom } from '../PrintingFloatDom';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const PRINTING_COMPONENT_KEY = 'printing-visible-content';
+
+class TestPrintingScene {
+ getAncestorScale() {
+ return { scaleX: 1.5, scaleY: 2 };
+ }
+
+ getViewport(key: string) {
+ if (key !== SHEET_VIEWPORT_KEY.VIEW_MAIN) {
+ return null;
+ }
+
+ return {
+ left: 0,
+ top: 0,
+ right: 600,
+ bottom: 500,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ };
+ }
+}
+
+class TestPrintingSkeleton {
+ readonly rowHeaderWidth = 46;
+ readonly columnHeaderHeight = 28;
+
+ rowStartY(row: number): number {
+ return row * 24;
+ }
+
+ colStartX(column: number): number {
+ return column * 72;
+ }
+}
+
+class TestPrintingWorksheet {
+ getFreeze() {
+ return {
+ startColumn: 0,
+ startRow: 0,
+ xSplit: 0,
+ ySplit: 0,
+ };
+ }
+}
+
+function PrintingContent() {
+ return <span data-testid="printed-content">printed</span>;
+}
+
+function createFloatDomInfo(): IFloatDomData {
+ return {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: 'printed-float-dom',
+ drawingType: DrawingTypeEnum.DRAWING_DOM,
+ componentKey: PRINTING_COMPONENT_KEY,
+ transform: {
+ left: 20,
+ top: 40,
+ width: 200,
+ height: 100,
+ angle: 27,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ },
+ data: {
+ label: 'printing',
+ },
+ axisAlignSheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
+ },
+ };
+}
+
+describe('PrintingFloatDom', () => {
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createSheetsDrawingUiTestBed> | undefined;
+ let unmountPrintingFloatDom: (() => void) | undefined;
+
+ afterEach(() => {
+ act(() => {
+ unmountPrintingFloatDom?.();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ container = undefined;
+ currentTestBed = undefined;
+ unmountPrintingFloatDom = undefined;
+ });
+
+ it('prints floating doms with the scene scale applied to size and rotation', async () => {
+ currentTestBed = createSheetsDrawingUiTestBed(undefined, [
+ [ComponentManager],
+ ]);
+ currentTestBed.injector.get(ComponentManager).register(PRINTING_COMPONENT_KEY, PrintingContent);
+ const root = document.createElement('div');
+ container = root;
+ document.body.appendChild(root);
+
+ await act(async () => {
+ unmountPrintingFloatDom = mountPrintingFloatDom({
+ floatDomInfos: [createFloatDomInfo()],
+ scene: new TestPrintingScene() as unknown as Scene,
+ skeleton: new TestPrintingSkeleton() as unknown as SpreadsheetSkeleton,
+ worksheet: new TestPrintingWorksheet() as unknown as Worksheet,
+ }, root, currentTestBed!.injector);
+ await Promise.resolve();
+ });
+
+ const printedFloatDom = root.querySelector<HTMLElement>('#printed-float-dom');
+ if (!printedFloatDom?.parentElement) {
+ throw new Error('Printed float dom was not rendered');
+ }
+
+ expect(printedFloatDom.style.width).toBe('296px');
+ expect(printedFloatDom.style.height).toBe('196px');
+ expect(printedFloatDom.parentElement.style.width).toBe('298px');
+ expect(printedFloatDom.parentElement.style.height).toBe('198px');
+ expect(printedFloatDom.parentElement.style.transform).toBe('rotate(27deg)');
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx b/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx
index e62f411978..3fc53c4330 100644
--- a/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx
+++ b/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx
@@ -194,6 +194,26 @@ class TestBatchSaveImagesService implements IBatchSaveImagesService {
}
}
+class TestEmptyBatchSaveImagesService extends TestBatchSaveImagesService {
+ override getCellImagesInSelection(): ICellImageInfo[] {
+ return [];
+ }
+
+ override getCellImagesFromRanges(): ICellImageInfo[] {
+ return [];
+ }
+}
+
+class TestNoDataColumnsBatchSaveImagesService extends TestBatchSaveImagesService {
+ override getDataColumns(): Array<{ index: number; label: string }> {
+ return [];
+ }
+
+ override getDataColumnsForRanges(): Array<{ index: number; label: string }> {
+ return [];
+ }
+}
+
function createImage(imageId: string, cellAddress: string, row: number, col: number): ICellImageInfo {
return {
row,
@@ -240,11 +260,11 @@ describe('BatchSaveImagesDialog', () => {
container = undefined;
});
- async function renderDialog() {
+ async function renderDialog(batchSaveImagesService = TestBatchSaveImagesService) {
const testBed = createSheetsDrawingUiTestBed(undefined, [
[IDialogService, { useClass: TestDialogService }],
[IMarkSelectionService, { useClass: TestMarkSelectionService }],
- [IBatchSaveImagesService, { useClass: TestBatchSaveImagesService }],
+ [IBatchSaveImagesService, { useClass: batchSaveImagesService }],
]);
container = document.createElement('div');
@@ -323,6 +343,107 @@ describe('BatchSaveImagesDialog', () => {
testBed.univer.dispose();
});
+ it('removes the highlighted lookup column when column values are no longer used in file names', async () => {
+ const { testBed, batchSaveService, dialogService, markSelectionService } = await renderDialog();
+ const columnValueCheckbox = getCheckbox(container!, 1);
+
+ await act(async () => {
+ columnValueCheckbox.click();
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([{
+ startRow: 2,
+ endRow: 3,
+ startColumn: 4,
+ endColumn: 4,
+ }]);
+
+ await act(async () => {
+ columnValueCheckbox.click();
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([]);
+ expect(markSelectionService.removedIds).toEqual(['shape-1']);
+
+ await act(async () => {
+ getButton(container!, 'sheets-drawing-ui.save.confirm').click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedImages.map((image) => image.imageId)).toEqual(['image-a', 'image-b']);
+ expect(batchSaveService.savedConfig).toEqual({
+ fileNameParts: [FileNamePart.CELL_ADDRESS],
+ columnIndex: undefined,
+ });
+ expect(dialogService.closedIds).toEqual([BATCH_SAVE_IMAGES_DIALOG_ID]);
+
+ testBed.univer.dispose();
+ });
+
+ it('keeps cell address naming when the user tries to clear the last file name option', async () => {
+ const { testBed, batchSaveService, dialogService, markSelectionService } = await renderDialog();
+ const cellAddressCheckbox = getCheckbox(container!, 0);
+
+ await act(async () => {
+ cellAddressCheckbox.click();
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([]);
+
+ await act(async () => {
+ getButton(container!, 'sheets-drawing-ui.save.confirm').click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedImages.map((image) => image.imageId)).toEqual(['image-a', 'image-b']);
+ expect(batchSaveService.savedConfig).toEqual({
+ fileNameParts: [FileNamePart.CELL_ADDRESS],
+ columnIndex: undefined,
+ });
+ expect(dialogService.closedIds).toEqual([BATCH_SAVE_IMAGES_DIALOG_ID]);
+
+ testBed.univer.dispose();
+ });
+
+ it('clears lookup column highlight without saving when the dialog is cancelled', async () => {
+ const { testBed, batchSaveService, dialogService, markSelectionService } = await renderDialog();
+ const columnValueCheckbox = getCheckbox(container!, 1);
+
+ await act(async () => {
+ columnValueCheckbox.click();
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([{
+ startRow: 2,
+ endRow: 3,
+ startColumn: 4,
+ endColumn: 4,
+ }]);
+
+ await act(async () => {
+ getButton(container!, 'sheets-drawing-ui.save.cancel').click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedConfig).toBeNull();
+ expect(dialogService.closedIds).toEqual([BATCH_SAVE_IMAGES_DIALOG_ID]);
+
+ await act(async () => {
+ root!.unmount();
+ root = undefined;
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([]);
+ expect(markSelectionService.removedIds).toEqual(['shape-1']);
+
+ testBed.univer.dispose();
+ });
+
it('keeps the dialog open and shows the save error when saving fails', async () => {
const { testBed, batchSaveService, dialogService } = await renderDialog();
batchSaveService.failSaving();
@@ -338,4 +459,44 @@ describe('BatchSaveImagesDialog', () => {
testBed.univer.dispose();
});
+
+ it('saves by cell address when no lookup columns are available', async () => {
+ const { testBed, batchSaveService, dialogService, markSelectionService } = await renderDialog(TestNoDataColumnsBatchSaveImagesService);
+
+ expect(container!.querySelector('[data-u-comp="select"]')).toBeNull();
+ expect(container!.textContent).not.toContain('sheets-drawing-ui.save.useColumnValue');
+ expect(markSelectionService.activeRanges).toEqual([]);
+
+ await act(async () => {
+ getButton(container!, 'sheets-drawing-ui.save.confirm').click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedImages.map((image) => image.imageId)).toEqual(['image-a', 'image-b']);
+ expect(batchSaveService.savedConfig).toEqual({
+ fileNameParts: [FileNamePart.CELL_ADDRESS],
+ columnIndex: undefined,
+ });
+ expect(dialogService.closedIds).toEqual([BATCH_SAVE_IMAGES_DIALOG_ID]);
+
+ testBed.univer.dispose();
+ });
+
+ it('prevents confirming when the selection contains no images', async () => {
+ const { testBed, batchSaveService, dialogService, markSelectionService } = await renderDialog(TestEmptyBatchSaveImagesService);
+ const confirmButton = getButton(container!, 'sheets-drawing-ui.save.confirm');
+
+ expect(confirmButton.disabled).toBe(true);
+
+ await act(async () => {
+ confirmButton.click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedConfig).toBeNull();
+ expect(dialogService.closedIds).toEqual([]);
+ expect(markSelectionService.activeRanges).toEqual([]);
+
+ testBed.univer.dispose();
+ });
});
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx
index bef85342b2..62e9a7591a 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx
@@ -17,7 +17,7 @@
import type { ISheetDrawing } from '@univerjs/sheets-drawing';
import type { Root } from 'react-dom/client';
import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
-import { IDrawingManagerService } from '@univerjs/drawing';
+import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import { RediContext } from '@univerjs/ui';
@@ -155,4 +155,90 @@ describe('SheetDrawingAnchor', () => {
testBed.univer.dispose();
});
+
+ it('hides anchor controls when the transformer clears the sheet image selection', async () => {
+ const testBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ ]);
+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ const drawings = [
+ createSheetDrawing('drawing-a', SheetDrawingAnchorType.Position),
+ ];
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <SheetDrawingAnchor drawings={drawings} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(container.firstElementChild?.classList.contains('univer-hidden')).toBe(false);
+
+ await act(async () => {
+ renderManagerService.clearControl$.next(true);
+ await Promise.resolve();
+ });
+
+ expect(container.firstElementChild?.classList.contains('univer-hidden')).toBe(true);
+
+ testBed.univer.dispose();
+ });
+
+ it('syncs the selected anchor mode when the transformer starts editing another sheet image', async () => {
+ const testBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ ]);
+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ const drawings = [
+ createSheetDrawing('drawing-a', SheetDrawingAnchorType.Both),
+ createSheetDrawing('drawing-b', SheetDrawingAnchorType.None),
+ ];
+
+ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: testBed.unitId,
+ drawings,
+ });
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <SheetDrawingAnchor drawings={[drawings[0]]} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const options = Array.from(container.querySelectorAll<HTMLInputElement>('input[type="radio"]'));
+ expect(options.map((option) => option.checked)).toEqual([true, false, false]);
+
+ const drawingBShapeKey = getDrawingShapeKeyByDrawingSearch({
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ drawingId: 'drawing-b',
+ });
+
+ await act(async () => {
+ renderManagerService.changeStart$.next({
+ objects: new Map([[
+ drawingBShapeKey,
+ { oKey: drawingBShapeKey },
+ ]]),
+ });
+ await Promise.resolve();
+ });
+
+ expect(options.map((option) => option.checked)).toEqual([false, false, true]);
+
+ testBed.univer.dispose();
+ });
});
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
new file mode 100644
index 0000000000..f146868055
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
@@ -0,0 +1,284 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISheetDrawing } from '@univerjs/sheets-drawing';
+import type { Root } from 'react-dom/client';
+import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { DrawingImageClipService } from '@univerjs/drawing-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
+import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+import { SheetDrawingPanel } from '../SheetDrawingPanel';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestTransformer {
+ readonly clearControl$ = new Subject<boolean>();
+ readonly changeStart$ = new Subject<{ objects: Map<string, { oKey: string }> }>();
+ readonly changing$ = new Subject<{ objects: Map<string, { oKey: string }> }>();
+ readonly changeEnd$ = new Subject<{ objects: Map<string, { oKey: string }> }>();
+ keepRatio = true;
+
+ refreshControls() {
+ return {
+ changeNotification: () => undefined,
+ };
+ }
+}
+
+class TestScene {
+ ancestorLeft = 0;
+ ancestorTop = 0;
+
+ constructor(private readonly _transformer: TestTransformer) {}
+
+ getEngine() {
+ return {
+ activeScene: {
+ width: 500,
+ height: 400,
+ },
+ };
+ }
+
+ getTransformerByCreate() {
+ return this._transformer;
+ }
+}
+
+class TestRenderManagerService {
+ readonly transformer = new TestTransformer();
+ readonly scene = new TestScene(this.transformer);
+
+ getRenderById() {
+ return {
+ scene: this.scene,
+ };
+ }
+}
+
+function createSheetDrawing(unitId: string, subUnitId: string, drawingId: string, anchorType: SheetDrawingAnchorType): ISheetDrawing {
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType: ImageSourceType.URL,
+ source: `https://example.com/${drawingId}.png`,
+ anchorType,
+ transform: {
+ left: 10,
+ top: 20,
+ width: 100,
+ height: 80,
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ },
+ sheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
+ },
+ axisAlignSheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },
+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },
+ },
+ };
+}
+
+describe('SheetDrawingPanel behavior', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createSheetsDrawingUiTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('applies anchor changes after the image panel receives focused drawings', async () => {
+ currentTestBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ [IconManager],
+ [ComponentManager],
+ [DrawingImageClipService],
+ ]);
+ const drawingManagerService = currentTestBed.get(IDrawingManagerService);
+ const sheetDrawingService = currentTestBed.get(ISheetDrawingService);
+ const drawings = [
+ createSheetDrawing(currentTestBed.unitId, currentTestBed.subUnitId, 'drawing-a', SheetDrawingAnchorType.Position),
+ createSheetDrawing(currentTestBed.unitId, currentTestBed.subUnitId, 'drawing-b', SheetDrawingAnchorType.Both),
+ ];
+
+ await currentTestBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: currentTestBed.unitId,
+ drawings,
+ });
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetDrawingPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));
+ await Promise.resolve();
+ });
+
+ const noResizeOrMoveOption = container.querySelectorAll<HTMLInputElement>('input[type="radio"]')[2];
+
+ await act(async () => {
+ noResizeOrMoveOption.click();
+ await Promise.resolve();
+ });
+
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: 'drawing-a',
+ })?.anchorType).toBe(SheetDrawingAnchorType.None);
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: 'drawing-b',
+ })?.anchorType).toBe(SheetDrawingAnchorType.None);
+ });
+
+ it('applies anchor changes when the image panel opens with an existing sheet image focus', async () => {
+ currentTestBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ [IconManager],
+ [ComponentManager],
+ [DrawingImageClipService],
+ ]);
+ const drawingManagerService = currentTestBed.get(IDrawingManagerService);
+ const sheetDrawingService = currentTestBed.get(ISheetDrawingService);
+ const drawings = [
+ createSheetDrawing(currentTestBed.unitId, currentTestBed.subUnitId, 'drawing-a', SheetDrawingAnchorType.None),
+ ];
+
+ await currentTestBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: currentTestBed.unitId,
+ drawings,
+ });
+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetDrawingPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const resizeAndMoveOption = container.querySelectorAll<HTMLInputElement>('input[type="radio"]')[0];
+
+ await act(async () => {
+ resizeAndMoveOption.click();
+ await Promise.resolve();
+ });
+
+ expect(sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: 'drawing-a',
+ })?.anchorType).toBe(SheetDrawingAnchorType.Both);
+ });
+
+ it('removes image controls when sheet drawing focus is cleared', async () => {
+ currentTestBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ [IconManager],
+ [ComponentManager],
+ [DrawingImageClipService],
+ ]);
+ const drawingManagerService = currentTestBed.get(IDrawingManagerService);
+ const drawings = [
+ createSheetDrawing(currentTestBed.unitId, currentTestBed.subUnitId, 'drawing-a', SheetDrawingAnchorType.Position),
+ ];
+
+ await currentTestBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: currentTestBed.unitId,
+ drawings,
+ });
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetDrawingPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ expect(container.firstElementChild).toBeNull();
+
+ await act(async () => {
+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));
+ await Promise.resolve();
+ });
+
+ expect(container.querySelectorAll('input[type="radio"]')).toHaveLength(3);
+
+ await act(async () => {
+ drawingManagerService.focusDrawing([]);
+ await Promise.resolve();
+ });
+
+ expect(container.firstElementChild).toBeNull();
+ });
+});
diff --git a/packages/sheets-filter-ui/src/__testing__/data.ts b/packages/sheets-filter-ui/src/__tests__/data.ts
similarity index 100%
rename from packages/sheets-filter-ui/src/__testing__/data.ts
rename to packages/sheets-filter-ui/src/__tests__/data.ts
diff --git a/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts b/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts
index 4c08e1f6ad..29d4f967be 100644
--- a/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts
+++ b/packages/sheets-filter-ui/src/commands/commands/__tests__/sheets-filter.command.spec.ts
@@ -24,7 +24,7 @@ import { MarkDirtyFilterChangeMutation, RangeProtectionRuleModel, RefRangeServic
import { SetSheetsFilterRangeMutation, SheetsFilterService, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { ClearSheetsFilterCriteriaCommand, ReCalcSheetsFilterCommand, SetSheetsFilterCriteriaCommand, SmartToggleSheetsFilterCommand } from '@univerjs/sheets-filter/commands/commands/sheets-filter.command.js';
import { IMessageService } from '@univerjs/ui';
-import { MockMessageService } from '@univerjs/ui/services/message/__testing__/mock-message.service.js';
+import { MockMessageService } from '@univerjs/ui/services/message/__tests__/mock-message.service.js';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
function testWorkbookDataFactory(): IWorkbookData {
diff --git a/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts b/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts
index 2595ecf266..b67adb896b 100644
--- a/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts
+++ b/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts
@@ -59,7 +59,7 @@ import {
WithTwoFilterColumnsFactory,
WithValuesAndEmptyFilterModelFactory,
WithValuesFilterModelFactory,
-} from '../../__testing__/data';
+} from '../../__tests__/data';
import { CloseFilterPanelOperation, OpenFilterPanelOperation } from '../../commands/operations/sheets-filter.operation';
import { FilterConditionItems } from '../../models/conditions';
import { ExtendCustomFilterOperator } from '../../models/extended-operators';
diff --git a/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx b/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx
index 301fcf2434..296a255837 100644
--- a/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx
+++ b/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.stories.tsx
@@ -23,7 +23,7 @@ import { ClearSheetsFilterCriteriaCommand, ReCalcSheetsFilterCommand, SetSheetsF
import { SetCellEditVisibleOperation } from '@univerjs/sheets-ui';
import { IShortcutService, IUIPartsService, RediContext, ShortcutService, UIPartsService } from '@univerjs/ui';
import { useState } from 'react';
-import { WithCustomFilterModelFactory, WithValuesFilterModelFactory } from '../../__testing__/data';
+import { WithCustomFilterModelFactory, WithValuesFilterModelFactory } from '../../__tests__/data';
import { ChangeFilterByOperation, CloseFilterPanelOperation, OpenFilterPanelOperation } from '../../commands/operations/sheets-filter.operation';
import enUS from '../../locale/en-US';
import ruRU from '../../locale/ru-RU';
diff --git a/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx b/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx
index c97282c909..f3cee81b37 100644
--- a/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx
+++ b/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx
@@ -53,7 +53,7 @@ import { ILayoutService, IMessageService, IUIPartsService, RediContext, UIPartsS
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it } from 'vitest';
-import { WithValuesAndEmptyFilterModelFactory, WithValuesFilterModelFactory } from '../../../__testing__/data';
+import { WithValuesAndEmptyFilterModelFactory, WithValuesFilterModelFactory } from '../../../__tests__/data';
import {
ChangeFilterByOperation,
CloseFilterPanelOperation,
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
index d80924fa33..5208bfd39b 100644
--- a/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts
+++ b/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts
@@ -65,4 +65,53 @@ describe('hitCell', () => {
expect(res2.hit).toBe(true);
expect(res2.replaceable).toBe(false);
});
+
+ it('should support whole-cell matching with edge spaces', () => {
+ const worksheet = {
+ getCellRaw: () => ({ v: ' abc ' }),
+ };
+
+ const res = hitCell(worksheet as any, 0, 0, {
+ ...baseQuery,
+ matchesTheWholeCell: true,
+ findString: 'abc',
+ }, { v: ' abc ' } as any);
+
+ expect(res.hit).toBe(true);
+ expect(res.replaceable).toBe(true);
+ });
+
+ it('should extract number and boolean cell values for matching', () => {
+ const worksheet = {
+ getCellRaw: (_row: number, col: number) => (col === 0 ? { v: 123 } : { v: true }),
+ };
+
+ expect(hitCell(worksheet as any, 0, 0, { ...baseQuery, findString: '23' }, { v: 123 } as any).hit).toBe(true);
+ expect(hitCell(worksheet as any, 0, 1, { ...baseQuery, findString: '1' }, { v: true } as any).hit).toBe(true);
+ });
+
+ it('should report misses for empty values and unmatched formula display values', () => {
+ const formulaWorksheet = {
+ getCellRaw: () => ({ f: '=SUM(1)' }),
+ };
+ const formulaRawMiss = hitCell(formulaWorksheet as any, 0, 0, {
+ ...baseQuery,
+ findBy: FindBy.FORMULA,
+ findString: '=missing',
+ }, { v: 'alpha' } as any);
+ expect(formulaRawMiss.hit).toBe(false);
+ expect(formulaRawMiss.replaceable).toBe(false);
+
+ const formulaMiss = hitCell(formulaWorksheet as any, 0, 0, { ...baseQuery, findString: 'missing' }, { v: 'alpha' } as any);
+ expect(formulaMiss.hit).toBe(false);
+ expect(formulaMiss.replaceable).toBe(false);
+ expect(formulaMiss.isFormula).toBe(true);
+
+ const emptyWorksheet = {
+ getCellRaw: () => ({ v: '' }),
+ };
+ const emptyMiss = hitCell(emptyWorksheet as any, 0, 0, baseQuery, { v: '' } as any);
+ expect(emptyMiss.hit).toBe(false);
+ expect(emptyMiss.replaceable).toBe(false);
+ });
});
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts
new file mode 100644
index 0000000000..5d790f74f8
--- /dev/null
+++ b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts
@@ -0,0 +1,521 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICellData, IRange } from '@univerjs/core';
+import type { IFindQuery } from '@univerjs/find-replace';
+import { UniverInstanceType } from '@univerjs/core';
+import { RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';
+import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
+import { SelectRangeCommand, SetRangeValuesCommand, SetWorksheetActivateCommand } from '@univerjs/sheets';
+import { ScrollToCellCommand } from '@univerjs/sheets-ui';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetReplaceCommand } from '../../commands/commands/sheet-replace.command';
+import { SheetFindModel, SheetsFindReplaceController } from '../sheet-find-replace.controller';
+
+vi.mock('@univerjs/sheets-ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/sheets-ui')>();
+
+ return {
+ ...actual,
+ getCoordByCell: vi.fn((row: number, col: number) => ({
+ startX: col * 10,
+ startY: row * 20,
+ endX: (col + 1) * 10,
+ endY: (row + 1) * 20,
+ })),
+ };
+});
+
+const baseQuery: IFindQuery = {
+ replaceRevealed: false,
+ findString: 'alpha',
+ caseSensitive: false,
+ matchesTheWholeCell: false,
+ findDirection: FindDirection.ROW,
+ findScope: FindScope.SUBUNIT,
+ findBy: FindBy.VALUE,
+};
+
+function createWorksheet(sheetId: string, cells: Record<string, ICellData>, options?: { hidden?: boolean; filteredRows?: number[] }) {
+ const getCellData = (row: number, col: number) => cells[`${row},${col}`];
+
+ return {
+ getSheetId: () => sheetId,
+ getRowCount: () => 4,
+ getColumnCount: () => 4,
+ isSheetHidden: () => !!options?.hidden,
+ getMergedCell: () => null,
+ getRowFiltered: (row: number) => options?.filteredRows?.includes(row) ?? false,
+ getRowRawVisible: () => true,
+ getColVisible: () => true,
+ getCellRaw: vi.fn((row: number, col: number) => getCellData(row, col) ?? null),
+ * iterateByRow(range: IRange) {
+ for (let row = range.startRow; row <= range.endRow; row++) {
+ for (let col = range.startColumn; col <= range.endColumn; col++) {
+ const value = getCellData(row, col);
+ if (value) {
+ yield { row, col, value };
+ }
+ }
+ }
+ },
+ * iterateByColumn(range: IRange) {
+ for (let col = range.startColumn; col <= range.endColumn; col++) {
+ for (let row = range.startRow; row <= range.endRow; row++) {
+ const value = getCellData(row, col);
+ if (value) {
+ yield { row, col, value };
+ }
+ }
+ }
+ },
+ } as any;
+}
+
+function createWorkbook(activeSheet: any, sheets = [activeSheet]) {
+ return {
+ getUnitId: () => 'unit-1',
+ type: UniverInstanceType.UNIVER_SHEET,
+ getActiveSheet: vi.fn(() => activeSheet),
+ getSheets: vi.fn(() => sheets),
+ getSheetOrders: vi.fn(() => sheets.map((sheet) => sheet.getSheetId())),
+ getSheetBySheetId: vi.fn((sheetId: string) => sheets.find((sheet) => sheet.getSheetId() === sheetId)),
+ activeSheet$: new Subject<any>(),
+ } as any;
+}
+
+function createModel(
+ workbook: any,
+ selections: any[] = [{ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }],
+ overrides: {
+ skeletonService?: any;
+ renderManagerService?: any;
+ themeService?: any;
+ } = {}
+) {
+ const skeletonService = overrides.skeletonService ?? {
+ currentSkeleton$: new Subject<any>(),
+ getCurrentSkeleton: vi.fn(() => null),
+ };
+ const commandCallbacks: Array<(command: any, options?: any) => void> = [];
+ const commandService = {
+ executeCommand: vi.fn(() => Promise.resolve(true)),
+ onCommandExecuted: vi.fn((callback: (command: any, options?: any) => void) => {
+ commandCallbacks.push(callback);
+ return { dispose: vi.fn() };
+ }),
+ emitCommand(command: any, options?: any) {
+ commandCallbacks.forEach((callback) => callback(command, options));
+ },
+ };
+ const contextService = { setContextValue: vi.fn() };
+ const selectionService = {
+ getWorkbookSelections: vi.fn(() => ({
+ getCurrentSelections: vi.fn(() => selections),
+ getCurrentLastSelection: vi.fn(() => selections.at(-1)),
+ })),
+ };
+
+ const model = new SheetFindModel(
+ workbook,
+ skeletonService as any,
+ {} as any,
+ (overrides.renderManagerService ?? { getRenderById: vi.fn(() => null) }) as any,
+ commandService as any,
+ contextService as any,
+ (overrides.themeService ?? { getColorFromTheme: vi.fn(() => '#ff0') }) as any,
+ selectionService as any
+ );
+
+ return { model, commandService, contextService, skeletonService };
+}
+
+describe('SheetsFindReplaceController integration', () => {
+ it('registers a real sheets provider, preprocesses queries and closes on editor activation', async () => {
+ const activeSheet = createWorksheet('sheet-1', {
+ '0,0': { v: 'Alpha' },
+ '0,1': { v: 'beta' },
+ '1,0': { f: '=SUM(1)', v: 'alpha result' },
+ '2,0': { v: 'alpha filtered' },
+ }, { filteredRows: [2] });
+ const workbook = createWorkbook(activeSheet);
+ const skeletonService = {
+ currentSkeleton$: new Subject<any>(),
+ getCurrentSkeleton: vi.fn(() => null),
+ };
+ const renderManagerService = {
+ getRenderById: vi.fn(() => ({ with: vi.fn(() => skeletonService) })),
+ };
+ const commandService = {
+ registerCommand: vi.fn(() => ({ dispose: vi.fn() })),
+ executeCommand: vi.fn(() => Promise.resolve(true)),
+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),
+ };
+ const contextValue$ = new Subject<boolean>();
+ const contextService = {
+ subscribeContextValue$: vi.fn(() => contextValue$),
+ setContextValue: vi.fn(),
+ };
+ const selectionService = {
+ getWorkbookSelections: vi.fn(() => ({
+ getCurrentSelections: vi.fn(() => [{ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }]),
+ getCurrentLastSelection: vi.fn(() => ({ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } })),
+ })),
+ };
+ const univerInstanceService = {
+ getCurrentUnitOfType: vi.fn(() => workbook),
+ };
+ const injector = {
+ createInstance: vi.fn((Ctor: any, ...args: any[]) => {
+ if (Ctor.name === 'SheetsFindReplaceProvider') {
+ return new Ctor(univerInstanceService, renderManagerService, injector);
+ }
+
+ return new Ctor(
+ args[0],
+ args[1],
+ univerInstanceService,
+ renderManagerService,
+ commandService,
+ contextService,
+ { getColorFromTheme: vi.fn(() => '#ff0') },
+ selectionService
+ );
+ }),
+ };
+ let provider: any;
+ const findReplaceService = {
+ registerFindReplaceProvider: vi.fn((registeredProvider) => {
+ provider = registeredProvider;
+ return { dispose: vi.fn() };
+ }),
+ };
+ const findReplaceController = { closePanel: vi.fn() };
+
+ const controller = new SheetsFindReplaceController(
+ injector as any,
+ findReplaceController as any,
+ contextService as any,
+ findReplaceService as any,
+ commandService as any
+ );
+
+ contextValue$.next(true);
+ const [model] = await provider.find({ ...baseQuery, findString: ' ALPHA ' });
+
+ expect(commandService.registerCommand).toHaveBeenCalledWith(SheetReplaceCommand);
+ expect(findReplaceController.closePanel).toHaveBeenCalledTimes(1);
+ expect(model).toBeInstanceOf(SheetFindModel);
+ expect(model.matchesCount).toBe(2);
+ expect(model.getMatches().map((match: any) => match.range.range.startRow)).toEqual([0, 1]);
+ expect(model.getMatches().map((match: any) => match.replaceable)).toEqual([true, false]);
+
+ controller.dispose();
+ expect(findReplaceController.closePanel).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns no models when the provider has no active workbook', async () => {
+ const injector = {
+ createInstance: vi.fn((Ctor: any) => new Ctor(
+ { getCurrentUnitOfType: vi.fn(() => null) },
+ { getRenderById: vi.fn() },
+ injector
+ )),
+ };
+ let provider: any;
+ const controller = new SheetsFindReplaceController(
+ injector as any,
+ { closePanel: vi.fn() } as any,
+ { subscribeContextValue$: vi.fn(() => new Subject<boolean>()) } as any,
+ {
+ registerFindReplaceProvider: vi.fn((registeredProvider) => {
+ provider = registeredProvider;
+ return { dispose: vi.fn() };
+ }),
+ } as any,
+ { registerCommand: vi.fn(() => ({ dispose: vi.fn() })) } as any
+ );
+
+ await expect(provider.find(baseQuery)).resolves.toEqual([]);
+ provider.terminate();
+ controller.dispose();
+ });
+});
+
+describe('SheetFindModel search and replace', () => {
+ it('finds in selected ranges with deduplication and toggles raw formula mode', () => {
+ const activeSheet = createWorksheet('sheet-1', {
+ '0,0': { v: 'alpha' },
+ '0,1': { v: 'alpha again' },
+ '1,0': { v: 'beta' },
+ });
+ const workbook = createWorkbook(activeSheet);
+ const { model, contextService } = createModel(workbook, [
+ { range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 } },
+ { range: { startRow: 0, startColumn: 1, endRow: 1, endColumn: 1 } },
+ ]);
+
+ const complete = model.findInActiveWorksheet({ ...baseQuery, findBy: FindBy.FORMULA });
+
+ expect(contextService.setContextValue).not.toHaveBeenCalled();
+ expect(complete.results).toHaveLength(2);
+ expect(complete.results.map((match: any) => match.range.range.startColumn)).toEqual([0, 1]);
+ expect(model.matchesCount).toBe(2);
+
+ model.start({ ...baseQuery, findBy: FindBy.FORMULA, findString: '=sum' });
+ expect(contextService.setContextValue).toHaveBeenCalledWith(RENDER_RAW_FORMULA_KEY, true);
+
+ model.dispose();
+ expect(contextService.setContextValue).toHaveBeenLastCalledWith(RENDER_RAW_FORMULA_KEY, false);
+ });
+
+ it('finds across visible workbook sheets and skips hidden sheets', () => {
+ const sheet1 = createWorksheet('sheet-1', { '0,0': { v: 'alpha' } });
+ const sheet2 = createWorksheet('sheet-2', { '0,0': { v: 'alpha second' } });
+ const hiddenSheet = createWorksheet('hidden', { '0,0': { v: 'alpha hidden' } }, { hidden: true });
+ const workbook = createWorkbook(sheet1, [sheet1, sheet2, hiddenSheet]);
+ const { model } = createModel(workbook);
+
+ const complete = model.findInWorkbook({ ...baseQuery, findScope: FindScope.UNIT });
+
+ expect(complete.results.map((match: any) => match.range.subUnitId)).toEqual(['sheet-1', 'sheet-2']);
+ expect(model.matchesCount).toBe(2);
+
+ model.dispose();
+ });
+
+ it('starts workbook-scope searches from the public start entry and no-ops focus without a match', () => {
+ const sheet1 = createWorksheet('sheet-1', { '0,0': { v: 'alpha' } });
+ const sheet2 = createWorksheet('sheet-2', { '0,0': { v: 'alpha second' } });
+ const workbook = createWorkbook(sheet1, [sheet1, sheet2]);
+ const { model, commandService } = createModel(workbook);
+
+ model.focusSelection();
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+
+ model.start({ ...baseQuery, findScope: FindScope.UNIT });
+ expect(model.matchesCount).toBe(2);
+
+ model.dispose();
+ });
+
+ it('returns no active worksheet matches when the workbook has no active sheet', () => {
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getActiveSheet: vi.fn(() => null),
+ activeSheet$: new Subject<any>(),
+ };
+ const { model } = createModel(workbook);
+
+ expect(model.findInActiveWorksheet(baseQuery)).toBeUndefined();
+
+ model.dispose();
+ });
+
+ it('moves between matches, focuses selections and executes focus commands', async () => {
+ const activeSheet = createWorksheet('sheet-1', {
+ '0,0': { v: 'alpha' },
+ '1,1': { v: 'alpha next' },
+ });
+ const workbook = createWorkbook(activeSheet);
+ const { model, commandService } = createModel(workbook);
+
+ expect(model.moveToNextMatch()).toBeNull();
+
+ model.start(baseQuery);
+ const first = model.moveToNextMatch({ ignoreSelection: true });
+ expect(first?.range.range).toMatchObject({ startRow: 0, startColumn: 0 });
+ expect(model.matchesPosition).toBe(1);
+ expect(commandService.executeCommand).toHaveBeenLastCalledWith(ScrollToCellCommand.id, {
+ range: first!.range.range,
+ }, {
+ fromFindReplace: true,
+ });
+
+ model.focusSelection();
+ expect(commandService.executeCommand).toHaveBeenLastCalledWith(SelectRangeCommand.id, {
+ unitId: 'unit-1',
+ subUnit: 'sheet-1',
+ range: first!.range.range,
+ });
+
+ const stayed = model.moveToNextMatch({ stayIfOnMatch: true, noFocus: true });
+ expect(stayed).toBe(first);
+
+ const second = model.moveToNextMatch({ noFocus: true });
+ expect(second?.range.range).toMatchObject({ startRow: 1, startColumn: 1 });
+
+ expect(model.moveToNextMatch({ noFocus: true })).toBeNull();
+ expect(model.matchesPosition).toBe(0);
+
+ const previous = model.moveToPreviousMatch({ noFocus: true, ignoreSelection: true });
+ expect(previous?.range.range).toMatchObject({ startRow: 1, startColumn: 1 });
+ expect(model.moveToPreviousMatch({ stayIfOnMatch: true, noFocus: true })).toBe(previous);
+
+ model.dispose();
+ });
+
+ it('focuses a match on another sheet through activation and scroll commands', async () => {
+ const sheet1 = createWorksheet('sheet-1', { '0,0': { v: 'alpha' } });
+ const sheet2 = createWorksheet('sheet-2', { '1,1': { v: 'alpha' } });
+ const workbook = createWorkbook(sheet1, [sheet1, sheet2]);
+ const { model, commandService } = createModel(workbook);
+ const match = {
+ unitId: 'unit-1',
+ provider: 'sheets-find-replace-provider',
+ replaceable: true,
+ isFormula: false,
+ range: {
+ subUnitId: 'sheet-2',
+ range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1 },
+ },
+ };
+
+ await (model as any)._focusMatch(match);
+
+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(1, SetWorksheetActivateCommand.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-2',
+ }, {
+ fromFindReplace: true,
+ });
+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, ScrollToCellCommand.id, {
+ range: match.range.range,
+ }, {
+ fromFindReplace: true,
+ });
+
+ model.dispose();
+ });
+
+ it('renders find highlights for visible matches and updates the current highlight', () => {
+ const activeSheet = createWorksheet('sheet-1', {
+ '0,0': { v: 'alpha' },
+ '1,1': { v: 'alpha next' },
+ });
+ const workbook = createWorkbook(activeSheet);
+ const skeletonSubject = new Subject<any>();
+ const skeletonService = {
+ currentSkeleton$: skeletonSubject,
+ getCurrentSkeleton: vi.fn(() => ({ rowColumnSegment: {} })),
+ };
+ const scene = {
+ addObjects: vi.fn(),
+ makeDirty: vi.fn(),
+ };
+ const { model } = createModel(workbook, undefined, {
+ skeletonService,
+ renderManagerService: { getRenderById: vi.fn(() => ({ scene })) },
+ themeService: { getColorFromTheme: vi.fn(() => '#ff0') },
+ });
+
+ model.start(baseQuery);
+
+ let highlightShapes = scene.addObjects.mock.calls.at(-1)![0] as any[];
+ expect(highlightShapes).toHaveLength(2);
+ expect(highlightShapes[0].width).toBe(10);
+ expect(highlightShapes[0].height).toBe(20);
+ expect(scene.makeDirty).toHaveBeenCalled();
+
+ model.moveToNextMatch({ noFocus: true, ignoreSelection: true });
+ highlightShapes = scene.addObjects.mock.calls.at(-1)![0] as any[];
+ expect(highlightShapes[0]._activated).toBe(true);
+
+ skeletonSubject.next({});
+ expect(scene.addObjects).toHaveBeenCalledTimes(2);
+
+ model.dispose();
+ });
+
+ it('replaces the current match and replaces all replaceable matches by sheet', async () => {
+ const activeSheet = createWorksheet('sheet-1', {
+ '0,0': { v: 'alpha plain' },
+ '0,1': { f: '=ALPHA()', v: 'alpha formula result' },
+ '1,0': { p: { body: { dataStream: 'alpha rich\r\n' } } as any },
+ });
+ const workbook = createWorkbook(activeSheet);
+ const { model, commandService } = createModel(workbook);
+
+ model.start(baseQuery);
+ model.moveToNextMatch({ noFocus: true, ignoreSelection: true });
+
+ await expect(model.replace('omega')).resolves.toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ value: {
+ 0: {
+ 0: { v: 'omega plain' },
+ },
+ },
+ });
+
+ await model.replaceAll('omega');
+ expect(commandService.executeCommand).toHaveBeenLastCalledWith(SheetReplaceCommand.id, {
+ unitId: 'unit-1',
+ replacements: [
+ {
+ count: 2,
+ subUnitId: 'sheet-1',
+ value: expect.objectContaining({
+ 0: expect.objectContaining({ 0: { v: 'omega plain' } }),
+ 1: expect.objectContaining({ 0: expect.objectContaining({ p: expect.any(Object) }) }),
+ }),
+ },
+ ],
+ });
+
+ model.dispose();
+ });
+
+ it('replaces formulas only in formula search mode', async () => {
+ const activeSheet = createWorksheet('sheet-1', {
+ '0,0': { f: '=ALPHA()', v: 'alpha result' },
+ });
+ const workbook = createWorkbook(activeSheet);
+ const { model, commandService } = createModel(workbook);
+
+ model.start({ ...baseQuery, findBy: FindBy.FORMULA, findString: '=alpha' });
+ model.moveToNextMatch({ noFocus: true, ignoreSelection: true });
+
+ await expect(model.replace('=OMEGA')).resolves.toBe(true);
+ expect(commandService.executeCommand).toHaveBeenLastCalledWith(SetRangeValuesCommand.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ value: {
+ 0: {
+ 0: { f: '=OMEGA()', v: null },
+ },
+ },
+ });
+
+ model.dispose();
+ });
+
+ it('returns empty replacement results when nothing is searchable', async () => {
+ const activeSheet = createWorksheet('sheet-1', {});
+ const workbook = createWorkbook(activeSheet);
+ const { model, commandService } = createModel(workbook);
+
+ expect(model.findInActiveWorksheet(baseQuery).results).toEqual([]);
+ await expect(model.replace('omega')).resolves.toBe(false);
+ await expect(model.replaceAll('omega')).resolves.toEqual({ success: 0, failure: 0 });
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+
+ model.dispose();
+ });
+});
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts
index aee0f03e32..df14bc009c 100644
--- a/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts
+++ b/packages/sheets-find-replace/src/controllers/__tests__/utils.spec.ts
@@ -26,6 +26,7 @@ import {
isBehindPositionWithColumnPriority,
isBehindPositionWithRowPriority,
isSamePosition,
+ isSelectionSingleCell,
} from '../utils';
describe('Test sheet find replace utils', () => {
@@ -199,6 +200,18 @@ describe('Test sheet find replace utils', () => {
)
).toBeFalsy();
});
+
+ it('Should "isSelectionSingleCell" treat a full merged range as one cell', () => {
+ const mergedRange = { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 };
+ const worksheet = {
+ getMergedCell: () => mergedRange,
+ } as any;
+
+ expect(isSelectionSingleCell({ range: mergedRange } as any, worksheet)).toBe(true);
+ expect(isSelectionSingleCell({
+ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ } as any, worksheet)).toBe(false);
+ });
});
describe('test "hitCell" method', () => {
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
index 3fdf66b36d..2ed49de592 100644
--- a/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts
+++ b/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import { Injector } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { SheetFindReplaceHighlightShape } from '../find-replace-highlight.shape';
@@ -56,6 +57,16 @@ function drawShape(shape: SheetFindReplaceHighlightShape, context: TestCanvasCon
(shape as unknown as { _draw: (ctx: TestCanvasContext) => void })._draw(context);
}
+function createViewTestBed() {
+ const injector = new Injector();
+
+ return {
+ createHighlightShape(key: string, props: ConstructorParameters<typeof SheetFindReplaceHighlightShape>[1]) {
+ return injector.createInstance(SheetFindReplaceHighlightShape, key, props);
+ },
+ };
+}
+
describe('SheetFindReplaceHighlightShape', () => {
it('draws a translucent search result highlight without a border by default', () => {
const shape = new SheetFindReplaceHighlightShape('result', {
@@ -125,4 +136,177 @@ describe('SheetFindReplaceHighlightShape', () => {
expect(inactiveContext.lineWidth).toBe(0);
expect(inactiveContext.strokeCount).toBe(0);
});
+
+ it('redraws refreshed search results with the latest bounds and color', () => {
+ const shape = new SheetFindReplaceHighlightShape('refreshed-result', {
+ inHiddenRange: false,
+ color: { r: 10, g: 20, b: 30 },
+ activated: true,
+ width: 12,
+ height: 24,
+ });
+
+ shape.setShapeProps({
+ color: { r: 40, g: 50, b: 60 },
+ activated: true,
+ width: 36,
+ height: 48,
+ });
+ const context = new TestCanvasContext();
+
+ drawShape(shape, context);
+
+ expect(context.rects).toEqual([{ left: 0, top: 0, width: 36, height: 48 }]);
+ expect(context.fillStyle).toBe('rgba(40, 50, 60, 0.35)');
+ expect(context.strokeStyle).toBe('rgb(40, 50, 60)');
+ expect(context.lineWidth).toBe(2);
+ expect(context.fillCount).toBe(1);
+ expect(context.strokeCount).toBe(1);
+ });
+
+ it('marks the current match in a hidden range with a compact active highlight', () => {
+ const shape = new SheetFindReplaceHighlightShape('hidden-current-result', {
+ inHiddenRange: true,
+ color: { r: 70, g: 80, b: 90 },
+ activated: true,
+ width: 2,
+ height: 2,
+ });
+ const context = new TestCanvasContext();
+
+ drawShape(shape, context);
+
+ expect(context.rects).toEqual([{ left: 0, top: 0, width: 2, height: 2 }]);
+ expect(context.fillStyle).toBe('rgba(70, 80, 90, 0.35)');
+ expect(context.strokeStyle).toBe('rgb(70, 80, 90)');
+ expect(context.lineWidth).toBe(2);
+ expect(context.fillCount).toBe(1);
+ expect(context.strokeCount).toBe(1);
+ });
+
+ it('keeps a hidden non-current match compact without drawing an active border', () => {
+ const shape = new SheetFindReplaceHighlightShape('hidden-result', {
+ inHiddenRange: true,
+ color: { r: 90, g: 100, b: 110 },
+ activated: false,
+ width: 2,
+ height: 2,
+ });
+ const context = new TestCanvasContext();
+
+ drawShape(shape, context);
+
+ expect(context.rects).toEqual([{ left: 0, top: 0, width: 2, height: 2 }]);
+ expect(context.fillStyle).toBe('rgba(90, 100, 110, 0.35)');
+ expect(context.lineWidth).toBe(0);
+ expect(context.fillCount).toBe(1);
+ expect(context.strokeCount).toBe(0);
+ });
+
+ it('activates an existing hidden-range highlight without changing its compact marker', () => {
+ const shape = new SheetFindReplaceHighlightShape('hidden-result-to-activate', {
+ inHiddenRange: true,
+ color: { r: 120, g: 130, b: 140 },
+ activated: false,
+ width: 2,
+ height: 2,
+ });
+
+ shape.setShapeProps({ activated: true });
+ const context = new TestCanvasContext();
+
+ drawShape(shape, context);
+
+ expect(context.rects).toEqual([{ left: 0, top: 0, width: 2, height: 2 }]);
+ expect(context.fillStyle).toBe('rgba(120, 130, 140, 0.35)');
+ expect(context.strokeStyle).toBe('rgb(120, 130, 140)');
+ expect(context.lineWidth).toBe(2);
+ expect(context.fillCount).toBe(1);
+ expect(context.strokeCount).toBe(1);
+ });
+
+ it('moves the current-match border between result highlights while preserving both fills', () => {
+ const previousCurrent = new SheetFindReplaceHighlightShape('previous-current-result', {
+ inHiddenRange: false,
+ color: { r: 12, g: 34, b: 56 },
+ activated: true,
+ width: 18,
+ height: 22,
+ });
+ const nextCurrent = new SheetFindReplaceHighlightShape('next-current-result', {
+ inHiddenRange: false,
+ color: { r: 78, g: 90, b: 123 },
+ activated: false,
+ width: 24,
+ height: 28,
+ });
+
+ previousCurrent.setShapeProps({ activated: false });
+ nextCurrent.setShapeProps({ activated: true });
+
+ const previousContext = new TestCanvasContext();
+ const nextContext = new TestCanvasContext();
+
+ drawShape(previousCurrent, previousContext);
+ drawShape(nextCurrent, nextContext);
+
+ expect(previousContext.rects).toEqual([{ left: 0, top: 0, width: 18, height: 22 }]);
+ expect(previousContext.fillStyle).toBe('rgba(12, 34, 56, 0.35)');
+ expect(previousContext.lineWidth).toBe(0);
+ expect(previousContext.fillCount).toBe(1);
+ expect(previousContext.strokeCount).toBe(0);
+ expect(nextContext.rects).toEqual([{ left: 0, top: 0, width: 24, height: 28 }]);
+ expect(nextContext.fillStyle).toBe('rgba(78, 90, 123, 0.35)');
+ expect(nextContext.strokeStyle).toBe('rgb(78, 90, 123)');
+ expect(nextContext.lineWidth).toBe(2);
+ expect(nextContext.fillCount).toBe(1);
+ expect(nextContext.strokeCount).toBe(1);
+ });
+
+ it('creates search highlights as passive overlays above the sheet content', () => {
+ const testBed = createViewTestBed();
+ const shape = testBed.createHighlightShape('visible-result-overlay', {
+ left: 32,
+ top: 48,
+ inHiddenRange: false,
+ color: { r: 230, g: 180, b: 40 },
+ width: 96,
+ height: 24,
+ evented: false,
+ zIndex: 10000,
+ });
+
+ expect(shape.evented).toBe(false);
+ expect(shape.zIndex).toBe(10000);
+ expect(shape.left).toBe(32);
+ expect(shape.top).toBe(48);
+ expect(shape.width).toBe(96);
+ expect(shape.height).toBe(24);
+ });
+
+ it('keeps a found cell anchored when navigation only toggles the active match state', () => {
+ const testBed = createViewTestBed();
+ const shape = testBed.createHighlightShape('anchored-result', {
+ left: 120,
+ top: 72,
+ inHiddenRange: false,
+ color: { r: 24, g: 144, b: 255 },
+ width: 64,
+ height: 22,
+ evented: false,
+ zIndex: 10000,
+ });
+
+ shape.setShapeProps({ activated: true });
+ const context = new TestCanvasContext();
+
+ drawShape(shape, context);
+
+ expect(shape.left).toBe(120);
+ expect(shape.top).toBe(72);
+ expect(context.rects).toEqual([{ left: 0, top: 0, width: 64, height: 22 }]);
+ expect(context.strokeStyle).toBe('rgb(24, 144, 255)');
+ expect(context.lineWidth).toBe(2);
+ expect(context.strokeCount).toBe(1);
+ });
});
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
index 55afd1b5bd..9d44a874be 100644
--- 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
@@ -89,4 +89,34 @@ describe('FormulaAlertRenderController', () => {
expect(vi.mocked(extractFormulaError)).toHaveBeenCalledWith({ v: 'plain-text' }, false);
expect(ErrorType.DIV_BY_ZERO).toBeTruthy();
});
+
+ it('hides alerts when the workbook has no active worksheet for the hovered cell', async () => {
+ vi.useFakeTimers();
+ const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
+ const removedAlerts: string[] = [];
+ const shownAlerts: unknown[] = [];
+ const controller = new FormulaAlertRenderController(
+ { unit: { getActiveSheet: () => null } } as never,
+ { currentCell$ } as never,
+ {
+ currentAlert: new Map(),
+ removeAlert: (key: string) => {
+ removedAlerts.push(key);
+ },
+ showAlert: (alert: unknown) => {
+ shownAlerts.push(alert);
+ },
+ } as never,
+ { t: (key: string) => key } as never,
+ { getArrayFormulaCellData: () => null } as never
+ );
+
+ currentCell$.next({ location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 3, col: 4 } });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(removedAlerts).toEqual(['SHEET_FORMULA_ALERT']);
+ expect(shownAlerts).toEqual([]);
+
+ controller.dispose();
+ });
});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
index 01297a3266..7d126df15a 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts
@@ -17,16 +17,77 @@
import type { Dependency, ICellData, IDisposable, IRange, IWorkbookData, Nullable, Workbook } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { ICellDataWithSpanInfo } from '@univerjs/sheets-ui';
-import { DisposableCollection, ICommandService, ILogService, Inject, Injector, IUniverInstanceService, LocaleService, LocaleType, LogLevel, ObjectMatrix, Plugin, RANGE_TYPE, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';
-import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, HyperlinkEngineFormulaService, ICalculateFormulaService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, IHyperlinkEngineFormulaService, LexerTreeBuilder, SetArrayFormulaDataMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';
+import {
+ DisposableCollection,
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ ObjectMatrix,
+ Plugin,
+ RANGE_TYPE,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ CalculateFormulaService,
+ DefinedNamesService,
+ FormulaCurrentConfigService,
+ FormulaDataModel,
+ FormulaRuntimeService,
+ HyperlinkEngineFormulaService,
+ ICalculateFormulaService,
+ IDefinedNamesService,
+ IFormulaCurrentConfigService,
+ IFormulaRuntimeService,
+ IHyperlinkEngineFormulaService,
+ LexerTreeBuilder,
+ SetArrayFormulaDataMutation,
+ SetFormulaDataMutation,
+} from '@univerjs/engine-formula';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { discreteRangeToRange, MoveRangeMutation, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetActiveOperation, SetWorksheetRowAutoHeightMutation, SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ discreteRangeToRange,
+ MoveRangeMutation,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ SetWorksheetRowAutoHeightMutation,
+ SheetInterceptorService,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
import { UpdateFormulaController } from '@univerjs/sheets-formula';
-import { COPY_TYPE, IMarkSelectionService, ISheetClipboardService, ISheetSelectionRenderService, PREDEFINED_HOOK_NAME_PASTE, SheetClipboardController, SheetClipboardService, SheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { BrowserClipboardService, DesktopMessageService, IClipboardInterfaceService, IMessageService, INotificationService, IPlatformService, IUIPartsService, UIPartsService } from '@univerjs/ui';
+import {
+ COPY_TYPE,
+ IMarkSelectionService,
+ ISheetClipboardService,
+ ISheetSelectionRenderService,
+ PREDEFINED_HOOK_NAME_COPY,
+ PREDEFINED_HOOK_NAME_PASTE,
+ SheetClipboardController,
+ SheetClipboardService,
+ SheetSelectionRenderService,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
+import {
+ BrowserClipboardService,
+ DesktopMessageService,
+ IClipboardInterfaceService,
+ IMessageService,
+ INotificationService,
+ IPlatformService,
+ IUIPartsService,
+ UIPartsService,
+} from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { getSetCellFormulaMutations } from '../formula-clipboard.controller';
+import { FormulaClipboardController, getSetCellFormulaMutations } from '../formula-clipboard.controller';
import { createCommandTestBed } from './create-command-test-bed';
interface ITestSheetClipboardService extends ISheetClipboardService {
@@ -82,6 +143,112 @@ class testPlatformService {
isLinux: boolean = false;
}
+describe('FormulaClipboardController formula-only copy hook', () => {
+ it('copies only formulas, resolves shared formula strings and reports filtered rows', () => {
+ const hooks: any[] = [];
+ const worksheet = {
+ getSheetId: () => 'sheet1',
+ getUnitId: () => 'unit1',
+ getCellRaw: (row: number, col: number) => {
+ if (row === 0 && col === 0) return { f: '=A1' };
+ if (row === 0 && col === 1) return { si: 'shared-1' };
+ if (row === 0 && col === 2) return { v: 10 };
+ return null;
+ },
+ getRowFiltered: (row: number) => row === 2,
+ };
+ const workbook = {
+ getSheetBySheetId: () => worksheet,
+ };
+ const controller = new FormulaClipboardController(
+ {
+ getUnit: () => workbook,
+ getCurrentUnitOfType: () => ({ getActiveSheet: () => worksheet }),
+ } as never,
+ {} as never,
+ {
+ addClipboardHook: (hook: unknown) => {
+ hooks.push(hook);
+ return { dispose: () => undefined };
+ },
+ } as never,
+ {} as never,
+ { getFormulaStringByCell: () => '=A2' } as never
+ );
+ const formulaOnlyHook = hooks.find((hook) => hook.id === PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY);
+
+ formulaOnlyHook.onBeforeCopy('unit1', 'sheet1');
+
+ expect(formulaOnlyHook.onCopyCellContent(0, 0)).toBe('=A1');
+ expect(formulaOnlyHook.onCopyCellContent(0, 1)).toBe('=A2');
+ expect(formulaOnlyHook.onCopyCellContent(0, 2)).toBe('');
+ expect(formulaOnlyHook.getFilteredOutRows('unit1', 'sheet1', {
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 0,
+ })).toEqual([2]);
+
+ formulaOnlyHook.onAfterCopy();
+ expect(formulaOnlyHook.onCopyCellContent(0, 0)).toBe('');
+
+ controller.dispose();
+ });
+
+ it('writes formulas to copy matrices and clears non-formula cells in formula-only copy', () => {
+ const hooks: any[] = [];
+ const worksheet = {
+ getSheetId: () => 'sheet1',
+ getUnitId: () => 'unit1',
+ getCellRaw: () => null,
+ getRowFiltered: () => false,
+ };
+ const workbook = {
+ getSheetBySheetId: () => worksheet,
+ };
+ const controller = new FormulaClipboardController(
+ {
+ getUnit: () => workbook,
+ getCurrentUnitOfType: () => ({ getActiveSheet: () => worksheet }),
+ } as never,
+ {} as never,
+ {
+ addClipboardHook: (hook: unknown) => {
+ hooks.push(hook);
+ return { dispose: () => undefined };
+ },
+ } as never,
+ {} as never,
+ { getFormulaStringByCell: () => '=A2' } as never
+ );
+ const formulaOnlyHook = hooks.find((hook) => hook.id === PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY);
+ const matrix = new ObjectMatrix<ICellDataWithSpanInfo>({
+ 0: {
+ 0: { f: '=A1' },
+ 1: { si: 'shared-1' },
+ 2: { v: 10 },
+ },
+ });
+ const matrixFragment = new ObjectMatrix<ICellDataWithSpanInfo>();
+ const plainMatrix = new ObjectMatrix<ICellDataWithSpanInfo>();
+
+ formulaOnlyHook.onBeforeCopy('unit1', 'sheet1');
+ formulaOnlyHook.handleMatrixOnCell(0, 0, 0, 0, matrix, matrixFragment, plainMatrix);
+ formulaOnlyHook.handleMatrixOnCell(0, 1, 0, 1, matrix, matrixFragment, plainMatrix);
+ formulaOnlyHook.handleMatrixOnCell(0, 2, 0, 2, matrix, matrixFragment, plainMatrix);
+
+ expect(matrixFragment.getValue(0, 0)).toMatchObject({ f: '=A1' });
+ expect(plainMatrix.getValue(0, 0)).toMatchObject({ f: '=A1', displayV: '=A1' });
+ expect(matrixFragment.getValue(0, 1)).toMatchObject({ f: '=A2' });
+ expect(plainMatrix.getValue(0, 1)).toMatchObject({ f: '=A2', displayV: '=A2' });
+ expect(matrixFragment.getValue(0, 2)).toMatchObject({ v: null, f: null, si: null, p: null });
+ expect(plainMatrix.getValue(0, 2)).toMatchObject({ v: null, f: null, si: null, p: null });
+ expect(matrix.getValue(0, 2)).toMatchObject({ v: null, f: null, si: null, p: null });
+
+ controller.dispose();
+ });
+});
+
export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {
const univer = new Univer();
const injector = univer.__getInjector();
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
new file mode 100644
index 0000000000..cccb35a24e
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.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 { BEFORE_CELL_EDIT, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { FormulaEditorShowController } from '../formula-editor-show.controller';
+
+function createController() {
+ let editInterceptor: any;
+ let beforeCommandHandler: ((command: { id: string; params?: unknown }) => void) | undefined;
+ let commandExecutedHandler: ((command: { id: string; params?: unknown }, options?: unknown) => void) | undefined;
+ const currentSkeleton$ = new Subject<any>();
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ unitId: 'unit-1',
+ getCell: vi.fn(() => ({ f: '=SUM(A1:A2)' })),
+ };
+ const skeleton = { worksheet };
+
+ const controller = new FormulaEditorShowController(
+ { unitId: 'unit-1' } as never,
+ {
+ writeCellInterceptor: {
+ intercept: vi.fn((point, config) => {
+ expect(point).toBe(BEFORE_CELL_EDIT);
+ editInterceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ },
+ } as never,
+ { getSkeleton: vi.fn(() => skeleton) } as never,
+ {
+ getArrayFormulaRange: vi.fn(() => null),
+ getArrayFormulaCellData: vi.fn(() => ({})),
+ getFormulaStringByCell: vi.fn(() => '=SUM(A1:A2)'),
+ } as never,
+ { getColorFromTheme: vi.fn(() => '#fff') } as never,
+ { getRenderById: vi.fn(() => null) } as never,
+ {
+ currentSkeleton$,
+ getCurrentSkeleton: vi.fn(() => skeleton),
+ } as never,
+ {
+ onCommandExecuted: vi.fn((handler) => {
+ commandExecutedHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ beforeCommandExecuted: vi.fn((handler) => {
+ beforeCommandHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ { debug: vi.fn() } as never
+ );
+
+ currentSkeleton$.next({ skeleton, unitId: 'unit-1', sheetId: 'sheet-1' });
+
+ return {
+ controller,
+ editInterceptor: () => editInterceptor,
+ beforeCommandHandler: () => beforeCommandHandler,
+ commandExecutedHandler: () => commandExecutedHandler,
+ worksheet,
+ };
+}
+
+describe('FormulaEditorShowController', () => {
+ it('preserves the formula string when starting to edit a calculated formula cell', () => {
+ const { controller, editInterceptor, worksheet } = createController();
+ const originalCell = { v: 3 };
+ const result = editInterceptor().handler(
+ originalCell,
+ {
+ row: 0,
+ col: 1,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ worksheet,
+ },
+ vi.fn((cell) => cell)
+ );
+
+ expect(result).toEqual({ v: 3, f: '=SUM(A1:A2)' });
+
+ controller.dispose();
+ });
+
+ it('passes empty edit values through and registers row-height refresh listener', () => {
+ const { controller, editInterceptor, beforeCommandHandler } = createController();
+ const next = vi.fn((cell) => cell);
+
+ expect(editInterceptor().handler(null, {
+ row: 0,
+ col: 1,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ worksheet: {},
+ }, next)).toBeNull();
+ expect(next).toHaveBeenCalledWith(null);
+
+ beforeCommandHandler()?.({
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rowsAutoHeightInfo: [{ row: 0 }],
+ },
+ });
+
+ expect(beforeCommandHandler()).toBeDefined();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts
new file mode 100644
index 0000000000..aabfd525e2
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts
@@ -0,0 +1,102 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { INTERCEPTOR_POINT } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { FormulaRenderManagerController } from '../formula-render.controller';
+
+vi.mock('@univerjs/engine-formula', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/engine-formula')>();
+
+ return {
+ ...actual,
+ extractFormulaError: vi.fn(),
+ };
+});
+
+describe('FormulaRenderManagerController', () => {
+ it('marks formula error cells without mutating raw cell data', () => {
+ let interceptor: any;
+ const disposable = { dispose: vi.fn() };
+ const sheetInterceptorService = {
+ intercept: vi.fn((point, config) => {
+ interceptor = config;
+ return disposable;
+ }),
+ };
+ const formulaDataModel = {
+ getArrayFormulaCellData: vi.fn(() => ({ unit: { sheet: { 1: { 2: { f: '=A1' } } } } })),
+ };
+ const controller = new FormulaRenderManagerController(sheetInterceptorService as any, formulaDataModel as any);
+ const rawCell = { v: '#DIV/0!', markers: { br: { size: 1 } } };
+ vi.mocked(extractFormulaError).mockReturnValue(ErrorType.DIV_BY_ZERO);
+
+ const result = interceptor.handler(rawCell, {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ row: 1,
+ col: 2,
+ rawData: rawCell,
+ }, (cell: unknown) => cell);
+
+ expect(sheetInterceptorService.intercept).toHaveBeenCalledWith(
+ INTERCEPTOR_POINT.CELL_CONTENT,
+ expect.objectContaining({ priority: 10 })
+ );
+ expect(result).not.toBe(rawCell);
+ expect(result.markers).toEqual(expect.objectContaining({
+ br: { size: 1 },
+ tl: { size: 6, color: '#409f11' },
+ }));
+ expect(extractFormulaError).toHaveBeenCalledWith(rawCell, true);
+
+ controller.dispose();
+ expect(disposable.dispose).toHaveBeenCalled();
+ });
+
+ it('passes through cells when there is no formula error or cell data', () => {
+ let interceptor: any;
+ const controller = new FormulaRenderManagerController({
+ intercept: vi.fn((_point, config) => {
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as any, {
+ getArrayFormulaCellData: vi.fn(() => null),
+ } as any);
+
+ vi.mocked(extractFormulaError).mockReturnValueOnce(null as never);
+ expect(interceptor.handler({ v: 'plain' }, {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ row: 0,
+ col: 0,
+ rawData: { v: 'plain' },
+ }, (cell: unknown) => cell)).toEqual({ v: 'plain' });
+
+ vi.mocked(extractFormulaError).mockReturnValueOnce(ErrorType.VALUE);
+ expect(interceptor.handler(null, {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ row: 0,
+ col: 0,
+ rawData: null,
+ }, (cell: unknown) => cell)).toBeNull();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-reorder.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-reorder.controller.spec.ts
new file mode 100644
index 0000000000..8e7a830422
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-reorder.controller.spec.ts
@@ -0,0 +1,117 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ReorderRangeCommand, SetRangeValuesMutation } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { FormulaReorderController } from '../formula-reorder.controller';
+
+function createController(options?: { worksheet?: any }) {
+ let interceptor: any;
+ const disposable = { dispose: vi.fn() };
+ const sheetInterceptorService = {
+ interceptCommand: vi.fn((registeredInterceptor) => {
+ interceptor = registeredInterceptor;
+ return disposable;
+ }),
+ };
+ const workbook = {
+ getSheetBySheetId: vi.fn(() => options?.worksheet ?? null),
+ };
+ const controller = new FormulaReorderController(
+ sheetInterceptorService as any,
+ { getUniverSheetInstance: vi.fn(() => workbook) } as any,
+ { getFormulaStringByCell: vi.fn(() => '=A2') } as any,
+ { moveFormulaRefOffset: vi.fn(() => '=A1') } as any
+ );
+
+ return { controller, interceptor, disposable };
+}
+
+describe('FormulaReorderController', () => {
+ it('creates redo and undo mutations with formula references shifted to the reordered row', () => {
+ const matrix = {
+ getValue: vi.fn((row: number, col: number) => {
+ if (row === 1 && col === 0) {
+ return { f: '=A2', si: 'shared' };
+ }
+ if (row === 0 && col === 0) {
+ return { v: 'old-row' };
+ }
+ return { v: `cell-${row}-${col}` };
+ }),
+ };
+ const { controller, interceptor, disposable } = createController({
+ worksheet: { getCellMatrix: vi.fn(() => matrix) },
+ });
+
+ const result = interceptor.getMutations({
+ id: ReorderRangeCommand.id,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ order: { 0: 1 },
+ },
+ });
+
+ expect(result.redos).toEqual([{
+ id: SetRangeValuesMutation.id,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ cellValue: {
+ 0: {
+ 0: { f: '=A1', si: null },
+ },
+ },
+ },
+ }]);
+ expect(result.undos).toEqual([{
+ id: SetRangeValuesMutation.id,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ cellValue: {
+ 0: {
+ 0: { v: 'old-row' },
+ },
+ },
+ },
+ }]);
+
+ controller.dispose();
+ expect(disposable.dispose).toHaveBeenCalled();
+ });
+
+ it('returns empty mutations for non-reorder commands, missing worksheets and ranges without formulas', () => {
+ const { interceptor } = createController();
+ expect(interceptor.getMutations({ id: 'other-command', params: {} })).toEqual({ redos: [], undos: [] });
+ expect(interceptor.getMutations({
+ id: ReorderRangeCommand.id,
+ params: { unitId: 'unit', subUnitId: 'missing', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, order: {} },
+ })).toEqual({ redos: [], undos: [] });
+
+ const noFormula = createController({
+ worksheet: {
+ getCellMatrix: vi.fn(() => ({ getValue: vi.fn(() => ({ v: 'plain' })) })),
+ },
+ });
+ expect(noFormula.interceptor.getMutations({
+ id: ReorderRangeCommand.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, order: {} },
+ })).toEqual({ redos: [], undos: [] });
+ });
+});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/image-formula-render.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/image-formula-render.controller.spec.ts
new file mode 100644
index 0000000000..37ed6d5eae
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/image-formula-render.controller.spec.ts
@@ -0,0 +1,73 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { UniverInstanceType } from '@univerjs/core';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { ImageFormulaRenderController } from '../image-formula-render.controller';
+
+describe('ImageFormulaRenderController', () => {
+ it('refreshes sheet skeleton and marks the main component dirty for image formula changes', () => {
+ let refresh: () => void = () => undefined;
+ const skeletonManagerService = { reCalculate: vi.fn() };
+ const mainComponent = { makeDirty: vi.fn() };
+ const render = {
+ with: vi.fn((token) => token === SheetSkeletonManagerService ? skeletonManagerService : null),
+ mainComponent,
+ };
+ const workbook = { getUnitId: vi.fn(() => 'unit-1') };
+
+ new ImageFormulaRenderController(
+ { registerRefreshRenderFunction: vi.fn((fn) => { refresh = fn; }) } as any,
+ { getRenderById: vi.fn(() => render) } as any,
+ { getCurrentUnitOfType: vi.fn((type) => type === UniverInstanceType.UNIVER_SHEET ? workbook : null) } as any
+ );
+
+ refresh();
+
+ expect(render.with).toHaveBeenCalledWith(SheetSkeletonManagerService);
+ expect(skeletonManagerService.reCalculate).toHaveBeenCalled();
+ expect(mainComponent.makeDirty).toHaveBeenCalled();
+ });
+
+ it('does nothing when there is no workbook, render, or main component', () => {
+ let refresh: () => void = () => undefined;
+ const imageFormulaController = { registerRefreshRenderFunction: vi.fn((fn) => {
+ refresh = fn;
+ }) };
+ const renderManagerService = { getRenderById: vi.fn<(...args: any[]) => any>(() => null) };
+ const univerInstanceService = { getCurrentUnitOfType: vi.fn<(...args: any[]) => any>(() => null) };
+
+ new ImageFormulaRenderController(
+ imageFormulaController as any,
+ renderManagerService as any,
+ univerInstanceService as any
+ );
+
+ refresh();
+ expect(renderManagerService.getRenderById).not.toHaveBeenCalled();
+
+ univerInstanceService.getCurrentUnitOfType.mockReturnValue({ getUnitId: () => 'unit-1' });
+ refresh();
+ expect(renderManagerService.getRenderById).toHaveBeenCalledWith('unit-1');
+
+ renderManagerService.getRenderById.mockReturnValue({
+ with: vi.fn(() => ({ reCalculate: vi.fn() })),
+ mainComponent: null,
+ });
+ expect(() => refresh()).not.toThrow();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/controllers/components.controller.ts b/packages/sheets-formula-ui/src/controllers/components.controller.ts
index 9c7ade4d89..6660d99644 100644
--- a/packages/sheets-formula-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/components.controller.ts
@@ -30,7 +30,6 @@ export class ComponentsController extends Disposable {
) {
super();
- this._registerComponents2();
this._registerIcons();
this._registerComponents();
}
@@ -42,10 +41,8 @@ export class ComponentsController extends Disposable {
}
private _registerComponents(): void {
- this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MoreFunctions);
- }
+ this.disposeWithMe(this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MoreFunctions));
- private _registerComponents2(): void {
this.disposeWithMe(this._componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, RangeSelector));
this.disposeWithMe(this._componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, FormulaEditor));
diff --git a/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.spec.ts b/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.spec.ts
new file mode 100644
index 0000000000..15b9af0cbc
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/shortcuts/__tests__/formula-shortcuts.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 { QuickSumCommand } from '@univerjs/sheets-formula';
+import { KeyCode, MetaKeys } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { ReferenceAbsoluteOperation } from '../../../commands/operations/reference-absolute.operation';
+
+const whenSheetEditorActivatedMock = vi.fn();
+const whenSheetEditorFocusedMock = vi.fn();
+
+vi.mock('@univerjs/sheets-ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/sheets-ui')>();
+
+ return {
+ ...actual,
+ whenSheetEditorActivated: whenSheetEditorActivatedMock,
+ whenSheetEditorFocused: whenSheetEditorFocusedMock,
+ };
+});
+
+describe('formula shortcuts', () => {
+ it('binds F4 to reference absolute switching only while the sheet editor is active', async () => {
+ const { ChangeRefToAbsoluteShortcut } = await import('../prompt.shortcut');
+ const contextService = {};
+ whenSheetEditorActivatedMock.mockReturnValueOnce(true);
+
+ expect(ChangeRefToAbsoluteShortcut.id).toBe(ReferenceAbsoluteOperation.id);
+ expect(ChangeRefToAbsoluteShortcut.binding).toBe(KeyCode.F4);
+ expect(ChangeRefToAbsoluteShortcut.preconditions?.(contextService as never)).toBe(true);
+ expect(whenSheetEditorActivatedMock).toHaveBeenCalledWith(contextService);
+ });
+
+ it('binds quick sum to platform shortcuts while the sheet editor is focused', async () => {
+ const { QuickSumShortcut } = await import('../quick-sum.shortcut');
+
+ expect(QuickSumShortcut.id).toBe(QuickSumCommand.id);
+ expect(QuickSumShortcut.binding).toBe(MetaKeys.ALT | KeyCode.EQUAL);
+ expect(QuickSumShortcut.mac).toBe(MetaKeys.CTRL_COMMAND | MetaKeys.ALT | KeyCode.EQUAL);
+ expect(QuickSumShortcut.preconditions).toBe(whenSheetEditorFocusedMock);
+ expect(QuickSumShortcut.description).toBe('sheets-formula-ui.shortcut.quick-sum');
+ expect(QuickSumShortcut.group).toBe('4_sheet-edit');
+ expect(QuickSumShortcut.groupTitle).toBe('sheets-ui.shortcut.sheet-edit');
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/help-function/__tests__/HelpFunction.spec.tsx b/packages/sheets-formula-ui/src/views/formula-editor/help-function/__tests__/HelpFunction.spec.tsx
new file mode 100644
index 0000000000..fc258ea8dd
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/help-function/__tests__/HelpFunction.spec.tsx
@@ -0,0 +1,346 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Editor } from '@univerjs/docs-ui';
+import type { IFunctionInfo } from '@univerjs/engine-formula';
+import type { Root } from 'react-dom/client';
+import {
+ ConfigService,
+ ContextService,
+ IConfigService,
+ IContextService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+} from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { FunctionType, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { ISidebarService, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { FormulaPromptService, IFormulaPromptService } from '../../../../services/prompt.service';
+import { HelpFunction } from '../HelpFunction';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const sumInfo: IFunctionInfo = {
+ functionName: 'SUM',
+ functionType: FunctionType.Math,
+ description: 'Adds values together.',
+ abstract: 'Adds values.',
+ functionParameter: [
+ {
+ name: 'number1',
+ detail: 'First value.',
+ example: 'A1',
+ require: 1,
+ repeat: 0,
+ },
+ {
+ name: 'number2',
+ detail: 'Additional values.',
+ example: 'B1',
+ require: 0,
+ repeat: 1,
+ },
+ ],
+};
+
+class HelpDescriptionService {
+ getFunctionInfo(searchText: string) {
+ return searchText.toUpperCase() === sumInfo.functionName ? sumInfo : undefined;
+ }
+
+ hasDefinedNameDescription() {
+ return false;
+ }
+}
+
+class HelpEditorBridgeService {
+ readonly helpFunctionVisible$ = new BehaviorSubject(true);
+}
+
+class HelpEditorService {
+ getEditor(): unknown {
+ return HelpState.editor;
+ }
+}
+
+class HelpSidebarService {
+ readonly scrollEvent$ = new Subject<Event>();
+}
+
+class HelpUniverInstanceService {
+ readonly unitAdded$ = new Subject<void>();
+}
+
+class HelpResizeObserver {
+ observe(): void {}
+ disconnect(): void {}
+ unobserve(): void {}
+}
+
+class HelpState {
+ static editor: Editor;
+ static switched: number[] = [];
+ static closed = 0;
+
+ static reset(): void {
+ this.switched = [];
+ this.closed = 0;
+ }
+}
+
+function createEditor(): Editor {
+ const selectionChange$ = new Subject<{ textRanges: Array<{ startOffset: number; endOffset: number; collapsed: boolean }> }>();
+
+ return {
+ selectionChange$,
+ getEditorId: () => 'help-function-editor',
+ getBoundingClientRect: () => ({ left: 10, top: 20, right: 180, bottom: 44 }),
+ getDocumentData: () => ({ documentStyle: { marginTop: 0, marginBottom: 0 } }),
+ getSkeleton: () => ({
+ getSkeletonData: () => ({
+ pages: [{ height: 24 }],
+ }),
+ }),
+ } as unknown as Editor;
+}
+
+function createHelpFunctionTestBed() {
+ const injector = new Injector();
+
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);
+ injector.add([IFormulaPromptService, { useClass: FormulaPromptService }]);
+ injector.add([IDescriptionService, { useClass: HelpDescriptionService as never }]);
+ injector.add([IEditorBridgeService, { useClass: HelpEditorBridgeService as never }]);
+ injector.add([IEditorService, { useClass: HelpEditorService as never }]);
+ injector.add([ISidebarService, { useClass: HelpSidebarService as never }]);
+ injector.add([IUniverInstanceService, { useClass: HelpUniverInstanceService as never }]);
+
+ injector.get(LocaleService).load({
+ [LocaleType.ZH_CN]: {
+ 'sheets-formula-ui': {
+ prompt: {
+ required: 'Required.',
+ optional: 'Optional.',
+ helpExample: 'Example',
+ helpAbstract: 'Summary',
+ },
+ },
+ },
+ });
+
+ const editor = createEditor();
+ HelpState.editor = editor;
+
+ return {
+ injector,
+ editor,
+ editorBridgeService: injector.get(IEditorBridgeService) as unknown as HelpEditorBridgeService,
+ };
+}
+
+function renderWithInjector(root: Root, injector: Injector, element: React.ReactNode) {
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ {element}
+ </RediContext.Provider>
+ );
+ });
+}
+
+async function showHelpForSum(editor: Editor) {
+ await act(async () => {
+ (editor.selectionChange$ as unknown as Subject<{ textRanges: Array<{ startOffset: number; endOffset: number; collapsed: boolean }> }>).next({
+ textRanges: [{ startOffset: 4, endOffset: 4, collapsed: true }],
+ });
+ await new Promise((resolve) => setTimeout(resolve, 80));
+ });
+}
+
+function getHelpControls(): HTMLElement[] {
+ return Array.from(document.body.querySelectorAll('div'))
+ .filter((node) => node.className.includes('univer-size-6'));
+}
+
+function getHelpControl(index: number): HTMLElement {
+ const control = getHelpControls()[index];
+ if (!control) {
+ throw new TypeError(`Help control ${index} was not rendered`);
+ }
+
+ return control;
+}
+
+function getTextElement(text: string, classNamePart?: string): HTMLElement {
+ const element = Array.from(document.body.querySelectorAll('div,span'))
+ .filter((node) => node.textContent === text)
+ .filter((node) => !classNamePart || node.className.includes(classNamePart))
+ .at(-1);
+
+ if (!(element instanceof HTMLElement)) {
+ throw new TypeError(`Element with text ${text} was not rendered`);
+ }
+
+ return element;
+}
+
+describe('HelpFunction', () => {
+ let container: HTMLDivElement;
+ let popupRoot: HTMLDivElement;
+ let root: Root;
+ let resizeObserver: typeof ResizeObserver | undefined;
+
+ beforeEach(() => {
+ HelpState.reset();
+ resizeObserver = globalThis.ResizeObserver;
+ globalThis.ResizeObserver = HelpResizeObserver as typeof ResizeObserver;
+ container = document.createElement('div');
+ popupRoot = document.createElement('div');
+ popupRoot.id = 'univer-popup-portal';
+ document.body.appendChild(container);
+ document.body.appendChild(popupRoot);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ popupRoot.remove();
+ if (resizeObserver) {
+ globalThis.ResizeObserver = resizeObserver;
+ } else {
+ delete (globalThis as { ResizeObserver?: unknown }).ResizeObserver;
+ }
+ });
+
+ it('expands the active function help and reports parameter switches', async () => {
+ const { injector, editor } = createHelpFunctionTestBed();
+
+ renderWithInjector(
+ root,
+ injector, (
+ <HelpFunction
+ isFocus
+ editor={editor}
+ formulaText="=SUM("
+ onParamsSwitch={(index) => HelpState.switched.push(index)}
+ />
+ ));
+
+ await showHelpForSum(editor);
+
+ expect(document.body.textContent).toContain('SUM(number1,[number2,...])');
+
+ await act(async () => {
+ getHelpControl(0).click();
+ await Promise.resolve();
+ });
+
+ expect(document.body.textContent).toContain('SUM(A1,B1)');
+ expect(document.body.textContent).toContain('Adds values together.');
+ expect(document.body.textContent).toContain('Required. First value.');
+ expect(document.body.textContent).toContain('Optional. Additional values.');
+
+ await act(async () => {
+ getTextElement('[number2,...]').click();
+ await Promise.resolve();
+ });
+
+ expect(HelpState.switched).toEqual([1]);
+ });
+
+ it('hides the help card after close and restores it from the compact tip', async () => {
+ const { editor, editorBridgeService, injector } = createHelpFunctionTestBed();
+
+ renderWithInjector(
+ root,
+ injector, (
+ <HelpFunction
+ isFocus
+ editor={editor}
+ formulaText="=SUM("
+ onClose={() => {
+ HelpState.closed += 1;
+ }}
+ />
+ ));
+
+ await showHelpForSum(editor);
+
+ expect(document.body.textContent).toContain('SUM(number1,[number2,...])');
+
+ await act(async () => {
+ getHelpControl(1).click();
+ await Promise.resolve();
+ });
+
+ expect(HelpState.closed).toBe(1);
+ expect(editorBridgeService.helpFunctionVisible$.getValue()).toBe(false);
+ expect(document.body.textContent).not.toContain('SUM(number1,[number2,...])');
+ expect(document.body.textContent).toContain('?');
+
+ await act(async () => {
+ getTextElement('?', 'univer-cursor-pointer').click();
+ await Promise.resolve();
+ });
+
+ expect(editorBridgeService.helpFunctionVisible$.getValue()).toBe(true);
+ expect(document.body.textContent).toContain('SUM(number1,[number2,...])');
+ });
+
+ it('keeps the prior hidden preference until the compact tip restores help', async () => {
+ const { editor, editorBridgeService, injector } = createHelpFunctionTestBed();
+
+ editorBridgeService.helpFunctionVisible$.next(false);
+
+ renderWithInjector(
+ root,
+ injector, (
+ <HelpFunction
+ isFocus
+ editor={editor}
+ formulaText="=SUM("
+ />
+ ));
+
+ await showHelpForSum(editor);
+
+ expect(editorBridgeService.helpFunctionVisible$.getValue()).toBe(false);
+ expect(document.body.textContent).not.toContain('SUM(number1,[number2,...])');
+ expect(document.body.textContent).toContain('?');
+
+ await act(async () => {
+ getTextElement('?', 'univer-cursor-pointer').click();
+ await Promise.resolve();
+ });
+
+ expect(editorBridgeService.helpFunctionVisible$.getValue()).toBe(true);
+ expect(document.body.textContent).toContain('SUM(number1,[number2,...])');
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts
index 7100e681e5..a2347686db 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts
@@ -35,6 +35,22 @@ describe('getFormulaReplaceResult', () => {
});
});
+ it('does not duplicate the call bracket when the typed function already has one', () => {
+ expect(getFormulaReplaceResult(
+ [
+ { nodeType: sequenceNodeType.FUNCTION, token: 'SU', startIndex: 0, endIndex: 1 },
+ '(',
+ 'A1:A3)',
+ ],
+ 0,
+ 'SUM',
+ FunctionType.Math
+ )).toEqual({
+ text: 'SUM(A1:A3)',
+ offset: -1,
+ });
+ });
+
it('does not append an open bracket when replacing table names', () => {
expect(getFormulaReplaceResult(
[{ nodeType: sequenceNodeType.FUNCTION, token: 'Ord', startIndex: 0, endIndex: 2 }],
@@ -46,4 +62,16 @@ describe('getFormulaReplaceResult', () => {
offset: -3,
});
});
+
+ it('does not append an open bracket when replacing defined names', () => {
+ expect(getFormulaReplaceResult(
+ [{ nodeType: sequenceNodeType.FUNCTION, token: 'Tax', startIndex: 0, endIndex: 2 }],
+ 0,
+ 'TaxRate',
+ FunctionType.DefinedName
+ )).toEqual({
+ text: 'TaxRate',
+ offset: -4,
+ });
+ });
});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx b/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx
index 9b6fd06fb2..fbe036bb5d 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx
@@ -30,8 +30,9 @@ import {
} from '@univerjs/core';
import { IEditorService } from '@univerjs/docs-ui';
import { FunctionType, sequenceNodeType } from '@univerjs/engine-formula';
+import { DeviceInputEventType } from '@univerjs/engine-render';
import { IDescriptionService } from '@univerjs/sheets-formula';
-import { IShortcutService, ISidebarService, RediContext } from '@univerjs/ui';
+import { IShortcutService, ISidebarService, KeyCode, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { Subject } from 'rxjs';
@@ -48,24 +49,38 @@ const sumInfo: IFunctionInfo = {
functionParameter: [],
};
+const subtotalInfo: IFunctionInfo = {
+ functionName: 'SUBTOTAL',
+ functionType: FunctionType.Math,
+ description: 'Returns a subtotal in a list.',
+ abstract: 'Returns subtotal.',
+ functionParameter: [],
+};
+
class TestDescriptionService {
getSearchListByNameFirstLetter(searchText: string) {
- if (!sumInfo.functionName.startsWith(searchText.toUpperCase())) {
- return [];
- }
- return [{
- name: sumInfo.functionName,
- desc: sumInfo.description,
- functionType: sumInfo.functionType,
- }];
+ return [sumInfo, subtotalInfo]
+ .filter((info) => info.functionName.startsWith(searchText.toUpperCase()))
+ .map((info) => ({
+ name: info.functionName,
+ desc: info.description,
+ functionType: info.functionType,
+ }));
}
}
class TestCommandService {
readonly registered: ICommandInfo[] = [];
- executeCommand(): Promise<boolean> {
- return Promise.resolve(true);
+ async executeCommand(id?: string, params?: unknown): Promise<boolean> {
+ const command = this.registered.find((item) => item.id === id);
+ const handler = (command as { handler?: (_accessor: unknown, params?: unknown) => boolean | Promise<boolean> | void } | undefined)?.handler;
+ if (!handler) {
+ return true;
+ }
+
+ const result = await handler(undefined, params);
+ return result !== false;
}
registerCommand(command: ICommandInfo): IDisposable {
@@ -158,11 +173,13 @@ class SearchFunctionState {
static editor: unknown;
static selected: Array<{ text: string; offset: number }> = [];
static focused = 0;
+ static closed = 0;
static reset(): void {
this.editor = undefined;
this.selected = [];
this.focused = 0;
+ this.closed = 0;
}
}
@@ -200,7 +217,7 @@ function createSearchFunctionTestBed() {
const editor = createEditor();
SearchFunctionState.editor = editor;
- return { injector, editor };
+ return { injector, editor, commandService: injector.get(ICommandService) as unknown as TestCommandService };
}
async function waitForSearchList(editor: Editor): Promise<void> {
@@ -210,16 +227,32 @@ async function waitForSearchList(editor: Editor): Promise<void> {
});
}
+async function runFormulaSearchKeyboardCommand(commandService: TestCommandService, editor: Editor, keyCode: KeyCode): Promise<void> {
+ await act(async () => {
+ await commandService.executeCommand(`sheet.formula-embedding-editor.search_function.${editor.getEditorId()}`, {
+ eventType: DeviceInputEventType.Keyboard,
+ keyCode,
+ });
+ await Promise.resolve();
+ });
+}
+
describe('SearchFunction', () => {
let container: HTMLDivElement;
let popupRoot: HTMLDivElement;
let root: Root;
let resizeObserver: typeof ResizeObserver | undefined;
+ let scrollToDescriptor: PropertyDescriptor | undefined;
beforeEach(() => {
SearchFunctionState.reset();
resizeObserver = globalThis.ResizeObserver;
globalThis.ResizeObserver = TestResizeObserver as typeof ResizeObserver;
+ scrollToDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollTo');
+ Object.defineProperty(HTMLElement.prototype, 'scrollTo', {
+ configurable: true,
+ value() {},
+ });
container = document.createElement('div');
popupRoot = document.createElement('div');
popupRoot.id = 'univer-popup-portal';
@@ -239,6 +272,11 @@ describe('SearchFunction', () => {
} else {
delete (globalThis as { ResizeObserver?: unknown }).ResizeObserver;
}
+ if (scrollToDescriptor) {
+ Object.defineProperty(HTMLElement.prototype, 'scrollTo', scrollToDescriptor);
+ } else {
+ delete (HTMLElement.prototype as { scrollTo?: unknown }).scrollTo;
+ }
});
it('replaces the typed function token and refocuses the editor when a search result is selected', async () => {
@@ -273,4 +311,114 @@ describe('SearchFunction', () => {
expect(SearchFunctionState.focused).toBe(1);
expect(document.body.textContent).not.toContain('Adds selected values.');
});
+
+ it('accepts the highlighted formula suggestion from the registered keyboard command', async () => {
+ const { injector, editor, commandService } = createSearchFunctionTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SearchFunction
+ isFocus
+ editor={editor}
+ sequenceNodes={[{ nodeType: sequenceNodeType.FUNCTION, token: 'SU' } as never]}
+ onSelect={(result) => SearchFunctionState.selected.push(result)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await waitForSearchList(editor);
+ expect(document.body.textContent).toContain('SUM');
+
+ await runFormulaSearchKeyboardCommand(commandService, editor, KeyCode.ENTER);
+
+ expect(SearchFunctionState.selected).toEqual([{ text: 'SUM(', offset: -2 }]);
+ expect(document.body.textContent).not.toContain('Adds selected values.');
+ });
+
+ it('accepts the next formula suggestion after keyboard navigation moves the highlight', async () => {
+ const { injector, editor, commandService } = createSearchFunctionTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SearchFunction
+ isFocus
+ editor={editor}
+ sequenceNodes={[{ nodeType: sequenceNodeType.FUNCTION, token: 'SU' } as never]}
+ onSelect={(result) => SearchFunctionState.selected.push(result)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await waitForSearchList(editor);
+ expect(document.body.textContent).toContain('SUM');
+ expect(document.body.textContent).toContain('SUBTOTAL');
+
+ await runFormulaSearchKeyboardCommand(commandService, editor, KeyCode.ARROW_DOWN);
+ await runFormulaSearchKeyboardCommand(commandService, editor, KeyCode.ENTER);
+
+ expect(SearchFunctionState.selected).toEqual([{ text: 'SUBTOTAL(', offset: -7 }]);
+ expect(document.body.textContent).not.toContain('Returns a subtotal in a list.');
+ });
+
+ it('accepts the highlighted formula suggestion when tab completes the function token', async () => {
+ const { injector, editor, commandService } = createSearchFunctionTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SearchFunction
+ isFocus
+ editor={editor}
+ sequenceNodes={[{ nodeType: sequenceNodeType.FUNCTION, token: 'SU' } as never]}
+ onSelect={(result) => SearchFunctionState.selected.push(result)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await waitForSearchList(editor);
+ expect(document.body.textContent).toContain('SUM');
+
+ await runFormulaSearchKeyboardCommand(commandService, editor, KeyCode.TAB);
+
+ expect(SearchFunctionState.selected).toEqual([{ text: 'SUM(', offset: -2 }]);
+ expect(document.body.textContent).not.toContain('Adds selected values.');
+ });
+
+ it('closes formula suggestions without selecting a function when escape is pressed', async () => {
+ const { injector, editor, commandService } = createSearchFunctionTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SearchFunction
+ isFocus
+ editor={editor}
+ sequenceNodes={[{ nodeType: sequenceNodeType.FUNCTION, token: 'SU' } as never]}
+ onSelect={(result) => SearchFunctionState.selected.push(result)}
+ onClose={() => {
+ SearchFunctionState.closed += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await waitForSearchList(editor);
+ expect(document.body.textContent).toContain('SUM');
+
+ await runFormulaSearchKeyboardCommand(commandService, editor, KeyCode.ESC);
+
+ expect(SearchFunctionState.closed).toBe(1);
+ expect(SearchFunctionState.selected).toEqual([]);
+ expect(document.body.textContent).not.toContain('SUM');
+ });
});
diff --git a/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx b/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx
index f3d696e39b..987580cbda 100644
--- a/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx
@@ -180,4 +180,41 @@ describe('FormulaProgressBar', () => {
expect(controller.cleared).toBe(1);
});
+
+ it('keeps in-progress calculation visible until completion finishes transitioning', async () => {
+ const { controller, injector } = createProgressTestBed();
+
+ renderProgress(injector);
+
+ await act(async () => {
+ controller.setProgress({ done: 1, count: 2, label: 'Halfway' });
+ await Promise.resolve();
+ });
+
+ const progressBarInner = Array.from(container.querySelectorAll('div'))
+ .find((node) => node.style.width === '50%') as HTMLDivElement | undefined;
+ expect(progressBarInner).toBeDefined();
+
+ await act(async () => {
+ progressBarInner!.dispatchEvent(new Event('transitionend', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(controller.cleared).toBe(0);
+ expect(container.textContent).toContain('Halfway');
+
+ await act(async () => {
+ controller.setProgress({ done: 2, count: 2, label: 'Done' });
+ await Promise.resolve();
+ });
+
+ expect(progressBarInner!.style.width).toBe('100%');
+
+ await act(async () => {
+ progressBarInner!.dispatchEvent(new Event('transitionend', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(controller.cleared).toBe(1);
+ });
});
diff --git a/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx b/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
index 38e1a4eb90..f710f98809 100644
--- a/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
@@ -327,6 +327,10 @@ function createFormulaViewTestBed() {
optional: 'Optional.',
helpExample: 'Example',
},
+ functionType: {
+ math: 'Math',
+ statistical: 'Statistical',
+ },
},
},
});
@@ -335,6 +339,7 @@ function createFormulaViewTestBed() {
injector,
commandService: injector.get(ICommandService) as unknown as TestCommandService,
editorService: injector.get(IEditorService) as unknown as TestEditorService,
+ sidebarService: injector.get(ISidebarService) as unknown as TestSidebarService,
};
}
@@ -354,6 +359,30 @@ function writeInput(input: HTMLInputElement, value: string) {
input.dispatchEvent(new Event('input', { bubbles: true }));
}
+function pressKey(element: HTMLElement, key: string) {
+ element.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }));
+}
+
+async function chooseFunctionType(label: string) {
+ const select = document.body.querySelector('[data-u-comp="select"]') as HTMLElement | null;
+ expect(select).toBeDefined();
+
+ await act(async () => {
+ select!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const item = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((node) => node.textContent === label) as HTMLElement | undefined;
+ expect(item).toBeDefined();
+
+ await act(async () => {
+ item!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
describe('formula function picker views', () => {
let container: HTMLDivElement;
let root: Root;
@@ -409,6 +438,78 @@ describe('formula function picker views', () => {
expect(container.textContent).toContain('AVERAGE(A1:A3)');
});
+ it('selects the highlighted function from the keyboard list and updates the preview', async () => {
+ const { injector } = createFormulaViewTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SelectFunction onChange={(value) => SelectionState.values.push(value)} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ expect(SelectionState.values.at(-1)?.functionName).toBe('SUM');
+
+ await act(async () => {
+ pressKey(input, 'ArrowDown');
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ pressKey(input, 'Enter');
+ await Promise.resolve();
+ });
+
+ expect(SelectionState.values.at(-1)?.functionName).toBe('AVERAGE');
+ expect(container.textContent).toContain('Returns the average value.');
+ expect(container.textContent).toContain('AVERAGE(A1:A3)');
+ expect(container.textContent).not.toContain('Adds values together.');
+ });
+
+ it('inserts the first function from the selected category instead of a stale previous selection', async () => {
+ const { commandService, editorService, injector } = createFormulaViewTestBed();
+
+ await act(async () => {
+ renderWithInjector(root, injector, <MoreFunctions />);
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('SUM');
+ expect(container.textContent).toContain('Adds values together.');
+
+ await chooseFunctionType('Statistical');
+
+ expect(container.textContent).toContain('AVERAGE');
+ expect(container.textContent).toContain('Returns the average value.');
+ expect(container.textContent).not.toContain('SUM');
+ expect(container.textContent).not.toContain('Adds values together.');
+
+ const confirmButton = Array.from(container.querySelectorAll('button'))
+ .find((node) => node.textContent === 'Confirm') as HTMLButtonElement | undefined;
+ expect(confirmButton).toBeDefined();
+ expect(confirmButton!.disabled).toBe(false);
+
+ await act(async () => {
+ confirmButton!.click();
+ await Promise.resolve();
+ });
+
+ expect(commandService.executed).toEqual([
+ {
+ id: 'sheet.operation.set-cell-edit-visible',
+ params: expect.objectContaining({
+ visible: true,
+ unitId: 'formula-book',
+ }),
+ },
+ ]);
+ expect(editorService.replaced.get(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=AVERAGE(', cover: undefined }]);
+ expect(editorService.replaced.get(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=AVERAGE(', cover: false }]);
+ });
+
it('inserts the selected function call into both sheet editors after confirmation', async () => {
const { commandService, editorService, injector } = createFormulaViewTestBed();
@@ -448,4 +549,106 @@ describe('formula function picker views', () => {
expect(editorService.replaced.get(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=AVERAGE(', cover: undefined }]);
expect(editorService.replaced.get(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=AVERAGE(', cover: false }]);
});
+
+ it('does not insert a previously selected function after search removes all results', async () => {
+ const { commandService, editorService, injector } = createFormulaViewTestBed();
+
+ await act(async () => {
+ renderWithInjector(root, injector, <MoreFunctions />);
+ await Promise.resolve();
+ });
+
+ const averageItem = Array.from(container.querySelectorAll('li'))
+ .find((node) => node.textContent?.includes('AVERAGE')) as HTMLElement | undefined;
+ expect(averageItem).toBeDefined();
+
+ await act(async () => {
+ averageItem!.click();
+ await Promise.resolve();
+ });
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ writeInput(input, 'NOT_A_FUNCTION');
+ await Promise.resolve();
+ });
+
+ const confirmButton = Array.from(container.querySelectorAll('button'))
+ .find((node) => node.textContent === 'Confirm') as HTMLButtonElement | undefined;
+ expect(confirmButton).toBeDefined();
+ expect(confirmButton!.disabled).toBe(true);
+
+ await act(async () => {
+ confirmButton!.click();
+ await Promise.resolve();
+ });
+
+ expect(commandService.executed).toEqual([]);
+ expect(editorService.replaced.size).toBe(0);
+ });
+
+ it('resets search and selected function when the function sidebar is reopened', async () => {
+ const { commandService, editorService, injector, sidebarService } = createFormulaViewTestBed();
+
+ await act(async () => {
+ renderWithInjector(root, injector, <MoreFunctions />);
+ await Promise.resolve();
+ });
+
+ const averageItem = Array.from(container.querySelectorAll('li'))
+ .find((node) => node.textContent?.includes('AVERAGE')) as HTMLElement | undefined;
+ expect(averageItem).toBeDefined();
+
+ await act(async () => {
+ averageItem!.click();
+ await Promise.resolve();
+ });
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ writeInput(input, 'AVE');
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('AVERAGE');
+ expect(container.textContent).not.toContain('SUM');
+
+ await act(async () => {
+ sidebarService.sidebarOptions$.next({ visible: true });
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(input.value).toBe('');
+ expect(container.textContent).toContain('SUM');
+ expect(container.textContent).toContain('AVERAGE');
+ expect(container.textContent).toContain('Adds values together.');
+ expect(container.textContent).not.toContain('Returns the average value.');
+
+ const confirmButton = Array.from(container.querySelectorAll('button'))
+ .find((node) => node.textContent === 'Confirm') as HTMLButtonElement | undefined;
+ expect(confirmButton).toBeDefined();
+ expect(confirmButton!.disabled).toBe(false);
+
+ await act(async () => {
+ confirmButton!.click();
+ await Promise.resolve();
+ });
+
+ expect(commandService.executed).toEqual([
+ {
+ id: 'sheet.operation.set-cell-edit-visible',
+ params: expect.objectContaining({
+ visible: true,
+ unitId: 'formula-book',
+ }),
+ },
+ ]);
+ expect(editorService.replaced.get(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=SUM(', cover: undefined }]);
+ expect(editorService.replaced.get(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=SUM(', cover: false }]);
+ });
});
diff --git a/packages/sheets-formula-ui/src/views/more-functions/input-params/__tests__/InputParams.spec.tsx b/packages/sheets-formula-ui/src/views/more-functions/input-params/__tests__/InputParams.spec.tsx
new file mode 100644
index 0000000000..0488f28a8d
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/more-functions/input-params/__tests__/InputParams.spec.tsx
@@ -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 type { IFunctionInfo } from '@univerjs/engine-formula';
+import type { Root } from 'react-dom/client';
+import { FunctionType } from '@univerjs/engine-formula';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { InputParams } from '../InputParams';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const countIfInfo: IFunctionInfo = {
+ functionName: 'COUNTIF',
+ functionType: FunctionType.Statistical,
+ description: 'Counts cells that meet a condition.',
+ abstract: 'Conditional count.',
+ functionParameter: [
+ {
+ name: 'range',
+ detail: 'Cells to evaluate.',
+ example: 'A1:A10',
+ require: 1,
+ repeat: 0,
+ },
+ {
+ name: 'criterion',
+ detail: 'Condition to apply.',
+ example: '">5"',
+ require: 0,
+ repeat: 0,
+ },
+ ],
+};
+
+describe('InputParams', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it('shows the selected function signature and description before a parameter is active', () => {
+ const changes: string[][] = [];
+
+ act(() => {
+ root.render(<InputParams functionInfo={countIfInfo} onChange={(params) => changes.push(params)} />);
+ });
+
+ expect(container.textContent).toContain('range');
+ expect(container.textContent).toContain('criterion');
+ expect(container.textContent).toContain('COUNTIF(range,[criterion])');
+ expect(container.textContent).toContain('Counts cells that meet a condition.');
+ expect(changes).toEqual([]);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx
new file mode 100644
index 0000000000..b3f1b8761d
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx
@@ -0,0 +1,451 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IDisposable, IUnitRangeName } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import type { Root } from 'react-dom/client';
+import type { IRangeSelectorInstance } from '../index';
+import {
+ CommandType,
+ ICommandService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ ThemeService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { IMarkSelectionService } from '@univerjs/sheets-ui';
+import { RediContext } from '@univerjs/ui';
+import { act, createRef } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Subject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { GlobalRangeSelectorService } from '../../../services/range-selector.service';
+import { GlobalRangeSelector } from '../Global';
+import { RangeSelector } from '../index';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestCommandService {
+ readonly executed: Array<{ id: string; params?: unknown }> = [];
+
+ executeCommand(id: string, params?: unknown): Promise<boolean> {
+ this.executed.push({ id, params });
+ return Promise.resolve(true);
+ }
+
+ registerCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ registerMultipleCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ beforeCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ onCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ syncExecuteCommand(): boolean {
+ return true;
+ }
+
+ setCommandExecutedListener(): void {}
+
+ getCommands(): Map<string, ICommandInfo> {
+ return new Map();
+ }
+
+ getCommand(): ICommandInfo {
+ return { id: 'test.command', type: CommandType.OPERATION };
+ }
+}
+
+class TestEditorService {
+ readonly blur$ = new Subject<void>();
+ readonly focus$ = new Subject<{ unitId: string }>();
+
+ blur(): void {
+ this.blur$.next();
+ }
+
+ focus(unitId: string): void {
+ this.focus$.next({ unitId });
+ }
+}
+
+class TestDescriptionService {
+ hasDefinedNameDescription() {
+ return false;
+ }
+}
+
+class TestSheetsSelectionsService {
+ readonly selectionMoveStart$ = new Subject();
+ readonly selectionMoving$ = new Subject();
+ readonly selectionMoveEnd$ = new Subject();
+}
+
+class TestMarkSelectionService {
+ private _nextId = 0;
+
+ addShape() {
+ return `shape-${this._nextId++}`;
+ }
+
+ addShapeWithNoFresh() {
+ return this.addShape();
+ }
+
+ removeShape(): void {}
+
+ removeAllShapes(): void {}
+
+ refreshShapes(): void {}
+
+ getShapeMap() {
+ return new Map();
+ }
+}
+
+class TestUniverInstanceService {
+ private readonly _workbook = {
+ getActiveSheet: () => ({
+ getSheetId: () => 'sheet-1',
+ getName: () => 'Sheet1',
+ }),
+ };
+
+ getUnit(_unitId: string, type?: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this._workbook : null;
+ }
+
+ getCurrentUnitOfType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this._workbook : null;
+ }
+}
+
+function createGlobalRangeSelectorTestBed() {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.add([ThemeService, { useClass: ThemeService }]);
+ injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);
+ injector.add([IDescriptionService, { useClass: TestDescriptionService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService as never }]);
+ injector.add([SheetsSelectionsService, { useClass: TestSheetsSelectionsService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([GlobalRangeSelectorService]);
+
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'sheets-formula-ui': {
+ rangeSelector: {
+ title: 'Select a data range',
+ addAnotherRange: 'Add range',
+ placeHolder: 'Select range or enter.',
+ confirm: 'Confirm',
+ cancel: 'Cancel',
+ },
+ },
+ },
+ });
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+
+ return {
+ injector,
+ service: injector.get(GlobalRangeSelectorService),
+ commandService: injector.get(ICommandService) as unknown as TestCommandService,
+ };
+}
+
+function writeInput(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+async function clickButton(text: string) {
+ const button = Array.from(document.body.querySelectorAll('button'))
+ .find((node) => node.textContent === text) as HTMLButtonElement | undefined;
+ expect(button).toBeDefined();
+
+ await act(async () => {
+ button!.click();
+ await Promise.resolve();
+ });
+}
+
+describe('GlobalRangeSelector', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it('opens the global selector dialog and resolves the confirmed range', async () => {
+ const { injector, service } = createGlobalRangeSelectorTestBed();
+ const callbackRanges: IUnitRangeName[][] = [];
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <GlobalRangeSelector />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ let promise!: Promise<IUnitRangeName[]>;
+
+ await act(async () => {
+ promise = service.showRangeSelectorDialog({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ callback: (ranges) => callbackRanges.push(ranges),
+ });
+ await Promise.resolve();
+ });
+
+ const input = document.body.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ writeInput(input, 'B2:C3');
+ await Promise.resolve();
+ });
+
+ await clickButton('Confirm');
+
+ await expect(promise).resolves.toEqual([
+ expect.objectContaining({
+ unitId: '',
+ sheetName: '',
+ range: expect.objectContaining({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ }),
+ }),
+ ]);
+ expect(callbackRanges).toEqual([
+ [
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ }),
+ }),
+ ],
+ ]);
+ });
+
+ it('restores the caller selection when a range selector dialog is cancelled', async () => {
+ const { commandService, injector } = createGlobalRangeSelectorTestBed();
+ const selectorRef = createRef<IRangeSelectorInstance | null>();
+ const resetRange: ISelectionWithStyle[] = [{
+ range: {
+ startRow: 4,
+ endRow: 5,
+ startColumn: 2,
+ endColumn: 3,
+ },
+ primary: null,
+ } as ISelectionWithStyle];
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <RangeSelector
+ unitId="book-1"
+ subUnitId="sheet-1"
+ hideEditor
+ selectorRef={selectorRef}
+ resetRange={resetRange}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ selectorRef.current!.showDialog([]);
+ await Promise.resolve();
+ });
+
+ await clickButton('Cancel');
+
+ expect(commandService.executed).toEqual([
+ {
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ selections: resetRange,
+ },
+ },
+ ]);
+ });
+
+ it('confirms the typed range without leaving the temporary range selection active', async () => {
+ const { commandService, injector } = createGlobalRangeSelectorTestBed();
+ const selectorRef = createRef<IRangeSelectorInstance | null>();
+ const resetRange: ISelectionWithStyle[] = [{
+ range: {
+ startRow: 8,
+ endRow: 8,
+ startColumn: 1,
+ endColumn: 1,
+ },
+ primary: null,
+ } as ISelectionWithStyle];
+ const changes: string[] = [];
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <RangeSelector
+ unitId="book-1"
+ subUnitId="sheet-1"
+ hideEditor
+ selectorRef={selectorRef}
+ resetRange={resetRange}
+ onChange={(_, value) => changes.push(value)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ selectorRef.current!.showDialog([]);
+ await Promise.resolve();
+ });
+
+ const input = document.body.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ writeInput(input, 'D4:E5');
+ await Promise.resolve();
+ });
+
+ await clickButton('Confirm');
+
+ expect(changes).toEqual(['D4:E5']);
+ expect(commandService.executed).toEqual([
+ {
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ selections: resetRange,
+ },
+ },
+ ]);
+ });
+
+ it('confirms only the latest global selector request after another request replaces it', async () => {
+ const { injector, service } = createGlobalRangeSelectorTestBed();
+ const firstCallbackRanges: IUnitRangeName[][] = [];
+ const secondCallbackRanges: IUnitRangeName[][] = [];
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <GlobalRangeSelector />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ service.showRangeSelectorDialog({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ callback: (ranges) => firstCallbackRanges.push(ranges),
+ });
+ await Promise.resolve();
+ });
+
+ let secondPromise!: Promise<IUnitRangeName[]>;
+ await act(async () => {
+ secondPromise = service.showRangeSelectorDialog({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ callback: (ranges) => secondCallbackRanges.push(ranges),
+ });
+ await Promise.resolve();
+ });
+
+ const input = document.body.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ writeInput(input, 'F6:G7');
+ await Promise.resolve();
+ });
+
+ await clickButton('Confirm');
+
+ expect(firstCallbackRanges).toEqual([]);
+ await expect(secondPromise).resolves.toEqual([
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 5,
+ endRow: 6,
+ startColumn: 5,
+ endColumn: 6,
+ }),
+ }),
+ ]);
+ expect(secondCallbackRanges).toEqual([
+ [
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 5,
+ endRow: 6,
+ startColumn: 5,
+ endColumn: 6,
+ }),
+ }),
+ ],
+ ]);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
index 29f40b0b8b..38a382d1e3 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
@@ -17,7 +17,14 @@
import type { IUnitRangeName } from '@univerjs/core';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { Root } from 'react-dom/client';
-import { Injector, IUniverInstanceService, LocaleService, LocaleType, UniverInstanceType } from '@univerjs/core';
+import {
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ RANGE_TYPE,
+ UniverInstanceType,
+} from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SheetsSelectionsService } from '@univerjs/sheets';
import { RediContext } from '@univerjs/ui';
@@ -114,6 +121,24 @@ function writeInput(input: HTMLInputElement, value: string) {
input.dispatchEvent(new Event('input', { bubbles: true }));
}
+async function emitSelection(injector: Injector, range: ISelectionWithStyle['range']) {
+ const selectionsService = injector.get(SheetsSelectionsService) as never as TestSheetsSelectionsService;
+
+ await act(async () => {
+ selectionsService.selectionMoveStart$.next([{ range } as ISelectionWithStyle]);
+ await Promise.resolve();
+ });
+}
+
+async function finishSelections(injector: Injector, ranges: Array<ISelectionWithStyle['range']>) {
+ const selectionsService = injector.get(SheetsSelectionsService) as never as TestSheetsSelectionsService;
+
+ await act(async () => {
+ selectionsService.selectionMoveEnd$.next(ranges.map((range) => ({ range }) as ISelectionWithStyle));
+ await Promise.resolve();
+ });
+}
+
async function clickButton(text: string): Promise<void> {
const button = Array.from(document.body.querySelectorAll('button'))
.find((node) => node.textContent === text) as HTMLButtonElement | undefined;
@@ -179,4 +204,240 @@ describe('RangeSelectorDialog', () => {
]]);
expect(RangeDialogState.closed).toBe(0);
});
+
+ it('closes without confirming typed ranges when the user cancels the dialog', async () => {
+ renderRangeDialog(root, createRangeDialogTestBed());
+
+ const firstInput = document.body.querySelector('input') as HTMLInputElement;
+ expect(firstInput).toBeDefined();
+
+ await act(async () => {
+ writeInput(firstInput, 'A1:B2');
+ await Promise.resolve();
+ });
+
+ await clickButton('Cancel');
+
+ expect(RangeDialogState.confirmed).toEqual([]);
+ expect(RangeDialogState.closed).toBe(1);
+ });
+
+ it('confirms only the remaining ranges after a typed range is removed', async () => {
+ renderRangeDialog(root, createRangeDialogTestBed());
+
+ const firstInput = document.body.querySelector('input') as HTMLInputElement;
+ expect(firstInput).toBeDefined();
+
+ await act(async () => {
+ writeInput(firstInput, 'A1:A2');
+ await Promise.resolve();
+ });
+
+ await clickButton('Add range');
+
+ const inputs = Array.from(document.body.querySelectorAll('input')) as HTMLInputElement[];
+ expect(inputs.length).toBe(2);
+
+ await act(async () => {
+ writeInput(inputs[1], 'C3:D4');
+ await Promise.resolve();
+ });
+
+ const removeFirstRangeIcon = Array.from(document.body.querySelectorAll<SVGElement>('svg'))
+ .find((node) => node.classList.contains('univer-cursor-pointer'));
+ expect(removeFirstRangeIcon).toBeDefined();
+
+ await act(async () => {
+ removeFirstRangeIcon!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ await clickButton('Confirm');
+
+ expect(RangeDialogState.confirmed).toEqual([[
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 3,
+ }),
+ }),
+ ]]);
+ expect(RangeDialogState.closed).toBe(0);
+ });
+
+ it('replaces the active range input with a sheet selection before confirming', async () => {
+ const injector = createRangeDialogTestBed();
+ renderRangeDialog(root, injector);
+
+ const firstInput = document.body.querySelector('input') as HTMLInputElement;
+ expect(firstInput).toBeDefined();
+
+ await act(async () => {
+ writeInput(firstInput, 'A1:A2');
+ await Promise.resolve();
+ });
+
+ await clickButton('Add range');
+
+ await emitSelection(injector, {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+
+ const inputs = Array.from(document.body.querySelectorAll('input')) as HTMLInputElement[];
+ expect(inputs.map((input) => input.value)).toEqual(['A1:A2', 'B2:C3']);
+
+ await clickButton('Confirm');
+
+ expect(RangeDialogState.confirmed).toEqual([[
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 0,
+ }),
+ }),
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ }),
+ }),
+ ]]);
+ expect(RangeDialogState.closed).toBe(0);
+ });
+
+ it('replaces the focused typed range when the user picks a sheet selection', async () => {
+ const injector = createRangeDialogTestBed();
+ renderRangeDialog(root, injector);
+
+ const firstInput = document.body.querySelector('input') as HTMLInputElement;
+ expect(firstInput).toBeDefined();
+
+ await act(async () => {
+ writeInput(firstInput, 'A1:A2');
+ await Promise.resolve();
+ });
+
+ await clickButton('Add range');
+
+ const inputs = Array.from(document.body.querySelectorAll('input')) as HTMLInputElement[];
+ expect(inputs.length).toBe(2);
+
+ await act(async () => {
+ writeInput(inputs[1], 'D4:D5');
+ inputs[0].dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ await emitSelection(injector, {
+ startRow: 5,
+ endRow: 6,
+ startColumn: 2,
+ endColumn: 3,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+
+ expect(inputs.map((input) => input.value)).toEqual(['C6:D7', 'D4:D5']);
+
+ await clickButton('Confirm');
+
+ expect(RangeDialogState.confirmed).toEqual([[
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 5,
+ endRow: 6,
+ startColumn: 2,
+ endColumn: 3,
+ }),
+ }),
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 3,
+ endRow: 4,
+ startColumn: 3,
+ endColumn: 3,
+ }),
+ }),
+ ]]);
+ expect(RangeDialogState.closed).toBe(0);
+ });
+
+ it('confirms only the first ranges from a multi-range sheet selection when capped', async () => {
+ const injector = createRangeDialogTestBed();
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <RangeSelectorDialog
+ visible
+ initialValue={[]}
+ unitId="book-1"
+ subUnitId="sheet-1"
+ maxRangeCount={2}
+ onConfirm={(ranges) => RangeDialogState.confirmed.push(ranges)}
+ onClose={() => {
+ RangeDialogState.closed += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ });
+
+ await finishSelections(injector, [
+ {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ {
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 3,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 4,
+ endColumn: 4,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ ]);
+
+ const inputs = Array.from(document.body.querySelectorAll('input')) as HTMLInputElement[];
+ expect(inputs.map((input) => input.value)).toEqual(['A1', 'C3:D4']);
+
+ await clickButton('Confirm');
+
+ expect(RangeDialogState.confirmed).toEqual([[
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ }),
+ }),
+ expect.objectContaining({
+ range: expect.objectContaining({
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 3,
+ }),
+ }),
+ ]]);
+ expect(RangeDialogState.closed).toBe(0);
+ });
});
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
index 58463ba560..3605feadec 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts
@@ -18,6 +18,8 @@ import { RANGE_TYPE } from '@univerjs/core';
import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';
import { describe, expect, it } from 'vitest';
import { filterReferenceNode, isComma, isReference } from '../filter-reference-node';
+import { rangePreProcess } from '../range-pre-process';
+import { sequenceNodeToText } from '../sequence-node-to-text';
import { unitRangesToText } from '../unit-ranges-to-text';
import { verifyRange } from '../verify-range';
@@ -42,6 +44,14 @@ describe('range selector utils', () => {
expect(verifyRange([referenceNode as never, ';'])).toBe(false);
});
+ it('rebuilds typed range text with separators when editing multiple references', () => {
+ expect(sequenceNodeToText([
+ { nodeType: sequenceNodeType.REFERENCE, token: 'A1:B2' } as never,
+ matchToken.COMMA,
+ { nodeType: sequenceNodeType.REFERENCE, token: "'Data Sheet'!D3" } as never,
+ ])).toBe("A1:B2,'Data Sheet'!D3");
+ });
+
it('serializes selected ranges with sheet and workbook qualifiers only when the formula needs them', () => {
const ranges = [
{
@@ -60,4 +70,18 @@ describe('range selector utils', () => {
expect(unitRangesToText(ranges, true, 'Sheet1')).toEqual(['A1:B2', "'Data Sheet'!D3"]);
expect(unitRangesToText(ranges, true, 'Sheet1', true)).toEqual(["'[book-1]Sheet1'!A1:B2", "'[book-1]Data Sheet'!D3"]);
});
+
+ it('normalizes a reverse-dragged range before the selector confirms it', () => {
+ expect(rangePreProcess({
+ startRow: 8,
+ endRow: 2,
+ startColumn: 5,
+ endColumn: 1,
+ })).toEqual({
+ startRow: 2,
+ endRow: 8,
+ startColumn: 1,
+ endColumn: 5,
+ });
+ });
});
diff --git a/packages/sheets-numfmt-ui/src/controllers/components.controller.ts b/packages/sheets-numfmt-ui/src/controllers/components.controller.ts
index af448e2b02..6114146361 100644
--- a/packages/sheets-numfmt-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-numfmt-ui/src/controllers/components.controller.ts
@@ -31,13 +31,6 @@ export class ComponentsController extends Disposable {
this._registerComponents();
this._registerIcons();
- this._registerComponents2();
- }
-
- private _registerComponents(): void {
- this.disposeWithMe(
- this._componentManager.register(SHEET_NUMFMT_PANEL, SheetNumfmtPanel)
- );
}
private _registerIcons(): void {
@@ -52,7 +45,11 @@ export class ComponentsController extends Disposable {
}));
}
- private _registerComponents2(): void {
+ private _registerComponents(): void {
+ this.disposeWithMe(
+ this._componentManager.register(SHEET_NUMFMT_PANEL, SheetNumfmtPanel)
+ );
+
([
[MORE_NUMFMT_TYPE_KEY, MoreNumfmtType],
[OPTIONS_KEY, Options],
diff --git a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx
index 9d87d792dc..482e65ed00 100644
--- a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx
+++ b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx
@@ -55,8 +55,8 @@ export const SheetNumfmtPanel: FC<ISheetNumfmtPanelProps> = (props) => {
[localeService]
);
const [type, setType] = useState(findDefaultType);
- const [key, setKey] = useState(() => `${row}_${col}`);
- const { mark, userHabitCurrency } = useCurrencyOptions(() => setKey(`${row}_${col}_userCurrency'`));
+ const [key, setKey] = useState(() => `${row}_${col}_${defaultPattern}`);
+ const { mark, userHabitCurrency } = useCurrencyOptions(() => setKey(`${row}_${col}_${defaultPattern}_userCurrency`));
const BusinessComponent = useMemo(() => typeOptions.find((item) => item.label === type)?.component, [type]);
@@ -109,8 +109,8 @@ export const SheetNumfmtPanel: FC<ISheetNumfmtPanelProps> = (props) => {
useEffect(() => {
setType(findDefaultType());
- setKey(`${row}_${col}`);
- }, [row, col]);
+ setKey(`${row}_${col}_${defaultPattern}`);
+ }, [row, col, defaultPattern]);
return (
<div
diff --git a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx
index 7e725d57d0..c3f394f333 100644
--- a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx
+++ b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx
@@ -18,6 +18,7 @@ import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs
import type { Root } from 'react-dom/client';
import {
CellValueType,
+ currencySymbols,
ICommandService,
ILocalStorageService,
ILogService,
@@ -42,7 +43,12 @@ import {
SheetInterceptorService,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { getPatternType, SetNumfmtCommand, SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';
+import {
+ getCurrencyType,
+ getPatternType,
+ SetNumfmtCommand,
+ SheetsNumfmtCellContentController,
+} from '@univerjs/sheets-numfmt';
import { ILayoutService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
@@ -57,6 +63,7 @@ import { SheetNumfmtPanel } from '../SheetNumfmtPanel';
const UNIT_ID = 'test';
const SUB_UNIT_ID = 'sheet1';
const CUSTOM_HISTORY_KEY = 'numfmt_custom_pattern';
+const CURRENCY_HABIT_KEY = 'userHabitController_numfmtCurrency';
class TestLocalStorageService implements ILocalStorageService {
private readonly _data = new Map<string, unknown>();
@@ -302,6 +309,45 @@ describe('MoreNumfmtType Options', () => {
expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toBeNull();
expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 1)).toBeNull();
});
+
+ it('applies percent format to the current sheet selection and returns focus to the sheet', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ currentTestBed.selectionService.setSelections([{
+ range: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: null,
+ }] as never);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <Options />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const percentItem = Array.from(container.querySelectorAll('.univer-flex.univer-h-7'))
+ .find((item) => item.textContent?.includes('Percent')) as HTMLElement | undefined;
+
+ expect(percentItem).toBeDefined();
+
+ await act(async () => {
+ percentItem!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({ pattern: '0.00%' });
+ expect((currentTestBed.injector.get(ILayoutService) as unknown as TestLayoutService).checkContentIsFocused()).toBe(true);
+ });
});
describe('CustomFormat', () => {
@@ -462,6 +508,28 @@ describe('SheetNumfmtPanel', () => {
});
}
+ async function cancelPanel() {
+ const cancelButton = Array.from(container!.querySelectorAll('[data-u-comp="button"]'))[0] as HTMLElement;
+
+ await act(async () => {
+ cancelButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+ }
+
+ async function changePanelInput(value: string) {
+ const input = container!.querySelector('input') as HTMLInputElement | null;
+
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input!.dispatchEvent(new Event('input', { bubbles: true }));
+ await Promise.resolve();
+ });
+ }
+
afterEach(() => {
act(() => {
root?.unmount();
@@ -612,4 +680,582 @@ describe('SheetNumfmtPanel', () => {
expect(results).toEqual([true]);
expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({ pattern: 'yyyy/MM/dd' });
});
+
+ it('applies changed decimal places from the number panel through the real SetNumfmtCommand', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Number');
+ const incrementDecimalButton = container.querySelector('[aria-label="increment"]') as HTMLElement;
+
+ for (let i = 0; i < 2; i++) {
+ await act(async () => {
+ incrementDecimalButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+ }
+
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: '#,##0.00_);(#,##0.00)',
+ });
+ });
+
+ it('applies the selected negative number style through the real SetNumfmtCommand', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Number');
+ const redParenthesesOption = Array.from(container.querySelectorAll('a')).find((item) => {
+ const label = item.querySelector('span') as HTMLSpanElement | null;
+ return label?.textContent?.includes('(1,235)') && label.style.color === 'red';
+ }) as HTMLElement | undefined;
+
+ expect(redParenthesesOption).toBeDefined();
+
+ await act(async () => {
+ redParenthesesOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: '#,##0_);[Red](#,##0)',
+ });
+ });
+
+ it('applies decreased decimal places from an existing number format through the real SetNumfmtCommand', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '#,##0.00_);(#,##0.00)',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const decrementDecimalButton = container.querySelector('[aria-label="decrement"]') as HTMLElement;
+
+ await act(async () => {
+ decrementDecimalButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: '#,##0.0_);(#,##0.0)',
+ });
+ });
+
+ it('keeps the current date pattern when the selected date option is clicked again', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: 'yyyy-MM-dd',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await selectPanelListOption('1930-08-05');
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({ pattern: 'yyyy-MM-dd' });
+ });
+
+ it('refreshes the active panel state when the loaded format changes for the same cell', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ const renderPanel = async (defaultPattern: string) => {
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern,
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+ };
+
+ await renderPanel('yyyy-MM-dd');
+ await renderPanel('#,##0.00_);(#,##0.00)');
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: '#,##0.00_);(#,##0.00)',
+ });
+ });
+
+ it('applies a typed custom format through the real SetNumfmtCommand when confirmed', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Custom format');
+ await changePanelInput('0.000 kg');
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: '0.000 kg',
+ });
+ expect(await currentTestBed.localStorageService.getItem<string[]>(CUSTOM_HISTORY_KEY)).toEqual(['0.000 kg']);
+ });
+
+ it('keeps the loaded currency symbol when decimal places are changed and confirmed', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+ const currencySymbol = currencySymbols[3];
+ const loadedCurrencyPattern = `"${currencySymbol}"#,##0.00_);"${currencySymbol}"#,##0.00`;
+ const confirmedCurrencyPattern = `"${currencySymbol}"#,##0.0_);"${currencySymbol}"#,##0.0`;
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: loadedCurrencyPattern,
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const decrementDecimalButton = container.querySelector('[aria-label="decrement"]') as HTMLElement;
+
+ await act(async () => {
+ decrementDecimalButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: confirmedCurrencyPattern,
+ });
+ });
+
+ it('does not apply or save a typed custom format when cancelled', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const events: Array<{ type: 'change' | 'cancel' | 'confirm'; value: string }> = [];
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ events.push(event);
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Custom format');
+ await changePanelInput('0.000 kg');
+ await cancelPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([]);
+ expect(events.at(-1)).toEqual({ type: 'cancel', value: '' });
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toBeNull();
+ expect(await currentTestBed.localStorageService.getItem<string[]>(CUSTOM_HISTORY_KEY)).toEqual([]);
+ });
+
+ it('records confirmed currency and accounting symbols in the user habit order', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ await currentTestBed.localStorageService.setItem(CURRENCY_HABIT_KEY, []);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const events: Array<{ type: 'change' | 'cancel' | 'confirm'; value: string }> = [];
+ const currencySymbol = currencySymbols[7];
+ const accountingSymbol = currencySymbols[8];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: `${currencySymbol}#,##0.00`,
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => events.push(event)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await confirmPanel();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ const confirmedCurrencyPattern = events.at(-1)?.value ?? '';
+
+ expect(getCurrencyType(confirmedCurrencyPattern)).toBe(currencySymbol);
+ expect(await currentTestBed.localStorageService.getItem<string[]>(CURRENCY_HABIT_KEY)).toEqual([
+ currencySymbol,
+ ]);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: `_("${accountingSymbol}"* #,##0.00_)`,
+ row: 1,
+ col: 0,
+ }}
+ onChange={(event) => events.push(event)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await confirmPanel();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ const confirmedAccountingPattern = events.at(-1)?.value ?? '';
+
+ expect(getCurrencyType(confirmedAccountingPattern)).toBe(accountingSymbol);
+ expect(await currentTestBed.localStorageService.getItem<string[]>(CURRENCY_HABIT_KEY)).toEqual([
+ accountingSymbol,
+ currencySymbol,
+ ]);
+ });
+
+ it('uses the most recent saved currency habit when a blank cell is confirmed as Currency', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ const topHabit = currencySymbols[19];
+ const previousHabit = currencySymbols[5];
+ await currentTestBed.localStorageService.setItem(CURRENCY_HABIT_KEY, [topHabit, previousHabit]);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+ const events: Array<{ type: 'change' | 'cancel' | 'confirm'; value: string }> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ events.push(event);
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Currency');
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+ const confirmedPattern = events.at(-1)?.value ?? '';
+
+ expect(results).toEqual([true]);
+ expect(getCurrencyType(confirmedPattern)).toBe(topHabit);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: `"${topHabit}"#,##0.00_);"${topHabit}"#,##0.00`,
+ });
+ });
+
+ it('uses the most recent saved currency habit when a blank cell is confirmed as Accounting', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ const topHabit = currencySymbols[18];
+ const previousHabit = currencySymbols[6];
+ await currentTestBed.localStorageService.setItem(CURRENCY_HABIT_KEY, [topHabit, previousHabit]);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+ const events: Array<{ type: 'change' | 'cancel' | 'confirm'; value: string }> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ events.push(event);
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Accounting');
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+ const confirmedPattern = events.at(-1)?.value ?? '';
+
+ expect(results).toEqual([true]);
+ expect(getCurrencyType(confirmedPattern)).toBe(topHabit);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({
+ pattern: `_("${topHabit}"* #,##0.00_)`,
+ });
+ });
});
diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.ts
new file mode 100644
index 0000000000..5296213867
--- /dev/null
+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.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 { BehaviorSubject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../../const';
+import { SheetsTableComponentController } from '../sheet-table-component.controller';
+
+function createController() {
+ const contextValues = new Map<string, unknown>();
+ const panelOpened$ = new BehaviorSubject<unknown>(undefined);
+ const popupDisposables: Array<{ dispose: ReturnType<typeof vi.fn> }> = [];
+ const contextService = {
+ getContextValue: vi.fn((key: string) => contextValues.get(key)),
+ setContextValue: vi.fn((key: string, value: unknown) => {
+ contextValues.set(key, value);
+ panelOpened$.next(value);
+ }),
+ subscribeContextValue$: vi.fn(() => panelOpened$),
+ };
+ const popupService = {
+ attachPopupToCell: vi.fn((..._args: unknown[]) => {
+ const disposable = { dispose: vi.fn() };
+ popupDisposables.push(disposable);
+ return disposable;
+ }),
+ };
+ const dialogService = { close: vi.fn() };
+ const controller = new SheetsTableComponentController(
+ contextService as never,
+ popupService as never,
+ dialogService as never
+ );
+
+ return { controller, contextService, popupService, dialogService, popupDisposables };
+}
+
+describe('SheetsTableComponentController', () => {
+ it('opens, toggles and reopens the table filter popup based on current filter cell', () => {
+ const { controller, contextService, popupService, popupDisposables } = createController();
+ const info = { unitId: 'unit-1', subUnitId: 'sheet-1', tableId: 'table-1', row: 2, column: 3 };
+
+ controller.openOrToggleFilterPanel(info);
+
+ expect(contextService.setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, true);
+ expect(popupService.attachPopupToCell).toHaveBeenCalledWith(2, 3, expect.objectContaining({
+ componentKey: SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,
+ direction: 'horizontal',
+ offset: [5, 0],
+ portal: true,
+ }));
+ expect(controller.getCurrentTableFilterInfo()).toEqual(info);
+
+ controller.openOrToggleFilterPanel(info);
+
+ expect(contextService.setContextValue).toHaveBeenLastCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);
+ expect(popupDisposables[0].dispose).toHaveBeenCalled();
+ expect(controller.getCurrentTableFilterInfo()).toBeNull();
+
+ controller.dispose();
+ });
+
+ it('disposes the previous popup and opens a new one when switching to another filter cell', () => {
+ const { controller, contextService, popupService, popupDisposables } = createController();
+ const firstInfo = { unitId: 'unit-1', subUnitId: 'sheet-1', tableId: 'table-1', row: 2, column: 3 };
+ const secondInfo = { unitId: 'unit-1', subUnitId: 'sheet-1', tableId: 'table-1', row: 2, column: 4 };
+
+ controller.openOrToggleFilterPanel(firstInfo);
+ controller.openOrToggleFilterPanel(secondInfo);
+
+ expect(contextService.setContextValue).toHaveBeenCalledTimes(1);
+ expect(popupDisposables[0].dispose).toHaveBeenCalled();
+ expect(popupService.attachPopupToCell).toHaveBeenLastCalledWith(2, 4, expect.any(Object));
+ expect(controller.getCurrentTableFilterInfo()).toEqual(secondInfo);
+
+ controller.dispose();
+ });
+
+ it('closes the filter dialog and context when clicking outside the popup', () => {
+ const { controller, popupService, dialogService, contextService } = createController();
+ const info = { unitId: 'unit-1', subUnitId: 'sheet-1', tableId: 'table-1', row: 2, column: 3 };
+
+ controller.openOrToggleFilterPanel(info);
+ const popupCall = popupService.attachPopupToCell.mock.calls[0] as [number, number, { onClickOutside: () => void }];
+ const popupOptions = popupCall[2];
+ popupOptions.onClickOutside();
+
+ expect(dialogService.close).toHaveBeenCalledWith(UNIVER_SHEET_TABLE_FILTER_PANEL_ID);
+ expect(contextService.setContextValue).toHaveBeenLastCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);
+ expect(controller.getCurrentTableFilterInfo()).toBeNull();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts
index 4a0a50baa9..6bd626a783 100644
--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts
+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
+import { INTERCEPTOR_POINT } from '@univerjs/sheets';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
-
+import { FILTER_ICON_PADDING, FILTER_ICON_SIZE } from '../../views/widgets/table-filter-button.shape';
import { SheetsTableFilterButtonRenderController } from '../sheet-table-filter-button-render.controller';
vi.hoisted(() => {
@@ -78,4 +79,88 @@ describe('SheetsTableFilterButtonRenderController', () => {
expect((controller as any)._tableFilterButtonShapes).toEqual([]);
expect((controller as any)._buttonRenderDisposable).toBeNull();
});
+
+ it('adds right padding only to table header cells covered by filter buttons', () => {
+ let interceptor: any;
+ const controller = new SheetsTableFilterButtonRenderController(
+ {
+ unit: {
+ getUnitId: () => 'u1',
+ getActiveSheet: () => null,
+ },
+ unitId: 'u1',
+ scene: {
+ addObjects: vi.fn(),
+ makeDirty: vi.fn(),
+ },
+ } as any,
+ { createInstance: vi.fn() } as any,
+ {
+ currentSkeleton$: new Subject(),
+ getCurrentSkeleton: () => null,
+ } as any,
+ {
+ intercept: vi.fn((point, config) => {
+ expect(point).toBe(INTERCEPTOR_POINT.CELL_CONTENT);
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as any,
+ {
+ tableAdd$: new Subject(),
+ tableNameChanged$: new Subject(),
+ tableRangeChanged$: new Subject(),
+ tableThemeChanged$: new Subject(),
+ tableDelete$: new Subject(),
+ tableFilterChanged$: new Subject(),
+ getSheetFilterRangeWithState: vi.fn(() => []),
+ } as any,
+ {
+ getRangeThemeStyle: vi.fn(),
+ } as any,
+ {
+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),
+ } as any
+ );
+
+ (controller as any)._interceptCellContent('u1', 's1', {
+ startRow: 4,
+ endRow: 8,
+ startColumn: 2,
+ endColumn: 4,
+ });
+
+ const rawCell = { v: 'Header', fontRenderExtension: { leftOffset: 3 } };
+ const headerResult = interceptor.handler(rawCell, {
+ unitId: 'u1',
+ subUnitId: 's1',
+ row: 4,
+ col: 3,
+ rawData: rawCell,
+ }, (cell: unknown) => cell);
+
+ expect(headerResult).not.toBe(rawCell);
+ expect(headerResult.fontRenderExtension).toEqual({
+ leftOffset: 3,
+ rightOffset: FILTER_ICON_SIZE + FILTER_ICON_PADDING + 2,
+ });
+
+ const bodyCell = { v: 'Body' };
+ expect(interceptor.handler(bodyCell, {
+ unitId: 'u1',
+ subUnitId: 's1',
+ row: 5,
+ col: 3,
+ rawData: bodyCell,
+ }, (cell: unknown) => cell)).toBe(bodyCell);
+ expect(interceptor.handler(bodyCell, {
+ unitId: 'u1',
+ subUnitId: 'other',
+ row: 4,
+ col: 3,
+ rawData: bodyCell,
+ }, (cell: unknown) => cell)).toBe(bodyCell);
+
+ controller.dispose();
+ });
});
diff --git a/packages/sheets-table-ui/src/controllers/components.controller.ts b/packages/sheets-table-ui/src/controllers/components.controller.ts
index 804c876177..6673d85474 100644
--- a/packages/sheets-table-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/components.controller.ts
@@ -31,7 +31,6 @@ export class ComponentsController extends Disposable {
super();
this._registerComponents();
- this._registerComponents2();
this._registerIcons();
}
@@ -42,9 +41,7 @@ export class ComponentsController extends Disposable {
] as const).forEach(([key, comp]) => {
this.disposeWithMe(this._componentManager.register(key, comp));
});
- }
- private _registerComponents2(): void {
([
[TABLE_SELECTOR_DIALOG, SheetTableSelector],
[SHEET_TABLE_THEME_PANEL, SheetTableThemePanel],
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx
index e7cf9cf2dd..53b42a4b3e 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableItemsFilterPanel.tsx
@@ -32,10 +32,10 @@ interface ISheetTableItemsFilterPanelProps {
setCheckedItemSet: Dispatch<SetStateAction<Set<string>>>;
}
-const getCheckedCount = (map: Map<string, number>) => {
+const getCheckedItemCount = (map: Map<string, number>, checkedItemSet: Set<string>) => {
let count = 0;
- map.forEach((value) => {
- count += value;
+ checkedItemSet.forEach((item) => {
+ count += map.get(item) ?? 0;
});
return count;
};
@@ -50,7 +50,7 @@ export function SheetTableItemsFilterPanel(props: ISheetTableItemsFilterPanelPro
// const allChecked = tableFilter === undefined ? true : checkedItemSet.size === itemsCountMap.size;
const [allChecked, setAllChecked] = useState<boolean>(tableFilter === undefined ? true : checkedItemSet.size === itemsCountMap.size);
- const [checkedCount, setCheckedCount] = useState<number>(allChecked ? allItemsCount : getCheckedCount(itemsCountMap));
+ const [checkedCount, setCheckedCount] = useState<number>(allChecked ? allItemsCount : getCheckedItemCount(itemsCountMap, checkedItemSet));
const indeterminate = !allChecked && checkedItemSet.size > 0;
const [searchText, setSearchText] = useState('');
@@ -178,9 +178,7 @@ export function SheetTableItemsFilterPanel(props: ISheetTableItemsFilterPanelPro
})}
</div>
</div>
-
</div>
</div>
-
);
}
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx
new file mode 100644
index 0000000000..433f8a630f
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx
@@ -0,0 +1,1394 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency, IDisposable, IDocumentData, IWorkbookData, Workbook } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import type { IConditionInfo } from '../type';
+import {
+ createIdentifier,
+ ICommandService,
+ Inject,
+ Injector,
+ IPermissionService,
+ LocaleService,
+ LocaleType,
+ Plugin,
+ toDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DefinedNamesService, FormulaDataModel, IDefinedNamesService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ AddRangeThemeMutation,
+ RemoveRangeThemeMutation,
+ ReorderRangeCommand,
+ ReorderRangeMutation,
+ SetRangeThemeMutation,
+ SheetInterceptorService,
+ SheetRangeThemeModel,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+} from '@univerjs/sheets';
+import { SheetsSortController, SheetsSortService } from '@univerjs/sheets-sort';
+import {
+ AddTableThemeCommand,
+ RemoveTableThemeCommand,
+ SetSheetTableCommand,
+ SetSheetTableFilterCommand,
+ SetSheetTableFilterMutation,
+ SetSheetTableMutation,
+ SheetsTableSortStateEnum,
+ SheetTableInsertColumnAtCommand,
+ SheetTableService,
+ TABLE_FILTER_EMPTY_VALUE,
+ TableColumnFilterTypeEnum,
+ TableConditionTypeEnum,
+ TableManager,
+ TableNumberCompareTypeEnum,
+ TableStringCompareTypeEnum,
+} from '@univerjs/sheets-table';
+import { IMarkSelectionService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
+import { IDialogService, IShortcutService, RediContext } from '@univerjs/ui';
+import { act, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SheetsTableComponentController } from '../../../controllers/sheet-table-component.controller';
+import { SheetTableThemeUIController } from '../../../controllers/sheet-table-theme-ui.controller';
+import { SheetsTableUiService } from '../../../services/sheets-table-ui.service';
+import { SheetTableConditionPanel } from '../SheetTableConditionPanel';
+import { SheetTableFilterPanel } from '../SheetTableFilterPanel';
+import { SheetTableRenameDialog } from '../SheetTableRenameDialog';
+import { SheetTableSelector } from '../SheetTableSelector';
+import { SheetTableThemePanel } from '../SheetTableThemePanel';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const IEditorService = createIdentifier<TestEditorService>('univer.editor.service');
+const IDescriptionService = createIdentifier<TestDescriptionService>('formula.description-service');
+
+class TestComponentController extends SheetsTableComponentController {
+ closeCount = 0;
+
+ override closeFilterPanel(): void {
+ this.closeCount += 1;
+ super.closeFilterPanel();
+ }
+}
+
+class TestSheetCanvasPopManagerService {
+ attachPopupToCell(): IDisposable {
+ return toDisposable(() => {});
+ }
+}
+
+class TestDialogService {
+ open(): IDisposable {
+ return toDisposable(() => {});
+ }
+
+ close(): void {
+ // no-op
+ }
+
+ closeAll(): void {
+ // no-op
+ }
+
+ getDialogs$() {
+ throw new Error('Dialogs are not observed in this component test.');
+ }
+}
+
+class TestRenderManagerService {
+ getRenderById(): undefined {
+ return undefined;
+ }
+}
+
+class TestMarkSelectionService {
+ addShape(): string | null {
+ return 'selection-shape';
+ }
+
+ removeShape(): void {
+ // no-op
+ }
+}
+
+class TestEditorModel {
+ private _data: IDocumentData;
+ readonly change$ = new Subject<void>();
+
+ constructor(data: IDocumentData) {
+ this._data = data;
+ }
+
+ getPlainText(): string {
+ return this._data.body?.dataStream?.replace(/\r?\n$/, '') ?? '';
+ }
+
+ getDocumentData(): IDocumentData {
+ return this._data;
+ }
+
+ setDocumentData(data: IDocumentData): void {
+ this._data = data;
+ this.change$.next();
+ }
+}
+
+class TestDocSkeletonDataModel {
+ updateDocumentDataPageSize(): void {
+ // no-op
+ }
+}
+
+class TestDocSkeletonViewModel {
+ private readonly _dataModel = new TestDocSkeletonDataModel();
+
+ getDataModel(): TestDocSkeletonDataModel {
+ return this._dataModel;
+ }
+}
+
+class TestDocSkeletonManagerService {
+ private readonly _viewModel = new TestDocSkeletonViewModel();
+
+ getViewModel(): TestDocSkeletonViewModel {
+ return this._viewModel;
+ }
+
+ getSkeleton() {
+ return {
+ getActualSize: () => ({
+ actualWidth: 160,
+ actualHeight: 32,
+ }),
+ };
+ }
+}
+
+class TestEditorRender {
+ private _disposed = false;
+ private readonly _docSkeletonManagerService = new TestDocSkeletonManagerService();
+ readonly components = new Map<string, { translate: (x: number, y: number) => void }>();
+ readonly scene = {
+ transformByState: () => {
+ // no-op
+ },
+ getViewport: () => undefined,
+ };
+
+ readonly mainComponent = {
+ resize: () => {
+ // no-op
+ },
+ translate: () => {
+ // no-op
+ },
+ };
+
+ with(): TestDocSkeletonManagerService {
+ return this._docSkeletonManagerService;
+ }
+
+ isDisposed(): boolean {
+ return this._disposed;
+ }
+
+ dispose(): void {
+ this._disposed = true;
+ }
+}
+
+class TestEditor {
+ readonly change$ = new Subject<void>();
+ readonly input$ = new Subject<void>();
+ readonly paste$ = new Subject<void>();
+ readonly blur$ = new Subject<void>();
+ readonly focus$ = new Subject<void>();
+ readonly selectionChange$ = new Subject<void>();
+ readonly render = new TestEditorRender();
+ private readonly _model: TestEditorModel;
+
+ constructor(
+ private readonly _editorId: string,
+ data: IDocumentData
+ ) {
+ this._model = new TestEditorModel(data);
+ }
+
+ getEditorId(): string {
+ return this._editorId;
+ }
+
+ getDocumentData(): IDocumentData {
+ return this._model.getDocumentData();
+ }
+
+ setDocumentData(data: IDocumentData): void {
+ this._model.setDocumentData(data);
+ }
+
+ getDocumentDataModel(): TestEditorModel {
+ return this._model;
+ }
+
+ replaceText(text: string): void {
+ this._model.setDocumentData({
+ ...this.getDocumentData(),
+ body: {
+ ...this.getDocumentData().body,
+ dataStream: text,
+ },
+ });
+ }
+
+ setSelectionRanges(): void {
+ // no-op
+ }
+
+ getSelectionRanges(): [] {
+ return [];
+ }
+
+ getBoundingClientRect() {
+ return {
+ width: 160,
+ height: 32,
+ };
+ }
+
+ blur(): void {
+ this.blur$.next();
+ }
+
+ focus(): void {
+ this.focus$.next();
+ }
+
+ dispose(): void {
+ this.render.dispose();
+ this.change$.complete();
+ this.input$.complete();
+ this.paste$.complete();
+ this.blur$.complete();
+ this.focus$.complete();
+ this.selectionChange$.complete();
+ }
+}
+
+class TestEditorService {
+ private readonly _editors = new Map<string, TestEditor>();
+ private _focusId: string | undefined;
+ readonly blur$ = new Subject<void>();
+ readonly focus$ = new Subject<void>();
+
+ register(config: { editorUnitId?: string; initialSnapshot: IDocumentData }): IDisposable {
+ const editorId = config.editorUnitId ?? config.initialSnapshot.id!;
+ const editor = new TestEditor(editorId, config.initialSnapshot);
+ this._editors.set(editorId, editor);
+
+ return toDisposable(() => {
+ editor.dispose();
+ this._editors.delete(editorId);
+ });
+ }
+
+ getEditor(id?: string): TestEditor | undefined {
+ return id ? this._editors.get(id) : undefined;
+ }
+
+ getAllEditor(): Map<string, TestEditor> {
+ return this._editors;
+ }
+
+ isEditor(editorUnitId: string): boolean {
+ return this._editors.has(editorUnitId);
+ }
+
+ getEditorRenderConfig(): undefined {
+ return undefined;
+ }
+
+ isSheetEditor(): boolean {
+ return false;
+ }
+
+ blur(): void {
+ this._focusId = undefined;
+ this.blur$.next();
+ }
+
+ focus(editorUnitId: string): void {
+ this._focusId = editorUnitId;
+ this.focus$.next();
+ }
+
+ getFocusId(): string | undefined {
+ return this._focusId;
+ }
+
+ getFocusEditor(): TestEditor | undefined {
+ return this._focusId ? this._editors.get(this._focusId) : undefined;
+ }
+}
+
+class TestShortcutService {
+ registerShortcut(): IDisposable {
+ return toDisposable(() => {});
+ }
+}
+
+class TestDescriptionService {
+ getDescriptions(): Map<string, unknown> {
+ return new Map();
+ }
+
+ hasFunction(): boolean {
+ return false;
+ }
+
+ getFunctionInfo(): undefined {
+ return undefined;
+ }
+
+ getSearchListByName(): unknown[] {
+ return [];
+ }
+
+ getSearchListByNameFirstLetter(): unknown[] {
+ return [];
+ }
+
+ getSearchListByType(): unknown[] {
+ return [];
+ }
+
+ registerDescriptions(): IDisposable {
+ return toDisposable(() => {});
+ }
+
+ unregisterDescriptions(): void {
+ // no-op
+ }
+
+ hasDescription(): boolean {
+ return false;
+ }
+
+ hasDefinedNameDescription(): boolean {
+ return false;
+ }
+
+ isFormulaDefinedName(): boolean {
+ return false;
+ }
+}
+
+interface ITestBed {
+ univer: Univer;
+ injector: Injector;
+ workbook: Workbook;
+}
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'test',
+ sheetOrder: ['sheet1'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {
+ 0: {
+ 0: { v: 'product' },
+ 1: { v: 'amount' },
+ },
+ 1: {
+ 0: { v: 'book' },
+ 1: { v: 12 },
+ },
+ 2: {
+ 0: { v: 'pen' },
+ 1: { v: 3 },
+ },
+ 3: {
+ 1: { v: 8 },
+ },
+ },
+ },
+ },
+ styles: {},
+ };
+}
+
+function createTestBed(): ITestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ const dependencies: Dependency[] = [
+ [TableManager],
+ [SheetTableService],
+ [SheetsTableUiService],
+ [SheetsSortService, { useClass: SheetsSortService }],
+ [SheetsSortController, { useClass: SheetsSortController }],
+ [FormulaDataModel, { useClass: FormulaDataModel }],
+ [SheetRangeThemeModel],
+ [SheetTableThemeUIController],
+ [SheetInterceptorService],
+ [SheetSkeletonService, { useClass: SheetSkeletonService }],
+ [SheetsSelectionsService],
+ [IRenderManagerService, { useClass: TestRenderManagerService }],
+ [IEditorService, { useClass: TestEditorService as never }],
+ [IMarkSelectionService, { useClass: TestMarkSelectionService as never }],
+ [IShortcutService, { useClass: TestShortcutService as never }],
+ [IDescriptionService, { useClass: TestDescriptionService }],
+ [LexerTreeBuilder],
+ [IDefinedNamesService, { useClass: DefinedNamesService }],
+ [SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService }],
+ [IDialogService, { useClass: TestDialogService }],
+ [SheetsTableComponentController, { useClass: TestComponentController }],
+ ];
+ dependencies.forEach((dependency) => this._injector.add(dependency));
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const localeService = injector.get(LocaleService);
+ localeService.load({
+ [LocaleType.EN_US]: {
+ 'sheets-table': {
+ tableNameError: 'Invalid table name',
+ },
+ 'sheets-table-ui': {
+ cancel: 'Cancel',
+ confirm: 'Confirm',
+ customStyle: 'Custom style',
+ defaultStyle: 'Default style',
+ customTooMore: 'Custom styles limit reached',
+ header: 'Header',
+ firstLine: 'First line',
+ secondLine: 'Second line',
+ footer: 'Footer',
+ renamePlaceholder: 'Enter table name',
+ tableNameError: 'Invalid table name',
+ columnMenu: {
+ 'insert-left': 'Insert 1 table column left',
+ 'insert-right': 'Insert 1 table column right',
+ delete: 'Delete table column',
+ },
+ sort: {
+ 'sort-asc': 'Ascending',
+ 'sort-desc': 'Descending',
+ },
+ tableRangeWithOtherTableError: 'Table range cannot overlap with other tables',
+ tableRangeSingleRowError: 'Table range cannot be a single row',
+ updateError: 'Cannot set table range to an area that does not overlap with the original and is not in the same row',
+ condition: {
+ empty: '(Empty)',
+ string: 'Text',
+ },
+ string: {
+ compare: {
+ equal: 'Is equal to',
+ },
+ },
+ filter: {
+ 'by-values': 'Filter by values',
+ 'by-conditions': 'Filter by conditions',
+ cancel: 'Cancel',
+ 'clear-filter': 'Clear filter',
+ confirm: 'Confirm',
+ 'search-placeholder': 'Search',
+ 'select-all': 'Select all',
+ },
+ },
+ 'sheets-formula-ui': {
+ rangeSelector: {
+ title: 'Select a data range',
+ addAnotherRange: 'Add range',
+ buttonTooltip: 'Select data range',
+ cancel: 'Cancel',
+ confirm: 'Confirm',
+ placeHolder: 'Select range or enter.',
+ },
+ },
+ },
+ });
+ localeService.setLocale(LocaleType.EN_US);
+
+ const commandService = injector.get(ICommandService);
+ [
+ SetSheetTableCommand,
+ SetSheetTableMutation,
+ SetSheetTableFilterCommand,
+ SetSheetTableFilterMutation,
+ ReorderRangeCommand,
+ ReorderRangeMutation,
+ AddRangeThemeMutation,
+ RemoveRangeThemeMutation,
+ SetRangeThemeMutation,
+ AddTableThemeCommand,
+ RemoveTableThemeCommand,
+ SheetTableInsertColumnAtCommand,
+ ].forEach((command) => {
+ commandService.registerCommand(command);
+ });
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
+ const permissionService = injector.get(IPermissionService);
+ permissionService.addPermissionPoint(new WorkbookEditablePermission(workbook.getUnitId()));
+ const sheetTableService = injector.get(SheetTableService);
+ sheetTableService.addTable(
+ workbook.getUnitId(),
+ 'sheet1',
+ 'Orders',
+ { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 },
+ ['Product', 'Amount'],
+ 'table-orders'
+ );
+ sheetTableService.addTable(
+ workbook.getUnitId(),
+ 'sheet1',
+ 'Archive',
+ { startRow: 5, endRow: 7, startColumn: 0, endColumn: 1 },
+ ['Product', 'Amount'],
+ 'table-archive'
+ );
+ injector.get(SheetsSortController);
+
+ return {
+ univer,
+ injector,
+ workbook,
+ };
+}
+
+function renderWithRediContext(testBed: ITestBed, element: React.ReactElement) {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ {element}
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, root };
+}
+
+function changeInput(input: HTMLInputElement, value: string): void {
+ act(() => {
+ if (!input.getAttribute('type')) {
+ input.setAttribute('type', 'text');
+ }
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+function clickElement(element: Element): void {
+ act(() => {
+ element.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, cancelable: true }));
+ element.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, cancelable: true }));
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
+ });
+}
+
+function clickButtonByText(container: HTMLElement, text: string): void {
+ const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent === text);
+ if (!button) {
+ throw new Error(`Button with text "${text}" was not found.`);
+ }
+
+ clickElement(button);
+}
+
+function getButtonByText(scope: ParentNode, text: string): HTMLButtonElement {
+ const button = Array.from(scope.querySelectorAll('button')).reverse().find((item) => item.textContent === text);
+ if (!button) {
+ throw new Error(`Button with text "${text}" was not found.`);
+ }
+
+ return button;
+}
+
+async function selectRangeThroughDialog(container: HTMLElement, rangeText: string): Promise<void> {
+ const selectorIcon = container.querySelector('svg');
+ if (!selectorIcon) {
+ throw new Error('Range selector icon was not found.');
+ }
+
+ clickElement(selectorIcon);
+ await flushCommands();
+
+ const dialogInput = Array.from(document.body.querySelectorAll('input')).at(-1) as HTMLInputElement | undefined;
+ if (!dialogInput) {
+ throw new Error('Range selector dialog input was not found.');
+ }
+
+ changeInput(dialogInput, rangeText);
+ clickElement(getButtonByText(document.body, 'Confirm'));
+ await flushCommands();
+}
+
+function clickCheckboxByText(container: HTMLElement, text: string): void {
+ const label = Array.from(container.querySelectorAll('label')).find((item) => item.textContent?.includes(text));
+ const input = label?.querySelector('input');
+ if (!input) {
+ throw new Error(`Checkbox with text "${text}" was not found.`);
+ }
+
+ act(() => {
+ input.click();
+ });
+}
+
+function clickCustomThemeAddControl(container: HTMLElement): void {
+ const addControl = Array.from(container.querySelectorAll('div')).find((item) => {
+ return item.textContent?.trim() === '+' && item.className.includes('univer-leading-10');
+ });
+ if (!addControl) {
+ throw new Error('Custom theme add control was not found.');
+ }
+
+ clickElement(addControl);
+}
+
+function clickCustomThemeRemoveControl(container: HTMLElement): void {
+ const removeControl = Array.from(container.querySelectorAll('div')).find((item) => {
+ return item.textContent?.trim() === 'x' && item.className.includes('univer-absolute');
+ });
+ if (!removeControl) {
+ throw new Error('Custom theme remove control was not found.');
+ }
+
+ clickElement(removeControl);
+}
+
+async function flushCommands(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ });
+}
+
+describe('sheet table view components', () => {
+ let testBed: ITestBed | undefined;
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+ let closeDisposable: IDisposable | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ vi.useRealTimers();
+ closeDisposable?.dispose();
+ container?.remove();
+ testBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ closeDisposable = undefined;
+ testBed = undefined;
+ });
+
+ it('renames a table through the table command when the user confirms a new name', async () => {
+ testBed = createTestBed();
+ let closeCount = 0;
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableRenameDialog
+ unitId={testBed.workbook.getUnitId()}
+ tableId="table-orders"
+ onClose={() => {
+ closeCount += 1;
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ changeInput(container.querySelector('input')!, ' Revenue2026 ');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getDisplayName()).toBe('Revenue2026');
+ expect(closeCount).toBe(1);
+ });
+
+ it('keeps an existing table name when the submitted name conflicts with another table', async () => {
+ testBed = createTestBed();
+ let closeCount = 0;
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableRenameDialog
+ unitId={testBed.workbook.getUnitId()}
+ tableId="table-orders"
+ onClose={() => {
+ closeCount += 1;
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ changeInput(container.querySelector('input')!, 'Archive');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getDisplayName()).toBe('Orders');
+ expect(container.textContent).toContain('Invalid table name');
+ expect(closeCount).toBe(0);
+ });
+
+ it('rejects an empty table name without closing the rename dialog', async () => {
+ testBed = createTestBed();
+ let closeCount = 0;
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableRenameDialog
+ unitId={testBed.workbook.getUnitId()}
+ tableId="table-orders"
+ onClose={() => {
+ closeCount += 1;
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ changeInput(container.querySelector('input')!, ' ');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getDisplayName()).toBe('Orders');
+ expect(container.textContent).toContain('Invalid table name');
+ expect(closeCount).toBe(0);
+ });
+
+ it('does not confirm a selected range that overlaps another table', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const confirmed: unknown[] = [];
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableSelector
+ unitId={unitId}
+ subUnitId="sheet1"
+ range={{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }}
+ onConfirm={(info) => {
+ confirmed.push(info);
+ }}
+ onCancel={() => {}}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ await selectRangeThroughDialog(container, 'A6:B8');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ expect(container.textContent).toContain('Table range cannot overlap with other tables');
+ expect(confirmed).toHaveLength(0);
+ });
+
+ it('does not confirm a table range that only contains the header row', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const confirmed: unknown[] = [];
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableSelector
+ unitId={unitId}
+ subUnitId="sheet1"
+ range={{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }}
+ onConfirm={(info) => {
+ confirmed.push(info);
+ }}
+ onCancel={() => {}}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ await selectRangeThroughDialog(container, 'A10:B10');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ expect(container.textContent).toContain('Table range cannot be a single row');
+ expect(confirmed).toHaveLength(0);
+ });
+
+ it('keeps the range selector editor stable when its delayed resize runs', async () => {
+ vi.useFakeTimers();
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableSelector
+ unitId={unitId}
+ subUnitId="sheet1"
+ range={{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }}
+ onConfirm={() => {}}
+ onCancel={() => {}}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ await act(async () => {
+ vi.advanceTimersByTime(500);
+ await Promise.resolve();
+ });
+
+ expect(container.querySelector('svg')).not.toBeNull();
+ });
+
+ it('cancels table range selection without submitting a range update', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const confirmed: unknown[] = [];
+ let cancelCount = 0;
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableSelector
+ unitId={unitId}
+ subUnitId="sheet1"
+ tableId="table-orders"
+ range={{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }}
+ onConfirm={(info) => {
+ confirmed.push(info);
+ }}
+ onCancel={() => {
+ cancelCount += 1;
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Cancel');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-orders')!;
+ expect(confirmed).toEqual([]);
+ expect(cancelCount).toBe(1);
+ expect(table.getRange()).toEqual({
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 1,
+ });
+ });
+
+ it('confirms a same-header-row range update for the existing table', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const confirmed: unknown[] = [];
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableSelector
+ unitId={unitId}
+ subUnitId="sheet1"
+ tableId="table-orders"
+ range={{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 }}
+ onConfirm={(info) => {
+ confirmed.push(info);
+ }}
+ onCancel={() => {}}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ await selectRangeThroughDialog(container, 'A1:B5');
+
+ expect(confirmed).toEqual([{
+ unitId,
+ subUnitId: 'sheet1',
+ range: expect.objectContaining({
+ startRow: 0,
+ endRow: 4,
+ startColumn: 0,
+ endColumn: 1,
+ }),
+ }]);
+ });
+
+ it('applies a value filter from item checkbox changes', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickCheckboxByText(container, 'book');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['pen', TABLE_FILTER_EMPTY_VALUE],
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('leaves an unfiltered column unchanged when all values remain selected', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getTableFilterColumn(0)).toBeUndefined();
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('keeps the existing value filter when item changes are cancelled', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickCheckboxByText(container, 'pen');
+ clickButtonByText(container, 'Cancel');
+ await flushCommands();
+
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('applies a value filter from the currently searched items only', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ const searchInput = container.querySelector('input') as HTMLInputElement | null;
+ if (!searchInput) {
+ throw new Error('Filter search input was not found.');
+ }
+ changeInput(searchInput, 'bo');
+ clickCheckboxByText(container, 'Select all');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('shows the checked item count from an existing manual filter', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ const selectAllLabel = Array.from(container.querySelectorAll('label'))
+ .find((item) => item.textContent?.includes('Select all'));
+
+ expect(selectAllLabel?.textContent).toContain('(1/3)');
+ });
+
+ it('closes without changing the filter when confirmed value selections are unchanged', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('clears an existing table filter through the filter panel clear action', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Clear filter');
+ await flushCommands();
+
+ expect(table.getTableFilterColumn(0)).toBeUndefined();
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('does not delete or close from the filter panel when the table has only one column', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const sheetTableService = testBed.injector.get(SheetTableService);
+ sheetTableService.addTable(
+ unitId,
+ 'sheet1',
+ 'SingleColumnTable',
+ { startRow: 0, endRow: 3, startColumn: 3, endColumn: 3 },
+ ['Only'],
+ 'table-single-column'
+ );
+ componentController.setCurrentTableFilterInfo({
+ unitId,
+ subUnitId: 'sheet1',
+ tableId: 'table-single-column',
+ row: 0,
+ column: 3,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ const deleteButton = getButtonByText(container, 'Delete table column');
+ clickElement(deleteButton);
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-single-column')!;
+ expect(deleteButton.disabled).toBe(true);
+ expect(table.getRange()).toEqual({
+ startRow: 0,
+ endRow: 3,
+ startColumn: 3,
+ endColumn: 3,
+ });
+ expect(componentController.closeCount).toBe(0);
+ });
+
+ it('inserts a table column to the right from the filter panel column menu', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId,
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 1,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Insert 1 table column right');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-orders')!;
+ expect(table.getRange()).toEqual({
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 2,
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('sorts the table body descending from the filter panel sort action', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const unitId = testBed.workbook.getUnitId();
+ const worksheet = testBed.workbook.getSheetBySheetId('sheet1')!;
+ componentController.setCurrentTableFilterInfo({
+ unitId,
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Descending');
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-orders')!;
+ expect(worksheet.getCellRaw(1, 0)?.v).toBe('pen');
+ expect(worksheet.getCellRaw(2, 0)?.v).toBe('book');
+ expect(worksheet.getCellRaw(3, 0)?.v).toBe(undefined);
+ expect(table.getTableFilters().getSortState()).toEqual({
+ columnIndex: 0,
+ sortState: SheetsTableSortStateEnum.Desc,
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('applies a condition filter from the condition tab input', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ expectedValue: 'pen',
+ },
+ });
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ const conditionInput = container.querySelector('input') as HTMLInputElement | null;
+ if (!conditionInput) {
+ throw new Error('Condition input was not found.');
+ }
+ changeInput(conditionInput, 'book');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ expectedValue: 'book',
+ },
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('keeps the opposite numeric bound when editing a between condition endpoint', () => {
+ testBed = createTestBed();
+ let currentConditionInfo: IConditionInfo | undefined;
+
+ function ConditionPanelHarness() {
+ const [conditionInfo, setConditionInfo] = useState<IConditionInfo>({
+ type: TableConditionTypeEnum.Number,
+ compare: TableNumberCompareTypeEnum.Between,
+ info: { numberRange: [10, 20] },
+ });
+ currentConditionInfo = conditionInfo;
+
+ return (
+ <SheetTableConditionPanel
+ unitId={testBed!.workbook.getUnitId()}
+ subUnitId="sheet1"
+ tableFilter={undefined}
+ tableId="table-orders"
+ columnIndex={1}
+ conditionInfo={conditionInfo}
+ onChange={setConditionInfo}
+ />
+ );
+ }
+
+ const rendered = renderWithRediContext(testBed, <ConditionPanelHarness />);
+ root = rendered.root;
+ container = rendered.container;
+ const inputs = Array.from(container.querySelectorAll('input')) as HTMLInputElement[];
+ if (inputs.length !== 2) {
+ throw new Error('The numeric range condition should render two endpoint inputs.');
+ }
+
+ changeInput(inputs[0], '12');
+ expect(currentConditionInfo).toEqual({
+ type: TableConditionTypeEnum.Number,
+ compare: TableNumberCompareTypeEnum.Between,
+ info: { numberRange: [12, 20] },
+ });
+
+ changeInput(inputs[1], '24');
+ expect(currentConditionInfo).toEqual({
+ type: TableConditionTypeEnum.Number,
+ compare: TableNumberCompareTypeEnum.Between,
+ info: { numberRange: [12, 24] },
+ });
+ });
+
+ it('adds a custom theme and selects it for the table', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-orders')!;
+ const rangeThemeModel = testBed.injector.get(SheetRangeThemeModel);
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableThemePanel
+ unitId={unitId}
+ subUnitId="sheet1"
+ tableId="table-orders"
+ oldConfig={{}}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickCustomThemeAddControl(container);
+ await flushCommands();
+
+ expect(rangeThemeModel.getCustomRangeThemeStyle(unitId, 'table-custom-1')).toBeDefined();
+ expect(table.getTableStyleId()).toBe('table-custom-1');
+ });
+
+ it('removes an unused custom theme without changing the table style', async () => {
+ testBed = createTestBed();
+ const unitId = testBed.workbook.getUnitId();
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-orders')!;
+ const rangeThemeModel = testBed.injector.get(SheetRangeThemeModel);
+ const rendered = renderWithRediContext(
+ testBed,
+ <SheetTableThemePanel
+ unitId={unitId}
+ subUnitId="sheet1"
+ tableId="table-orders"
+ oldConfig={{}}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickCustomThemeAddControl(container);
+ await flushCommands();
+ clickCustomThemeAddControl(container);
+ await flushCommands();
+
+ expect(rangeThemeModel.getCustomRangeThemeStyle(unitId, 'table-custom-1')).toBeDefined();
+ expect(rangeThemeModel.getCustomRangeThemeStyle(unitId, 'table-custom-2')).toBeDefined();
+ expect(table.getTableStyleId()).toBe('table-custom-2');
+
+ clickCustomThemeRemoveControl(container);
+ await flushCommands();
+
+ expect(rangeThemeModel.getCustomRangeThemeStyle(unitId, 'table-custom-1')).toBeUndefined();
+ expect(rangeThemeModel.getCustomRangeThemeStyle(unitId, 'table-custom-2')).toBeDefined();
+ expect(table.getTableStyleId()).toBe('table-custom-2');
+ });
+});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-components.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-components.spec.tsx
deleted file mode 100644
index 478c89406d..0000000000
--- a/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-components.spec.tsx
+++ /dev/null
@@ -1,427 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';
-import type { Root } from 'react-dom/client';
-import {
- ICommandService,
- Inject,
- Injector,
- LocaleService,
- LocaleType,
- Plugin,
- toDisposable,
- Univer,
- UniverInstanceType,
-} from '@univerjs/core';
-import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';
-import { SheetInterceptorService } from '@univerjs/sheets';
-import {
- SetSheetTableCommand,
- SetSheetTableFilterCommand,
- SetSheetTableFilterMutation,
- SetSheetTableMutation,
- SheetTableService,
- TABLE_FILTER_EMPTY_VALUE,
- TableColumnFilterTypeEnum,
- TableConditionTypeEnum,
- TableManager,
- TableStringCompareTypeEnum,
-} from '@univerjs/sheets-table';
-import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
-import { IDialogService, RediContext } from '@univerjs/ui';
-import { act } from 'react';
-import { createRoot } from 'react-dom/client';
-import { afterEach, describe, expect, it } from 'vitest';
-import { SheetsTableComponentController } from '../../../controllers/sheet-table-component.controller';
-import { SheetsTableUiService } from '../../../services/sheets-table-ui.service';
-import { SheetTableFilterPanel } from '../SheetTableFilterPanel';
-import { SheetTableRenameDialog } from '../SheetTableRenameDialog';
-
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-class TestComponentController extends SheetsTableComponentController {
- closeCount = 0;
-
- override closeFilterPanel(): void {
- this.closeCount += 1;
- super.closeFilterPanel();
- }
-}
-
-class TestSheetCanvasPopManagerService {
- attachPopupToCell(): IDisposable {
- return toDisposable(() => {});
- }
-}
-
-class TestDialogService {
- open(): IDisposable {
- return toDisposable(() => {});
- }
-
- close(): void {
- // no-op
- }
-
- closeAll(): void {
- // no-op
- }
-
- getDialogs$() {
- throw new Error('Dialogs are not observed in this component test.');
- }
-}
-
-interface ITestBed {
- univer: Univer;
- injector: Injector;
- workbook: Workbook;
-}
-
-function createWorkbookData(): IWorkbookData {
- return {
- id: 'test',
- appVersion: '3.0.0-alpha',
- locale: LocaleType.EN_US,
- name: 'test',
- sheetOrder: ['sheet1'],
- sheets: {
- sheet1: {
- id: 'sheet1',
- name: 'Sheet1',
- rowCount: 20,
- columnCount: 20,
- cellData: {
- 0: {
- 0: { v: 'product' },
- 1: { v: 'amount' },
- },
- 1: {
- 0: { v: 'book' },
- 1: { v: 12 },
- },
- 2: {
- 0: { v: 'pen' },
- 1: { v: 3 },
- },
- 3: {
- 1: { v: 8 },
- },
- },
- },
- },
- styles: {},
- };
-}
-
-function createTestBed(): ITestBed {
- const univer = new Univer();
- const injector = univer.__getInjector();
-
- class TestPlugin extends Plugin {
- static override pluginName = 'test-plugin';
- static override type = UniverInstanceType.UNIVER_SHEET;
-
- constructor(
- _config: undefined,
- @Inject(Injector) override readonly _injector: Injector
- ) {
- super();
- }
-
- override onStarting(): void {
- const dependencies: Dependency[] = [
- [TableManager],
- [SheetTableService],
- [SheetsTableUiService],
- [SheetInterceptorService],
- [IDefinedNamesService, { useClass: DefinedNamesService }],
- [SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService }],
- [IDialogService, { useClass: TestDialogService }],
- [SheetsTableComponentController, { useClass: TestComponentController }],
- ];
- dependencies.forEach((dependency) => this._injector.add(dependency));
- }
- }
-
- univer.registerPlugin(TestPlugin);
-
- const localeService = injector.get(LocaleService);
- localeService.load({
- [LocaleType.EN_US]: {
- 'sheets-table': {
- tableNameError: 'Invalid table name',
- },
- 'sheets-table-ui': {
- cancel: 'Cancel',
- confirm: 'Confirm',
- renamePlaceholder: 'Enter table name',
- tableNameError: 'Invalid table name',
- condition: {
- empty: '(Empty)',
- string: 'Text',
- },
- string: {
- compare: {
- equal: 'Is equal to',
- },
- },
- filter: {
- 'by-values': 'Filter by values',
- 'by-conditions': 'Filter by conditions',
- cancel: 'Cancel',
- 'clear-filter': 'Clear filter',
- confirm: 'Confirm',
- 'search-placeholder': 'Search',
- 'select-all': 'Select all',
- },
- },
- },
- });
- localeService.setLocale(LocaleType.EN_US);
-
- const commandService = injector.get(ICommandService);
- [SetSheetTableCommand, SetSheetTableMutation, SetSheetTableFilterCommand, SetSheetTableFilterMutation].forEach((command) => {
- commandService.registerCommand(command);
- });
-
- const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
- const sheetTableService = injector.get(SheetTableService);
- sheetTableService.addTable(
- workbook.getUnitId(),
- 'sheet1',
- 'Orders',
- { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 },
- ['Product', 'Amount'],
- 'table-orders'
- );
- sheetTableService.addTable(
- workbook.getUnitId(),
- 'sheet1',
- 'Archive',
- { startRow: 5, endRow: 7, startColumn: 0, endColumn: 1 },
- ['Product', 'Amount'],
- 'table-archive'
- );
-
- return {
- univer,
- injector,
- workbook,
- };
-}
-
-function renderWithRediContext(testBed: ITestBed, element: React.ReactElement) {
- const container = document.createElement('div');
- document.body.appendChild(container);
- const root = createRoot(container);
-
- act(() => {
- root.render(
- <RediContext.Provider value={{ injector: testBed.injector }}>
- {element}
- </RediContext.Provider>
- );
- });
-
- return { container, root };
-}
-
-function changeInput(input: HTMLInputElement, value: string): void {
- act(() => {
- if (!input.getAttribute('type')) {
- input.setAttribute('type', 'text');
- }
- const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
- valueSetter?.call(input, value);
- input.dispatchEvent(new Event('input', { bubbles: true }));
- });
-}
-
-function clickElement(element: Element): void {
- act(() => {
- element.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
- element.dispatchEvent(new MouseEvent('pointerup', { bubbles: true }));
- element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- });
-}
-
-function clickButtonByText(container: HTMLElement, text: string): void {
- const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent === text);
- if (!button) {
- throw new Error(`Button with text "${text}" was not found.`);
- }
-
- clickElement(button);
-}
-
-function clickCheckboxByText(container: HTMLElement, text: string): void {
- const label = Array.from(container.querySelectorAll('label')).find((item) => item.textContent?.includes(text));
- const input = label?.querySelector('input');
- if (!input) {
- throw new Error(`Checkbox with text "${text}" was not found.`);
- }
-
- act(() => {
- input.click();
- });
-}
-
-async function flushCommands(): Promise<void> {
- await act(async () => {
- await Promise.resolve();
- });
-}
-
-describe('sheet table view components', () => {
- let testBed: ITestBed | undefined;
- let root: Root | undefined;
- let container: HTMLElement | undefined;
- let closeDisposable: IDisposable | undefined;
-
- afterEach(() => {
- act(() => {
- root?.unmount();
- });
- closeDisposable?.dispose();
- container?.remove();
- testBed?.univer.dispose();
- root = undefined;
- container = undefined;
- closeDisposable = undefined;
- testBed = undefined;
- });
-
- it('renames a table through the table command when the user confirms a new name', async () => {
- testBed = createTestBed();
- let closeCount = 0;
- const rendered = renderWithRediContext(
- testBed,
- <SheetTableRenameDialog
- unitId={testBed.workbook.getUnitId()}
- tableId="table-orders"
- onClose={() => {
- closeCount += 1;
- }}
- />
- );
- root = rendered.root;
- container = rendered.container;
-
- changeInput(container.querySelector('input')!, ' Revenue2026 ');
- clickButtonByText(container, 'Confirm');
- await flushCommands();
-
- const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
- expect(table.getDisplayName()).toBe('Revenue2026');
- expect(closeCount).toBe(1);
- });
-
- it('keeps an existing table name when the submitted name conflicts with another table', async () => {
- testBed = createTestBed();
- let closeCount = 0;
- const rendered = renderWithRediContext(
- testBed,
- <SheetTableRenameDialog
- unitId={testBed.workbook.getUnitId()}
- tableId="table-orders"
- onClose={() => {
- closeCount += 1;
- }}
- />
- );
- root = rendered.root;
- container = rendered.container;
-
- changeInput(container.querySelector('input')!, 'Archive');
- clickButtonByText(container, 'Confirm');
- await flushCommands();
-
- const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
- expect(table.getDisplayName()).toBe('Orders');
- expect(container.textContent).toContain('Invalid table name');
- expect(closeCount).toBe(0);
- });
-
- it('applies a value filter from item checkbox changes', async () => {
- testBed = createTestBed();
- const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
- componentController.setCurrentTableFilterInfo({
- unitId: testBed.workbook.getUnitId(),
- subUnitId: 'sheet1',
- tableId: 'table-orders',
- row: 0,
- column: 0,
- });
- const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
- root = rendered.root;
- container = rendered.container;
-
- clickCheckboxByText(container, 'book');
- clickButtonByText(container, 'Confirm');
- await flushCommands();
-
- const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
- expect(table.getTableFilterColumn(0)).toEqual({
- filterType: TableColumnFilterTypeEnum.manual,
- values: ['pen', TABLE_FILTER_EMPTY_VALUE],
- });
- expect(componentController.closeCount).toBe(1);
- });
-
- it('applies a condition filter from the condition tab input', async () => {
- testBed = createTestBed();
- const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
- const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
- table.setTableFilterColumn(0, {
- filterType: TableColumnFilterTypeEnum.condition,
- filterInfo: {
- conditionType: TableConditionTypeEnum.String,
- compareType: TableStringCompareTypeEnum.Equal,
- expectedValue: 'pen',
- },
- });
- componentController.setCurrentTableFilterInfo({
- unitId: testBed.workbook.getUnitId(),
- subUnitId: 'sheet1',
- tableId: 'table-orders',
- row: 0,
- column: 0,
- });
- const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
- root = rendered.root;
- container = rendered.container;
-
- const conditionInput = container.querySelector('input') as HTMLInputElement | null;
- if (!conditionInput) {
- throw new Error('Condition input was not found.');
- }
- changeInput(conditionInput, 'book');
- clickButtonByText(container, 'Confirm');
- await flushCommands();
-
- expect(table.getTableFilterColumn(0)).toEqual({
- filterType: TableColumnFilterTypeEnum.condition,
- filterInfo: {
- conditionType: TableConditionTypeEnum.String,
- compareType: TableStringCompareTypeEnum.Equal,
- expectedValue: 'book',
- },
- });
- expect(componentController.closeCount).toBe(1);
- });
-});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-util.spec.ts b/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-util.spec.ts
new file mode 100644
index 0000000000..30eea8ec52
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-util.spec.ts
@@ -0,0 +1,94 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ITableFilterItem } from '@univerjs/sheets-table';
+import {
+ TableColumnFilterTypeEnum,
+ TableConditionTypeEnum,
+ TableDateCompareTypeEnum,
+ TableNumberCompareTypeEnum,
+ TableStringCompareTypeEnum,
+} from '@univerjs/sheets-table';
+import { describe, expect, it } from 'vitest';
+import { ConditionSubComponentEnum } from '../type';
+import { getInitConditionInfo, getSubComponentType } from '../util';
+
+describe('sheet table condition utilities', () => {
+ it('initializes a new condition filter as a text equality rule', () => {
+ expect(getInitConditionInfo()).toEqual({
+ type: TableConditionTypeEnum.String,
+ compare: TableStringCompareTypeEnum.Equal,
+ info: {},
+ });
+ });
+
+ it('maps condition compare types to the editor control needed by users', () => {
+ expect(getSubComponentType(TableConditionTypeEnum.String, TableStringCompareTypeEnum.Contains)).toBe(ConditionSubComponentEnum.Input);
+ expect(getSubComponentType(TableConditionTypeEnum.Number, TableNumberCompareTypeEnum.Between)).toBe(ConditionSubComponentEnum.Inputs);
+ 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);
+ });
+
+ it('hydrates saved date filters back into panel state without losing relative date choices', () => {
+ const absoluteDateFilter: ITableFilterItem = {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Between,
+ expectedValue: ['2026-01-01', '2026-01-31'],
+ },
+ };
+ const quarterFilter: ITableFilterItem = {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Q3,
+ },
+ };
+ const relativeDateFilter: ITableFilterItem = {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.ThisMonth,
+ },
+ };
+
+ expect(getInitConditionInfo(absoluteDateFilter)).toMatchObject({
+ type: TableConditionTypeEnum.Date,
+ compare: TableDateCompareTypeEnum.Between,
+ info: {
+ dateRange: [
+ new Date('2026-01-01'),
+ new Date('2026-01-31'),
+ ],
+ },
+ });
+ expect(getInitConditionInfo(quarterFilter)).toEqual({
+ type: TableConditionTypeEnum.Date,
+ compare: TableDateCompareTypeEnum.Quarter,
+ info: {
+ dateSelect: TableDateCompareTypeEnum.Q3,
+ },
+ });
+ expect(getInitConditionInfo(relativeDateFilter)).toEqual({
+ type: TableConditionTypeEnum.Date,
+ compare: TableDateCompareTypeEnum.ThisMonth,
+ info: {},
+ });
+ });
+});
diff --git a/packages/sheets-table-ui/src/views/components/util.ts b/packages/sheets-table-ui/src/views/components/util.ts
index bb60ed5e25..1b3030810a 100644
--- a/packages/sheets-table-ui/src/views/components/util.ts
+++ b/packages/sheets-table-ui/src/views/components/util.ts
@@ -323,7 +323,7 @@ export function getInitConditionInfo(tableFilter?: ITableFilterItem) {
if (!tableFilter || tableFilter.filterType !== 'condition') {
return {
type: TableConditionTypeEnum.String,
- compareType: TableStringCompareTypeEnum.Equal,
+ compare: TableStringCompareTypeEnum.Equal,
info: {},
};
}
diff --git a/packages/sheets-table-ui/src/views/widgets/__tests__/table-controls-util.spec.ts b/packages/sheets-table-ui/src/views/widgets/__tests__/table-controls-util.spec.ts
index 39fc9e1bca..fb514c9af3 100644
--- a/packages/sheets-table-ui/src/views/widgets/__tests__/table-controls-util.spec.ts
+++ b/packages/sheets-table-ui/src/views/widgets/__tests__/table-controls-util.spec.ts
@@ -14,8 +14,49 @@
* limitations under the License.
*/
+import type { SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';
import { describe, expect, it } from 'vitest';
-import { buildCenteredPlusSegments, buildTableMenuRegions, hitTestTableControl, TABLE_CONTROL_INSERT_BUTTON_SIZE } from '../table-controls-util';
+import {
+ buildCenteredPlusSegments,
+ buildTableMenuRegions,
+ hitTestTableControl,
+ TABLE_CONTROL_INSERT_BUTTON_SIZE,
+} from '../table-controls-util';
+import { SheetTableControlsShape } from '../table-controls.shape';
+
+class DrawableSheetTableControlsShape extends SheetTableControlsShape {
+ drawForTest(ctx: UniverRenderingContext): void {
+ this._draw(ctx);
+ }
+}
+
+function createCanvasContext(): UniverRenderingContext {
+ return new Proxy({}, {
+ get(_target, property) {
+ if (property === 'measureText') {
+ return () => ({ width: 0 });
+ }
+
+ return () => {};
+ },
+ set() {
+ return true;
+ },
+ }) as UniverRenderingContext;
+}
+
+function createSkeleton(): SpreadsheetSkeleton {
+ return {
+ rowHeaderWidth: 40,
+ columnTotalWidth: 400,
+ columnHeaderHeight: 32,
+ rowTotalHeight: 600,
+ getNoMergeCellWithCoordByIndex: () => ({
+ startX: 40,
+ startY: 60,
+ }),
+ } as unknown as SpreadsheetSkeleton;
+}
describe('table controls geometry', () => {
it('hit-tests the topmost region first', () => {
@@ -48,4 +89,52 @@ describe('table controls geometry', () => {
{ fromX: 20, fromY: 26, toX: 20, toY: 34 },
]);
});
+
+ it('opens a table menu whose action rows can be hit-tested', () => {
+ const shape = new DrawableSheetTableControlsShape('table-controls', createSkeleton);
+ shape.setItems([{
+ tableId: 'table-orders',
+ tableName: 'Orders',
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 },
+ fill: '#1f5eff',
+ text: '#ffffff',
+ }]);
+ shape.setOpenedMenuTableId('table-orders');
+
+ shape.drawForTest(createCanvasContext());
+
+ expect(shape.hitTest(56, 170)).toMatchObject({
+ type: 'menu-item',
+ tableId: 'table-orders',
+ action: 'delete',
+ });
+ });
+
+ it('activates the hovered insert region for row and column insertion', () => {
+ const shape = new DrawableSheetTableControlsShape('table-controls', createSkeleton);
+ shape.setItems([{
+ tableId: 'table-orders',
+ tableName: 'Orders',
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 },
+ fill: '#1f5eff',
+ text: '#ffffff',
+ }]);
+ shape.setHoveredInsertRegion({
+ type: 'insert-row',
+ tableId: 'table-orders',
+ index: 2,
+ left: 100,
+ top: 120,
+ width: TABLE_CONTROL_INSERT_BUTTON_SIZE,
+ height: TABLE_CONTROL_INSERT_BUTTON_SIZE,
+ });
+
+ shape.drawForTest(createCanvasContext());
+
+ expect(shape.hitTest(111, 131)).toMatchObject({
+ type: 'insert-row',
+ tableId: 'table-orders',
+ index: 2,
+ });
+ });
});
diff --git a/packages/sheets-table-ui/src/views/widgets/__tests__/table-filter-button.shape.spec.ts b/packages/sheets-table-ui/src/views/widgets/__tests__/table-filter-button.shape.spec.ts
new file mode 100644
index 0000000000..89e3d4705c
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/widgets/__tests__/table-filter-button.shape.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 type { IMouseEvent } from '@univerjs/engine-render';
+import type { IOpenTableFilterPanelOperationParams } from '../../../commands/operations/open-table-filter-dialog.opration';
+import { CommandType, ICommandService, Univer } from '@univerjs/core';
+import { SheetsTableButtonStateEnum } from '@univerjs/sheets-table';
+import { afterEach, describe, expect, it } from 'vitest';
+import { OpenTableFilterPanelOperation } from '../../../commands/operations/open-table-filter-dialog.opration';
+import { SheetsTableFilterButtonShape } from '../table-filter-button.shape';
+
+function createPointerEvent(button: number): IMouseEvent {
+ return { button } as IMouseEvent;
+}
+
+async function waitForFilterButtonDelay(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 230));
+ await Promise.resolve();
+}
+
+describe('sheet table filter button shape', () => {
+ let univer: Univer | undefined;
+
+ afterEach(() => {
+ univer?.dispose();
+ univer = undefined;
+ });
+
+ function createShape(executedParams: IOpenTableFilterPanelOperationParams[]): SheetsTableFilterButtonShape {
+ univer = new Univer();
+ const commandService = univer.__getInjector().get(ICommandService);
+ commandService.registerCommand({
+ id: OpenTableFilterPanelOperation.id,
+ type: CommandType.OPERATION,
+ handler: (_accessor, params?: IOpenTableFilterPanelOperationParams) => {
+ if (params) {
+ executedParams.push(params);
+ }
+ return true;
+ },
+ });
+
+ return new SheetsTableFilterButtonShape('filter-button', {
+ width: 16,
+ height: 16,
+ cellWidth: 72,
+ cellHeight: 28,
+ iconColor: '#ffffff',
+ hoverBackground: '#eeeeee',
+ hoverIconColor: '#111111',
+ filterParams: {
+ row: 3,
+ col: 4,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ buttonState: SheetsTableButtonStateEnum.FilterNoneSortNone,
+ tableId: 'table-orders',
+ },
+ }, commandService);
+ }
+
+ it('opens the table filter panel with the current cell and table parameters on primary pointer down', async () => {
+ const executedParams: IOpenTableFilterPanelOperationParams[] = [];
+ const shape = createShape(executedParams);
+
+ shape.onPointerDown(createPointerEvent(0));
+ await waitForFilterButtonDelay();
+
+ expect(executedParams).toEqual([{
+ row: 3,
+ col: 4,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ tableId: 'table-orders',
+ }]);
+ });
+
+ it('opens the filter panel with updated cell and table parameters after the shape is reused', async () => {
+ const executedParams: IOpenTableFilterPanelOperationParams[] = [];
+ const shape = createShape(executedParams);
+
+ shape.setShapeProps({
+ filterParams: {
+ row: 8,
+ col: 2,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ buttonState: SheetsTableButtonStateEnum.FilterNoneSortNone,
+ tableId: 'table-archive',
+ },
+ });
+ shape.onPointerDown(createPointerEvent(0));
+ await waitForFilterButtonDelay();
+
+ expect(executedParams).toEqual([{
+ row: 8,
+ col: 2,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ tableId: 'table-archive',
+ }]);
+ });
+
+ it('keeps the filter panel closed for secondary pointer down', async () => {
+ const executedParams: IOpenTableFilterPanelOperationParams[] = [];
+ const shape = createShape(executedParams);
+
+ shape.onPointerDown(createPointerEvent(2));
+ await waitForFilterButtonDelay();
+
+ expect(executedParams).toEqual([]);
+ });
+});
diff --git a/packages/sheets-table/src/models/filter-util/__tests__/filter-util.spec.ts b/packages/sheets-table/src/models/filter-util/__tests__/filter-util.spec.ts
new file mode 100644
index 0000000000..c236fb5481
--- /dev/null
+++ b/packages/sheets-table/src/models/filter-util/__tests__/filter-util.spec.ts
@@ -0,0 +1,497 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { CellValueType, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ TableColumnFilterTypeEnum,
+ TableConditionTypeEnum,
+ TableDateCompareTypeEnum,
+ TableNumberCompareTypeEnum,
+ TableStringCompareTypeEnum,
+} from '../../../types/enum';
+import {
+ excelSerialToDateTime,
+ getCellValueWithConditionType,
+ getConditionExecuteFunc,
+ getStringFromDataStream,
+ isDateDynamicFilter,
+ isNumberDynamicFilter,
+} from '../condition';
+import {
+ dateM1,
+ dateM10,
+ dateM11,
+ dateM12,
+ dateM2,
+ dateM3,
+ dateM4,
+ dateM5,
+ dateM6,
+ dateM7,
+ dateM8,
+ dateM9,
+ dateQ1,
+ dateQ2,
+ dateQ3,
+ dateQ4,
+ getDateFilterExecuteFunc,
+ lastQuarter,
+ lastWeek,
+ lastYear,
+ nextMonth,
+ nextQuarter,
+ nextWeek,
+ nextYear,
+ thisMonth,
+ thisQuarter,
+ thisWeek,
+ thisYear,
+ today,
+ tomorrow,
+ yearToDate,
+ yesterday,
+} from '../date-filter-util';
+import { above, below, getBottomN, getNumberFilterExecuteFunc, getTopN } from '../number-filter-util';
+import {
+ getTextFilterExecuteFunc,
+ textContain,
+ textEndWith,
+ textEqual,
+ textNotContain,
+ textNotEqual,
+ textStartWith,
+} from '../text-filter-util';
+import { getLargestK, getSmallestK } from '../top-n';
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: 'filter-util-workbook',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'filter-util-workbook',
+ sheetOrder: ['sheet-1'],
+ styles: {},
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Sheet-1',
+ rowCount: 10,
+ columnCount: 8,
+ cellData: {
+ 0: {
+ 0: { v: 'plain text', t: CellValueType.STRING },
+ 1: { v: 'true', t: CellValueType.BOOLEAN },
+ 2: { v: 1, t: CellValueType.BOOLEAN },
+ 3: { v: true },
+ 4: { p: { body: { dataStream: 'rich text\r\n' } } as any },
+ },
+ 1: {
+ 0: { v: '42', t: CellValueType.NUMBER },
+ 1: { v: 44927, t: CellValueType.NUMBER },
+ 2: { v: undefined },
+ },
+ },
+ },
+ },
+ };
+}
+
+describe('table filter utilities', () => {
+ let univer: Univer | undefined;
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ univer?.dispose();
+ univer = undefined;
+ });
+
+ it('matches relative date filters from a fixed business anchor', () => {
+ const anchor = new Date(2024, 5, 12, 12);
+
+ expect(today(new Date(2024, 5, 12, 8), anchor)).toBe(true);
+ expect(yesterday(new Date(2024, 5, 11), anchor)).toBe(true);
+ expect(tomorrow(new Date(2024, 5, 13), anchor)).toBe(true);
+ expect(thisWeek(new Date(2024, 5, 10), anchor)).toBe(true);
+ expect(lastWeek(new Date(2024, 5, 5), anchor)).toBe(true);
+ expect(nextWeek(new Date(2024, 5, 17), anchor)).toBe(true);
+ expect(thisMonth(new Date(2024, 5, 1), anchor)).toBe(true);
+ expect(nextMonth(new Date(2024, 6, 1), anchor)).toBe(true);
+ expect(nextMonth(new Date(2024, 7, 1), anchor)).toBe(false);
+ expect(thisQuarter(new Date(2024, 3, 1), anchor)).toBe(true);
+ expect(lastQuarter(new Date(2024, 1, 15), anchor)).toBe(true);
+ expect(nextQuarter(new Date(2024, 6, 15), anchor)).toBe(true);
+ expect(thisYear(new Date(2024, 0, 1), anchor)).toBe(true);
+ expect(lastYear(new Date(2023, 11, 31), anchor)).toBe(true);
+ expect(nextYear(new Date(2025, 0, 1), anchor)).toBe(true);
+ expect(yearToDate(new Date(2024, 2, 1), anchor)).toBe(true);
+ expect(yearToDate(new Date(2024, 5, 13), anchor)).toBe(false);
+ });
+
+ it('matches date month and quarter presets used by table filter menus', () => {
+ const monthChecks = [
+ dateM1,
+ dateM2,
+ dateM3,
+ dateM4,
+ dateM5,
+ dateM6,
+ dateM7,
+ dateM8,
+ dateM9,
+ dateM10,
+ dateM11,
+ dateM12,
+ ];
+
+ monthChecks.forEach((matchMonth, month) => {
+ expect(matchMonth(new Date(2024, month, 1))).toBe(true);
+ expect(matchMonth(new Date(2024, (month + 1) % 12, 1))).toBe(false);
+ });
+
+ expect(dateQ1(new Date(2024, 1, 1))).toBe(true);
+ expect(dateQ2(new Date(2024, 4, 1))).toBe(true);
+ expect(dateQ3(new Date(2024, 7, 1))).toBe(true);
+ expect(dateQ4(new Date(2024, 10, 1))).toBe(true);
+ });
+
+ it('builds executable date predicates for fixed and relative date filters', () => {
+ const anchor = new Date(2024, 5, 12).getTime();
+ const onJuneTen = new Date(2024, 5, 10);
+ const onJuneTwelve = new Date(2024, 5, 12);
+
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Equal,
+ expectedValue: onJuneTen,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.NotEqual,
+ expectedValue: onJuneTen,
+ })(onJuneTwelve)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.After,
+ expectedValue: onJuneTen,
+ })(onJuneTwelve)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.AfterOrEqual,
+ expectedValue: onJuneTen,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Before,
+ expectedValue: onJuneTwelve,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.BeforeOrEqual,
+ expectedValue: onJuneTwelve,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Between,
+ expectedValue: [onJuneTen, onJuneTwelve],
+ })(new Date(2024, 5, 11))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.NotBetween,
+ expectedValue: [onJuneTen, onJuneTwelve],
+ })(new Date(2024, 5, 14))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Today,
+ anchorTime: anchor,
+ })(onJuneTwelve)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Yesterday,
+ anchorTime: anchor,
+ })(new Date(2024, 5, 11))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Tomorrow,
+ anchorTime: anchor,
+ })(new Date(2024, 5, 13))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.ThisWeek,
+ anchorTime: anchor,
+ })(new Date(2024, 5, 10))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.LastWeek,
+ anchorTime: anchor,
+ })(new Date(2024, 5, 5))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.NextWeek,
+ anchorTime: anchor,
+ })(new Date(2024, 5, 17))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.ThisMonth,
+ anchorTime: anchor,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.LastMonth,
+ anchorTime: anchor,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.NextMonth,
+ anchorTime: anchor,
+ })(new Date(2024, 6, 1))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.ThisQuarter,
+ anchorTime: anchor,
+ })(onJuneTen)).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.LastQuarter,
+ anchorTime: anchor,
+ })(new Date(2024, 1, 15))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.NextQuarter,
+ anchorTime: anchor,
+ })(new Date(2024, 6, 15))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.ThisYear,
+ anchorTime: anchor,
+ })(new Date(2024, 0, 1))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.LastYear,
+ anchorTime: anchor,
+ })(new Date(2023, 0, 1))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.NextYear,
+ anchorTime: anchor,
+ })(new Date(2025, 0, 1))).toBe(true);
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.YearToDate,
+ anchorTime: anchor,
+ })(new Date(2024, 2, 1))).toBe(true);
+ [
+ TableDateCompareTypeEnum.M1,
+ TableDateCompareTypeEnum.M2,
+ TableDateCompareTypeEnum.M3,
+ TableDateCompareTypeEnum.M4,
+ TableDateCompareTypeEnum.M5,
+ TableDateCompareTypeEnum.M6,
+ TableDateCompareTypeEnum.M7,
+ TableDateCompareTypeEnum.M8,
+ TableDateCompareTypeEnum.M9,
+ TableDateCompareTypeEnum.M10,
+ TableDateCompareTypeEnum.M11,
+ TableDateCompareTypeEnum.M12,
+ ].forEach((compareType, month) => {
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType,
+ })(new Date(2024, month, 1))).toBe(true);
+ });
+ expect(getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Q2,
+ })(onJuneTwelve)).toBe(true);
+ expect(() => getDateFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: 'unsupported' as TableDateCompareTypeEnum,
+ })).toThrow('Unsupported compare type');
+ });
+
+ it('matches numeric filters including ranges, averages and top n lists', () => {
+ expect(above(8, 5)).toBe(true);
+ expect(below(3, 5)).toBe(true);
+ expect(getTopN([9, 1, 5, 3], 2, 9)).toBe(true);
+ expect(getBottomN([9, 1, 5, 3], 2, 1)).toBe(true);
+ expect(getLargestK([9, 1, 5, 3], 2).sort((a, b) => a - b)).toEqual([5, 9]);
+ expect(getSmallestK([9, 1, 5, 3], 2).sort((a, b) => a - b)).toEqual([1, 3]);
+
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.Equal,
+ expectedValue: 10,
+ }, undefined)!(10)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.NotEqual,
+ expectedValue: 10,
+ }, undefined)!(9)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.GreaterThanOrEqual,
+ expectedValue: 10,
+ }, undefined)!(10)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.GreaterThan,
+ expectedValue: 10,
+ }, undefined)!(11)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.LessThan,
+ expectedValue: 10,
+ }, undefined)!(9)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.LessThanOrEqual,
+ expectedValue: 10,
+ }, undefined)!(10)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.Between,
+ expectedValue: [20, 10],
+ }, undefined)!(15)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.NotBetween,
+ expectedValue: [10, 20],
+ }, undefined)!(25)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.Above,
+ expectedValue: 0,
+ }, { average: 12 })!(13)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.Below,
+ expectedValue: 0,
+ }, { average: 12 })!(11)).toBe(true);
+ expect(getNumberFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.TopN,
+ expectedValue: 2,
+ }, { list: [10, 30, 20] })!(30)).toBe(true);
+ });
+
+ it('matches text filters with wildcard-aware predicates', () => {
+ expect(textEqual('North-01', 'North-*')).toBe(true);
+ expect(textNotEqual('South-01', 'North-*')).toBe(true);
+ expect(textContain('FY24 Revenue', 'Revenue')).toBe(true);
+ expect(textNotContain('FY24 Cost', 'Revenue')).toBe(true);
+ expect(textStartWith('Table Sales', 'Table')).toBe(true);
+ expect(textEndWith('Table Sales', 'Sales')).toBe(true);
+
+ expect(getTextFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Contains,
+ expectedValue: 'West',
+ })('West Region')).toBe(true);
+ expect(getTextFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ expectedValue: 'West*',
+ })('West Region')).toBe(true);
+ expect(getTextFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.NotEqual,
+ expectedValue: 'East*',
+ })('West Region')).toBe(true);
+ expect(getTextFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.NotContains,
+ expectedValue: 'East',
+ })('West Region')).toBe(true);
+ expect(getTextFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.EndsWith,
+ expectedValue: 'Region',
+ })('West Region')).toBe(true);
+
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(getTextFilterExecuteFunc({
+ conditionType: TableConditionTypeEnum.String,
+ compareType: 'unknown' as TableStringCompareTypeEnum,
+ expectedValue: 'x',
+ })('anything')).toBe(true);
+ expect(errorSpy).toHaveBeenCalled();
+ });
+
+ it('selects condition filter executors and reads typed worksheet values from real workbook data', () => {
+ univer = new Univer();
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
+ const worksheet = workbook.getSheetBySheetId('sheet-1')!;
+
+ expect(isNumberDynamicFilter(TableNumberCompareTypeEnum.TopN)).toBe(true);
+ expect(isNumberDynamicFilter(TableNumberCompareTypeEnum.Equal)).toBe(false);
+ expect(isDateDynamicFilter(TableDateCompareTypeEnum.ThisWeek)).toBe(true);
+ expect(isDateDynamicFilter(TableDateCompareTypeEnum.Equal)).toBe(false);
+
+ expect((getConditionExecuteFunc({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.TopN,
+ expectedValue: 2,
+ },
+ }, { list: [1, 2, 3] }) as (value: unknown) => boolean)(999)).toBe(true);
+ expect((getConditionExecuteFunc({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.StartsWith,
+ expectedValue: 'plain',
+ },
+ }, undefined) as (value: unknown) => boolean)('plain text')).toBe(true);
+ expect((getConditionExecuteFunc({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.Equal,
+ expectedValue: 42,
+ },
+ }, undefined) as (value: unknown) => boolean)(42)).toBe(true);
+ expect((getConditionExecuteFunc({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Equal,
+ expectedValue: new Date(2024, 5, 12),
+ },
+ }, undefined) as (value: unknown) => boolean)(new Date(2024, 5, 12))).toBe(true);
+ expect((getConditionExecuteFunc({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Logic,
+ compareType: TableNumberCompareTypeEnum.Equal,
+ expectedValue: [],
+ },
+ }, undefined) as (value: unknown) => boolean)('any')).toBe(true);
+
+ expect(getStringFromDataStream({ body: { dataStream: 'rich text\r\n' } } as any)).toBe('rich text');
+ expect(getCellValueWithConditionType(worksheet, 0, 0, TableConditionTypeEnum.String)).toBe('plain text');
+ expect(getCellValueWithConditionType(worksheet, 0, 1, TableConditionTypeEnum.String)).toBe('TRUE');
+ expect(getCellValueWithConditionType(worksheet, 0, 2, TableConditionTypeEnum.String)).toBe('TRUE');
+ expect(getCellValueWithConditionType(worksheet, 0, 3, TableConditionTypeEnum.String)).toBe('TRUE');
+ expect(getCellValueWithConditionType(worksheet, 0, 4, TableConditionTypeEnum.String)).toBe('rich text');
+ expect(getCellValueWithConditionType(worksheet, 1, 0, TableConditionTypeEnum.Number)).toBe(42);
+ expect(getCellValueWithConditionType(worksheet, 0, 4, TableConditionTypeEnum.Number)).toBeNull();
+ expect(getCellValueWithConditionType(worksheet, 1, 2, TableConditionTypeEnum.String)).toBeUndefined();
+ expect(getCellValueWithConditionType(worksheet, 1, 1, TableConditionTypeEnum.Date)).toEqual(excelSerialToDateTime(44927));
+ expect(getCellValueWithConditionType(worksheet, 9, 9, TableConditionTypeEnum.String)).toBeNull();
+ });
+});
diff --git a/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-hover.controller.spec.ts b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-hover.controller.spec.ts
new file mode 100644
index 0000000000..6340f03ac6
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-hover.controller.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 { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SheetsThreadCommentHoverController } from '../sheets-thread-comment-hover.controller';
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+function createController(options?: { activePopup?: unknown; canView?: boolean; resolved?: boolean }) {
+ const currentCell$ = new Subject<any>();
+ const popupService = {
+ activePopup: options?.activePopup ?? null,
+ showPopup: vi.fn(),
+ hidePopup: vi.fn(),
+ };
+ const controller = new SheetsThreadCommentHoverController(
+ { currentCell$ } as never,
+ popupService as never,
+ {
+ getByLocation: vi.fn(() => 'comment-1'),
+ getComment: vi.fn(() => ({ id: 'comment-1', resolved: options?.resolved ?? false })),
+ } as never,
+ { permissionCheckWithRanges: vi.fn(() => options?.canView ?? true) } as never
+ );
+
+ return { controller, currentCell$, popupService };
+}
+
+describe('SheetsThreadCommentHoverController', () => {
+ it('shows a temporary popup when hovering an unresolved visible comment marker', async () => {
+ vi.useFakeTimers();
+ const { controller, currentCell$, popupService } = createController();
+
+ currentCell$.next({
+ location: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ },
+ });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(popupService.showPopup).toHaveBeenCalledWith({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ commentId: 'comment-1',
+ temp: true,
+ });
+
+ controller.dispose();
+ });
+
+ it('does not replace a persistent popup and hides an existing temp popup when no marker exists', async () => {
+ vi.useFakeTimers();
+ const { controller, currentCell$, popupService } = createController({ activePopup: { temp: false } });
+ currentCell$.next({
+ location: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ },
+ });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(popupService.showPopup).not.toHaveBeenCalled();
+ controller.dispose();
+
+ const noMarkerCell$ = new Subject<any>();
+ const tempPopupService = {
+ activePopup: { temp: true },
+ showPopup: vi.fn(),
+ hidePopup: vi.fn(),
+ };
+ const noMarkerController = new SheetsThreadCommentHoverController(
+ { currentCell$: noMarkerCell$ } as never,
+ tempPopupService as never,
+ { getByLocation: vi.fn(() => null), getComment: vi.fn() } as never,
+ { permissionCheckWithRanges: vi.fn(() => true) } as never
+ );
+
+ noMarkerCell$.next({ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 2, col: 3 } });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(tempPopupService.hidePopup).toHaveBeenCalled();
+ noMarkerController.dispose();
+ });
+});
diff --git a/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.controller.spec.ts b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.controller.spec.ts
new file mode 100644
index 0000000000..cf8090e40f
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.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 { AddCommentCommand, DeleteCommentCommand, UpdateCommentCommand } from '@univerjs/thread-comment';
+import { describe, expect, it, vi } from 'vitest';
+import { ShowAddSheetCommentModalOperation } from '../../commands/operations/comment.operation';
+import { SheetsThreadCommentPermissionController } from '../sheets-thread-comment-permission.controller';
+
+describe('SheetsThreadCommentPermissionController', () => {
+ it('blocks comment panel, add, update and delete actions when comment permissions are denied', () => {
+ let beforeCommandHandler: ((command: { id: string; params?: unknown }) => void) | undefined;
+ const permissionCheck = {
+ permissionCheckWithoutRange: vi.fn(() => false),
+ permissionCheckWithRanges: vi.fn(() => false),
+ blockExecuteWithoutPermission: vi.fn(),
+ };
+ const controller = new SheetsThreadCommentPermissionController(
+ { t: (key: string) => key } as never,
+ {
+ beforeCommandExecuted: vi.fn((handler) => {
+ beforeCommandHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ permissionCheck as never,
+ {
+ getComment: vi.fn(() => ({ id: 'comment-1', ref: 'C4' })),
+ } as never
+ );
+
+ beforeCommandHandler?.({ id: ShowAddSheetCommentModalOperation.id });
+ beforeCommandHandler?.({
+ id: AddCommentCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ comment: { ref: 'B2' },
+ },
+ });
+ beforeCommandHandler?.({
+ id: UpdateCommentCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ payload: { commentId: 'comment-1' },
+ },
+ });
+ beforeCommandHandler?.({
+ id: DeleteCommentCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ commentId: 'comment-1',
+ },
+ });
+
+ expect(permissionCheck.permissionCheckWithoutRange).toHaveBeenCalledTimes(1);
+ expect(permissionCheck.permissionCheckWithRanges).toHaveBeenCalledWith(expect.any(Object), [{
+ startRow: 1,
+ startColumn: 1,
+ endRow: 1,
+ endColumn: 1,
+ }], 'unit-1', 'sheet-1');
+ expect(permissionCheck.permissionCheckWithRanges).toHaveBeenCalledWith(expect.any(Object), [{
+ startRow: 3,
+ startColumn: 2,
+ endRow: 3,
+ endColumn: 2,
+ }], 'unit-1', 'sheet-1');
+ expect(permissionCheck.blockExecuteWithoutPermission).toHaveBeenCalledTimes(4);
+ expect(permissionCheck.blockExecuteWithoutPermission).toHaveBeenLastCalledWith('sheets-thread-comment-ui.permission.commentErr');
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx b/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx
index 01b0861dd3..12f0ee4325 100644
--- a/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx
+++ b/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx
@@ -105,6 +105,11 @@ export const SheetsThreadCommentPanel = () => {
};
const handleHover = (comment: IThreadComment) => {
+ if (hoverShapeId.current) {
+ markSelectionService.removeShape(hoverShapeId.current);
+ hoverShapeId.current = null;
+ }
+
if (
activeCommentId &&
activeCommentId.unitId === comment.unitId &&
@@ -114,11 +119,6 @@ export const SheetsThreadCommentPanel = () => {
return;
}
- if (hoverShapeId.current) {
- markSelectionService.removeShape(hoverShapeId.current);
- hoverShapeId.current = null;
- }
-
hoverShapeId.current = showShape(comment);
};
@@ -138,6 +138,7 @@ export const SheetsThreadCommentPanel = () => {
useEffect(() => {
if (!panelVisible && hoverShapeId.current) {
markSelectionService.removeShape(hoverShapeId.current);
+ hoverShapeId.current = null;
}
}, [markSelectionService, panelVisible]);
diff --git a/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
index eb7570f5b8..e1ad77ceb9 100644
--- a/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
+++ b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
@@ -14,27 +14,42 @@
* limitations under the License.
*/
-import type { IDisposable, IDocumentBody, Injector, IWorkbookData, Workbook } from '@univerjs/core';
+import type {
+ IDisposable,
+ IDocumentBody,
+ IDocumentData,
+ Injector,
+ IWorkbookData,
+ Nullable,
+ Workbook,
+} from '@univerjs/core';
+import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { IThreadComment } from '@univerjs/thread-comment';
-import type { ISidebarMethodOptions } from '@univerjs/ui';
+import type { IShortcutItem, ISidebarMethodOptions } from '@univerjs/ui';
import type { Root } from 'react-dom/client';
import {
+ createIdentifier,
Disposable,
ICommandService,
IUniverInstanceService,
LifecycleService,
LifecycleStages,
LocaleType,
+ RANGE_TYPE,
toDisposable,
Univer,
UniverInstanceType,
UserManagerService,
} from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
import { CellPopupManagerService, IMarkSelectionService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
import {
AddCommentMutation,
+ DeleteCommentMutation,
+ DeleteCommentTreeCommand,
IThreadCommentDataSourceService,
ResolveCommentCommand,
ResolveCommentMutation,
@@ -43,12 +58,14 @@ import {
} from '@univerjs/thread-comment';
import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
import threadCommentEnUS from '@univerjs/thread-comment-ui/locale/en-US';
-import { ISidebarService, RediContext } from '@univerjs/ui';
+import { IShortcutService, ISidebarService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { ShowAddSheetCommentModalOperation } from '../../commands/operations/comment.operation';
import { SheetsThreadCommentPopupService } from '../../services/sheets-thread-comment-popup.service';
+import { SheetsThreadCommentCell } from '../SheetsThreadCommentCell';
import { SheetsThreadCommentPanel } from '../SheetsThreadCommentPanel';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -56,6 +73,7 @@ import { SheetsThreadCommentPanel } from '../SheetsThreadCommentPanel';
const unitId = 'sheet-thread-comment-panel-test';
const sheet1 = 'sheet-1';
const sheet2 = 'sheet-2';
+const IEditorService = createIdentifier<TestEditorService>('univer.editor.service');
const workbookData: IWorkbookData = {
id: unitId,
@@ -186,6 +204,212 @@ class TestCellPopupManagerService {
class TestSheetCanvasPopManagerService {}
+class TestRenderManagerService {
+ readonly createRender$ = new Subject<string>();
+ readonly created$ = new Subject<unknown>();
+ readonly disposed$ = new Subject<string>();
+ readonly defaultEngine = {};
+
+ addRender(): void {}
+ createRender() { return undefined; }
+ removeRender(): void {}
+ getRenderById() { return undefined; }
+ getRenderUnitById() { return undefined; }
+ getAllRenderersOfType() { return []; }
+ getRenderAll() { return new Map(); }
+ create(): void {}
+ has() { return false; }
+ registerRenderModule(): IDisposable { return toDisposable(() => undefined); }
+ dispose(): void {}
+}
+
+class TestShortcutService {
+ readonly shortcutChanged$ = new Subject<void>();
+ readonly shortcuts: IShortcutItem[] = [];
+
+ forceEscape(): IDisposable { return toDisposable(() => undefined); }
+ forceDisable(): IDisposable { return toDisposable(() => undefined); }
+ dispatch(): undefined { return undefined; }
+ registerShortcut(shortcut: IShortcutItem): IDisposable {
+ this.shortcuts.push(shortcut);
+ return toDisposable(() => undefined);
+ }
+
+ getShortcutDisplay(): string | null { return null; }
+ getShortcutDisplayOfCommand(): string | null { return null; }
+ getAllShortcuts(): IShortcutItem[] { return this.shortcuts; }
+}
+
+interface IEditorRecord {
+ id: string;
+ data: IDocumentData;
+ selections: ISuccinctDocRangeParam[];
+ focused: boolean;
+}
+
+class TestEditor {
+ readonly input$ = new Subject<unknown>();
+ readonly paste$ = new Subject<unknown>();
+ readonly focus$ = new Subject<unknown>();
+ readonly blur$ = new Subject<unknown>();
+ readonly change$ = new Subject<unknown>();
+ readonly selectionChange$ = new Subject<unknown>();
+
+ readonly render = {
+ isDisposed: () => false,
+ with: () => ({
+ getSkeleton: () => ({
+ getActualSize: () => ({ actualWidth: 0, actualHeight: 0 }),
+ }),
+ getViewModel: () => ({
+ getDataModel: () => ({
+ updateDocumentDataPageSize: () => undefined,
+ }),
+ }),
+ }),
+ scene: {
+ transformByState: () => undefined,
+ getViewport: () => undefined,
+ },
+ mainComponent: {
+ resize: () => undefined,
+ translate: () => undefined,
+ },
+ components: {
+ get: () => undefined,
+ },
+ };
+
+ constructor(private readonly _record: IEditorRecord) {
+ }
+
+ isFocus() {
+ return this._record.focused;
+ }
+
+ focus(): void {
+ this._record.focused = true;
+ this.focus$.next(undefined);
+ }
+
+ blur(): void {
+ this._record.focused = false;
+ this.blur$.next(undefined);
+ }
+
+ select(): void {}
+
+ setSelectionRanges(ranges: ISuccinctDocRangeParam[]): void {
+ this._record.selections = ranges;
+ this.selectionChange$.next(undefined);
+ }
+
+ getSelectionRanges() {
+ return this._record.selections;
+ }
+
+ getEditorId() {
+ return this._record.id;
+ }
+
+ getDocumentData() {
+ return this._record.data;
+ }
+
+ setDocumentData(data: IDocumentData, ranges: ISuccinctDocRangeParam[] = []): void {
+ this._record.data = data;
+ this._record.selections = ranges;
+ this.selectionChange$.next(undefined);
+ }
+
+ replaceText(value: string): void {
+ this._record.data = {
+ ...this._record.data,
+ body: {
+ dataStream: `${value}\r\n`,
+ },
+ };
+ this.selectionChange$.next(undefined);
+ }
+
+ clearUndoRedoHistory(): void {}
+
+ getValue() {
+ return this._record.data.body?.dataStream ?? '';
+ }
+
+ isSheetEditor() {
+ return false;
+ }
+
+ getBoundingClientRect() {
+ return { width: 320, height: 64 };
+ }
+}
+
+class TestEditorService {
+ private readonly _editors = new Map<string, TestEditor>();
+ private _focusId: Nullable<string>;
+ readonly blur$ = new Subject<unknown>();
+ readonly focus$ = new Subject<ISuccinctDocRangeParam>();
+
+ getEditor(id?: string): Nullable<TestEditor> {
+ return id ? this._editors.get(id) : undefined;
+ }
+
+ register(config: { initialSnapshot: IDocumentData }, _container: HTMLDivElement): IDisposable {
+ const snapshot = config.initialSnapshot;
+ const record: IEditorRecord = {
+ id: snapshot.id,
+ data: snapshot,
+ selections: [],
+ focused: false,
+ };
+ const editor = new TestEditor(record);
+ this._editors.set(record.id, editor);
+
+ return toDisposable(() => {
+ this._editors.delete(record.id);
+ });
+ }
+
+ getAllEditor() {
+ return this._editors;
+ }
+
+ isEditor(editorUnitId: string) {
+ return this._editors.has(editorUnitId);
+ }
+
+ getEditorRenderConfig() {
+ return null;
+ }
+
+ isSheetEditor() {
+ return false;
+ }
+
+ blur(): void {
+ this.getFocusEditor()?.blur();
+ this._focusId = null;
+ this.blur$.next(undefined);
+ }
+
+ focus(editorUnitId: string): void {
+ this._focusId = editorUnitId;
+ this.getEditor(editorUnitId)?.focus();
+ this.focus$.next({ startOffset: 0, endOffset: 0 });
+ }
+
+ getFocusId() {
+ return this._focusId;
+ }
+
+ getFocusEditor() {
+ return this._focusId ? this.getEditor(this._focusId) : undefined;
+ }
+}
+
function createTextBody(text: string): IDocumentBody {
const dataStream = `${text}\r\n`;
return {
@@ -219,7 +443,29 @@ function createComment(id: string, subUnitId: string, ref: string, text: string,
};
}
-function createTestBed() {
+function createSelection(row: number, column: number): ISelectionWithStyle {
+ return {
+ range: {
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ },
+ primary: {
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ };
+}
+
+function createTestBed(testWorkbookData: IWorkbookData = workbookData) {
const univer = new Univer({
locale: LocaleType.EN_US,
locales: {
@@ -235,20 +481,27 @@ function createTestBed() {
injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService }]);
injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);
injector.add([SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService as never }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IShortcutService, { useClass: TestShortcutService as never }]);
+ injector.add([SheetsSelectionsService]);
injector.add([SheetsThreadCommentPopupService]);
injector.add([ISidebarService, { useClass: TestSidebarService as never }]);
injector.add([ThreadCommentPanelService]);
- univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData);
+ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, testWorkbookData);
get(IUniverInstanceService).focusUnit(unitId);
get(LifecycleService).stage = LifecycleStages.Rendered;
get(UserManagerService).setCurrentUser({ userID: 'user-1', name: 'Ada' });
const commandService = get(ICommandService);
commandService.registerCommand(AddCommentMutation);
+ commandService.registerCommand(DeleteCommentMutation);
+ commandService.registerCommand(DeleteCommentTreeCommand);
commandService.registerCommand(ResolveCommentMutation);
commandService.registerCommand(ResolveCommentCommand);
commandService.registerCommand(SetActiveCommentOperation);
+ commandService.registerCommand(ShowAddSheetCommentModalOperation);
return {
univer,
@@ -258,6 +511,7 @@ function createTestBed() {
threadCommentModel: get(ThreadCommentModel),
popupService: get(SheetsThreadCommentPopupService),
panelService: get(ThreadCommentPanelService),
+ selectionService: get(SheetsSelectionsService),
};
}
@@ -277,6 +531,22 @@ function renderPanel(injector: Injector) {
return { container, root };
}
+function renderCell(injector: Injector) {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SheetsThreadCommentCell />
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, root };
+}
+
function orderOf(text: string, ...items: string[]) {
return items.map((item) => {
const index = text.indexOf(item);
@@ -291,6 +561,19 @@ function dispatchMouseEvent(element: Element, type: string) {
});
}
+function getRootDeleteAction(panelItem: Element) {
+ const header = panelItem.firstElementChild;
+ const controls = header?.lastElementChild;
+ const action = controls?.lastElementChild;
+ expect(action).toBeInstanceOf(HTMLElement);
+
+ return action as HTMLElement;
+}
+
+function waitForTreeRefresh() {
+ return new Promise((resolve) => setTimeout(resolve, 40));
+}
+
describe('SheetsThreadCommentPanel', () => {
let univer: Univer | undefined;
let root: Root | undefined;
@@ -346,6 +629,78 @@ describe('SheetsThreadCommentPanel', () => {
expect(sheet2A1).toBeLessThan(resolvedSheet1A1);
});
+ it('filters panel comments to the active sheet when current-sheet scope is selected', async () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('current-sheet-thread', sheet1, 'B2', 'Current sheet B2'));
+ testBed.threadCommentModel.addComment(unitId, sheet2, createComment('other-sheet-thread', sheet2, 'C3', 'Other sheet C3'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.textContent).toContain('Current sheet B2');
+ expect(container.textContent).toContain('Other sheet C3');
+
+ await act(async () => {
+ container!.querySelectorAll('[data-u-comp="select"]')[0].dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const currentSheetOption = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((button) => button.textContent === 'Current sheet');
+
+ expect(currentSheetOption).toBeDefined();
+
+ await act(async () => {
+ currentSheetOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('Current sheet B2');
+ expect(container.textContent).not.toContain('Other sheet C3');
+ });
+
+ it('updates current-sheet scoped comments when the active sheet changes', async () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('sheet-one-thread', sheet1, 'B2', 'Sheet one B2'));
+ testBed.threadCommentModel.addComment(unitId, sheet2, createComment('sheet-two-thread', sheet2, 'C3', 'Sheet two C3'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ await act(async () => {
+ container!.querySelectorAll('[data-u-comp="select"]')[0].dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const currentSheetOption = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((button) => button.textContent === 'Current sheet');
+
+ expect(currentSheetOption).toBeDefined();
+
+ await act(async () => {
+ currentSheetOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('Sheet one B2');
+ expect(container.textContent).not.toContain('Sheet two C3');
+
+ const workbook = testBed.get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const secondSheet = workbook.getSheetBySheetId(sheet2);
+ expect(secondSheet).toBeDefined();
+
+ act(() => {
+ workbook.setActiveSheet(secondSheet!);
+ });
+
+ expect(container.textContent).toContain('Sheet two C3');
+ expect(container.textContent).not.toContain('Sheet one B2');
+ });
+
it('highlights only unresolved comments on the current sheet and closes the cell popup when resolved', () => {
const testBed = createTestBed();
univer = testBed.univer;
@@ -404,6 +759,143 @@ describe('SheetsThreadCommentPanel', () => {
expect(TestState.popupDisposeCount).toBe(1);
});
+ it('expands hover highlight to the whole merged cell containing the comment', () => {
+ const mergedWorkbookData: IWorkbookData = {
+ ...workbookData,
+ sheets: {
+ ...workbookData.sheets,
+ [sheet1]: {
+ ...workbookData.sheets[sheet1],
+ mergeData: [
+ { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },
+ ],
+ },
+ },
+ };
+ const testBed = createTestBed(mergedWorkbookData);
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('merged-cell-thread', sheet1, 'C3', 'Merged cell thread'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const mergedCellThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-merged-cell-thread`);
+ expect(mergedCellThread).toBeInstanceOf(HTMLElement);
+
+ dispatchMouseEvent(mergedCellThread!, 'mouseover');
+
+ expect(TestState.shapes).toEqual([
+ expect.objectContaining({
+ selection: expect.objectContaining({
+ range: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ }),
+ }),
+ ]);
+ });
+
+ it('clears the previous hover highlight when entering the active comment item', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('first-thread', sheet1, 'B2', 'First thread'));
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('active-thread', sheet1, 'D4', 'Active thread'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const firstThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-first-thread`);
+ const activeThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-active-thread`);
+ expect(firstThread).toBeInstanceOf(HTMLElement);
+ expect(activeThread).toBeInstanceOf(HTMLElement);
+
+ dispatchMouseEvent(firstThread!, 'mouseover');
+ expect(TestState.shapes).toEqual([
+ expect.objectContaining({
+ selection: expect.objectContaining({
+ range: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ },
+ }),
+ }),
+ ]);
+
+ act(() => {
+ testBed.panelService.setActiveComment({
+ unitId,
+ subUnitId: sheet1,
+ commentId: 'active-thread',
+ trigger: 'cell',
+ });
+ });
+ dispatchMouseEvent(activeThread!, 'mouseover');
+
+ expect(TestState.shapes).toHaveLength(0);
+ expect(TestState.removedShapeIds).toEqual(['shape-1']);
+ });
+
+ it('activates an unresolved sheet comment from the panel and skips hover highlight for the active item', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('panel-thread', sheet1, 'E5', 'Panel thread'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const panelThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-panel-thread`);
+ expect(panelThread).toBeInstanceOf(HTMLElement);
+
+ act(() => {
+ panelThread!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(testBed.panelService.activeCommentId).toEqual({
+ unitId,
+ subUnitId: sheet1,
+ commentId: 'panel-thread',
+ temp: false,
+ });
+
+ dispatchMouseEvent(panelThread!, 'mouseover');
+
+ expect(TestState.shapes).toHaveLength(0);
+ });
+
+ it('opens the add-comment popup at the active sheet cell from the empty panel action', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.selectionService.setSelections(unitId, sheet1, [createSelection(4, 4)]);
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const addButton = Array.from(container.querySelectorAll('button')).find((button) => button.textContent?.includes('Add Comment'));
+ expect(addButton).toBeInstanceOf(HTMLButtonElement);
+
+ act(() => {
+ addButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(testBed.popupService.activePopup).toMatchObject({
+ unitId,
+ subUnitId: sheet1,
+ row: 4,
+ col: 4,
+ });
+ expect(testBed.panelService.activeCommentId).toBeUndefined();
+ });
+
it('removes the hover highlight when the panel is hidden by service state', () => {
const testBed = createTestBed();
univer = testBed.univer;
@@ -427,4 +919,184 @@ describe('SheetsThreadCommentPanel', () => {
expect(TestState.shapes).toHaveLength(0);
expect(TestState.removedShapeIds).toEqual(['shape-1']);
});
+
+ it('does not remove a stale hover highlight again after panel visibility cleanup', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.panelService.setPanelVisible(true);
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('current-sheet-thread', sheet1, 'B2', 'Current sheet B2'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const currentThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-current-sheet-thread`);
+ expect(currentThread).toBeInstanceOf(HTMLElement);
+
+ dispatchMouseEvent(currentThread!, 'mouseover');
+
+ act(() => {
+ testBed.panelService.setPanelVisible(false);
+ });
+
+ dispatchMouseEvent(currentThread!, 'mouseout');
+
+ expect(TestState.shapes).toHaveLength(0);
+ expect(TestState.removedShapeIds).toEqual(['shape-1']);
+ });
+
+ it('removes the sheet highlight and thread when a hovered panel comment is deleted', async () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('delete-thread', sheet1, 'B2', 'Delete me'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const panelThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-delete-thread`);
+ expect(panelThread).toBeInstanceOf(HTMLElement);
+
+ dispatchMouseEvent(panelThread!, 'mouseover');
+ expect(TestState.shapes).toHaveLength(1);
+
+ await act(async () => {
+ getRootDeleteAction(panelThread!).dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await waitForTreeRefresh();
+ });
+
+ expect(testBed.threadCommentModel.getComment(unitId, sheet1, 'delete-thread')).toBeUndefined();
+ expect(container.textContent).not.toContain('Delete me');
+ expect(TestState.shapes).toHaveLength(0);
+ expect(TestState.removedShapeIds).toEqual(['shape-1']);
+ });
+
+ it('renders the unresolved thread for the active cell popup and persists a temporary popup when clicked', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('resolved-thread', sheet1, 'B2', 'Resolved B2', true));
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('open-thread', sheet1, 'B2', 'Open B2'));
+ testBed.popupService.showPopup({
+ unitId,
+ subUnitId: sheet1,
+ row: 1,
+ col: 1,
+ temp: true,
+ trigger: 'hover',
+ });
+
+ const rendered = renderCell(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const cellThread = container.querySelector(`#CELL-${unitId}-${sheet1}-open-thread`);
+ expect(cellThread).toBeInstanceOf(HTMLElement);
+ expect(container.textContent).toContain('B2 · Sheet 1');
+ expect(container.textContent).toContain('Open B2');
+ expect(container.textContent).not.toContain('Resolved B2');
+
+ act(() => {
+ cellThread!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(testBed.popupService.activePopup).toEqual(expect.objectContaining({
+ temp: false,
+ }));
+ });
+
+ it('updates an open cell popup when a thread is added at that cell location', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.popupService.showPopup({
+ unitId,
+ subUnitId: sheet2,
+ row: 3,
+ col: 2,
+ trigger: 'context-menu',
+ });
+
+ const rendered = renderCell(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.textContent).toContain('C4 · Sheet 2');
+ expect(container.textContent).not.toContain('Created after popup opens');
+
+ act(() => {
+ testBed.threadCommentModel.addComment(unitId, sheet2, createComment('created-thread', sheet2, 'C4', 'Created after popup opens'));
+ });
+
+ expect(container.textContent).toContain('Created after popup opens');
+ });
+
+ it('keeps an open cell popup scoped to its sheet when another sheet receives the same cell reference', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.popupService.showPopup({
+ unitId,
+ subUnitId: sheet2,
+ row: 3,
+ col: 2,
+ trigger: 'context-menu',
+ });
+
+ const rendered = renderCell(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.textContent).toContain('C4 · Sheet 2');
+
+ act(() => {
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('same-cell-other-sheet', sheet1, 'C4', 'Same cell on sheet one'));
+ testBed.threadCommentModel.addComment(unitId, sheet2, createComment('same-cell-current-sheet', sheet2, 'C4', 'Same cell on sheet two'));
+ });
+
+ expect(container.textContent).toContain('Same cell on sheet two');
+ expect(container.textContent).not.toContain('Same cell on sheet one');
+ });
+
+ it('closes an empty cell popup when the user cancels the new comment editor', async () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.popupService.showPopup({
+ unitId,
+ subUnitId: sheet1,
+ row: 2,
+ col: 3,
+ trigger: 'context-menu',
+ });
+
+ const rendered = renderCell(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.textContent).toContain('D3 · Sheet 1');
+ expect(testBed.popupService.activePopup).toMatchObject({
+ unitId,
+ subUnitId: sheet1,
+ row: 2,
+ col: 3,
+ });
+
+ const editorPlaceholder = Array.from(container.querySelectorAll('div')).reverse().find((element) => element.textContent === 'Reply or add others with @');
+ expect(editorPlaceholder).toBeInstanceOf(HTMLElement);
+ const editorSurface = editorPlaceholder!.parentElement?.parentElement?.parentElement;
+ expect(editorSurface).toBeInstanceOf(HTMLElement);
+
+ await act(async () => {
+ editorSurface!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const cancelButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent?.trim() === 'Cancel');
+ expect(cancelButton).toBeInstanceOf(HTMLButtonElement);
+
+ act(() => {
+ cancelButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(testBed.popupService.activePopup).toBeNull();
+ expect(TestState.popupDisposeCount).toBe(1);
+ });
});
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
index 319028bde8..47d7efd885 100644
--- a/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts
@@ -20,6 +20,7 @@ import type { SheetInterceptorService } from '@univerjs/sheets';
import {
CancelMarkDirtyRowAutoHeightOperation,
MarkDirtyRowAutoHeightOperation,
+ SetWorksheetRowAutoHeightMutation,
} from '@univerjs/sheets';
import { describe, expect, it } from 'vitest';
import { AutoHeightController } from '../auto-height.controller';
@@ -110,4 +111,63 @@ describe('AutoHeightController', () => {
},
]);
});
+
+ it('builds row auto-height undo/redo only for rows whose calculated height changed', () => {
+ const worksheet = {
+ getSheetId: () => 's-1',
+ getRowHeight: (row: number) => row === 1 ? 20 : 30,
+ getRowManager: () => ({
+ getRow: (row: number) => row === 1 ? { ah: 20 } : { ah: 30 },
+ }),
+ getConfig: () => ({ defaultRowHeight: 18 }),
+ } as unknown;
+
+ const workbook = {
+ getUnitId: () => 'u-1',
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: (sheetId: string) => (sheetId === 's-1' ? worksheet : null),
+ } as unknown as Workbook;
+
+ const controller = new AutoHeightController(
+ {
+ getRenderById: () => ({
+ with: () => ({
+ ensureSkeleton: () => ({
+ calculateAutoHeightInRange: () => [
+ { row: 1, autoHeight: 24 },
+ { row: 2, autoHeight: 30 },
+ { row: 3, autoHeight: 0 },
+ ],
+ }),
+ }),
+ }),
+ } as unknown as RenderManagerService,
+ { interceptAutoHeight: () => ({ dispose: () => { } }) } as unknown as SheetInterceptorService,
+ {
+ getCurrentUnitOfType: () => workbook,
+ getUnit: () => workbook,
+ } as unknown as IUniverInstanceService
+ );
+
+ expect(controller.getUndoRedoParamsOfAutoHeight([
+ { startRow: 1, endRow: 3, startColumn: 0, endColumn: 0 },
+ ])).toEqual({
+ redos: [{
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ rowsAutoHeightInfo: [{ row: 1, autoHeight: 24 }],
+ },
+ }],
+ undos: [{
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ rowsAutoHeightInfo: [{ row: 1, autoHeight: 20 }],
+ },
+ }],
+ });
+ });
});
diff --git a/packages/sheets-ui/src/controllers/__tests__/cell-custom-render.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/cell-custom-render.controller.spec.ts
new file mode 100644
index 0000000000..684d6b9920
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/__tests__/cell-custom-render.controller.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 { UnitAction } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { CellCustomRenderController } from '../cell-custom-render.controller';
+
+function createEventSubject() {
+ const subscribers = new Set<(evt: any) => void>();
+
+ return {
+ subscribeEvent: vi.fn((handler: (evt: any) => void) => {
+ subscribers.add(handler);
+ const unsubscribe = vi.fn(() => subscribers.delete(handler));
+
+ return { dispose: unsubscribe, unsubscribe };
+ }),
+ emit: (evt: any) => subscribers.forEach((handler) => handler(evt)),
+ };
+}
+
+function createController(options?: { editable?: boolean; selectionEditable?: boolean }) {
+ const pointerDown$ = createEventSubject();
+ const pointerMove$ = createEventSubject();
+ const renderA = {
+ zIndex: 1,
+ isHit: vi.fn(() => true),
+ onPointerDown: vi.fn(),
+ onPointerEnter: vi.fn(),
+ onPointerLeave: vi.fn(),
+ };
+ const renderB = {
+ zIndex: 2,
+ isHit: vi.fn(() => false),
+ onPointerEnter: vi.fn(),
+ onPointerLeave: vi.fn(),
+ };
+ const cellData = {
+ customRender: [renderB, renderA],
+ selectionProtection: [{ [UnitAction.Edit]: options?.selectionEditable ?? true }],
+ };
+ const worksheet = {
+ getSheetId: vi.fn(() => 'sheet-1'),
+ getMergedCell: vi.fn(() => null),
+ getCell: vi.fn(() => cellData),
+ };
+ const skeleton = {
+ worksheet,
+ getCellIndexByOffset: vi.fn(() => ({ row: 1, column: 2 })),
+ getStyles: vi.fn(() => ({ getStyleByCell: vi.fn(() => ({ fs: 12 })) })),
+ getCellWithCoordByIndex: vi.fn(() => ({ startX: 10, startY: 20 })),
+ };
+ const currentSkeleton$ = new Subject<any>();
+ const spreadsheet = {
+ onPointerDown$: pointerDown$,
+ onPointerMove$: pointerMove$,
+ };
+ const scene = {
+ getActiveViewportByCoord: vi.fn(() => ({ viewportScrollX: 5, viewportScrollY: 6 })),
+ getAncestorScale: vi.fn(() => ({ scaleX: 2, scaleY: 2 })),
+ };
+ const controller = new CellCustomRenderController(
+ {
+ unitId: 'unit-1',
+ unit: { getActiveSheet: vi.fn(() => worksheet) },
+ } as any,
+ {
+ currentSkeleton$,
+ getCurrentParam: vi.fn(() => ({ skeleton })),
+ } as any,
+ {
+ getRenderById: vi.fn(() => ({ mainComponent: spreadsheet, scene })),
+ } as any,
+ {
+ composePermission: vi.fn(() => [{ value: options?.editable ?? true }]),
+ } as any
+ );
+
+ return { controller, pointerDown$, pointerMove$, renderA, renderB, currentSkeleton$, skeleton, worksheet };
+}
+
+describe('CellCustomRenderController', () => {
+ it('dispatches pointer events to hit custom renderers when sheet and cell are editable', async () => {
+ const { controller, pointerDown$, pointerMove$, renderA, renderB } = createController();
+
+ pointerDown$.emit({ offsetX: 20, offsetY: 30 });
+ pointerMove$.emit({ offsetX: 20, offsetY: 30 });
+ await new Promise((resolve) => setTimeout(resolve, 35));
+ renderA.isHit.mockReturnValue(false);
+ pointerMove$.emit({ offsetX: 200, offsetY: 300 });
+ await new Promise((resolve) => setTimeout(resolve, 35));
+
+ expect(renderA.onPointerDown).toHaveBeenCalled();
+ expect(renderA.onPointerEnter).toHaveBeenCalled();
+ expect(renderA.onPointerLeave).toHaveBeenCalled();
+ expect(renderB.onPointerEnter).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('does not dispatch pointer down when workbook or protected cell is not editable', () => {
+ const nonEditable = createController({ editable: false });
+ nonEditable.pointerDown$.emit({ offsetX: 20, offsetY: 30 });
+ expect(nonEditable.renderA.onPointerDown).not.toHaveBeenCalled();
+ nonEditable.controller.dispose();
+
+ const protectedCell = createController({ selectionEditable: false });
+ protectedCell.pointerDown$.emit({ offsetX: 20, offsetY: 30 });
+ expect(protectedCell.renderA.onPointerDown).not.toHaveBeenCalled();
+ protectedCell.controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts
new file mode 100644
index 0000000000..7fa86c9d2b
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/__tests__/checkbox-force-string-auto-width.controller.spec.ts
@@ -0,0 +1,243 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { CURSOR_TYPE, getCurrentTypeOfRenderer } from '@univerjs/engine-render';
+import { INTERCEPTOR_POINT, SetWorksheetColWidthMutation, ToggleCellCheckboxCommand } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { CellAlertType } from '../../services/cell-alert-manager.service';
+import { AutoWidthController, createAutoColWidthUndoMutationsByRedos } from '../auto-width.controller';
+import { SheetCheckboxController } from '../checkbox.controller';
+import { ForceStringAlertRenderController } from '../force-string-alert-render.controller';
+import { ForceStringRenderController } from '../force-string-render.controller';
+
+const mainComponentMock = vi.hoisted(() => ({
+ setCursor: vi.fn(),
+}));
+
+vi.mock('@univerjs/engine-render', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/engine-render')>();
+
+ return {
+ ...actual,
+ getCurrentTypeOfRenderer: vi.fn(() => ({
+ mainComponent: mainComponentMock,
+ })),
+ };
+});
+
+describe('SheetCheckboxController', () => {
+ it('uses pointer cursor for checkbox bullets and toggles the clicked checkbox paragraph', () => {
+ const currentRichText$ = new Subject<any>();
+ const currentClickedCell$ = new Subject<any>();
+ const commandService = { executeCommand: vi.fn() };
+ const controller = new SheetCheckboxController(
+ { currentRichText$, currentClickedCell$ } as never,
+ {} as never,
+ commandService as never,
+ {} as never
+ );
+
+ currentRichText$.next({ bullet: { startIndex: 3 } });
+ expect(mainComponentMock.setCursor).toHaveBeenCalledWith(CURSOR_TYPE.POINTER);
+ expect(getCurrentTypeOfRenderer).toHaveBeenCalled();
+ currentRichText$.next(null);
+ expect(mainComponentMock.setCursor).toHaveBeenCalledWith(CURSOR_TYPE.AUTO);
+
+ currentClickedCell$.next({
+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 2, col: 4 },
+ bullet: { startIndex: 7 },
+ });
+ currentClickedCell$.next({
+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 3, col: 5 },
+ });
+
+ expect(commandService.executeCommand).toHaveBeenCalledTimes(1);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(ToggleCellCheckboxCommand.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 4,
+ paragraphIndex: 7,
+ });
+
+ controller.dispose();
+ });
+});
+
+describe('ForceStringRenderController', () => {
+ it('marks numeric-looking string cells unless disabled or formatted as text', () => {
+ let interceptor: any;
+ const controller = new ForceStringRenderController(
+ { unitId: 'unit-1' } as never,
+ { getCurrentParam: vi.fn(() => ({ skeleton: {} })) } as never,
+ {
+ intercept: vi.fn((point, config) => {
+ expect(point).toBe(INTERCEPTOR_POINT.CELL_CONTENT);
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ { getConfig: vi.fn(() => ({ disableForceStringMark: false })) } as never
+ );
+ const workbook = {
+ getStyles: vi.fn(() => ({
+ get: vi.fn((styleId: string) => styleId === 'text' ? { n: { pattern: '@' } } : undefined),
+ })),
+ };
+ const rawCell = { v: '123', t: CellValueType.STRING };
+
+ const result = interceptor.handler(rawCell, {
+ rawData: rawCell,
+ workbook,
+ }, (cell: unknown) => cell);
+
+ expect(result).not.toBe(rawCell);
+ expect(result.markers.tl).toEqual({ size: 6, color: '#409f11' });
+
+ expect(interceptor.handler({ ...rawCell, s: 'text' }, {
+ rawData: { ...rawCell, s: 'text' },
+ workbook,
+ }, (cell: unknown) => cell)).not.toHaveProperty('markers');
+
+ controller.dispose();
+ });
+});
+
+describe('ForceStringAlertRenderController', () => {
+ it('shows and hides force-string alert based on hovered cell value and format', () => {
+ const currentCell$ = new Subject<any>();
+ const cellAlertManagerService = {
+ currentAlert: new Map(),
+ showAlert: vi.fn((alert) => {
+ cellAlertManagerService.currentAlert.set(alert.key, { alert });
+ }),
+ removeAlert: vi.fn((key) => cellAlertManagerService.currentAlert.delete(key)),
+ };
+ const worksheet = {
+ getCell: vi.fn((row: number) => row === 1
+ ? { v: '123', t: CellValueType.STRING }
+ : { v: '123', t: CellValueType.STRING, s: 'text' }),
+ };
+ const workbook = {
+ getActiveSheet: vi.fn(() => worksheet),
+ getStyles: vi.fn(() => ({
+ get: vi.fn((styleId: string) => styleId === 'text' ? { n: { pattern: '@' } } : undefined),
+ })),
+ };
+ const controller = new ForceStringAlertRenderController(
+ { unit: workbook } as never,
+ { currentCell$ } as never,
+ cellAlertManagerService as never,
+ { t: vi.fn((key: string) => key) } as never,
+ { getConfig: vi.fn(() => ({ disableForceStringAlert: false })) } as never
+ );
+
+ currentCell$.next({ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 1, col: 2 } });
+ expect(cellAlertManagerService.showAlert).toHaveBeenCalledWith(expect.objectContaining({
+ type: CellAlertType.ERROR,
+ title: 'sheets-ui.info.error',
+ message: 'sheets-ui.info.forceStringInfo',
+ width: 200,
+ height: 74,
+ key: 'SHEET_FORCE_STRING_ALERT',
+ }));
+
+ currentCell$.next({ location: { unitId: 'unit-1', subUnitId: 'sheet-1', row: 2, col: 2 } });
+ expect(cellAlertManagerService.removeAlert).toHaveBeenCalledWith('SHEET_FORCE_STRING_ALERT');
+ currentCell$.next(null);
+ expect(cellAlertManagerService.removeAlert).toHaveBeenCalledTimes(2);
+
+ controller.dispose();
+ });
+});
+
+describe('AutoWidthController', () => {
+ it('creates undo params from existing column widths', () => {
+ expect(createAutoColWidthUndoMutationsByRedos({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startColumn: 1, endColumn: 3, startRow: 0, endRow: 0 }],
+ colWidth: { 1: 80, 2: 90, 3: 100 },
+ }, {
+ getColumnManager: () => ({
+ getColumnWidth: (col: number) => col * 10,
+ }),
+ } as never)).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startColumn: 1, endColumn: 3, startRow: 0, endRow: 0 }],
+ colWidth: { 1: 10, 2: 20, 3: 30 },
+ });
+ });
+
+ it('builds auto-width undo and redo mutations from calculated skeleton widths', () => {
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getColumnManager: () => ({
+ getColumnWidth: (col: number) => col === 2 ? 88 : 66,
+ }),
+ };
+ const controller = new AutoWidthController(
+ {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => ({
+ getCurrentParam: vi.fn(() => ({
+ skeleton: {
+ calculateAutoWidthInRange: vi.fn(() => [
+ { col: 2, width: 120 },
+ { col: 3, width: 140 },
+ ]),
+ },
+ })),
+ })),
+ })),
+ } as never,
+ {
+ getUnit: vi.fn(() => ({
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: vi.fn(() => worksheet),
+ })),
+ } as never
+ );
+
+ expect(controller.getUndoRedoParamsOfColWidth({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startColumn: 2, endColumn: 3, startRow: 0, endRow: 0 }],
+ })).toEqual({
+ undos: [{
+ id: SetWorksheetColWidthMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startColumn: 2, endColumn: 3, startRow: 0, endRow: 0 }],
+ colWidth: { 2: 88, 3: 66 },
+ },
+ }],
+ redos: [{
+ id: SetWorksheetColWidthMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startColumn: 2, endColumn: 3, startRow: 0, endRow: 0 }],
+ colWidth: { 2: 120, 3: 140 },
+ },
+ }],
+ });
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/__tests__/hover-move-range.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/hover-move-range.controller.spec.ts
new file mode 100644
index 0000000000..8f92d0cd40
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/__tests__/hover-move-range.controller.spec.ts
@@ -0,0 +1,173 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { MoveRangeCommand } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../common/keys';
+import { HoverRenderController } from '../hover-render.controller';
+import { MoveRangeRenderController } from '../move-range.controller';
+
+function createEventSubject() {
+ const handlers = new Set<(evt: any) => void>();
+
+ return {
+ subscribeEvent: vi.fn((handler: (evt: any) => void) => {
+ handlers.add(handler);
+ return { dispose: vi.fn(() => handlers.delete(handler)) };
+ }),
+ emit: (evt: any) => handlers.forEach((handler) => handler(evt)),
+ };
+}
+
+describe('HoverRenderController', () => {
+ it('forwards sheet body and header pointer events to hover manager services', () => {
+ const currentSkeleton$ = new Subject<any>();
+ const validViewportScrollInfo$ = new Subject<void>();
+ const mainComponent = {
+ onPointerEnter$: createEventSubject(),
+ onPointerMove$: createEventSubject(),
+ onPointerDown$: createEventSubject(),
+ onPointerUp$: createEventSubject(),
+ onClick$: createEventSubject(),
+ onDblclick$: createEventSubject(),
+ onPointerLeave$: createEventSubject(),
+ };
+ const rowHeader = {
+ onPointerMove$: createEventSubject(),
+ onPointerDown$: createEventSubject(),
+ onPointerUp$: createEventSubject(),
+ onDblclick$: createEventSubject(),
+ };
+ const colHeader = {
+ onPointerMove$: createEventSubject(),
+ onPointerDown$: createEventSubject(),
+ onPointerUp$: createEventSubject(),
+ onDblclick$: createEventSubject(),
+ };
+ const hoverManagerService = {
+ triggerMouseMove: vi.fn(),
+ triggerPointerDown: vi.fn(),
+ triggerPointerUp: vi.fn(),
+ triggerClick: vi.fn(),
+ triggerDbClick: vi.fn(),
+ triggerRowHeaderMouseMove: vi.fn(),
+ triggerRowHeaderPoniterDown: vi.fn(),
+ triggerRowHeaderPoniterUp: vi.fn(),
+ triggerRowHeaderClick: vi.fn(),
+ triggerRowHeaderDbClick: vi.fn(),
+ triggerColHeaderMouseMove: vi.fn(),
+ triggerColHeaderPoniterDown: vi.fn(),
+ triggerColHeaderPoniterUp: vi.fn(),
+ triggerColHeaderClick: vi.fn(),
+ triggerColHeaderDbClick: vi.fn(),
+ triggerScroll: vi.fn(),
+ };
+ const controller = new HoverRenderController(
+ {
+ unitId: 'unit-1',
+ mainComponent,
+ components: new Map([
+ [SHEET_VIEW_KEY.ROW, rowHeader],
+ [SHEET_VIEW_KEY.COLUMN, colHeader],
+ ]),
+ } as never,
+ hoverManagerService as never,
+ {
+ getCurrentParam: vi.fn(() => ({ skeleton: {} })),
+ currentSkeleton$,
+ } as never,
+ { validViewportScrollInfo$ } as never
+ );
+
+ mainComponent.onPointerEnter$.emit({});
+ expect(controller.active).toBe(true);
+ mainComponent.onPointerMove$.emit({ offsetX: 10, offsetY: 20 });
+ mainComponent.onPointerDown$.emit({ offsetX: 11, offsetY: 21 });
+ mainComponent.onPointerUp$.emit({ offsetX: 12, offsetY: 22 });
+ mainComponent.onClick$.emit({ offsetX: 13, offsetY: 23 });
+ mainComponent.onDblclick$.emit({ offsetX: 14, offsetY: 24 });
+ mainComponent.onPointerLeave$.emit({});
+ rowHeader.onPointerUp$.emit({ offsetX: 1, offsetY: 2 });
+ colHeader.onDblclick$.emit({ offsetX: 3, offsetY: 4 });
+ validViewportScrollInfo$.next();
+
+ expect(controller.active).toBe(false);
+ expect(hoverManagerService.triggerMouseMove).toHaveBeenCalledWith('unit-1', { offsetX: 10, offsetY: 20 });
+ expect(hoverManagerService.triggerPointerDown).toHaveBeenCalledWith('unit-1', { offsetX: 11, offsetY: 21 });
+ expect(hoverManagerService.triggerPointerUp).toHaveBeenCalledWith('unit-1', { offsetX: 12, offsetY: 22 });
+ expect(hoverManagerService.triggerClick).toHaveBeenCalledWith('unit-1', 13, 23);
+ expect(hoverManagerService.triggerDbClick).toHaveBeenCalledWith('unit-1', 14, 24);
+ expect(hoverManagerService.triggerRowHeaderPoniterUp).toHaveBeenCalledWith('unit-1', 1, 2);
+ expect(hoverManagerService.triggerRowHeaderClick).toHaveBeenCalledWith('unit-1', 1, 2);
+ expect(hoverManagerService.triggerColHeaderDbClick).toHaveBeenCalledWith('unit-1', 3, 4);
+ expect(hoverManagerService.triggerScroll).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
+
+describe('MoveRangeRenderController', () => {
+ it('executes move range command after dragging a selection to a valid different range', () => {
+ const selectionMoveEnd$ = new Subject<void>();
+ const controlMoveEnd$ = new Subject<any>();
+ const commandService = { executeCommand: vi.fn() };
+ const controller = new MoveRangeRenderController(
+ {} as never,
+ {
+ getSelectionControls: vi.fn(() => [{
+ model: {
+ getRange: vi.fn(() => ({
+ startRow: 1,
+ startColumn: 2,
+ endRow: 3,
+ endColumn: 4,
+ rangeType: 0,
+ })),
+ },
+ selectionMoveEnd$: controlMoveEnd$,
+ }]),
+ } as never,
+ { selectionMoveEnd$ } as never,
+ commandService as never
+ );
+
+ selectionMoveEnd$.next();
+ controlMoveEnd$.next({ startRow: 5, startColumn: 6, endRow: 7, endColumn: 8 });
+ controlMoveEnd$.next({ startRow: 1, startColumn: 2, endRow: 3, endColumn: 4 });
+ controlMoveEnd$.next({ startRow: -1, startColumn: 2, endRow: 3, endColumn: 4 });
+
+ expect(commandService.executeCommand).toHaveBeenCalledTimes(1);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(MoveRangeCommand.id, {
+ fromRange: {
+ startRow: 1,
+ startColumn: 2,
+ endRow: 3,
+ endColumn: 4,
+ rangeType: 0,
+ },
+ toRange: {
+ startRow: 5,
+ startColumn: 6,
+ endRow: 7,
+ endColumn: 8,
+ rangeType: 0,
+ },
+ });
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/components.controller.ts b/packages/sheets-ui/src/controllers/components.controller.ts
index e25e186e9e..3b786bdf79 100644
--- a/packages/sheets-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-ui/src/controllers/components.controller.ts
@@ -16,10 +16,98 @@
import type { IUniverSheetsUIConfig } from '../config/config';
import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core';
-import { AddImageIcon, AdjustHeightDoubleIcon, AdjustWidthDoubleIcon, AlignBottomIcon, AlignTopIcon, AllBorderIcon, AutoHeightDoubleIcon, AutoWidthDoubleIcon, AutowrapIcon, BackSlashDoubleIcon, BoldIcon, BrushIcon, CancelFreezeIcon, CancelMergeIcon, CheckMarkIcon, ClearFormatDoubleIcon, CodeIcon, CopyDoubleIcon, CutIcon, DeleteCellShiftLeftDoubleIcon, DeleteCellShiftUpDoubleIcon, DeleteColumnDoubleIcon, DeleteIcon, DeleteRowDoubleIcon, DownBorderDoubleIcon, DownloadImageIcon, EyeOutlineIcon, FontColorDoubleIcon, FontSizeIncreaseIcon, FontSizeReduceIcon, FreezeColumnIcon, FreezeRowIcon, FreezeToSelectedIcon, HideDoubleIcon, HideGridlinesDoubleIcon, HorizontalBorderDoubleIcon, HorizontallyIcon, HorizontalMergeIcon, InnerBorderDoubleIcon, InsertCellDownDoubleIcon, InsertCellShiftRightDoubleIcon, InsertDoubleIcon, InsertRowAboveDoubleIcon, InsertRowBelowDoubleIcon, ItalicIcon, LeftBorderDoubleIcon, LeftDoubleDiagonalDoubleIcon, LeftInsertColumnDoubleIcon, LeftJustifyingIcon, LeftRotationFortyFiveDegreesIcon, LeftRotationNinetyDegreesIcon, LeftTridiagonalDoubleIcon, LockIcon, MergeAllIcon, NoBorderIcon, NoColorDoubleIcon, NoRotationIcon, OuterBorderDoubleIcon, OverflowIcon, PaintBucketDoubleIcon, PasteSpecialDoubleIcon, PipingIcon, ProtectIcon, ReduceDoubleIcon, RightBorderDoubleIcon, RightDoubleDiagonalDoubleIcon, RightInsertColumnDoubleIcon, RightJustifyingIcon, RightRotationFortyFiveDegreesIcon, RightRotationNinetyDegreesIcon, SlashDoubleIcon, StrikethroughIcon, SubscriptIcon, SuperscriptIcon, TruncationIcon, UnderlineIcon, UpBorderDoubleIcon, VerticalBorderDoubleIcon, VerticalCenterIcon, VerticalIntegrationIcon, VerticalTextIcon, WriteIcon } from '@univerjs/icons';
+import {
+ AddImageIcon,
+ AdjustHeightDoubleIcon,
+ AdjustWidthDoubleIcon,
+ AlignBottomIcon,
+ AlignTopIcon,
+ AllBorderIcon,
+ AutoHeightDoubleIcon,
+ AutoWidthDoubleIcon,
+ AutowrapIcon,
+ BackSlashDoubleIcon,
+ BoldIcon,
+ BrushIcon,
+ CancelFreezeIcon,
+ CancelMergeIcon,
+ CheckMarkIcon,
+ ClearFormatDoubleIcon,
+ CodeIcon,
+ CopyDoubleIcon,
+ CutIcon,
+ DeleteCellShiftLeftDoubleIcon,
+ DeleteCellShiftUpDoubleIcon,
+ DeleteColumnDoubleIcon,
+ DeleteIcon,
+ DeleteRowDoubleIcon,
+ DownBorderDoubleIcon,
+ DownloadImageIcon,
+ EyeOutlineIcon,
+ FontColorDoubleIcon,
+ FontSizeIncreaseIcon,
+ FontSizeReduceIcon,
+ FreezeColumnIcon,
+ FreezeRowIcon,
+ FreezeToSelectedIcon,
+ HideDoubleIcon,
+ HideGridlinesDoubleIcon,
+ HorizontalBorderDoubleIcon,
+ HorizontallyIcon,
+ HorizontalMergeIcon,
+ InnerBorderDoubleIcon,
+ InsertCellDownDoubleIcon,
+ InsertCellShiftRightDoubleIcon,
+ InsertDoubleIcon,
+ InsertRowAboveDoubleIcon,
+ InsertRowBelowDoubleIcon,
+ ItalicIcon,
+ LeftBorderDoubleIcon,
+ LeftDoubleDiagonalDoubleIcon,
+ LeftInsertColumnDoubleIcon,
+ LeftJustifyingIcon,
+ LeftRotationFortyFiveDegreesIcon,
+ LeftRotationNinetyDegreesIcon,
+ LeftTridiagonalDoubleIcon,
+ LockIcon,
+ MergeAllIcon,
+ NoBorderIcon,
+ NoColorDoubleIcon,
+ NoRotationIcon,
+ OuterBorderDoubleIcon,
+ OverflowIcon,
+ PaintBucketDoubleIcon,
+ PasteSpecialDoubleIcon,
+ PipingIcon,
+ ProtectIcon,
+ ReduceDoubleIcon,
+ RightBorderDoubleIcon,
+ RightDoubleDiagonalDoubleIcon,
+ RightInsertColumnDoubleIcon,
+ RightJustifyingIcon,
+ RightRotationFortyFiveDegreesIcon,
+ RightRotationNinetyDegreesIcon,
+ SlashDoubleIcon,
+ StrikethroughIcon,
+ SubscriptIcon,
+ SuperscriptIcon,
+ TruncationIcon,
+ UnderlineIcon,
+ UpBorderDoubleIcon,
+ VerticalBorderDoubleIcon,
+ VerticalCenterIcon,
+ VerticalIntegrationIcon,
+ VerticalTextIcon,
+ WriteIcon,
+} from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../config/config';
-import { UNIVER_SHEET_PERMISSION_DIALOG, UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_USER_DIALOG, UNIVER_SHEET_PERMISSION_USER_PART } from '../consts/permission';
+import {
+ UNIVER_SHEET_PERMISSION_DIALOG,
+ UNIVER_SHEET_PERMISSION_PANEL,
+ UNIVER_SHEET_PERMISSION_USER_DIALOG,
+ UNIVER_SHEET_PERMISSION_USER_PART,
+} from '../consts/permission';
import { BorderPanel } from '../views/border-panel/BorderPanel';
import { BORDER_PANEL_COMPONENT } from '../views/border-panel/interface';
import { CELL_ALERT_KEY } from '../views/cell-alert';
@@ -44,19 +132,14 @@ export class ComponentsController extends Disposable {
this._registerComponents();
this._registerParts();
- this._registerIcons2();
- this._registerComponents2();
this._registerIcons();
- this._registerComponents3();
}
private _registerComponents(): void {
this.disposeWithMe(
this._componentManager.register(CELL_ALERT_KEY, CellAlert)
);
- }
- private _registerComponents2(): void {
([
[UNIVER_SHEET_PERMISSION_PANEL, SheetPermissionPanel],
[UNIVER_SHEET_PERMISSION_USER_DIALOG, SheetPermissionUserDialog],
@@ -68,19 +151,7 @@ export class ComponentsController extends Disposable {
comp
));
});
- }
- private _registerIcons(): void {
- this.disposeWithMe(this._iconManager.register({
- ProtectIcon,
- DeleteIcon,
- WriteIcon,
- CheckMarkIcon,
- LockIcon,
- }));
- }
-
- private _registerComponents3(): void {
const configService = this._injector.get(IConfigService);
const config = configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
@@ -106,7 +177,15 @@ export class ComponentsController extends Disposable {
}
// eslint-disable-next-line max-lines-per-function
- private _registerIcons2(): void {
+ private _registerIcons(): void {
+ this.disposeWithMe(this._iconManager.register({
+ ProtectIcon,
+ DeleteIcon,
+ WriteIcon,
+ CheckMarkIcon,
+ LockIcon,
+ }));
+
this.disposeWithMe(this._iconManager.register({
AdjustHeightDoubleIcon,
AdjustWidthDoubleIcon,
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts
new file mode 100644
index 0000000000..471134fdef
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts
@@ -0,0 +1,201 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ EDITOR_ACTIVATED,
+ FOCUSING_EDITOR_BUT_HIDDEN,
+ FOCUSING_EDITOR_INPUT_FORMULA,
+ FOCUSING_FX_BAR_EDITOR,
+ LocaleType,
+} from '@univerjs/core';
+import { VIEWPORT_KEY as DOC_VIEWPORT_KEY, MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs-ui';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { SetRangeValuesCommand } from '@univerjs/sheets';
+import { KeyCode } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../../commands/commands/set-selection.command';
+import { EditingRenderController } from '../editing.render-controller';
+
+function createController() {
+ const worksheet = {
+ getSheetId: vi.fn(() => 'sheet-1'),
+ getCellRaw: vi.fn(() => ({ v: 'old' })),
+ getComposedCellStyleWithoutSelf: vi.fn(() => ({})),
+ };
+ const styles = { get: vi.fn(() => undefined) };
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit-1'),
+ getActiveSheet: vi.fn(() => worksheet),
+ getSheetBySheetId: vi.fn(() => worksheet),
+ getStyles: vi.fn(() => styles),
+ };
+ const docModel = {
+ getSnapshot: vi.fn(() => ({
+ body: { dataStream: 'new value\r\n' },
+ documentStyle: {},
+ })),
+ };
+ const controller = Object.create(EditingRenderController.prototype) as any;
+ controller._editingUnit = 'unit-1';
+ controller._lexerTreeBuilder = new LexerTreeBuilder();
+ controller._localService = { getCurrentLocale: vi.fn(() => LocaleType.EN_US) };
+ controller._functionService = { getDescriptions: vi.fn(() => ({})) };
+ controller._undoRedoService = {
+ rollback: vi.fn(),
+ clearUndoRedo: vi.fn(),
+ };
+ controller._contextService = {
+ setContextValue: vi.fn(),
+ getContextValue: vi.fn(() => false),
+ };
+ controller._cellEditorManagerService = { setState: vi.fn() };
+ controller._editorService = { isSheetEditor: vi.fn(() => true) };
+ controller._editorBridgeService = {
+ getEditCellState: vi.fn(() => ({
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ row: 2,
+ column: 3,
+ documentLayoutObject: { documentModel: null },
+ })),
+ getEditLocation: vi.fn(() => ({ unitId: 'unit-1', sheetId: 'sheet-1', row: 2, column: 3 })),
+ getCurrentEditorId: vi.fn(() => DOCS_NORMAL_EDITOR_UNIT_ID_KEY),
+ isForceKeepVisible: vi.fn(() => false),
+ disableForceKeepVisible: vi.fn(),
+ };
+ controller._sheetInterceptorService = {
+ onWriteCell: vi.fn((_workbook, _worksheet, _row, _column, cellData) => cellData),
+ onValidateCell: vi.fn(() => true),
+ };
+ controller._commandService = {
+ syncExecuteCommand: vi.fn(() => true),
+ executeCommand: vi.fn(),
+ };
+ controller._univerInstanceService = {
+ getUnit: vi.fn((unitId: string) => unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY ? docModel : workbook),
+ getCurrentUnitOfType: vi.fn(() => workbook),
+ setCurrentUnitForType: vi.fn(),
+ };
+ const workbookSelections = {
+ getCurrentLastSelection: vi.fn(() => ({ range: { startRow: 1, startColumn: 1, endRow: 4, endColumn: 4 } })),
+ getSelectionsOfWorksheet: vi.fn(() => [{ range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 } }]),
+ };
+ controller._selectionManagerService = {
+ getWorkbookSelections: vi.fn(() => workbookSelections),
+ };
+ controller._renderManagerService = {
+ getRenderById: vi.fn(() => ({
+ scene: {
+ getViewport: vi.fn((key) => key === DOC_VIEWPORT_KEY.VIEW_MAIN
+ ? { scrollToViewportPos: vi.fn() }
+ : null),
+ },
+ with: vi.fn(() => ({ resetInitialWidth: vi.fn() })),
+ })),
+ };
+ controller._getEditorObject = vi.fn(() => ({
+ scene: {
+ getViewport: vi.fn((key) => key === DOC_VIEWPORT_KEY.VIEW_MAIN
+ ? { scrollToViewportPos: vi.fn() }
+ : null),
+ },
+ }));
+ controller._getEditorSkeleton = vi.fn(() => ({ resetInitialWidth: vi.fn() }));
+
+ return { controller, docModel, workbook, worksheet };
+}
+
+describe('EditingRenderController business methods', () => {
+ it('submits edited cell content and rolls back when validation rejects the value', async () => {
+ const { controller } = createController();
+ controller._sheetInterceptorService.onValidateCell.mockResolvedValue(false);
+
+ const result = await controller._submitEdit({
+ body: { dataStream: 'new value\r\n' },
+ documentStyle: {},
+ });
+
+ expect(result).toBe(false);
+ expect(controller._sheetInterceptorService.onWriteCell).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 2, 3, {
+ v: 'new value',
+ f: null,
+ si: null,
+ p: null,
+ });
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 },
+ value: { v: 'new value', f: null, si: null, p: null },
+ }));
+ expect(controller._undoRedoService.rollback).toHaveBeenCalledWith(expect.any(String), 'unit-1');
+ });
+
+ it('uses the whole current selection when committing an array edit', async () => {
+ const { controller } = createController();
+
+ await controller._submitEdit({
+ body: { dataStream: 'fill\r\n' },
+ documentStyle: {},
+ }, true);
+
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({
+ range: { startRow: 1, startColumn: 1, endRow: 4, endColumn: 4 },
+ }));
+ expect(controller._undoRedoService.rollback).not.toHaveBeenCalled();
+ });
+
+ it('moves sheet selection after finishing edit and switches back to the edited workbook when needed', () => {
+ const { controller } = createController();
+ controller._univerInstanceService.getCurrentUnitOfType.mockReturnValue({ getUnitId: () => 'other-unit' });
+
+ controller._moveSelection(KeyCode.ENTER, 'unit-1', 'sheet-1');
+ controller._moveSelection(KeyCode.ARROW_LEFT, 'unit-1', 'sheet-1');
+ controller._moveSelection(undefined, 'unit-1', 'sheet-1');
+
+ expect(controller._univerInstanceService.setCurrentUnitForType).toHaveBeenCalledWith('unit-1');
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionEnterAndTabCommand.id, {
+ keycode: KeyCode.ENTER,
+ direction: 2,
+ });
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionCommand.id, {
+ direction: 3,
+ });
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ subUnitId: 'sheet-1',
+ }));
+ });
+
+ it('moves the cursor inside the editor and resets editor state on exit', () => {
+ const { controller } = createController();
+
+ controller._moveInEditor(KeyCode.ARROW_RIGHT, false);
+ controller._moveInEditor(KeyCode.ARROW_UP, true);
+ controller._exitInput({ visible: false });
+
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveCursorOperation.id, { direction: 1 });
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(MoveSelectionOperation.id, { direction: 0 });
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(EDITOR_ACTIVATED, false);
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_EDITOR_BUT_HIDDEN, false);
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_FX_BAR_EDITOR, false);
+ expect(controller._cellEditorManagerService.setState).toHaveBeenCalledWith({ show: false });
+ expect(controller._undoRedoService.clearUndoRedo).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ expect(controller._undoRedoService.clearUndoRedo).toHaveBeenCalledWith(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts
new file mode 100644
index 0000000000..2b048fd37e
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/formula-editor.controller.spec.ts
@@ -0,0 +1,135 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ EDITOR_ACTIVATED,
+ FOCUSING_EDITOR_BUT_HIDDEN,
+ FOCUSING_FX_BAR_EDITOR,
+} from '@univerjs/core';
+import { CoverContentCommand, VIEWPORT_KEY as DOC_VIEWPORT_KEY } from '@univerjs/docs-ui';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
+import { FormulaEditorController } from '../formula-editor.controller';
+
+function createController() {
+ const fxBtnClick$ = new Subject<void>();
+ const position = { width: 240, height: 40 };
+ const contextValues = new Map<string, unknown>([
+ [FOCUSING_EDITOR_BUT_HIDDEN, true],
+ [EDITOR_ACTIVATED, false],
+ ]);
+ const scrollBar = { dispose: vi.fn() };
+ const viewport = {
+ getScrollBar: vi.fn(() => scrollBar),
+ scrollToViewportPos: vi.fn(),
+ resetCanvasSizeAndUpdateScroll: vi.fn(),
+ };
+ const scene = { transformByState: vi.fn(), getViewport: vi.fn((key) => key === DOC_VIEWPORT_KEY.VIEW_MAIN ? viewport : null) };
+ const mainComponent = { resize: vi.fn() };
+ const formulaDoc = {
+ getBody: vi.fn(() => ({ dataStream: 'SUM(A1:A3)\r\n' })),
+ getSnapshot: vi.fn(() => ({ documentStyle: { marginTop: 4, marginBottom: 6 } })),
+ updateDocumentDataPageSize: vi.fn(),
+ };
+ const render = {
+ scene,
+ mainComponent,
+ with: vi.fn(() => ({
+ getSkeleton: vi.fn(() => ({
+ getActualSize: vi.fn(() => ({ actualHeight: 24 })),
+ })),
+ })),
+ };
+ const controller = Object.create(FormulaEditorController.prototype) as any;
+ controller.dispose$ = new Subject<void>();
+ controller._formulaEditorManagerService = {
+ fxBtnClick$,
+ getPosition: vi.fn(() => position),
+ position$: new Subject(),
+ };
+ controller._renderManagerService = {
+ getRenderById: vi.fn((unitId: string) => unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY ? render : null),
+ };
+ controller._univerInstanceService = {
+ setCurrentUnitForType: vi.fn(),
+ getUniverDocInstance: vi.fn(() => formulaDoc),
+ };
+ controller._editorBridgeService = { isVisible: vi.fn(() => ({ visible: false })) };
+ controller._commandService = { syncExecuteCommand: vi.fn() };
+ controller._contextService = {
+ getContextValue: vi.fn((key: string) => contextValues.get(key)),
+ setContextValue: vi.fn((key: string, value: unknown) => contextValues.set(key, value)),
+ };
+ controller._textSelectionManagerService = { replaceDocRanges: vi.fn() };
+
+ return {
+ controller,
+ fxBtnClick$,
+ formulaDoc,
+ mainComponent,
+ scene,
+ scrollBar,
+ viewport,
+ };
+}
+
+describe('FormulaEditorController business methods', () => {
+ it('resizes the formula editor and resets scroll when content fits in the formula bar', () => {
+ const { controller, mainComponent, scene, scrollBar, viewport } = createController();
+
+ controller.autoScroll();
+
+ expect(scene.transformByState).toHaveBeenCalledWith({ width: 240, height: 34 });
+ expect(mainComponent.resize).toHaveBeenCalledWith(240, 34);
+ expect(viewport.scrollToViewportPos).toHaveBeenCalledWith({ viewportScrollX: 0, viewportScrollY: 0 });
+ expect(scrollBar.dispose).toHaveBeenCalled();
+ });
+
+ it('turns hidden formula-bar content into a formula when fx button is clicked', () => {
+ const { controller, fxBtnClick$ } = createController();
+ const raf = vi.spyOn(globalThis, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => {
+ cb(0);
+ return 1;
+ });
+
+ controller._listenFxBtnClick();
+ fxBtnClick$.next();
+
+ expect(controller._univerInstanceService.setCurrentUnitForType).toHaveBeenCalledWith(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ });
+ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(CoverContentCommand.id, {
+ unitId: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: '=SUM(A1:A3)' },
+ segmentId: '',
+ textRanges: [{ startOffset: 11, endOffset: 11 }],
+ });
+ expect(controller._textSelectionManagerService.replaceDocRanges).toHaveBeenCalledWith([], {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+ expect(controller._contextService.setContextValue).toHaveBeenCalledWith(FOCUSING_FX_BAR_EDITOR, true);
+
+ raf.mockRestore();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.controller.spec.ts b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.controller.spec.ts
new file mode 100644
index 0000000000..4e9d742891
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.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 { UnitAction } from '@univerjs/protocol';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEET_PERMISSION_PASTE_PLUGIN, SheetPermissionInterceptorClipboardController } from '../sheet-permission-interceptor-clipboard.controller';
+
+function createController(protectedCell?: { row: number; col: number }) {
+ let hook: any;
+ const worksheet = {
+ getCell: vi.fn((row: number, col: number) => protectedCell?.row === row && protectedCell?.col === col
+ ? { selectionProtection: [{ [UnitAction.Edit]: false }] }
+ : { selectionProtection: [{ [UnitAction.Edit]: true }] }),
+ };
+ const workbook = { getActiveSheet: vi.fn(() => worksheet) };
+ const permissionCheckController = { blockExecuteWithoutPermission: vi.fn() };
+ const controller = new SheetPermissionInterceptorClipboardController(
+ { getCurrentUnitOfType: vi.fn(() => workbook) } as any,
+ {
+ getCurrentLastSelection: vi.fn(() => ({
+ range: { startRow: 5, startColumn: 7 },
+ })),
+ } as any,
+ { t: vi.fn((key: string) => `translated:${key}`) } as any,
+ {
+ addClipboardHook: vi.fn((registeredHook) => {
+ hook = registeredHook;
+ return { dispose: vi.fn() };
+ }),
+ } as any,
+ permissionCheckController as any
+ );
+
+ return { controller, hook, permissionCheckController, worksheet };
+}
+
+describe('SheetPermissionInterceptorClipboardController', () => {
+ it('allows paste when the target range has edit permission', () => {
+ const { controller, hook, permissionCheckController } = createController();
+
+ expect(hook.id).toBe(SHEET_PERMISSION_PASTE_PLUGIN);
+ expect(hook.onBeforePaste({
+ range: {
+ rows: [0, 1],
+ cols: [0, 1],
+ },
+ })).toBe(true);
+ expect(permissionCheckController.blockExecuteWithoutPermission).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('blocks paste and shows permission feedback when any pasted cell is protected', () => {
+ const { controller, hook, permissionCheckController, worksheet } = createController({ row: 6, col: 8 });
+
+ expect(hook.onBeforePaste({
+ range: {
+ rows: [0, 1],
+ cols: [0, 1],
+ },
+ })).toBe(false);
+ expect(worksheet.getCell).toHaveBeenCalledWith(6, 8);
+ expect(permissionCheckController.blockExecuteWithoutPermission).toHaveBeenCalledWith('translated:sheets-ui.permission.dialog.pasteErr');
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-formula-render.controller.spec.ts b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-formula-render.controller.spec.ts
new file mode 100644
index 0000000000..8ab4e48dcb
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-formula-render.controller.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 { NullValueObject } from '@univerjs/engine-formula';
+import { UnitAction } from '@univerjs/protocol';
+import { WorksheetViewPermission } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetPermissionInterceptorFormulaRenderController } from '../sheet-permission-interceptor-formula-render.controller';
+
+function createFormulaValue(values: unknown[][], row = 3, col = 4) {
+ return {
+ getArrayValue: vi.fn(() => values),
+ getCurrentRow: vi.fn(() => row),
+ getCurrentColumn: vi.fn(() => col),
+ };
+}
+
+function createController(options?: { sheetViewable?: boolean; protectedCell?: { row: number; col: number } }) {
+ let handler: any;
+ const univerInstanceService = {
+ getCurrentUnitOfType: vi.fn(() => ({
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({
+ getSheetId: () => 'sheet-1',
+ getCellRaw: vi.fn(() => ({ v: 'raw' })),
+ }),
+ })),
+ };
+ const statusBarController = {
+ interceptor: {
+ getInterceptPoints: vi.fn(() => ({ STATUS_BAR_PERMISSION_CORRECT: 'status-bar-permission' })),
+ intercept: vi.fn((_point, config) => {
+ handler = config.handler;
+ return { dispose: vi.fn() };
+ }),
+ },
+ };
+ const controller = new SheetPermissionInterceptorFormulaRenderController(
+ {} as any,
+ univerInstanceService as any,
+ {
+ getPermissionPoint: vi.fn((id: string) => ({
+ value: id === new WorksheetViewPermission('unit-1', 'sheet-1').id ? options?.sheetViewable ?? true : true,
+ })),
+ } as any,
+ statusBarController as any,
+ {
+ getCellInfo: vi.fn((_unitId: string, _sheetId: string, row: number, col: number) => (
+ options?.protectedCell?.row === row && options?.protectedCell?.col === col
+ ? { [UnitAction.View]: false }
+ : { [UnitAction.View]: true }
+ )),
+ } as any
+ );
+
+ return { controller, handler, statusBarController };
+}
+
+describe('SheetPermissionInterceptorFormulaRenderController', () => {
+ it('clears every formula result when worksheet view permission is denied', () => {
+ const { controller, handler } = createController({ sheetViewable: false });
+ const value = createFormulaValue([[1, 2], [3, 4]]);
+
+ const result = handler([], [value]);
+
+ expect(result).toEqual([value]);
+ expect(value.getArrayValue()).toEqual([
+ [NullValueObject.create(), NullValueObject.create()],
+ [NullValueObject.create(), NullValueObject.create()],
+ ]);
+
+ controller.dispose();
+ });
+
+ it('clears only protected cell values when worksheet is viewable', () => {
+ const { controller, handler } = createController({ protectedCell: { row: 3, col: 4 } });
+ const value = createFormulaValue([[1, 2], [3, 4]]);
+
+ handler([], [value]);
+
+ expect(value.getArrayValue()[0][0]).toEqual(NullValueObject.create());
+ expect(value.getArrayValue()[0][1]).toBe(2);
+ expect(value.getArrayValue()[1][0]).toBe(3);
+ expect(value.getArrayValue()[1][1]).toBe(4);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-render.controller.spec.ts b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-render.controller.spec.ts
new file mode 100644
index 0000000000..228c173bd7
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-render.controller.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 { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ SheetPermissionRenderController,
+ WorksheetProtectionRenderController,
+} from '../sheet-permission-render.controller';
+
+describe('permission render controllers', () => {
+ it('registers range protection render extensions and marks skeleton dirty on permission changes', () => {
+ const permissionPointUpdate$ = new Subject<any>();
+ const rangeRuleInitStateChange$ = new Subject<any>();
+ const ruleChange$ = new Subject<any>();
+ const spreadsheet = {
+ getExtensionByKey: vi.fn(() => null),
+ register: vi.fn(),
+ makeDirty: vi.fn(),
+ };
+ const skeletonManagerService = { reCalculate: vi.fn() };
+
+ const controller = new SheetPermissionRenderController(
+ { mainComponent: spreadsheet } as any,
+ { rangeRuleInitStateChange$, ruleChange$ } as any,
+ skeletonManagerService as any,
+ { permissionPointUpdate$ } as any,
+ { getConfig: vi.fn(() => ({ protectedRangeShadow: 'always' })) } as any
+ );
+
+ expect(spreadsheet.register).toHaveBeenCalledTimes(2);
+
+ rangeRuleInitStateChange$.next({});
+ expect(skeletonManagerService.reCalculate).toHaveBeenCalled();
+ expect(spreadsheet.makeDirty).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('skips duplicate range protection extensions and clears render caches when rules change', () => {
+ const ruleChange$ = new Subject<any>();
+ const spreadsheet = {
+ getExtensionByKey: vi.fn(() => ({ alreadyRegistered: true })),
+ register: vi.fn(),
+ makeDirty: vi.fn(),
+ };
+ const controller = new SheetPermissionRenderController(
+ { mainComponent: spreadsheet } as any,
+ { rangeRuleInitStateChange$: new Subject(), ruleChange$ } as any,
+ { reCalculate: vi.fn() } as any,
+ { permissionPointUpdate$: new Subject() } as any,
+ { getConfig: vi.fn(() => ({ protectedRangeShadow: 'always' })) } as any
+ );
+
+ const canView = (controller as any)._rangeProtectionCanViewRenderExtension;
+ const canNotView = (controller as any)._rangeProtectionCanNotViewRenderExtension;
+ vi.spyOn(canView, 'clearCache');
+ vi.spyOn(canNotView, 'clearCache');
+ canView.renderCache.add('old-rule');
+ canNotView.renderCache.add('new-rule');
+ ruleChange$.next({ oldRule: { id: 'old-rule' }, rule: { id: 'new-rule' } });
+
+ expect(spreadsheet.register).not.toHaveBeenCalled();
+ expect(canView.clearCache).toHaveBeenCalled();
+ expect(canNotView.clearCache).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('registers worksheet protection extension unless shadow rendering is disabled', () => {
+ const worksheetRuleInitStateChange$ = new Subject<any>();
+ const spreadsheet = {
+ getExtensionByKey: vi.fn(() => null),
+ register: vi.fn(),
+ makeDirty: vi.fn(),
+ };
+ const skeletonManagerService = { reCalculate: vi.fn() };
+ const renderManagerService = { getRenderById: vi.fn(() => ({ mainComponent: spreadsheet })) };
+ const controller = new WorksheetProtectionRenderController(
+ { unitId: 'unit-1', mainComponent: spreadsheet } as any,
+ renderManagerService as any,
+ skeletonManagerService as any,
+ { worksheetRuleInitStateChange$ } as any,
+ { getConfig: vi.fn(() => ({ protectedRangeShadow: 'always' })) } as any
+ );
+
+ expect(spreadsheet.register).toHaveBeenCalledTimes(1);
+ worksheetRuleInitStateChange$.next({});
+ expect(skeletonManagerService.reCalculate).toHaveBeenCalled();
+ expect(spreadsheet.makeDirty).toHaveBeenCalled();
+ controller.dispose();
+
+ const disabledSpreadsheet = { getExtensionByKey: vi.fn(), register: vi.fn() };
+ const disabledController = new WorksheetProtectionRenderController(
+ { unitId: 'unit-1', mainComponent: disabledSpreadsheet } as any,
+ { getRenderById: vi.fn(() => ({ mainComponent: disabledSpreadsheet })) } as any,
+ { reCalculate: vi.fn() } as any,
+ { worksheetRuleInitStateChange$: new Subject() } as any,
+ { getConfig: vi.fn(() => ({ protectedRangeShadow: 'none' })) } as any
+ );
+
+ expect(disabledSpreadsheet.register).not.toHaveBeenCalled();
+ disabledController.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/contextmenu-render-business.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/contextmenu-render-business.spec.ts
new file mode 100644
index 0000000000..d7707b8e9d
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/contextmenu-render-business.spec.ts
@@ -0,0 +1,109 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { RANGE_TYPE } from '@univerjs/core';
+import { ContextMenuPosition } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import { SheetContextMenuRenderController } from '../contextmenu.render-controller';
+
+function createEventSubject() {
+ const handlers = new Set<(evt: any) => void>();
+
+ return {
+ subscribeEvent: vi.fn((handler: (evt: any) => void) => {
+ handlers.add(handler);
+ return { dispose: vi.fn(() => handlers.delete(handler)) };
+ }),
+ emit: (evt: any) => handlers.forEach((handler) => handler(evt)),
+ };
+}
+
+function createController(rangeType = RANGE_TYPE.NORMAL) {
+ const mainPointerDown$ = createEventSubject();
+ const rowHeaderPointerDown$ = createEventSubject();
+ const columnHeaderPointerDown$ = createEventSubject();
+ const contextMenuService = { triggerContextMenu: vi.fn() };
+ const selection = {
+ range: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ rangeType,
+ },
+ };
+ const skeleton = {
+ getNoMergeCellWithCoordByIndex: vi.fn((row: number, col: number) => ({
+ startX: col * 50,
+ endX: col * 50 + 49,
+ startY: row * 20,
+ endY: row * 20 + 19,
+ })),
+ };
+ const controller = new SheetContextMenuRenderController(
+ {
+ mainComponent: { onPointerDown$: mainPointerDown$ },
+ components: new Map([
+ [SHEET_VIEW_KEY.ROW, { onPointerDown$: rowHeaderPointerDown$ }],
+ [SHEET_VIEW_KEY.COLUMN, { onPointerDown$: columnHeaderPointerDown$ }],
+ ]),
+ } as any,
+ contextMenuService as any,
+ { getCurrentSelections: vi.fn(() => [selection]) } as any,
+ { getSkeleton: vi.fn(() => skeleton) } as any
+ );
+
+ return {
+ columnHeaderPointerDown$,
+ contextMenuService,
+ controller,
+ mainPointerDown$,
+ rowHeaderPointerDown$,
+ };
+}
+
+describe('SheetContextMenuRenderController business flows', () => {
+ it('opens the main-area menu for right-clicks inside and outside normal cell selections', () => {
+ const { contextMenuService, controller, mainPointerDown$ } = createController();
+
+ mainPointerDown$.emit({ button: 0, offsetX: 60, offsetY: 30 });
+ expect(contextMenuService.triggerContextMenu).not.toHaveBeenCalled();
+
+ mainPointerDown$.emit({ button: 2, offsetX: 60, offsetY: 30 });
+ mainPointerDown$.emit({ button: 2, offsetX: 500, offsetY: 300 });
+ expect(contextMenuService.triggerContextMenu).toHaveBeenNthCalledWith(1, expect.objectContaining({ button: 2 }), ContextMenuPosition.MAIN_AREA);
+ expect(contextMenuService.triggerContextMenu).toHaveBeenNthCalledWith(2, expect.objectContaining({ button: 2 }), ContextMenuPosition.MAIN_AREA);
+
+ controller.dispose();
+ });
+
+ it('uses row and column menu positions for header selections and header components', () => {
+ const row = createController(RANGE_TYPE.ROW);
+ row.mainPointerDown$.emit({ button: 2, offsetX: 10, offsetY: 25 });
+ row.rowHeaderPointerDown$.emit({ button: 2, offsetX: 10, offsetY: 25 });
+ expect(row.contextMenuService.triggerContextMenu).toHaveBeenNthCalledWith(1, expect.any(Object), ContextMenuPosition.ROW_HEADER);
+ expect(row.contextMenuService.triggerContextMenu).toHaveBeenNthCalledWith(2, expect.any(Object), ContextMenuPosition.ROW_HEADER);
+ row.controller.dispose();
+
+ const column = createController(RANGE_TYPE.COLUMN);
+ column.mainPointerDown$.emit({ button: 2, offsetX: 75, offsetY: 10 });
+ column.columnHeaderPointerDown$.emit({ button: 2, offsetX: 75, offsetY: 10 });
+ expect(column.contextMenuService.triggerContextMenu).toHaveBeenNthCalledWith(1, expect.any(Object), ContextMenuPosition.COL_HEADER);
+ expect(column.contextMenuService.triggerContextMenu).toHaveBeenNthCalledWith(2, expect.any(Object), ContextMenuPosition.COL_HEADER);
+ column.controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.ts
new file mode 100644
index 0000000000..66457f93dd
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.ts
@@ -0,0 +1,281 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET } from '@univerjs/core';
+import { DocSelectionRenderService } from '@univerjs/docs-ui';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import { ClearSelectionFormatCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SetZoomRatioCommand } from '../../../commands/commands/set-zoom-ratio.command';
+import { SetActivateCellEditOperation } from '../../../commands/operations/activate-cell-edit.operation';
+import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import { EditorBridgeRenderController } from '../editor-bridge.render-controller';
+
+function createEventSubject() {
+ const handlers = new Set<(evt: any) => void>();
+
+ return {
+ subscribeEvent: vi.fn((arg: any) => {
+ const handler = typeof arg === 'function' ? arg : arg.next;
+ handlers.add(handler);
+ return { dispose: vi.fn(() => handlers.delete(handler)) };
+ }),
+ emit: (evt: any) => handlers.forEach((handler) => handler(evt)),
+ };
+}
+
+function createCommandService() {
+ const afterHandlers = new Set<(command: any, options?: any) => void>();
+ const beforeHandlers = new Set<(command: any, options?: any) => void>();
+
+ return {
+ executeCommand: vi.fn(),
+ syncExecuteCommand: vi.fn(),
+ onCommandExecuted: vi.fn((handler: (command: any, options?: any) => void) => {
+ afterHandlers.add(handler);
+ return { dispose: vi.fn(() => afterHandlers.delete(handler)) };
+ }),
+ beforeCommandExecuted: vi.fn((handler: (command: any, options?: any) => void) => {
+ beforeHandlers.add(handler);
+ return { dispose: vi.fn(() => beforeHandlers.delete(handler)) };
+ }),
+ emitAfter: (command: any, options?: any) => afterHandlers.forEach((handler) => handler(command, options)),
+ emitBefore: (command: any, options?: any) => beforeHandlers.forEach((handler) => handler(command, options)),
+ };
+}
+
+function createController(options?: { editorVisible?: boolean; forceKeepVisible?: boolean; focusedUnitId?: string }) {
+ const workbook$ = new Subject<any>();
+ const selectionMoveEnd$ = new Subject<any>();
+ const selectionMoveStart$ = new Subject<any>();
+ const selectionSet$ = new Subject<any>();
+ const inputBefore$ = new Subject<any>();
+ const spreadsheet = {
+ onDblclick$: createEventSubject(),
+ onPointerDown$: createEventSubject(),
+ };
+ const spreadsheetRowHeader = { onPointerDown$: createEventSubject() };
+ const spreadsheetColumnHeader = { onPointerDown$: createEventSubject() };
+ const spreadsheetLeftTopPlaceholder = { onPointerDown$: createEventSubject() };
+ const scene = {};
+ const engine = {};
+ const worksheet = { getSheetId: vi.fn(() => 'sheet-1') };
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit-1'),
+ getActiveSheet: vi.fn(() => worksheet),
+ getCurrentUnitOfType: vi.fn(() => null as any),
+ };
+ workbook.getCurrentUnitOfType.mockReturnValue(workbook as any);
+ const commandService = createCommandService();
+ const contextValues = new Map<string, unknown>([
+ [FOCUSING_SHEET, true],
+ [FOCUSING_FX_BAR_EDITOR, false],
+ ]);
+ const context = {
+ unitId: 'unit-1',
+ unit: workbook,
+ isMainScene: true,
+ scene,
+ engine,
+ mainComponent: spreadsheet,
+ components: new Map([
+ [SHEET_VIEW_KEY.ROW, spreadsheetRowHeader],
+ [SHEET_VIEW_KEY.COLUMN, spreadsheetColumnHeader],
+ [SHEET_VIEW_KEY.LEFT_TOP, spreadsheetLeftTopPlaceholder],
+ ]),
+ };
+ const docSelectionRenderService = { onInputBefore$: inputBefore$ };
+ const renderManagerService = {
+ created$: new Subject<any>(),
+ getRenderById: vi.fn((unitId: string) => unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY
+ ? {
+ unitId,
+ with: vi.fn((token) => token === DocSelectionRenderService ? docSelectionRenderService : null),
+ }
+ : null),
+ };
+ const editorBridgeService = {
+ isVisible: vi.fn(() => ({ visible: options?.editorVisible ?? false })),
+ isForceKeepVisible: vi.fn(() => options?.forceKeepVisible ?? false),
+ refreshEditCellState: vi.fn(),
+ };
+ const controller = new EditorBridgeRenderController(
+ context as any,
+ {
+ getCurrentTypeOfUnit$: vi.fn(() => workbook$),
+ getFocusedUnit: vi.fn(() => ({
+ getUnitId: () => options?.focusedUnitId ?? 'unit-1',
+ })),
+ } as any,
+ commandService as any,
+ editorBridgeService as any,
+ {
+ selectionMoveEnd$,
+ selectionMoveStart$,
+ selectionSet$,
+ getWorkbookSelections: vi.fn(() => ({
+ getCurrentSelections: vi.fn(() => [{
+ primary: {
+ actualRow: 3,
+ actualColumn: 4,
+ startRow: 3,
+ startColumn: 4,
+ endRow: 3,
+ endColumn: 4,
+ },
+ }]),
+ })),
+ } as any,
+ {
+ getContextValue: vi.fn((key: string) => contextValues.get(key)),
+ setContextValue: vi.fn((key: string, value: unknown) => contextValues.set(key, value)),
+ } as any,
+ renderManagerService as any,
+ {
+ getSkeletonParam: vi.fn(() => ({
+ skeleton: {
+ getCellWithCoordByIndex: vi.fn(() => ({
+ actualRow: 1,
+ actualColumn: 2,
+ isMerged: true,
+ isMergedMainCell: true,
+ mergeInfo: {
+ startRow: 1,
+ startColumn: 2,
+ endRow: 4,
+ endColumn: 5,
+ },
+ })),
+ },
+ })),
+ } as any
+ );
+ workbook$.next(workbook);
+
+ return {
+ commandService,
+ controller,
+ editorBridgeService,
+ inputBefore$,
+ selectionMoveEnd$,
+ selectionSet$,
+ spreadsheet,
+ spreadsheetColumnHeader,
+ spreadsheetLeftTopPlaceholder,
+ spreadsheetRowHeader,
+ workbook,
+ };
+}
+
+describe('EditorBridgeRenderController business flows', () => {
+ it('moves the sheet editor to the latest selected cell and respects merged-cell coordinates', () => {
+ const { commandService, controller, selectionMoveEnd$ } = createController();
+
+ selectionMoveEnd$.next([{
+ primary: {
+ actualRow: 3,
+ actualColumn: 4,
+ startRow: 3,
+ startColumn: 4,
+ endRow: 3,
+ endColumn: 4,
+ },
+ }]);
+
+ expect(commandService.executeCommand).toHaveBeenCalledWith(SetActivateCellEditOperation.id, {
+ scene: expect.any(Object),
+ engine: expect.any(Object),
+ primary: {
+ actualRow: 1,
+ actualColumn: 2,
+ isMerged: true,
+ startRow: 1,
+ startColumn: 2,
+ endRow: 4,
+ endColumn: 5,
+ isMergedMainCell: true,
+ },
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ });
+
+ controller.refreshEditorPosition();
+ expect(commandService.executeCommand).toHaveBeenCalledTimes(2);
+
+ controller.dispose();
+ });
+
+ it('opens sheet editing from double click and keyboard input, then refreshes a hidden editor after formatting commands', () => {
+ const { commandService, controller, editorBridgeService, inputBefore$, spreadsheet } = createController();
+
+ spreadsheet.onDblclick$.emit({ button: 2 });
+ expect(commandService.executeCommand).not.toHaveBeenCalledWith(SetCellEditVisibleOperation.id, expect.anything());
+
+ spreadsheet.onDblclick$.emit({ button: 0 });
+ expect(commandService.executeCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'unit-1',
+ });
+
+ inputBefore$.next({ event: { data: 'A', which: 65 } });
+ inputBefore$.next({ event: { inputType: 'deleteContentBackward', which: 8 } });
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(1);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {
+ visible: true,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: 65,
+ unitId: 'unit-1',
+ });
+
+ commandService.emitAfter({ id: ClearSelectionFormatCommand.id });
+ commandService.emitAfter({ id: SetZoomRatioCommand.id });
+ expect(editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(2);
+
+ controller.dispose();
+ });
+
+ it('hides a visible editor from sheet pointer actions but keeps it while formula range input is active', () => {
+ const keepVisible = createController({ editorVisible: true, forceKeepVisible: true });
+ keepVisible.spreadsheet.onPointerDown$.emit({});
+ expect(keepVisible.commandService.syncExecuteCommand).not.toHaveBeenCalled();
+ keepVisible.controller.dispose();
+
+ const normal = createController({ editorVisible: true });
+ normal.spreadsheetColumnHeader.onPointerDown$.emit({});
+ expect(normal.commandService.syncExecuteCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: 'unit-1',
+ });
+
+ normal.commandService.syncExecuteCommand.mockClear();
+ normal.commandService.emitBefore({ id: SetWorksheetActiveOperation.id });
+ expect(normal.commandService.syncExecuteCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: 'unit-1',
+ });
+
+ normal.commandService.syncExecuteCommand.mockClear();
+ normal.commandService.emitBefore({ id: SetWorksheetActiveOperation.id }, { fromCollab: true });
+ expect(normal.commandService.syncExecuteCommand).not.toHaveBeenCalled();
+
+ normal.controller.dispose();
+ });
+});
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
index 7e6c7ee6fd..18ea288d26 100644
--- 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
@@ -16,9 +16,9 @@
import { ICommandService } from '@univerjs/core';
import { SHEET_VIEWPORT_KEY, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
-import { SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SetFrozenCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';
import { BehaviorSubject } from 'rxjs';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
import { HeaderFreezeRenderController } from '../freeze.render-controller';
import { createRenderTestBed } from './render-test-bed';
@@ -225,4 +225,57 @@ describe('HeaderFreezeRenderController', () => {
testBed.univer.dispose();
});
+
+ it('updates sheet freeze config after dragging the row freeze divider', () => {
+ 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, context, scene, viewportMap, commandService } = testBed;
+ const controller = injector.createInstance(HeaderFreezeRenderController, context as any);
+ const executeCommand = vi.spyOn(commandService, 'executeCommand');
+ const worksheet = sheet.getActiveSheet();
+ worksheet.getConfig().freeze = { startRow: 2, startColumn: -1, ySplit: 2, xSplit: 0 };
+ (viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) as any).isHit = () => true;
+
+ const headerRect = {
+ transformByState: vi.fn(() => headerRect),
+ setProps: vi.fn(() => headerRect),
+ };
+ const mainRect = {
+ transformByState: vi.fn(() => mainRect),
+ setProps: vi.fn(() => mainRect),
+ };
+
+ (controller as any)._freezeDown({ offsetX: 120, offsetY: 40 }, headerRect, mainRect);
+ scene.onPointerMove$.emit({ offsetX: 120, offsetY: 90 }, { stopPropagation: () => { } });
+ scene.onPointerUp$.emit({}, { stopPropagation: () => { } });
+
+ expect(scene.getViewports().some((viewport: any) => viewport.isHit?.({ x: 120, y: 90 }))).toBe(true);
+ expect(headerRect.transformByState).toHaveBeenCalledWith({ top: 79 });
+ expect(mainRect.transformByState).toHaveBeenCalledWith({ top: 79 });
+ expect(executeCommand).toHaveBeenCalledWith(SetFrozenCommand.id, {
+ startRow: 4,
+ startColumn: -1,
+ ySplit: 4,
+ xSplit: 0,
+ unitId: sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ });
+
+ testBed.univer.dispose();
+ });
});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet-render-business.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet-render-business.spec.ts
new file mode 100644
index 0000000000..c70a6b11a2
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/sheet-render-business.spec.ts
@@ -0,0 +1,324 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CommandType } from '@univerjs/core';
+import { SetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';
+import { SHEET_EXTENSION_PREFIX, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { MoveRangeMutation, SetRangeValuesMutation } from '@univerjs/sheets';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import { SheetRenderController } from '../sheet.render-controller';
+
+const renderClasses = vi.hoisted(() => {
+ class FakeComponent {
+ key: string;
+ updateSkeleton = vi.fn();
+ transformByState = vi.fn();
+ makeDirty = vi.fn();
+ setDirtyArea = vi.fn();
+
+ constructor(key: string) {
+ this.key = key;
+ }
+ }
+
+ class FakeSpreadsheet extends FakeComponent {}
+ class FakeSpreadsheetRowHeader extends FakeComponent {}
+ class FakeSpreadsheetColumnHeader extends FakeComponent {}
+ class FakeRect extends FakeComponent {
+ options: unknown;
+
+ constructor(key: string, options: unknown) {
+ super(key);
+ this.options = options;
+ }
+ }
+
+ class FakeViewport {
+ viewportKey: string;
+ options: Record<string, unknown>;
+ isActive = true;
+ cacheBound = { top: 0, left: 0, bottom: 500, right: 500 };
+ markDirty = vi.fn();
+
+ constructor(viewportKey: string, scene: any, options: Record<string, unknown> = {}) {
+ this.viewportKey = viewportKey;
+ this.options = options;
+ scene.__viewports.push(this);
+ }
+ }
+
+ class FakeScrollBar {
+ constructor(viewport: FakeViewport, options?: unknown) {
+ (viewport as any).scrollBarOptions = options;
+ }
+ }
+
+ return {
+ FakeRect,
+ FakeScrollBar,
+ FakeSpreadsheet,
+ FakeSpreadsheetColumnHeader,
+ FakeSpreadsheetRowHeader,
+ FakeViewport,
+ };
+});
+
+vi.mock('@univerjs/engine-render', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/engine-render')>();
+
+ return {
+ ...actual,
+ Rect: renderClasses.FakeRect,
+ ScrollBar: renderClasses.FakeScrollBar,
+ Spreadsheet: renderClasses.FakeSpreadsheet,
+ SpreadsheetColumnHeader: renderClasses.FakeSpreadsheetColumnHeader,
+ SpreadsheetRowHeader: renderClasses.FakeSpreadsheetRowHeader,
+ Viewport: renderClasses.FakeViewport,
+ };
+});
+
+function createCommandService() {
+ const handlers = new Set<(command: any, options?: any) => void>();
+
+ return {
+ onCommandExecuted: vi.fn((handler: (command: any, options?: any) => void) => {
+ handlers.add(handler);
+ return { dispose: vi.fn(() => handlers.delete(handler)) };
+ }),
+ emit: (command: any, options?: any) => handlers.forEach((handler) => handler(command, options)),
+ };
+}
+
+function createController() {
+ const activated$ = new BehaviorSubject(true);
+ const currentSkeleton$ = new Subject<any>();
+ const commandService = createCommandService();
+ const scene = {
+ __viewports: [] as any[],
+ render: vi.fn(),
+ addObjects: vi.fn(),
+ enableLayerCache: vi.fn(),
+ attachControl: vi.fn(),
+ makeDirty: vi.fn(),
+ getViewports: vi.fn(function (this: any) {
+ return this.__viewports;
+ }),
+ };
+ const engine = {
+ beginFrame$: new Subject<void>(),
+ endFrame$: new Subject<any>(),
+ renderFrameTimeMetric$: new Subject<[string, number]>(),
+ renderFrameTags$: new Subject<[string, unknown]>(),
+ runRenderLoop: vi.fn(),
+ stopRenderLoop: vi.fn(),
+ };
+ const worksheet = {
+ getSheetId: vi.fn(() => 'sheet-1'),
+ getConfig: vi.fn(() => ({
+ rowHeader: { width: 46 },
+ columnHeader: { height: 20 },
+ })),
+ };
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit-1'),
+ getActiveSheet: vi.fn(() => worksheet),
+ getSheetBySheetId: vi.fn(() => worksheet),
+ };
+ const skeleton = {
+ rowHeaderWidth: 46,
+ columnHeaderHeight: 20,
+ rowHeaderWidthAndMarginLeft: 66,
+ columnHeaderHeightAndMarginTop: 30,
+ rowHeightAccumulation: [20, 40, 60, 80, 100],
+ columnWidthAccumulation: [50, 100, 150, 200, 250],
+ };
+ const sheetSkeletonManagerService = {
+ currentSkeleton$,
+ setCurrent: vi.fn(),
+ makeDirty: vi.fn(),
+ reCalculate: vi.fn(),
+ getCurrentParam: vi.fn(() => ({ skeleton })),
+ };
+ const telemetryService = { capture: vi.fn() };
+ const context = {
+ unitId: 'unit-1',
+ unit: workbook,
+ scene,
+ engine,
+ activated$,
+ components: new Map(),
+ mainComponent: null as any,
+ };
+ const controller = new SheetRenderController(
+ context as any,
+ { getConfig: vi.fn(() => ({ scrollConfig: { barSize: 8 } })) } as any,
+ sheetSkeletonManagerService as any,
+ { checkMutationShouldTriggerRerender: vi.fn((id: string) => id === 'sheet.custom-rerender') } as any,
+ commandService as any,
+ telemetryService as any
+ );
+
+ return {
+ activated$,
+ commandService,
+ context,
+ controller,
+ engine,
+ scene,
+ sheetSkeletonManagerService,
+ skeleton,
+ telemetryService,
+ workbook,
+ worksheet,
+ };
+}
+
+describe('SheetRenderController business flows', () => {
+ it('creates sheet render components, viewports, and toggles the render loop with context activation', () => {
+ const { activated$, context, controller, engine, scene, sheetSkeletonManagerService } = createController();
+
+ expect(context.components.get(SHEET_VIEW_KEY.MAIN)).toBe(context.mainComponent);
+ expect(context.components.get(SHEET_VIEW_KEY.ROW)).toBeTruthy();
+ expect(context.components.get(SHEET_VIEW_KEY.COLUMN)).toBeTruthy();
+ expect(context.components.get(SHEET_VIEW_KEY.LEFT_TOP)).toBeTruthy();
+ expect(scene.addObjects).toHaveBeenCalledTimes(2);
+ expect(scene.enableLayerCache).toHaveBeenCalled();
+ expect(scene.attachControl).toHaveBeenCalled();
+ expect(scene.__viewports.map((viewport) => viewport.viewportKey)).toContain(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ expect(sheetSkeletonManagerService.setCurrent).toHaveBeenCalledWith({ sheetId: 'sheet-1' });
+ expect(engine.runRenderLoop).toHaveBeenCalledTimes(1);
+
+ const frameFn = engine.runRenderLoop.mock.calls[0][0];
+ frameFn();
+ expect(scene.render).toHaveBeenCalled();
+
+ activated$.next(false);
+ expect(engine.stopRenderLoop).toHaveBeenCalledWith(frameFn);
+ activated$.next(true);
+ expect(engine.runRenderLoop).toHaveBeenCalledWith(frameFn);
+
+ controller.dispose();
+ });
+
+ it('updates rendered sheet parts when a fresh skeleton is emitted', () => {
+ const { context, controller, sheetSkeletonManagerService, skeleton } = createController();
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as any;
+ const columnHeader = context.components.get(SHEET_VIEW_KEY.COLUMN) as any;
+ const placeholder = context.components.get(SHEET_VIEW_KEY.LEFT_TOP) as any;
+
+ sheetSkeletonManagerService.currentSkeleton$.next({ sheetId: 'sheet-1', skeleton });
+
+ expect(context.mainComponent.updateSkeleton).toHaveBeenCalledWith(skeleton);
+ expect(rowHeader.updateSkeleton).toHaveBeenCalledWith(skeleton);
+ expect(columnHeader.updateSkeleton).toHaveBeenCalledWith(skeleton);
+ expect(placeholder.transformByState).toHaveBeenCalledWith({ width: 66, height: 30 });
+
+ controller.dispose();
+ });
+
+ it('marks skeleton and dirty render areas for worksheet and value mutations', () => {
+ const { commandService, context, controller, scene, sheetSkeletonManagerService } = createController();
+ const mainViewport = scene.__viewports.find((viewport) => viewport.viewportKey === SHEET_VIEWPORT_KEY.VIEW_MAIN);
+
+ commandService.emit({
+ id: 'sheet.custom-rerender',
+ type: CommandType.MUTATION,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1' },
+ });
+ expect(sheetSkeletonManagerService.makeDirty).toHaveBeenCalledWith({
+ sheetId: 'sheet-1',
+ commandId: 'sheet.custom-rerender',
+ }, true);
+ expect(sheetSkeletonManagerService.setCurrent).toHaveBeenLastCalledWith({
+ sheetId: 'sheet-1',
+ commandId: 'sheet.custom-rerender',
+ });
+
+ commandService.emit({
+ id: SetRangeValuesMutation.id,
+ type: CommandType.MUTATION,
+ params: {
+ cellValue: {
+ 1: { 2: { v: 'A' } },
+ 2: { 3: { v: 'B' } },
+ },
+ },
+ });
+ expect(context.mainComponent.makeDirty).toHaveBeenCalled();
+ expect(scene.makeDirty).toHaveBeenCalled();
+ expect(mainViewport.markDirty).toHaveBeenCalledWith(true);
+ expect(context.mainComponent.setDirtyArea).toHaveBeenCalledWith([{
+ top: 0,
+ left: 0,
+ bottom: 80,
+ right: 246,
+ width: 246,
+ height: 80,
+ }]);
+
+ commandService.emit({
+ id: MoveRangeMutation.id,
+ type: CommandType.MUTATION,
+ params: {
+ fromRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ toRange: { startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 },
+ from: { value: { 0: { 0: {} } } },
+ to: { value: { 3: { 4: {} } } },
+ },
+ });
+ expect(context.mainComponent.setDirtyArea).toHaveBeenCalledTimes(2);
+
+ const dirtyCountBeforeCalculationNotification = scene.makeDirty.mock.calls.length;
+ commandService.emit({
+ id: SetFormulaCalculationNotificationMutation.id,
+ type: CommandType.MUTATION,
+ params: { stageInfo: { stage: 'calculating' } },
+ });
+ expect(scene.makeDirty).toHaveBeenCalledTimes(dirtyCountBeforeCalculationNotification);
+
+ controller.dispose();
+ });
+
+ it('summarizes sheet render frame metrics and captures telemetry after enough frames', () => {
+ const { controller, engine, telemetryService } = createController();
+ const metrics: any[] = [];
+ const subscription = controller.renderMetric$.subscribe((metric) => metrics.push(metric));
+
+ for (let i = 0; i < 62; i++) {
+ engine.beginFrame$.next();
+ engine.renderFrameTimeMetric$.next([`${SHEET_EXTENSION_PREFIX}_cell`, 1.111]);
+ engine.renderFrameTimeMetric$.next(['layout', 2.225]);
+ engine.renderFrameTags$.next(['scrolling', true]);
+ engine.endFrame$.next({ FPS: 60 - (i % 2), elapsedTime: i + 1, frameTime: 3.456 });
+ }
+
+ expect(metrics).toHaveLength(1);
+ expect(metrics[0]).toMatchObject({
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ elapsedTimeToStart: 61,
+ FPS: { max: 60, min: 59, avg: 59.51 },
+ frameTime: { max: 3.46, min: 3.46, avg: 3.46 },
+ extensionTotal: { max: 1.11, min: 1.11, avg: 1.11 },
+ });
+ expect(telemetryService.capture).toHaveBeenCalledWith('sheet_render_cost', metrics[0]);
+
+ subscription.unsubscribe();
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
new file mode 100644
index 0000000000..f80f356d5a
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
@@ -0,0 +1,153 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { RANGE_TYPE } from '@univerjs/core';
+import { DeltaColumnWidthCommand, DeltaRowHeightCommand } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { MobileHeaderResizeRenderController } from '../mobile-header-resize.render-controller';
+
+function createButton() {
+ return {
+ visible: false,
+ transformByState: vi.fn(function (this: any, state) {
+ Object.assign(this, state);
+ return this;
+ }),
+ setShapeProps: vi.fn(),
+ show: vi.fn(function (this: any) {
+ this.visible = true;
+ }),
+ hide: vi.fn(function (this: any) {
+ this.visible = false;
+ }),
+ dispose: vi.fn(),
+ onPointerDown$: { subscribeEvent: vi.fn() },
+ };
+}
+
+function createController() {
+ const canvasListeners = new Map<string, EventListener>();
+ const canvasElement = {
+ addEventListener: vi.fn((type: string, handler: EventListener) => canvasListeners.set(type, handler)),
+ removeEventListener: vi.fn(),
+ getBoundingClientRect: vi.fn(() => ({ left: 0, top: 0 })),
+ };
+ const scene = {
+ addObjects: vi.fn(),
+ addObject: vi.fn((shape: any) => {
+ shape.dispose ??= vi.fn();
+ shape.transformByState ??= vi.fn(() => shape);
+ }),
+ getAncestorScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),
+ getEngine: vi.fn(() => ({ getCanvasElement: () => canvasElement, width: 800, height: 600 })),
+ disableObjectsEvent: vi.fn(),
+ enableObjectsEvent: vi.fn(),
+ };
+ const skeleton = {
+ rowHeaderWidth: 48,
+ columnHeaderHeight: 24,
+ columnTotalWidth: 1000,
+ rowTotalHeight: 2000,
+ getOffsetByRow: vi.fn((row: number) => (row + 1) * 20),
+ getOffsetByColumn: vi.fn((col: number) => (col + 1) * 80),
+ getNoMergeCellWithCoordByIndex: vi.fn((row: number, col: number) => ({
+ startX: col * 80,
+ endX: (col + 1) * 80,
+ startY: row * 20,
+ endY: (row + 1) * 20,
+ })),
+ };
+ const controller = Object.create(MobileHeaderResizeRenderController.prototype) as any;
+ controller._context = {
+ scene,
+ unit: {
+ getActiveSheet: vi.fn(() => ({ getZoomRatio: vi.fn(() => 2) })),
+ },
+ };
+ controller._sheetSkeletonManagerService = {
+ getCurrentSkeleton: vi.fn(() => skeleton),
+ };
+ controller._commandService = { executeCommand: vi.fn() };
+ controller._contextService = { getContextValue: vi.fn(() => false) };
+ controller._rowResizeButton = createButton();
+ controller._columnResizeButton = createButton();
+ controller.disposeWithMe = vi.fn();
+
+ return { canvasElement, canvasListeners, controller, scene, skeleton };
+}
+
+describe('MobileHeaderResizeRenderController business methods', () => {
+ it('shows a row or column resize handle for header selections and updates it on scroll', () => {
+ const { controller } = createController();
+
+ controller._handleSelectionChange([{
+ range: { startRow: 2, endRow: 4, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.ROW },
+ }]);
+ expect(controller._currentRow).toBe(4);
+ expect(controller._rowResizeButton.show).toHaveBeenCalled();
+ expect(controller._rowResizeButton.transformByState).toHaveBeenCalledWith({
+ left: 18,
+ top: 94,
+ });
+
+ controller._handleSelectionChange([{
+ range: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 3, rangeType: RANGE_TYPE.COLUMN },
+ }]);
+ expect(controller._currentColumn).toBe(3);
+ expect(controller._columnResizeButton.show).toHaveBeenCalled();
+ expect(controller._columnResizeButton.transformByState).toHaveBeenCalledWith({
+ left: 314,
+ top: 6,
+ });
+
+ controller._updateButtonPositionOnScroll();
+ expect(controller._columnResizeButton.transformByState).toHaveBeenLastCalledWith({
+ left: 314,
+ top: 6,
+ });
+ });
+
+ it('executes row and column resize commands after a meaningful touch drag', () => {
+ const { canvasListeners, controller, scene } = createController();
+
+ controller._currentRow = 2;
+ controller._startResize({ offsetX: 12, offsetY: 60 }, 'row');
+ canvasListeners.get('touchmove')!({
+ touches: [{ clientX: 12, clientY: 90 }],
+ preventDefault: vi.fn(),
+ } as unknown as Event);
+ canvasListeners.get('touchend')!({ preventDefault: vi.fn() } as unknown as Event);
+ expect(scene.disableObjectsEvent).toHaveBeenCalled();
+ expect(scene.enableObjectsEvent).toHaveBeenCalled();
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(DeltaRowHeightCommand.id, {
+ deltaY: 15,
+ anchorRow: 2,
+ });
+
+ controller._commandService.executeCommand.mockClear();
+ controller._currentColumn = 1;
+ controller._startResize({ offsetX: 160, offsetY: 12 }, 'column');
+ canvasListeners.get('touchmove')!({
+ touches: [{ clientX: 200, clientY: 12 }],
+ preventDefault: vi.fn(),
+ } as unknown as Event);
+ canvasListeners.get('touchend')!({ preventDefault: vi.fn() } as unknown as Event);
+ expect(controller._commandService.executeCommand).toHaveBeenCalledWith(DeltaColumnWidthCommand.id, {
+ deltaX: 20,
+ anchorCol: 1,
+ });
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-scroll.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-scroll.render-controller.spec.ts
new file mode 100644
index 0000000000..f8dff40c1c
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-scroll.render-controller.spec.ts
@@ -0,0 +1,290 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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, RANGE_TYPE } from '@univerjs/core';
+import { 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 { SetZoomRatioCommand } from '../../../../commands/commands/set-zoom-ratio.command';
+import { SheetScrollManagerService } from '../../../../services/scroll-manager.service';
+import { createRenderTestBed } from '../../__tests__/render-test-bed';
+import { MobileSheetsScrollRenderController } from '../mobile-scroll.render-controller';
+
+function createController() {
+ const rawScrollInfo$ = new Subject<any>();
+ const validViewportScrollInfo$ = new Subject<any>();
+ const scrollStates = new Map<string, any>();
+ const scrollManagerService = {
+ rawScrollInfo$,
+ validViewportScrollInfo$,
+ setValidScrollStateToCurrSheet: vi.fn(),
+ setSearchParam: vi.fn(),
+ getCurrentScrollState: vi.fn(() => ({
+ sheetViewStartRow: 1,
+ sheetViewStartColumn: 1,
+ offsetX: 3,
+ offsetY: 4,
+ })),
+ getScrollStateByParam: vi.fn((param: any) => scrollStates.get(`${param.unitId}:${param.sheetId}`)),
+ calcViewportScrollFromRowColOffset: vi.fn((state: any) => state
+ ? {
+ viewportScrollX: state.sheetViewStartColumn * 100 + state.offsetX,
+ viewportScrollY: state.sheetViewStartRow * 20 + state.offsetY,
+ }
+ : { viewportScrollX: 0, viewportScrollY: 0 }),
+ };
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [SheetScrollManagerService, { useValue: scrollManagerService }],
+ ],
+ });
+ const { injector, context, skeleton, viewportMap, sheet, scene, renderManagerService } = testBed;
+ const commandService = injector.get(ICommandService);
+ const executeCommand = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as never);
+ const syncExecuteCommand = vi.spyOn(commandService, 'syncExecuteCommand').mockReturnValue(true as never);
+ const viewportMain = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) as any;
+ viewportMain.height = 120;
+ viewportMain.width = 250;
+ (skeleton as any).getRangeByViewport = vi.fn(() => ({
+ startRow: 2,
+ startColumn: 2,
+ endRow: 6,
+ endColumn: 5,
+ }));
+ const worksheet = sheet.getActiveSheet();
+ vi.spyOn(worksheet, 'getFreeze').mockReturnValue({
+ startRow: 0,
+ startColumn: 0,
+ ySplit: 0,
+ xSplit: 0,
+ } as any);
+ const canvasElement = {
+ parentElement: document.createElement('div'),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ getBoundingClientRect: vi.fn(() => ({ left: 0, top: 0 })),
+ };
+ vi.spyOn(scene, 'getEngine').mockReturnValue({
+ getCanvasElement: () => canvasElement,
+ width: 800,
+ height: 600,
+ } as any);
+
+ const controller = injector.createInstance(MobileSheetsScrollRenderController, context as any);
+
+ return {
+ canvasElement,
+ controller,
+ executeCommand,
+ rawScrollInfo$,
+ renderManagerService,
+ scene,
+ scrollManagerService,
+ scrollStates,
+ sheet,
+ sheetSkeletonManagerService: testBed.sheetSkeletonManagerService,
+ syncExecuteCommand,
+ testBed,
+ validViewportScrollInfo$,
+ viewportMain,
+ };
+}
+
+describe('MobileSheetsScrollRenderController', () => {
+ it('scrolls the selected range into view based on the current viewport bounds', () => {
+ const { controller, syncExecuteCommand, testBed } = createController();
+
+ expect(controller.scrollToRange({
+ startRow: 1,
+ endRow: 10,
+ startColumn: 1,
+ endColumn: 8,
+ })).toBe(true);
+ expect(syncExecuteCommand).toHaveBeenCalledWith(ScrollCommand.id, {
+ sheetViewStartRow: 5,
+ sheetViewStartColumn: 7,
+ offsetX: 0,
+ offsetY: 0,
+ });
+
+ syncExecuteCommand.mockClear();
+ controller.scrollToRange({
+ startRow: 8,
+ endRow: 12,
+ startColumn: 3,
+ endColumn: 9,
+ rangeType: RANGE_TYPE.ROW,
+ });
+ expect(syncExecuteCommand).toHaveBeenCalledWith(ScrollCommand.id, expect.objectContaining({
+ sheetViewStartRow: 7,
+ }));
+
+ testBed.univer.dispose();
+ });
+
+ it('syncs stored scroll state into the main viewport and emits valid scroll state after viewport scrolling', () => {
+ const { rawScrollInfo$, scrollManagerService, testBed, validViewportScrollInfo$, viewportMain } = createController();
+ const validStates: any[] = [];
+ validViewportScrollInfo$.subscribe((state) => validStates.push(state));
+
+ rawScrollInfo$.next({
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 2,
+ offsetX: 7,
+ offsetY: 9,
+ });
+ expect(viewportMain.viewportScrollX).toBe(207);
+ expect(viewportMain.viewportScrollY).toBe(69);
+
+ rawScrollInfo$.next(null);
+ expect(viewportMain.viewportScrollX).toBe(0);
+ expect(viewportMain.viewportScrollY).toBe(0);
+
+ viewportMain.onScrollAfter$.emit({
+ viewportScrollX: 245,
+ viewportScrollY: 78,
+ scrollX: 11,
+ scrollY: 22,
+ });
+ expect(scrollManagerService.setValidScrollStateToCurrSheet).toHaveBeenCalledWith({
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 2,
+ offsetX: 45,
+ offsetY: 18,
+ viewportScrollX: 245,
+ viewportScrollY: 78,
+ scrollX: 11,
+ scrollY: 22,
+ });
+ expect(validStates.at(-1)).toEqual(expect.objectContaining({
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 2,
+ viewportScrollX: 245,
+ viewportScrollY: 78,
+ }));
+
+ testBed.univer.dispose();
+ });
+
+ it('turns scrollbar movement into a sheet scroll command and restores scroll on skeleton switch', () => {
+ const { executeCommand, scene, scrollManagerService, scrollStates, sheet, sheetSkeletonManagerService, testBed, viewportMain } = createController();
+ const unitId = sheet.getUnitId();
+ scrollStates.set(`${unitId}:sheet1`, {
+ sheetViewStartRow: 4,
+ sheetViewStartColumn: 3,
+ offsetX: 8,
+ offsetY: 6,
+ });
+
+ viewportMain.onScrollByBar$.emit({
+ isTrigger: true,
+ viewportScrollX: 330,
+ viewportScrollY: 95,
+ });
+ expect(executeCommand).toHaveBeenCalledWith(ScrollCommand.id, {
+ sheetViewStartRow: 4,
+ sheetViewStartColumn: 3,
+ offsetX: 30,
+ offsetY: 15,
+ });
+
+ sheetSkeletonManagerService.emitCurrentSkeletonBefore({ unitId, sheetId: 'sheet1', skeleton: sheetSkeletonManagerService.getCurrentSkeleton() });
+ expect(scrollManagerService.setSearchParam).toHaveBeenCalledWith({ unitId, sheetId: 'sheet1' });
+ expect(viewportMain.viewportScrollX).toBe(308);
+ expect(viewportMain.viewportScrollY).toBe(86);
+ expect(scene.width).toBe(5046);
+ expect(scene.height).toBe(4020);
+
+ testBed.univer.dispose();
+ });
+
+ it('registers mobile touch listeners and cancels native propagation from sheet pointer down', () => {
+ const { canvasElement, testBed } = createController();
+
+ expect(canvasElement.addEventListener).toHaveBeenCalledWith('touchstart', expect.any(Function), { passive: false });
+ expect(canvasElement.addEventListener).toHaveBeenCalledWith('touchmove', expect.any(Function), { passive: false });
+ expect(canvasElement.addEventListener).toHaveBeenCalledWith('touchend', expect.any(Function), { passive: false });
+ expect(canvasElement.addEventListener).toHaveBeenCalledWith('touchcancel', expect.any(Function), { passive: false });
+
+ const pointerDown$ = testBed.context.mainComponent?.onPointerDown$ as any;
+ pointerDown$.emit({}, { stopPropagation: vi.fn() });
+ expect(pointerDown$.emit).toBeDefined();
+
+ testBed.univer.dispose();
+ });
+
+ it('translates touch drag and pinch gestures into scroll and zoom commands', () => {
+ const { canvasElement, executeCommand, sheet, testBed } = createController();
+ const listeners = new Map<string, EventListener>();
+ canvasElement.addEventListener.mock.calls.forEach(([type, handler]) => {
+ listeners.set(type, handler as EventListener);
+ });
+ const worksheet = sheet.getActiveSheet();
+ vi.spyOn(worksheet, 'getZoomRatio').mockReturnValue(1);
+ const now = vi.spyOn(performance, 'now');
+ now.mockReturnValueOnce(0).mockReturnValueOnce(16);
+
+ const preventDefault = vi.fn();
+ listeners.get('touchstart')!({
+ touches: [{ clientX: 120, clientY: 120 }],
+ preventDefault,
+ } as unknown as Event);
+ listeners.get('touchmove')!({
+ touches: [{ clientX: 90, clientY: 80 }],
+ preventDefault,
+ } as unknown as Event);
+
+ expect(preventDefault).toHaveBeenCalled();
+ expect(executeCommand).toHaveBeenCalledWith(SetScrollRelativeCommand.id, {
+ offsetX: 30,
+ offsetY: 40,
+ });
+
+ executeCommand.mockClear();
+ const pinchStart = vi.fn();
+ listeners.get('touchstart')!({
+ touches: [
+ { clientX: 100, clientY: 100 },
+ { clientX: 200, clientY: 100 },
+ ],
+ preventDefault: pinchStart,
+ } as unknown as Event);
+ expect(pinchStart).toHaveBeenCalled();
+
+ listeners.get('touchmove')!({
+ touches: [
+ { clientX: 75, clientY: 100 },
+ { clientX: 225, clientY: 100 },
+ ],
+ preventDefault: vi.fn(),
+ } as unknown as Event);
+
+ expect(executeCommand).toHaveBeenCalledWith(SetZoomRatioCommand.id, {
+ zoomRatio: 1.5,
+ unitId: sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ });
+ expect(executeCommand).toHaveBeenCalledWith(ScrollCommand.id, expect.objectContaining({
+ sheetViewStartRow: expect.any(Number),
+ sheetViewStartColumn: expect.any(Number),
+ }));
+ expect(canvasElement.parentElement.textContent).toContain('150%');
+
+ now.mockRestore();
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts
index f58c802882..dee332d8f2 100644
--- a/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IScrollState } from '../../views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar';
+import type { IScrollState } from '../sheet-bar/type';
import { Injector } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { ISheetBarService, SheetBarService } from '../sheet-bar/sheet-bar.service';
diff --git a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts
index 7980aa84f9..dfd36f908c 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts
@@ -43,6 +43,12 @@ import { BaseSelectionRenderService } from '../base-selection-render.service';
import { SelectionLayer } from '../selection-layer';
class TestSelectionRenderService extends BaseSelectionRenderService {
+ cleanupForTest() {
+ if (this._scene) {
+ this._clearUpdatingListeners();
+ }
+ }
+
emitMoving() {
this._selectionMoving$.next([]);
}
@@ -217,6 +223,7 @@ function createSelectionRenderService() {
injector.get(SheetSkeletonManagerService),
contextService
);
+ createdServices.push(service);
return { injector, contextService, service };
}
@@ -242,6 +249,8 @@ function viewportKey(viewport: unknown) {
return (viewport as { viewportKey?: string } | null)?.viewportKey;
}
+const createdServices: TestSelectionRenderService[] = [];
+
const selections: ISelectionWithStyle[] = [
createSelection({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL }),
createSelection({ startRow: 2, endRow: 3, startColumn: 2, endColumn: 4, rangeType: RANGE_TYPE.NORMAL }),
@@ -249,6 +258,8 @@ const selections: ISelectionWithStyle[] = [
describe('BaseSelectionRenderService', () => {
afterEach(() => {
+ createdServices.forEach((service) => service.cleanupForTest());
+ createdServices.length = 0;
vi.unstubAllGlobals();
});
diff --git a/packages/sheets-ui/src/services/sheet-bar/sheet-bar.service.ts b/packages/sheets-ui/src/services/sheet-bar/sheet-bar.service.ts
index a79dee4ee3..3ee509aa30 100644
--- a/packages/sheets-ui/src/services/sheet-bar/sheet-bar.service.ts
+++ b/packages/sheets-ui/src/services/sheet-bar/sheet-bar.service.ts
@@ -16,7 +16,7 @@
import type { IDisposable } from '@univerjs/core';
import type { Observable } from 'rxjs';
-import type { IScrollState } from '../../views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar';
+import type { IScrollState } from './type';
import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';
import { Subject } from 'rxjs';
diff --git a/presets/packages/preset-docs-hyper-link/src/types.ts b/packages/sheets-ui/src/services/sheet-bar/type.ts
similarity index 62%
rename from presets/packages/preset-docs-hyper-link/src/types.ts
rename to packages/sheets-ui/src/services/sheet-bar/type.ts
index 4d13fb9621..03442b4c8f 100644
--- a/presets/packages/preset-docs-hyper-link/src/types.ts
+++ b/packages/sheets-ui/src/services/sheet-bar/type.ts
@@ -14,16 +14,7 @@
* limitations under the License.
*/
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
+export interface IScrollState {
+ leftEnd: boolean;
+ rightEnd: boolean;
}
diff --git a/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx b/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx
index a0fb192df7..50dfa059c4 100644
--- a/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/SheetBar.tsx
@@ -15,8 +15,14 @@
*/
import type { IUniverSheetsUIConfig } from '../../config/config';
-import type { IScrollState } from './sheet-bar-tabs/utils/slide-tab-bar';
-import { DEFAULT_WORKSHEET_COLUMN_COUNT, DEFAULT_WORKSHEET_ROW_COUNT, ICommandService, IPermissionService, throttle } from '@univerjs/core';
+import type { IScrollState } from '../../services/sheet-bar/type';
+import {
+ DEFAULT_WORKSHEET_COLUMN_COUNT,
+ DEFAULT_WORKSHEET_ROW_COUNT,
+ ICommandService,
+ IPermissionService,
+ throttle,
+} from '@univerjs/core';
import { IncreaseIcon, MoreIcon } from '@univerjs/icons';
import { InsertSheetCommand, WorkbookCreateSheetPermission, WorkbookEditablePermission } from '@univerjs/sheets';
import { useConfigValue, useDependency, useObservable } from '@univerjs/ui';
@@ -61,7 +67,7 @@ export const SheetBar = () => {
return () => {
subscription.unsubscribe();
};
- }, []);
+ }, [sheetBarService.scroll$]);
// Complete the _addSheet, handleScrollLeft, and handleScrollRight functions
const addSheet = () => {
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
index 542b7440eb..57b3674070 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
@@ -17,8 +17,8 @@
import type { ICommandInfo } from '@univerjs/core';
import type { IUniverUIConfig } from '@univerjs/ui';
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
+import type { IScrollState } from '../../../services/sheet-bar/type';
import type { IBaseSheetBarProps } from './SheetBarItem';
-import type { IScrollState } from './utils/slide-tab-bar';
import {
ICommandService,
IConfirmService,
@@ -261,7 +261,9 @@ export function SheetBarTabs() {
} satisfies IBaseSheetBarProps;
});
+ // eslint-disable-next-line react/set-state-in-effect
setSheetList(sheetListItems);
+ // eslint-disable-next-line react/set-state-in-effect
setActiveSheetId(currentSubUnitId);
}, [rangeProtectionRuleModel, workbook, worksheetProtectionRuleModel]);
@@ -485,11 +487,9 @@ export function SheetBarTabs() {
}, [
canRenameActiveSheet,
commandService,
- getActiveTabRect,
nameEmptyCheck,
nameRepeatCheck,
observeResize,
- openContextMenu,
sheetBarService,
sheetNameSpecCharCheck,
updateSheetItems,
@@ -549,6 +549,7 @@ export function SheetBarTabs() {
useEffect(() => {
if (!showContextMenu && contextMenuVisible) {
+ // eslint-disable-next-line react/set-state-in-effect
setContextMenuVisible(false);
}
}, [contextMenuVisible, showContextMenu]);
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/sheet-tab-drag-sort.spec.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/sheet-tab-drag-sort.spec.ts
new file mode 100644
index 0000000000..3a83790452
--- /dev/null
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/sheet-tab-drag-sort.spec.ts
@@ -0,0 +1,78 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { calculateSheetTabDragSort, reorderItems } from '../sheet-tab-drag-sort';
+
+const layout = [
+ { id: 'sheet-0', left: 0, width: 40 },
+ { id: 'sheet-1', left: 45, width: 40 },
+ { id: 'sheet-2', left: 90, width: 40 },
+ { id: 'sheet-3', left: 135, width: 40 },
+];
+
+describe('sheet-tab-drag-sort', () => {
+ it('moves following tabs left when the dragged tab crosses their midlines', () => {
+ expect(calculateSheetTabDragSort(layout, 1, 10)).toEqual({
+ targetIndex: 1,
+ itemOffsets: [0, 10, 0, 0],
+ });
+
+ expect(calculateSheetTabDragSort(layout, 1, 30)).toEqual({
+ targetIndex: 2,
+ itemOffsets: [0, 30, -40, 0],
+ });
+
+ expect(calculateSheetTabDragSort(layout, 1, 75)).toEqual({
+ targetIndex: 3,
+ itemOffsets: [0, 75, -40, -40],
+ });
+ });
+
+ it('moves previous tabs right when the dragged tab crosses their midlines', () => {
+ expect(calculateSheetTabDragSort(layout, 2, -10)).toEqual({
+ targetIndex: 2,
+ itemOffsets: [0, 0, -10, 0],
+ });
+
+ expect(calculateSheetTabDragSort(layout, 2, -30)).toEqual({
+ targetIndex: 1,
+ itemOffsets: [0, 40, -30, 0],
+ });
+
+ expect(calculateSheetTabDragSort(layout, 2, -75)).toEqual({
+ targetIndex: 0,
+ itemOffsets: [40, 40, -75, 0],
+ });
+ });
+
+ it('ignores invalid active indexes', () => {
+ expect(calculateSheetTabDragSort(layout, -1, 20)).toEqual({
+ targetIndex: -1,
+ itemOffsets: [0, 0, 0, 0],
+ });
+ expect(calculateSheetTabDragSort(layout, 99, 20)).toEqual({
+ targetIndex: 99,
+ itemOffsets: [0, 0, 0, 0],
+ });
+ });
+
+ it('reorders arrays by the calculated target index', () => {
+ expect(reorderItems(['a', 'b', 'c', 'd'], 1, 3)).toEqual(['a', 'c', 'd', 'b']);
+ expect(reorderItems(['a', 'b', 'c', 'd'], 2, 0)).toEqual(['c', 'a', 'b', 'd']);
+ expect(reorderItems(['a', 'b', 'c', 'd'], 2, 2)).toEqual(['a', 'b', 'c', 'd']);
+ });
+});
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.ts
index ea089b0ac3..b09cd50d6b 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.ts
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.ts
@@ -94,7 +94,7 @@ function setupDOM() {
item.className = 'tab-item';
item.dataset.id = `sheet-${i}`;
const span = document.createElement('span');
- span.innerText = `Sheet ${i}`;
+ span.textContent = `Sheet ${i}`;
item.appendChild(span);
bar.appendChild(item);
}
@@ -197,7 +197,7 @@ describe('slide-tab-bar', () => {
renameFinishedCount += 1;
});
expect(editor.getAttribute('contentEditable')).toBe('true');
- editor.innerText = 'Renamed';
+ editor.textContent = 'Renamed';
editor.dispatchEvent(new FocusEvent('focusout'));
expect(events.changedNames).toEqual([{ id: 'sheet-0', name: 'Renamed' }]);
@@ -216,30 +216,16 @@ describe('slide-tab-bar', () => {
expect(frameState.cancellations).toEqual([1]);
});
- it('sorts dragged sheet tabs and starts or closes edge auto-scroll', () => {
+ it('starts or closes edge auto-scroll during sheet tab dragging', () => {
const { root, events } = setupDOM();
const frameState = new TestAnimationFrameState();
const bar = createBar(root, events, 1);
const items = bar.getSlideTabItems();
const active = items[1];
- let activeX = 45;
- active.getBoundingRect = () => rect(activeX, 40);
(bar as unknown as { _activeTabItem: SlideTabItem })._activeTabItem = active;
(bar as unknown as { _activeTabItemIndex: number })._activeTabItemIndex = 1;
- activeX = 110;
- (bar as unknown as { _compareRight: () => void })._compareRight();
- expect((bar as unknown as { _compareIndex: number })._compareIndex).toBeGreaterThanOrEqual(1);
-
- activeX = -30;
- (bar as unknown as { _compareLeft: () => void })._compareLeft();
- expect((bar as unknown as { _compareIndex: number })._compareIndex).toBeLessThanOrEqual(1);
-
- (bar as unknown as { _compareIndex: number })._compareIndex = 0;
- (bar as unknown as { _sortedItems: () => void })._sortedItems();
- expect(bar.getSlideTabItems()[0].getId()).toBe('sheet-1');
-
(bar as unknown as { _leftBoundingLine: number })._leftBoundingLine = 20;
(bar as unknown as { _rightBoundingLine: number })._rightBoundingLine = 20;
(bar as unknown as { _scrollIncremental: number })._scrollIncremental = 0;
@@ -261,7 +247,7 @@ describe('slide-tab-bar', () => {
it('handles static text-selection and slide-skip helpers', () => {
const el = document.createElement('span');
- el.innerText = 'abc';
+ el.textContent = 'abc';
document.body.appendChild(el);
SlideTabBar.keepSelectAll(el);
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/sheet-tab-drag-sort.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/sheet-tab-drag-sort.ts
new file mode 100644
index 0000000000..4295c15540
--- /dev/null
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/sheet-tab-drag-sort.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.
+ */
+
+export interface ISheetTabLayoutItem {
+ id: string;
+ left: number;
+ width: number;
+}
+
+export interface ISheetTabDragSortResult {
+ targetIndex: number;
+ itemOffsets: number[];
+}
+
+function getMidline(item: ISheetTabLayoutItem): number {
+ return item.left + item.width / 2;
+}
+
+export function calculateSheetTabDragSort(
+ items: ISheetTabLayoutItem[],
+ activeIndex: number,
+ dragOffsetX: number
+): ISheetTabDragSortResult {
+ const itemOffsets = items.map(() => 0);
+ const activeItem = items[activeIndex];
+
+ if (!activeItem) {
+ return {
+ targetIndex: activeIndex,
+ itemOffsets,
+ };
+ }
+
+ itemOffsets[activeIndex] = dragOffsetX;
+
+ const activeLeft = activeItem.left + dragOffsetX;
+ const activeRight = activeLeft + activeItem.width;
+ let targetIndex = activeIndex;
+
+ if (dragOffsetX > 0) {
+ for (let index = activeIndex + 1; index < items.length; index++) {
+ if (activeRight > getMidline(items[index])) {
+ itemOffsets[index] = -activeItem.width;
+ targetIndex = index;
+ }
+ }
+ } else if (dragOffsetX < 0) {
+ for (let index = activeIndex - 1; index >= 0; index--) {
+ if (activeLeft < getMidline(items[index])) {
+ itemOffsets[index] = activeItem.width;
+ targetIndex = index;
+ }
+ }
+ }
+
+ return {
+ targetIndex,
+ itemOffsets,
+ };
+}
+
+export function reorderItems<T>(items: T[], fromIndex: number, toIndex: number): T[] {
+ if (
+ fromIndex === toIndex ||
+ fromIndex < 0 ||
+ toIndex < 0 ||
+ fromIndex >= items.length ||
+ toIndex >= items.length
+ ) {
+ return [...items];
+ }
+
+ const nextItems = [...items];
+ const [movedItem] = nextItems.splice(fromIndex, 1);
+ nextItems.splice(toIndex, 0, movedItem);
+ return nextItems;
+}
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/sheet-tab-name-editor.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/sheet-tab-name-editor.ts
new file mode 100644
index 0000000000..27b2ec0231
--- /dev/null
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/sheet-tab-name-editor.ts
@@ -0,0 +1,163 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export interface IStartSheetTabNameEditorParams {
+ slideTabItem: HTMLElement;
+ canStart: () => boolean;
+ checkName: (name: string) => boolean;
+ setEditMode: (editing: boolean) => void;
+ beforeCommit: () => void;
+ onCommit: (name: string, event: FocusEvent) => void;
+}
+
+interface ISheetTabNameEditorActions {
+ blurAction: (event: FocusEvent) => void;
+ compositionstartAction: () => void;
+ compositionendAction: () => void;
+ inputAction: () => void;
+ keydownAction: (event: KeyboardEvent) => void;
+ pasteAction: (event: ClipboardEvent) => void;
+ cleanup: () => void;
+}
+
+const MAX_SHEET_NAME_LENGTH = 31;
+
+function getEditorText(input: HTMLElement): string {
+ return input.textContent ?? '';
+}
+
+export function keepLastTextIndex(inputHtml: HTMLElement) {
+ setTimeout(() => {
+ const range = window.getSelection();
+ if (range) {
+ range.selectAllChildren(inputHtml);
+ range.collapseToEnd();
+ }
+ });
+}
+
+export function keepTextSelected(inputHtml: HTMLElement) {
+ setTimeout(() => {
+ const selection = window.getSelection();
+ if (!selection) return;
+
+ const range = document.createRange();
+ range.selectNodeContents(inputHtml);
+
+ selection.removeAllRanges();
+ selection.addRange(range);
+ });
+}
+
+function createSheetTabNameEditorActions(
+ input: HTMLElement,
+ params: IStartSheetTabNameEditorParams
+): ISheetTabNameEditorActions {
+ let compositionFlag = true;
+ let cleanup = () => { };
+
+ const pasteAction = (event: ClipboardEvent) => {
+ event.preventDefault();
+ const text = event.clipboardData?.getData('text/plain');
+ if (text) {
+ const savedText = text.replace(/\s/g, '');
+ document.execCommand('insertText', false, savedText);
+ }
+ };
+
+ const blurAction = (focusEvent: FocusEvent) => {
+ if (params.checkName(getEditorText(input))) {
+ return;
+ }
+
+ params.setEditMode(false);
+ cleanup();
+ params.beforeCommit();
+ params.onCommit(getEditorText(input), focusEvent);
+ };
+
+ const keydownAction = (event: KeyboardEvent) => {
+ event.stopPropagation();
+
+ if (event.key === 'Enter') {
+ input.blur();
+ event.preventDefault();
+ }
+ };
+
+ const compositionstartAction = () => {
+ compositionFlag = false;
+ };
+
+ const compositionendAction = () => {
+ compositionFlag = true;
+ };
+
+ const inputAction = () => {
+ setTimeout(() => {
+ if (compositionFlag) {
+ const text = getEditorText(input);
+ if (text.length > MAX_SHEET_NAME_LENGTH) {
+ input.textContent = text.substring(0, MAX_SHEET_NAME_LENGTH);
+ keepLastTextIndex(input);
+ }
+ }
+ }, 0);
+ };
+
+ cleanup = () => {
+ input.removeAttribute('contentEditable');
+ input.removeEventListener('focusout', blurAction);
+ input.removeEventListener('compositionstart', compositionstartAction);
+ input.removeEventListener('compositionend', compositionendAction);
+ input.removeEventListener('input', inputAction);
+ input.removeEventListener('keydown', keydownAction);
+ input.removeEventListener('paste', pasteAction);
+ };
+
+ return {
+ blurAction,
+ compositionstartAction,
+ compositionendAction,
+ inputAction,
+ keydownAction,
+ pasteAction,
+ cleanup,
+ };
+}
+
+export function startSheetTabNameEditor(params: IStartSheetTabNameEditorParams): void {
+ if (!params.canStart()) {
+ return;
+ }
+
+ const input = params.slideTabItem.querySelector<HTMLElement>('span');
+ if (!input) {
+ return;
+ }
+
+ const actions = createSheetTabNameEditorActions(input, params);
+
+ input.setAttribute('contentEditable', 'true');
+ input.addEventListener('focusout', actions.blurAction);
+ input.addEventListener('compositionstart', actions.compositionstartAction);
+ input.addEventListener('compositionend', actions.compositionendAction);
+ input.addEventListener('input', actions.inputAction);
+ input.addEventListener('keydown', actions.keydownAction);
+ input.addEventListener('paste', actions.pasteAction);
+ params.setEditMode(true);
+ keepTextSelected(input);
+}
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts
index 0ac4fb803a..5a27662c0e 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts
@@ -14,12 +14,11 @@
* limitations under the License.
*/
+import type { IScrollState } from '../../../../services/sheet-bar/type';
import { Animate } from './animate';
+import { calculateSheetTabDragSort, reorderItems } from './sheet-tab-drag-sort';
+import { keepLastTextIndex, keepTextSelected, startSheetTabNameEditor } from './sheet-tab-name-editor';
-export interface IScrollState {
- leftEnd: boolean;
- rightEnd: boolean;
-}
export interface ISlideTabBarConfig {
slideTabBarSelector: string;
slideTabBarItemSelector: string;
@@ -116,105 +115,36 @@ export class SlideTabItem {
return this.getTranslateXDirection();
}
- // eslint-disable-next-line max-lines-per-function
setEditor(callback?: (event: FocusEvent) => void): void {
- if (!this._slideTabBar.getConfig().onNameChangeCheck()) {
+ if (this._editMode) {
return;
}
- let compositionFlag = true;
- if (this._editMode === false) {
- const input = this._slideTabItem.querySelector('span');
-
- const pasteAction = (e: ClipboardEvent) => {
- e.preventDefault();
- const text = e.clipboardData?.getData('text/plain');
- if (text) {
- const savedText = text.replace(/\s/g, '');
- document.execCommand('insertText', false, savedText);
- }
- };
-
- const blurAction = (focusEvent: FocusEvent) => {
- if (this.nameCheck()) return;
-
- this._editMode = false;
-
- if (input) {
- input.removeAttribute('contentEditable');
- input.removeEventListener('focusout', blurAction);
- input.removeEventListener('compositionstart', compositionstartAction);
- input.removeEventListener('compositionend', compositionendAction);
- input.removeEventListener('input', inputAction);
- input.removeEventListener('keydown', keydownAction);
- input.removeEventListener('paste', pasteAction);
- }
- // Event must be removed before updateItems
+ startSheetTabNameEditor({
+ slideTabItem: this._slideTabItem,
+ canStart: () => this._slideTabBar.getConfig().onNameChangeCheck(),
+ checkName: (name) => this._slideTabBar.getConfig().onNameCheckAlert(name),
+ setEditMode: (editing) => {
+ this._editMode = editing;
+ },
+ beforeCommit: () => {
this._slideTabBar.removeListener();
this._slideTabBar.updateItems();
- if (this._slideTabBar.getConfig().onChangeName) {
- const text = input?.innerText || '';
- const id = this.getId();
- this._slideTabBar.getConfig().onChangeName(id, text);
- }
-
+ },
+ onCommit: (name, focusEvent) => {
+ this._slideTabBar.getConfig().onChangeName(this.getId(), name);
if (callback) {
callback(focusEvent);
}
- };
-
- const keydownAction = (e: KeyboardEvent) => {
- if (!input) return;
- e.stopPropagation();
-
- if (e.key === 'Enter') {
- input.blur();
- e.preventDefault();
- }
- };
-
- const compositionstartAction = () => {
- compositionFlag = false;
- };
-
- const compositionendAction = () => {
- compositionFlag = true;
- };
-
- const inputAction = (e: Event) => {
- if (!input) return;
- const maxLength = 31;
-
- setTimeout(() => {
- if (compositionFlag) {
- const text = input.innerText;
- if (text.length > maxLength) {
- input.innerText = text.substring(0, maxLength);
- SlideTabBar.keepLastIndex(input);
- }
- }
- }, 0);
- };
-
- if (input) {
- input.setAttribute('contentEditable', 'true');
- input.addEventListener('focusout', blurAction);
- input.addEventListener('compositionstart', compositionstartAction);
- input.addEventListener('compositionend', compositionendAction);
- input.addEventListener('input', inputAction);
- input.addEventListener('keydown', keydownAction);
- input.addEventListener('paste', pasteAction);
- this._editMode = true;
- SlideTabBar.keepSelectAll(input);
- }
- }
+ },
+ });
}
nameCheck() {
const input = this._slideTabItem.querySelector('span');
if (!input) return false;
- const text = input.innerText;
+ const text = input.textContent ?? '';
const checkAlert = this._slideTabBar.getConfig().onNameCheckAlert(text);
return checkAlert;
}
@@ -316,7 +246,7 @@ export class SlideTabItem {
addEventListener<K extends keyof HTMLElementEventMap>(
type: K,
- action: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any,
+ action: (this: HTMLElement, ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions
) {
this._slideTabItem.addEventListener(type, action, options);
@@ -324,7 +254,7 @@ export class SlideTabItem {
removeEventListener<K extends keyof HTMLElementEventMap>(
type: K,
- action: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any,
+ action: (this: HTMLElement, ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions
) {
this._slideTabItem.removeEventListener(type, action, options);
@@ -629,26 +559,11 @@ export class SlideTabBar {
}
static keepLastIndex(inputHtml: HTMLElement) {
- setTimeout(() => {
- const range = window.getSelection();
- if (range) {
- range.selectAllChildren(inputHtml);
- range.collapseToEnd();
- }
- });
+ keepLastTextIndex(inputHtml);
}
static keepSelectAll(inputHtml: HTMLElement) {
- setTimeout(() => {
- const selection = window.getSelection();
- if (!selection) return;
-
- const range = document.createRange();
- range.selectNodeContents(inputHtml);
-
- selection.removeAllRanges();
- selection.addRange(range);
- });
+ keepTextSelected(inputHtml);
}
/**
@@ -751,14 +666,14 @@ export class SlideTabBar {
}
scrollToItem(index?: number): void {
- index = index ?? this._config.currentIndex;
+ const targetIndex = index ?? this._config.currentIndex;
// Check index validity
- if (index < 0 || index >= this._slideTabItems.length) {
+ if (targetIndex < 0 || targetIndex >= this._slideTabItems.length) {
console.error('Index out of bounds');
return;
}
- const right = this.calculateTabItemScrollX(index);
+ const right = this.calculateTabItemScrollX(targetIndex);
this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + right);
// Trigger a scroll event
@@ -896,24 +811,8 @@ export class SlideTabBar {
protected _autoScrollFrame(): void {
if (this._activeTabItem) {
- this._compareDirection = this._activeTabItem.translateX(this._moveActionX);
- switch (this._compareDirection) {
- case 1: {
- this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
- this._compareRight();
- break;
- }
- case 0: {
- this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
- this._compareIndex = this._activeTabItemIndex;
- break;
- }
- case -1: {
- this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
- this._compareLeft();
- break;
- }
- }
+ this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
+ this._updateDragSortState();
}
this._autoScrollTime = requestAnimationFrame(() => {
this._autoScrollFrame();
@@ -951,9 +850,7 @@ export class SlideTabBar {
protected _sortedItems(): void {
if (this._activeTabItem != null && this._activeTabItemIndex != null && this._compareIndex != null) {
- // data array list sort
- this._slideTabItems.splice(this._activeTabItemIndex, 1);
- this._slideTabItems.splice(this._compareIndex, 0, this._activeTabItem);
+ this._slideTabItems = reorderItems(this._slideTabItems, this._activeTabItemIndex, this._compareIndex);
// dom list sort
if (this._config.slideTabBarItemAutoSort) {
@@ -969,76 +866,42 @@ export class SlideTabBar {
}
protected _compareLeft(): void {
- if (this._activeTabItem && this._activeTabItemIndex) {
- const splice = this._slideTabItems.findIndex((item) => item.equals(this._activeTabItem));
- const length = this._slideTabItems.length;
- const collect = [];
-
- // collect compare item
- for (let i = 0; i < splice; i++) {
- if (i >= splice) {
- break;
- }
- collect.push(this._slideTabItems[i]);
- }
-
- // reset right
- for (let i = splice + 1; i < length; i++) {
- this._slideTabItems[i].animate().translateX(0);
- }
-
- // diff item midline
- let notFound = true;
- for (let i = collect.length - 1; i >= 0; i--) {
- const item = collect[i];
- // Left side border reaches the midline
- if (SlideTabItem.leftLine(this._activeTabItem) < item.getMidLine()) {
- item.animate().translateX(this._activeTabItem.getWidth());
- this._compareIndex = i;
- notFound = false;
- } else {
- item.animate().translateX(0);
- if (notFound) {
- this._compareIndex = this._activeTabItemIndex;
- }
- }
- }
- }
+ this._updateDragSortState();
}
protected _compareRight(): void {
- if (this._activeTabItem) {
- const splice = this._slideTabItems.findIndex((item) => item.equals(this._activeTabItem));
- const length = this._slideTabItems.length;
- const collect = [];
+ this._updateDragSortState();
+ }
- // collect compare item
- for (let i = splice + 1; i < length; i++) {
- collect.push(this._slideTabItems[i]);
- }
+ protected _updateDragSortState(): void {
+ if (!this._activeTabItem) {
+ return;
+ }
- // reset left
- for (let i = 0; i < splice; i++) {
- this._slideTabItems[i].animate().translateX(0);
+ const dragSortResult = calculateSheetTabDragSort(
+ this._slideTabItems.map((item) => ({
+ id: item.getId(),
+ left: item.getMidLine() - item.getWidth() / 2,
+ width: item.getWidth(),
+ })),
+ this._activeTabItemIndex,
+ this._moveActionX
+ );
+
+ this._compareIndex = dragSortResult.targetIndex;
+ dragSortResult.itemOffsets.forEach((offset, index) => {
+ const item = this._slideTabItems[index];
+ if (!item) {
+ return;
}
- // diff item midline
- let notFound = true;
- for (let i = 0; i < collect.length; i++) {
- const item = collect[i];
- // Right side border reaches the midline
- if (SlideTabItem.rightLine(this._activeTabItem) > item.getMidLine()) {
- item.animate().translateX(-this._activeTabItem.getWidth());
- this._compareIndex = splice + i + 1;
- notFound = false;
- } else {
- item.animate().translateX(0);
- if (notFound) {
- this._compareIndex = this._activeTabItemIndex;
- }
- }
+ if (item.equals(this._activeTabItem)) {
+ this._compareDirection = item.translateX(offset);
+ return;
}
- }
+
+ item.animate().translateX(offset);
+ });
}
protected _initConfig(): void {
diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.ts
index b6fcd3022b..84213e8580 100644
--- a/packages/ui/src/controllers/components.controller.ts
+++ b/packages/ui/src/controllers/components.controller.ts
@@ -35,7 +35,6 @@ export class ComponentsController extends Disposable {
) {
super();
- this._registerComponents2();
this._registerIcons();
this._registerComponents();
}
@@ -64,9 +63,7 @@ export class ComponentsController extends Disposable {
this._componentManager.register(key, comp)
);
});
- }
- private _registerComponents2(): void {
// register the panel
this.disposeWithMe(this._componentManager.register(ShortcutPanelComponentName, ShortcutPanel));
}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index b293aa197c..2dd40be185 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -91,7 +91,7 @@ export {
RibbonStartGroup,
RibbonViewGroup,
} from './services/menu/types';
-export { MockMessageService } from './services/message/__testing__/mock-message.service';
+export { MockMessageService } from './services/message/__tests__/mock-message.service';
export { DesktopMessageService } from './services/message/desktop-message.service';
export { IMessageService } from './services/message/message.service';
export { DesktopNotificationService } from './services/notification/desktop-notification.service';
diff --git a/packages/ui/src/services/message/__testing__/mock-message.service.spec.ts b/packages/ui/src/services/message/__tests__/mock-message.service.spec.ts
similarity index 100%
rename from packages/ui/src/services/message/__testing__/mock-message.service.spec.ts
rename to packages/ui/src/services/message/__tests__/mock-message.service.spec.ts
diff --git a/packages/ui/src/services/message/__testing__/mock-message.service.ts b/packages/ui/src/services/message/__tests__/mock-message.service.ts
similarity index 100%
rename from packages/ui/src/services/message/__testing__/mock-message.service.ts
rename to packages/ui/src/services/message/__tests__/mock-message.service.ts
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 967389e3e7..4e296c90fc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -777,9 +777,6 @@ importers:
lodash-es:
specifier: ^4.18.1
version: 4.18.1
- nanoid:
- specifier: 5.1.11
- version: 5.1.11
numfmt:
specifier: 3.2.6
version: 3.2.6
@@ -3041,6 +3038,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3075,6 +3075,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3103,6 +3106,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3143,6 +3149,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
rxjs:
specifier: ^7.8.2
version: 7.8.2
@@ -3168,6 +3177,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3196,6 +3208,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3260,6 +3275,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3291,6 +3309,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3328,6 +3349,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3356,6 +3380,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3384,6 +3411,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3412,6 +3442,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3473,6 +3506,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
rxjs:
specifier: ^7.8.2
version: 7.8.2
@@ -3495,6 +3531,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3523,6 +3562,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3551,6 +3593,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -3585,6 +3630,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../../../packages/core
+ '@univerjs/presets':
+ specifier: workspace:*
+ version: link:../..
react:
specifier: 19.2.7
version: 19.2.7
@@ -10060,11 +10108,6 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
- resolution: {integrity: sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==}
- engines: {node: ^18 || >=20}
- hasBin: true
-
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
@@ -18979,8 +19022,6 @@ snapshots:
-
diff --git a/presets/packages/preset-docs-core/package.json b/presets/packages/preset-docs-core/package.json
index dfbdc977e9..081ddbcf42 100644
--- a/presets/packages/preset-docs-core/package.json
+++ b/presets/packages/preset-docs-core/package.json
@@ -81,6 +81,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-docs-core/src/types.ts b/presets/packages/preset-docs-core/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-docs-core/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-docs-core/src/umd.ts b/presets/packages/preset-docs-core/src/umd.ts
index 7f538e771b..52764ee66b 100644
--- a/presets/packages/preset-docs-core/src/umd.ts
+++ b/presets/packages/preset-docs-core/src/umd.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
+import type { IPreset } from '@univerjs/presets';
import type { IUniverUIConfig } from '@univerjs/ui';
-import type { IPreset } from './types';
import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
diff --git a/presets/packages/preset-docs-drawing/package.json b/presets/packages/preset-docs-drawing/package.json
index 7aab9019f4..032d1f4aea 100644
--- a/presets/packages/preset-docs-drawing/package.json
+++ b/presets/packages/preset-docs-drawing/package.json
@@ -78,6 +78,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-docs-drawing/src/types.ts b/presets/packages/preset-docs-drawing/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-docs-drawing/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-docs-drawing/src/umd.ts b/presets/packages/preset-docs-drawing/src/umd.ts
index 6386ad1ad2..219ce5990b 100644
--- a/presets/packages/preset-docs-drawing/src/umd.ts
+++ b/presets/packages/preset-docs-drawing/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { IImageIoService } from '@univerjs/core';
import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
diff --git a/presets/packages/preset-docs-hyper-link/package.json b/presets/packages/preset-docs-hyper-link/package.json
index 784fe81911..29db278dea 100644
--- a/presets/packages/preset-docs-hyper-link/package.json
+++ b/presets/packages/preset-docs-hyper-link/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-docs-hyper-link/src/umd.ts b/presets/packages/preset-docs-hyper-link/src/umd.ts
index a697a79905..278fdf0a64 100644
--- a/presets/packages/preset-docs-hyper-link/src/umd.ts
+++ b/presets/packages/preset-docs-hyper-link/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link';
import { UniverDocsHyperLinkUIPlugin } from '@univerjs/docs-hyper-link-ui';
diff --git a/presets/packages/preset-docs-node-core/package.json b/presets/packages/preset-docs-node-core/package.json
index e993efbb41..47fe5b2c25 100644
--- a/presets/packages/preset-docs-node-core/package.json
+++ b/presets/packages/preset-docs-node-core/package.json
@@ -79,6 +79,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"rxjs": "^7.8.2",
"typescript": "^6.0.3"
}
diff --git a/presets/packages/preset-docs-node-core/src/types.ts b/presets/packages/preset-docs-node-core/src/types.ts
index 4cc75182fd..1761590e3e 100644
--- a/presets/packages/preset-docs-node-core/src/types.ts
+++ b/presets/packages/preset-docs-node-core/src/types.ts
@@ -14,21 +14,8 @@
* limitations under the License.
*/
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
import type { IUniverEngineFormulaConfig } from '@univerjs/engine-formula';
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
-
export interface IUniverFormulaConfig extends
Pick<IUniverEngineFormulaConfig, 'function'> {
}
diff --git a/presets/packages/preset-docs-node-core/src/umd.ts b/presets/packages/preset-docs-node-core/src/umd.ts
index 8d597af3fd..e33cac42b1 100644
--- a/presets/packages/preset-docs-node-core/src/umd.ts
+++ b/presets/packages/preset-docs-node-core/src/umd.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { IPreset, IUniverFormulaConfig } from './types';
+import type { IPreset } from '@univerjs/presets';
+import type { IUniverFormulaConfig } from './types';
import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link';
diff --git a/presets/packages/preset-docs-thread-comment/package.json b/presets/packages/preset-docs-thread-comment/package.json
index 287564a5a8..e0fa0f197b 100644
--- a/presets/packages/preset-docs-thread-comment/package.json
+++ b/presets/packages/preset-docs-thread-comment/package.json
@@ -77,6 +77,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-docs-thread-comment/src/types.ts b/presets/packages/preset-docs-thread-comment/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-docs-thread-comment/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-docs-thread-comment/src/umd.ts b/presets/packages/preset-docs-thread-comment/src/umd.ts
index cf140583d9..2d89135c56 100644
--- a/presets/packages/preset-docs-thread-comment/src/umd.ts
+++ b/presets/packages/preset-docs-thread-comment/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverDocsThreadCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';
import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
diff --git a/presets/packages/preset-sheets-conditional-formatting/package.json b/presets/packages/preset-sheets-conditional-formatting/package.json
index 0d3a955ce6..33b4dce690 100644
--- a/presets/packages/preset-sheets-conditional-formatting/package.json
+++ b/presets/packages/preset-sheets-conditional-formatting/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-conditional-formatting/src/types.ts b/presets/packages/preset-sheets-conditional-formatting/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-conditional-formatting/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-conditional-formatting/src/umd.ts b/presets/packages/preset-sheets-conditional-formatting/src/umd.ts
index 883cdc26d4..d6e971b0a9 100644
--- a/presets/packages/preset-sheets-conditional-formatting/src/umd.ts
+++ b/presets/packages/preset-sheets-conditional-formatting/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverSheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';
import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';
diff --git a/presets/packages/preset-sheets-core/package.json b/presets/packages/preset-sheets-core/package.json
index 8359a0cc8c..dcb66a8e5f 100644
--- a/presets/packages/preset-sheets-core/package.json
+++ b/presets/packages/preset-sheets-core/package.json
@@ -94,6 +94,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-core/src/types.ts b/presets/packages/preset-sheets-core/src/types.ts
index 1ce72d4c0d..32127ea701 100644
--- a/presets/packages/preset-sheets-core/src/types.ts
+++ b/presets/packages/preset-sheets-core/src/types.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
import type { IUniverDocsConfig } from '@univerjs/docs';
import type { IUniverEngineFormulaConfig } from '@univerjs/engine-formula';
import type { IUniverSheetsConfig } from '@univerjs/sheets';
@@ -22,18 +21,6 @@ import type { IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
import type { IUniverSheetsFormulaUIConfig } from '@univerjs/sheets-formula-ui';
import type { IUniverSheetsUIConfig } from '@univerjs/sheets-ui';
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
-
export interface IUniverFormulaConfig extends
Pick<IUniverEngineFormulaConfig, 'function'>,
Pick<IUniverSheetsFormulaBaseConfig, 'description' | 'initialFormulaComputing'>,
diff --git a/presets/packages/preset-sheets-core/src/umd.ts b/presets/packages/preset-sheets-core/src/umd.ts
index a64de87627..8142e31a4d 100644
--- a/presets/packages/preset-sheets-core/src/umd.ts
+++ b/presets/packages/preset-sheets-core/src/umd.ts
@@ -14,11 +14,12 @@
* limitations under the License.
*/
+import type { IPreset } from '@univerjs/presets';
import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';
import type { IUniverSheetsNumfmtConfig } from '@univerjs/sheets-numfmt';
import type { IUniverSheetsUIConfig } from '@univerjs/sheets-ui';
import type { IUniverUIConfig } from '@univerjs/ui';
-import type { IPreset, IUniverDocsPresetConfig, IUniverFormulaConfig, IUniverSheetsPresetConfig } from './types';
+import type { IUniverDocsPresetConfig, IUniverFormulaConfig, IUniverSheetsPresetConfig } from './types';
import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
diff --git a/presets/packages/preset-sheets-core/src/worker.ts b/presets/packages/preset-sheets-core/src/worker.ts
index 1e05815433..8a0f02b1e1 100644
--- a/presets/packages/preset-sheets-core/src/worker.ts
+++ b/presets/packages/preset-sheets-core/src/worker.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { IPreset, IUniverFormulaWorkerConfig } from './types';
+import type { IPreset } from '@univerjs/presets';
+import type { IUniverFormulaWorkerConfig } from './types';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';
import { UniverSheetsPlugin } from '@univerjs/sheets';
diff --git a/presets/packages/preset-sheets-data-validation/package.json b/presets/packages/preset-sheets-data-validation/package.json
index bdda86213c..31669315ff 100644
--- a/presets/packages/preset-sheets-data-validation/package.json
+++ b/presets/packages/preset-sheets-data-validation/package.json
@@ -77,6 +77,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-data-validation/src/types.ts b/presets/packages/preset-sheets-data-validation/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-data-validation/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-data-validation/src/umd.ts b/presets/packages/preset-sheets-data-validation/src/umd.ts
index 46c9aa845b..6412b8fdf3 100644
--- a/presets/packages/preset-sheets-data-validation/src/umd.ts
+++ b/presets/packages/preset-sheets-data-validation/src/umd.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
+import type { IPreset } from '@univerjs/presets';
import type { IUniverSheetsDataValidationUIConfig } from '@univerjs/sheets-data-validation-ui';
-import type { IPreset } from './types';
import { UniverDataValidationPlugin } from '@univerjs/data-validation';
import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';
import { UniverSheetsDataValidationUIPlugin } from '@univerjs/sheets-data-validation-ui';
diff --git a/presets/packages/preset-sheets-drawing/package.json b/presets/packages/preset-sheets-drawing/package.json
index 187a79b5c8..152a34d948 100644
--- a/presets/packages/preset-sheets-drawing/package.json
+++ b/presets/packages/preset-sheets-drawing/package.json
@@ -79,6 +79,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-drawing/src/types.ts b/presets/packages/preset-sheets-drawing/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-drawing/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-drawing/src/umd.ts b/presets/packages/preset-sheets-drawing/src/umd.ts
index f93a00e25a..0108b113d0 100644
--- a/presets/packages/preset-sheets-drawing/src/umd.ts
+++ b/presets/packages/preset-sheets-drawing/src/umd.ts
@@ -15,7 +15,7 @@
*/
import type { IUniverDrawingConfig } from '@univerjs/drawing';
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
import { IImageIoService, UniverDrawingPlugin } from '@univerjs/drawing';
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
diff --git a/presets/packages/preset-sheets-filter/package.json b/presets/packages/preset-sheets-filter/package.json
index 5beda21224..7495df39de 100644
--- a/presets/packages/preset-sheets-filter/package.json
+++ b/presets/packages/preset-sheets-filter/package.json
@@ -82,6 +82,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-filter/src/types.ts b/presets/packages/preset-sheets-filter/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-filter/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-filter/src/umd.ts b/presets/packages/preset-sheets-filter/src/umd.ts
index 33b0918a6c..267d1042cd 100644
--- a/presets/packages/preset-sheets-filter/src/umd.ts
+++ b/presets/packages/preset-sheets-filter/src/umd.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
+import type { IPreset } from '@univerjs/presets';
import type { IUniverSheetsFilterConfig } from '@univerjs/sheets-filter';
-import type { IPreset } from './types';
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { UniverSheetsFilterUIPlugin } from '@univerjs/sheets-filter-ui';
diff --git a/presets/packages/preset-sheets-filter/src/worker.ts b/presets/packages/preset-sheets-filter/src/worker.ts
index 5c87750db5..5801867976 100644
--- a/presets/packages/preset-sheets-filter/src/worker.ts
+++ b/presets/packages/preset-sheets-filter/src/worker.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
export function UniverSheetsFilterWorkerPreset(): IPreset {
diff --git a/presets/packages/preset-sheets-find-replace/package.json b/presets/packages/preset-sheets-find-replace/package.json
index e4c2064070..1f20b9907f 100644
--- a/presets/packages/preset-sheets-find-replace/package.json
+++ b/presets/packages/preset-sheets-find-replace/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-find-replace/src/types.ts b/presets/packages/preset-sheets-find-replace/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-find-replace/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-find-replace/src/umd.ts b/presets/packages/preset-sheets-find-replace/src/umd.ts
index f63e21954c..2b9a798330 100644
--- a/presets/packages/preset-sheets-find-replace/src/umd.ts
+++ b/presets/packages/preset-sheets-find-replace/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverFindReplacePlugin } from '@univerjs/find-replace';
import { UniverSheetsFindReplacePlugin } from '@univerjs/sheets-find-replace';
diff --git a/presets/packages/preset-sheets-hyper-link/package.json b/presets/packages/preset-sheets-hyper-link/package.json
index 7cec6f98b7..af9fa0f801 100644
--- a/presets/packages/preset-sheets-hyper-link/package.json
+++ b/presets/packages/preset-sheets-hyper-link/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-hyper-link/src/types.ts b/presets/packages/preset-sheets-hyper-link/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-hyper-link/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-hyper-link/src/umd.ts b/presets/packages/preset-sheets-hyper-link/src/umd.ts
index 60c6321c92..5f6ad258d4 100644
--- a/presets/packages/preset-sheets-hyper-link/src/umd.ts
+++ b/presets/packages/preset-sheets-hyper-link/src/umd.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
+import type { IPreset } from '@univerjs/presets';
import type { IUniverSheetsHyperLinkUIConfig } from '@univerjs/sheets-hyper-link-ui';
-import type { IPreset } from './types';
import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';
import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';
diff --git a/presets/packages/preset-sheets-node-core/package.json b/presets/packages/preset-sheets-node-core/package.json
index cc21d3ded4..656dd15c65 100644
--- a/presets/packages/preset-sheets-node-core/package.json
+++ b/presets/packages/preset-sheets-node-core/package.json
@@ -92,6 +92,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"rxjs": "^7.8.2",
"typescript": "^6.0.3"
}
diff --git a/presets/packages/preset-sheets-node-core/src/types.ts b/presets/packages/preset-sheets-node-core/src/types.ts
index 0205bd683d..4784c5b095 100644
--- a/presets/packages/preset-sheets-node-core/src/types.ts
+++ b/presets/packages/preset-sheets-node-core/src/types.ts
@@ -14,22 +14,9 @@
* limitations under the License.
*/
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
import type { IUniverEngineFormulaConfig } from '@univerjs/engine-formula';
import type { IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
-
export interface IUniverFormulaConfig extends
Pick<IUniverEngineFormulaConfig, 'function'>,
Pick<IUniverSheetsFormulaBaseConfig, 'description' | 'initialFormulaComputing'> {
diff --git a/presets/packages/preset-sheets-node-core/src/umd.ts b/presets/packages/preset-sheets-node-core/src/umd.ts
index 75ea2b1d44..19628ab372 100644
--- a/presets/packages/preset-sheets-node-core/src/umd.ts
+++ b/presets/packages/preset-sheets-node-core/src/umd.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { IPreset, IUniverFormulaConfig } from './types';
+import type { IPreset } from '@univerjs/presets';
+import type { IUniverFormulaConfig } from './types';
import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverRPCNodeMainPlugin } from '@univerjs/rpc-node';
diff --git a/presets/packages/preset-sheets-node-core/src/worker.ts b/presets/packages/preset-sheets-node-core/src/worker.ts
index fa3c624479..7b16d1d71b 100644
--- a/presets/packages/preset-sheets-node-core/src/worker.ts
+++ b/presets/packages/preset-sheets-node-core/src/worker.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { IPreset, IUniverFormulaWorkerConfig } from './types';
+import type { IPreset } from '@univerjs/presets';
+import type { IUniverFormulaWorkerConfig } from './types';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverRPCNodeWorkerPlugin } from '@univerjs/rpc-node';
import { UniverSheetsPlugin } from '@univerjs/sheets';
diff --git a/presets/packages/preset-sheets-note/package.json b/presets/packages/preset-sheets-note/package.json
index abd956cd3f..7d9e373af0 100644
--- a/presets/packages/preset-sheets-note/package.json
+++ b/presets/packages/preset-sheets-note/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-note/src/types.ts b/presets/packages/preset-sheets-note/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-note/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-note/src/umd.ts b/presets/packages/preset-sheets-note/src/umd.ts
index efffe455ce..348a122621 100644
--- a/presets/packages/preset-sheets-note/src/umd.ts
+++ b/presets/packages/preset-sheets-note/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverSheetsNotePlugin } from '@univerjs/sheets-note';
import { UniverSheetsNoteUIPlugin } from '@univerjs/sheets-note-ui';
diff --git a/presets/packages/preset-sheets-sort/package.json b/presets/packages/preset-sheets-sort/package.json
index 12bcabf012..16606a182b 100644
--- a/presets/packages/preset-sheets-sort/package.json
+++ b/presets/packages/preset-sheets-sort/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-sort/src/types.ts b/presets/packages/preset-sheets-sort/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-sort/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-sort/src/umd.ts b/presets/packages/preset-sheets-sort/src/umd.ts
index 843fb85f22..33e45a10a8 100644
--- a/presets/packages/preset-sheets-sort/src/umd.ts
+++ b/presets/packages/preset-sheets-sort/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';
import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';
diff --git a/presets/packages/preset-sheets-table/package.json b/presets/packages/preset-sheets-table/package.json
index c1543106bd..c5ac2da00f 100644
--- a/presets/packages/preset-sheets-table/package.json
+++ b/presets/packages/preset-sheets-table/package.json
@@ -76,6 +76,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-table/src/types.ts b/presets/packages/preset-sheets-table/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-table/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-table/src/umd.ts b/presets/packages/preset-sheets-table/src/umd.ts
index c51eb8ea3c..961d45e7e6 100644
--- a/presets/packages/preset-sheets-table/src/umd.ts
+++ b/presets/packages/preset-sheets-table/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverSheetsTablePlugin } from '@univerjs/sheets-table';
import { UniverSheetsTableUIPlugin } from '@univerjs/sheets-table-ui';
diff --git a/presets/packages/preset-sheets-thread-comment/package.json b/presets/packages/preset-sheets-thread-comment/package.json
index 3af74f760c..789d6d8850 100644
--- a/presets/packages/preset-sheets-thread-comment/package.json
+++ b/presets/packages/preset-sheets-thread-comment/package.json
@@ -78,6 +78,7 @@
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
"@univerjs/core": "workspace:*",
+ "@univerjs/presets": "workspace:*",
"react": "18.3.1",
"react-dom": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/presets/packages/preset-sheets-thread-comment/src/types.ts b/presets/packages/preset-sheets-thread-comment/src/types.ts
deleted file mode 100644
index 4d13fb9621..0000000000
--- a/presets/packages/preset-sheets-thread-comment/src/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IUniverConfig, Plugin, PluginCtor } from '@univerjs/core';
-
-/**
- * A collection of plugins and their default configs.
- */
-export interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
- locales?: IUniverConfig['locales'];
-}
-
-export interface IPresetOptions {
- lazy?: boolean;
-}
diff --git a/presets/packages/preset-sheets-thread-comment/src/umd.ts b/presets/packages/preset-sheets-thread-comment/src/umd.ts
index ecad38c067..a54e9de287 100644
--- a/presets/packages/preset-sheets-thread-comment/src/umd.ts
+++ b/presets/packages/preset-sheets-thread-comment/src/umd.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IPreset } from './types';
+import type { IPreset } from '@univerjs/presets';
import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';
import { UniverSheetsThreadCommentUIPlugin } from '@univerjs/sheets-thread-comment-ui';
import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
diff --git a/presets/src/umd.ts b/presets/src/umd.ts
index 1062d641db..94c79d502c 100644
--- a/presets/src/umd.ts
+++ b/presets/src/umd.ts
@@ -23,17 +23,20 @@ export * from '@univerjs/core/facade';
/**
* A collection of plugins and their default configs.
*/
-interface IPreset {
- plugins: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
+export type IPresetPlugin = PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]];
+
+export interface IPreset {
+ plugins: IPresetPlugin[];
+ locales?: IUniverConfig['locales'];
}
-interface IPresetOptions {
+export interface IPresetOptions {
lazy?: boolean;
}
type CreateUniverOptions = Partial<IUniverConfig> & {
presets: Array<IPreset | [IPreset, IPresetOptions]>;
- plugins?: Array<PluginCtor<Plugin> | [PluginCtor<Plugin>, ConstructorParameters<PluginCtor<Plugin>>[0]]>;
+ plugins?: IPresetPlugin[];
/**
* Overrides the dependencies defined in the plugin. Only dependencies that are identified by `IdentifierDecorator` can be overridden.
* If you override a dependency with `null`, the original dependency will be removed.