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.

fix(engine-formula): correct AST caching and preserve dependency updates (#8075)

wpxp1234569c57dcc4adf4
diff --git a/packages/core/src/shared/__tests__/r-tree.integration.spec.ts b/packages/core/src/shared/__tests__/r-tree.integration.spec.ts
index 49af727b62..574c0ba2db 100644
--- a/packages/core/src/shared/__tests__/r-tree.integration.spec.ts
+++ b/packages/core/src/shared/__tests__/r-tree.integration.spec.ts
@@ -14,11 +14,185 @@
* limitations under the License.
*/
+import { describe, expect, it, vi } from 'vitest';
import type { IRange } from '../../sheets/typedef';
-import { describe, expect, it } from 'vitest';
+import type { IRTreeItem } from '../r-tree';
import { RTree } from '../r-tree';
describe('RTree integration', () => {
+ it.each([[false, 2], [true, 2], [false, 8], [true, 8]] as const)('removes sparse ranges without collecting or rebuilding the whole tree (cell cache: %s, searches: %s)', (cellCache, searchCount) => {
+ const tree = new RTree(cellCache);
+ const items: IRTreeItem[] = Array.from({ length: 1000 }, (_, index) => ({
+ unitId: 'unit',
+ sheetId: 'sheet',
+ id: index,
+ range: { startRow: index * 3, endRow: index * 3 + 1, startColumn: 0, endColumn: 1 },
+ }));
+ tree.bulkInsert(items);
+ const index = tree.getTree('unit', 'sheet');
+ const collect = vi.spyOn(index, 'all');
+ const rebuild = vi.spyOn(index, 'load');
+ try {
+ const searches = Array.from({ length: searchCount }, (_, index) => items[Math.floor(index * 999 / (searchCount - 1))]);
+ tree.bulkRemove(searches);
+ expect(collect).not.toHaveBeenCalled();
+ expect(rebuild).not.toHaveBeenCalled();
+ expect(tree.bulkSearch(searches)).toEqual(new Set());
+ expect(tree.bulkSearch([items[1], items[998]])).toEqual(new Set([1, 998]));
+ expect(index.all()).toHaveLength(1000 - searchCount);
+ } finally {
+ collect.mockRestore();
+ rebuild.mockRestore();
+ tree.dispose();
+ }
+ });
+
+ it('keeps dense removal batched even when only two searches hit thousands of entries', () => {
+ const tree = new RTree();
+ const range = { startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 };
+ const removed = { unitId: 'unit', sheetId: 'sheet', id: 'removed', range };
+ tree.bulkInsert(Array.from({ length: 4096 }, () => removed));
+ tree.insert({ ...removed, id: 'keep', range: { startRow: 100, endRow: 101, startColumn: 0, endColumn: 1 } });
+ const index = tree.getTree('unit', 'sheet');
+ const rebuild = vi.spyOn(index, 'load');
+ try {
+ tree.bulkRemove([removed, { ...removed, id: 'absent' }]);
+ expect(rebuild).toHaveBeenCalledTimes(1);
+ expect(tree.bulkSearch([removed])).toEqual(new Set());
+ expect(index.all().map((item) => item.id)).toEqual(['keep']);
+ } finally {
+ rebuild.mockRestore();
+ tree.dispose();
+ }
+ });
+
+ it('removes cached points without deleting overlapping ranges with the same ID', () => {
+ const tree = new RTree(true);
+ const point = (row: number, id = 'same'): IRTreeItem => ({
+ unitId: 'unit',
+ sheetId: 'sheet',
+ id,
+ range: { startRow: row, endRow: row, startColumn: 1, endColumn: 1 },
+ });
+ tree.bulkInsert([point(1), point(2), point(1, 'keep'), point(2, 'keep'), {
+ ...point(1),
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ }]);
+ tree.openKdTree();
+ tree.bulkRemove([point(1), point(2)]);
+ expect(Array.from(tree.searchGenerator(point(1)))).toEqual(['keep', 'same']);
+ expect(Array.from(tree.searchGenerator(point(2)))).toEqual(['keep', 'same']);
+ tree.dispose();
+ });
+
+ it('removes unbounded cached ranges without walking every coordinate or affecting other IDs', () => {
+ const tree = new RTree(true);
+ const range = { startRow: 0, endRow: Infinity, startColumn: 0, endColumn: Infinity };
+ const removed = { unitId: 'unit', sheetId: 'sheet', id: 'removed', range };
+ tree.bulkInsert([
+ { ...removed, range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },
+ { ...removed, id: 'keep', range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },
+ { ...removed, range: { startRow: 2, endRow: 3, startColumn: 2, endColumn: 3 } },
+ ]);
+ tree.openKdTree();
+ tree.bulkRemove([removed, removed]);
+ expect(tree.bulkSearch([removed])).toEqual(new Set(['keep']));
+ expect(tree.getTree('unit', 'sheet').all()).toEqual([]);
+ tree.dispose();
+ });
+
+ it('does not allocate an index when removing from an unindexed sheet', () => {
+ const tree = new RTree();
+ const item = { unitId: 'unit', sheetId: 'sheet', id: 1, range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } };
+ tree.remove(item);
+ tree.bulkRemove([item, { ...item, id: 2 }]);
+ expect(tree.toJSON()).toEqual({});
+ tree.dispose();
+ });
+
+ it.each([false, true])('preserves batch removal of NaN IDs (cell cache: %s)', (cellCache) => {
+ const tree = new RTree(cellCache);
+ const items = [0, 10].map((row) => ({
+ unitId: 'unit',
+ sheetId: 'sheet',
+ id: Number.NaN,
+ range: { startRow: row, endRow: row + 1, startColumn: 0, endColumn: 1 },
+ }));
+ tree.bulkInsert([...items, { ...items[0], id: 'keep' }]);
+ tree.bulkRemove(items);
+ expect(tree.getTree('unit', 'sheet').all().map((item) => item.id)).toEqual(['keep']);
+ tree.dispose();
+ });
+
+ it.each([[0.5, 0], [0, 0.5]])('preserves cached-point deletion with fractional range starts (%s, %s)', (startRow, startColumn) => {
+ const tree = new RTree(true);
+ const point = { unitId: 'unit', sheetId: 'sheet', id: 'removed', range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } };
+ tree.bulkInsert([point, { ...point, id: 'keep' }]);
+ tree.openKdTree();
+ const range = { startRow, endRow: 2.5, startColumn, endColumn: 2.5 };
+ tree.bulkRemove([{ ...point, range }, { ...point, range, id: 'absent' }]);
+ expect(tree.bulkSearch([point])).toEqual(new Set(['keep']));
+ tree.dispose();
+ });
+
+ it('keeps ranged deletion of cached fractional coordinates equivalent to batch matching', () => {
+ const tree = new RTree(true);
+ const point = { unitId: 'unit', sheetId: 'sheet', id: 'removed', range: { startRow: 1.5, endRow: 1.5, startColumn: 1.5, endColumn: 1.5 } };
+ tree.bulkInsert([point, { ...point, id: 'keep' }]);
+ tree.openKdTree();
+ const range = { startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 };
+ tree.bulkRemove([{ ...point, range }, { ...point, range, id: 'absent' }]);
+ expect(tree.bulkSearch([point])).toEqual(new Set(['keep']));
+ tree.dispose();
+ });
+
+ it.each([false, true])('keeps batch removal equivalent to individual removal (cell cache: %s)', (cellCache) => {
+ const batch = new RTree(cellCache);
+ const individual = new RTree(cellCache);
+ const items: IRTreeItem[] = [];
+ for (const unitId of ['unit-a', 'unit-b']) {
+ for (const sheetId of ['sheet-a', 'sheet-b']) {
+ for (let index = 0; index < 40; index++) {
+ const row = index % 5;
+ const column = Math.floor(index / 5);
+ items.push({ unitId, sheetId, id: index % 7, range: {
+ startRow: row,
+ endRow: row + index % 2,
+ startColumn: column,
+ endColumn: column + index % 3,
+ } });
+ }
+ }
+ }
+ batch.bulkInsert(items);
+ individual.bulkInsert(items);
+ batch.openKdTree();
+ individual.openKdTree();
+ const searches = [
+ { ...items[2], range: { startRow: 2, endRow: 2, startColumn: 1, endColumn: 1 } },
+ { ...items[2], range: { startRow: 0, endRow: 0, startColumn: 6, endColumn: 6 } },
+ { ...items[0], range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 3 } },
+ { ...items[1], range: { startRow: 1, endRow: 4, startColumn: 2, endColumn: 4 } },
+ { ...items[0], range: { startRow: 4, endRow: 5, startColumn: 6, endColumn: 7 } },
+ { ...items[80], range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 10 } },
+ ];
+ batch.bulkRemove(searches);
+ for (const search of searches) {
+ individual.remove(search);
+ }
+ for (const unitId of ['unit-a', 'unit-b']) {
+ for (const sheetId of ['sheet-a', 'sheet-b']) {
+ for (let row = 0; row < 6; row++) {
+ for (let column = 0; column < 10; column++) {
+ const query = { unitId, sheetId, range: { startRow: row, endRow: row, startColumn: column, endColumn: column } };
+ expect(batch.bulkSearch([query])).toEqual(individual.bulkSearch([query]));
+ }
+ }
+ }
+ }
+ batch.dispose();
+ individual.dispose();
+ });
it('should index both single-cell and ranged items and support removal and serialization', () => {
const tree = new RTree(true);
diff --git a/packages/core/src/shared/r-tree.ts b/packages/core/src/shared/r-tree.ts
index da6d2ee7c5..5d09a3b76a 100644
--- a/packages/core/src/shared/r-tree.ts
+++ b/packages/core/src/shared/r-tree.ts
@@ -15,9 +15,9 @@
*/
import type { BBox } from 'rbush';
-import type { IUnitRange } from '../sheets/typedef';
import KDBush from 'kdbush';
import RBush from 'rbush';
+import type { IUnitRange } from '../sheets/typedef';
type StringOrNumber = string | number;
@@ -29,6 +29,11 @@ interface IRBushItem extends BBox {
id: StringOrNumber;
}
+interface IRBushNode extends BBox {
+ children: (IRBushNode | IRBushItem)[];
+ leaf: boolean;
+}
+
interface IRdTreeItem {
x: number;
y: number;
@@ -295,7 +300,8 @@ export class RTree {
private _removeRTreeItem(search: IRTreeItem) {
const { unitId, sheetId: subUnitId, range, id } = search;
- const tree = this.getTree(unitId, subUnitId);
+ const tree = this._tree.get(unitId)?.get(subUnitId);
+ if (!tree) return;
const items = tree.search({
minX: range.startColumn,
@@ -327,9 +333,127 @@ export class RTree {
}
bulkRemove(searchList: IRTreeItem[]) {
+ if (searchList.length < 2) {
+ for (const search of searchList) {
+ this.remove(search);
+ }
+ return;
+ }
+ const groups = new Map<string, Map<string, Map<StringOrNumber, IRTreeItem[]>>>();
for (const search of searchList) {
- this.remove(search);
+ let sheets = groups.get(search.unitId);
+ if (!sheets) {
+ sheets = new Map();
+ groups.set(search.unitId, sheets);
+ }
+ let ids = sheets.get(search.sheetId);
+ if (!ids) {
+ ids = new Map();
+ sheets.set(search.sheetId, ids);
+ }
+ const ranges = ids.get(search.id);
+ if (ranges) {
+ ranges.push(search);
+ } else {
+ ids.set(search.id, [search]);
+ }
+ }
+ for (const [unitId, sheets] of groups) {
+ for (const [sheetId, ids] of sheets) {
+ if (!this._removeSparseRanges(unitId, sheetId, ids)) {
+ this._bulkRemoveFromSheet(unitId, sheetId, ids);
+ }
+ }
+ }
+ }
+
+ private _bulkRemoveFromSheet(unitId: string, sheetId: string, searches: Map<StringOrNumber, IRTreeItem[]>) {
+ if (searches.size === 1) {
+ const [ranges] = searches.values();
+ if (ranges.length === 1) {
+ this.remove(ranges[0]);
+ return;
+ }
+ }
+ // With the point cache enabled, remove() treats point searches as point-cache-only removals.
+ const matches = (id: StringOrNumber, bounds: BBox, rangedOnly = false) => searches.get(id)?.some(({ range }) =>
+ (!rangedOnly || !this._enableOneCellCache || range.startRow !== range.endRow || range.startColumn !== range.endColumn) &&
+ range.startColumn <= bounds.maxX && range.endColumn >= bounds.minX &&
+ range.startRow <= bounds.maxY && range.endRow >= bounds.minY
+ ) ?? false;
+ const tree = this._tree.get(unitId)?.get(sheetId);
+ if (tree) {
+ const entries = tree.all();
+ let retained = 0;
+ for (const item of entries) {
+ if (!matches(item.id, item, true)) {
+ entries[retained++] = item;
+ }
+ }
+ if (retained !== entries.length) {
+ entries.length = retained;
+ tree.clear();
+ tree.load(entries);
+ }
+ }
+ const cells = this._oneCellCache.get(unitId)?.get(sheetId);
+ if (cells) {
+ for (const [row, columns] of cells) {
+ for (const [column, ids] of columns) {
+ const bounds = { minX: column, maxX: column, minY: row, maxY: row };
+ for (const id of ids) {
+ if (matches(id, bounds)) {
+ ids.delete(id);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private _removeSparseRanges(unitId: string, sheetId: string, searches: Map<StringOrNumber, IRTreeItem[]>) {
+ // Probe a bounded number of candidates without allocating a full-tree snapshot.
+ let remaining = 128;
+ if (searches.size > remaining) return false;
+ const visit = (node: IRBushNode, range: IUnitRange['range']): boolean => {
+ if (--remaining < 0) return false;
+ if (!node.leaf && range.startColumn <= node.minX && range.endColumn >= node.maxX &&
+ range.startRow <= node.minY && range.endRow >= node.maxY) {
+ return false;
+ }
+ for (const child of node.children) {
+ if (range.startColumn <= child.maxX && range.endColumn >= child.minX &&
+ range.startRow <= child.maxY && range.endRow >= child.minY) {
+ if (node.leaf) {
+ if (--remaining < 0) return false;
+ } else if (!visit(child as IRBushNode, range)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ };
+ const tree = this._tree.get(unitId)?.get(sheetId);
+ const root = tree?.toJSON() as IRBushNode | undefined;
+ const cells = this._oneCellCache.get(unitId)?.get(sheetId);
+ for (const [id, ranges] of searches) {
+ if (Number.isNaN(id)) return false;
+ for (const { range } of ranges) {
+ if (--remaining < 0) return false;
+ if (this._enableOneCellCache) {
+ if (range.startRow === range.endRow && range.startColumn === range.endColumn) continue;
+ // Ranged cache removal must visit stored coordinates, including sparse and fractional keys.
+ if (cells) return false;
+ }
+ if (root && !visit(root, range)) return false;
+ }
+ }
+ for (const ranges of searches.values()) {
+ for (const search of ranges) {
+ this.remove(search);
+ }
}
+ return true;
}
clear() {
diff --git a/packages/engine-formula/src/basics/__tests__/cache-lru.spec.ts b/packages/engine-formula/src/basics/__tests__/cache-lru.spec.ts
new file mode 100644
index 0000000000..89729ca5fe
--- /dev/null
+++ b/packages/engine-formula/src/basics/__tests__/cache-lru.spec.ts
@@ -0,0 +1,83 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { hashAlgorithm } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { FormulaAstLRU } from '../cache-lru';
+
+// Two AST cache keys that share a 32-bit hash. This is the pair from the reported
+// workbook: P1169 holds `=A1*326+23354`, Q16084 holds `=A1*645+321655`.
+const UNIT_ID = '00000000-0000-4000-8000-000000000001';
+const KEY_A = `${UNIT_ID}:sheet1:15:1168:=A1*326+23354`;
+const KEY_B = `${UNIT_ID}:sheet1:16:16083:=A1*645+321655`;
+
+describe('formulaAstLRU', () => {
+ it('keeps colliding keys as separate entries', () => {
+ expect(hashAlgorithm(KEY_A)).toBe(hashAlgorithm(KEY_B));
+
+ const lru = new FormulaAstLRU<number>(10);
+ lru.set(KEY_A, 26614);
+ lru.set(KEY_B, 328105);
+
+ expect(lru.get(KEY_A)).toBe(26614);
+ expect(lru.get(KEY_B)).toBe(328105);
+ });
+
+ it('keeps a cell without its own entry a miss even when another key collides', () => {
+ const lru = new FormulaAstLRU<number>(10);
+ lru.set(KEY_A, 26614);
+ lru.set(KEY_B, 328105);
+
+ const otherCellSameFormula = `${UNIT_ID}:sheet1:17:1168:=A1*326+23354`;
+ expect(lru.get(otherCellSameFormula)).toBeUndefined();
+ });
+
+ it('exposes original keys through forEach', () => {
+ const lru = new FormulaAstLRU<number>(10);
+ lru.set(KEY_A, 26614);
+ lru.set(KEY_B, 328105);
+
+ const seen = new Map<string, number>();
+ lru.forEach((value, key) => {
+ seen.set(key, value);
+ });
+
+ expect(seen.get(KEY_A)).toBe(26614);
+ expect(seen.get(KEY_B)).toBe(328105);
+ });
+
+ it('deletes only the requested key', () => {
+ const lru = new FormulaAstLRU<number>(10);
+ lru.set(KEY_A, 26614);
+
+ lru.delete(KEY_B);
+
+ expect(lru.get(KEY_A)).toBe(26614);
+
+ lru.delete(KEY_A);
+
+ expect(lru.get(KEY_A)).toBeUndefined();
+ });
+
+ it('keeps long and short keys independent', () => {
+ const lru = new FormulaAstLRU<string>(10);
+ lru.set('unit:sheet:0:0:=1+1', 'short');
+ lru.set(KEY_A, 'long');
+
+ expect(lru.get('unit:sheet:0:0:=1+1')).toBe('short');
+ expect(lru.get(KEY_A)).toBe('long');
+ });
+});
diff --git a/packages/engine-formula/src/basics/cache-lru.ts b/packages/engine-formula/src/basics/cache-lru.ts
index e54abc1871..9a58c4914b 100644
--- a/packages/engine-formula/src/basics/cache-lru.ts
+++ b/packages/engine-formula/src/basics/cache-lru.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { hashAlgorithm, LRUMap } from '@univerjs/core';
+import { LRUMap } from '@univerjs/core';
export class FormulaAstLRU<T> {
private _cache: LRUMap<string, T>;
@@ -23,14 +23,14 @@ export class FormulaAstLRU<T> {
this._cache = new LRUMap<string, T>(cacheCount);
}
+ // The full key is stored as-is. Hashing long keys into 32 bits let two different
+ // formulas share one entry, so a cell could be evaluated with another cell's AST.
set(formulaString: string, node: T) {
- const hash = this._hash(formulaString);
- this._cache.set(hash, node);
+ this._cache.set(formulaString, node);
}
get(formulaString: string) {
- const hash = this._hash(formulaString);
- return this._cache.get(hash);
+ return this._cache.get(formulaString);
}
clear() {
@@ -38,17 +38,10 @@ export class FormulaAstLRU<T> {
}
delete(formulaString: string) {
- this._cache.delete(this._hash(formulaString));
+ this._cache.delete(formulaString);
}
forEach(callbackfn: (value: T, key: string, map: LRUMap<string, T>) => void, thisArg?: any) {
this._cache.forEach(callbackfn, thisArg);
}
-
- private _hash(formulaString: string) {
- if (formulaString.length <= 64) {
- return formulaString;
- }
- return hashAlgorithm(formulaString).toString();
- }
}
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index 58dc20be56..5540fae76a 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -233,6 +233,10 @@ export interface ISuperTable {
showFooter?: boolean;
}
+export interface ISuperTableData extends Omit<ISuperTable, 'titleMap'> {
+ titleMap: Record<string, number>;
+}
+
export enum TableOptionType {
ALL = '#All',
DATA = '#Data',
diff --git a/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.ts b/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.ts
index 6a0d3f1fdb..6de6271110 100644
--- a/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.ts
+++ b/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.ts
@@ -110,6 +110,8 @@ describe('formula reference mutations', () => {
it('sets and removes structured-reference tables used by formulas', async () => {
const tableReference = {
+ sheetId: 'sheet-1',
+ titleMap: new Map([['Amount', 0]]),
range: {
startRow: 0,
endRow: 10,
@@ -136,6 +138,39 @@ describe('formula reference mutations', () => {
expect(superTableService.hasTable('book-1', 'SalesTable')).toBe(false);
});
+ it.each([true, false])('restores table column maps after JSON transport (showHeader=%s)', async (showHeader) => {
+ const titleMap = Object.fromEntries([
+ ['Amount', 0],
+ ['__proto__', 1],
+ ['constructor', 2],
+ ['净额\n含税', 3],
+ ['10', 4],
+ ]);
+ const params = JSON.parse(JSON.stringify({
+ unitId: 'book-1',
+ tableName: 'SalesTable',
+ reference: {
+ sheetId: 'sheet-1',
+ titleMap,
+ range: { startRow: 0, endRow: 10, startColumn: 0, endColumn: 4 },
+ showHeader,
+ showFooter: true,
+ },
+ }));
+
+ expect(await commandService.executeCommand(SetSuperTableMutation.id, params)).toBe(true);
+
+ const table = superTableService.getTable('book-1', 'SalesTable')!;
+ expect(table).toEqual({ ...params.reference, titleMap: new Map(Object.entries(titleMap)) });
+ expect(table.titleMap.get('__proto__')).toBe(1);
+ expect(table.titleMap.get('净额\n含税')).toBe(3);
+ expect(table.titleMap.get('10')).toBe(4);
+ // The main-thread handler must leave the outgoing mutation JSON serializable.
+ expect(params.reference.titleMap).toEqual(titleMap);
+ expect(JSON.parse(JSON.stringify(params))).toEqual(params);
+ expect(params.reference.titleMap).not.toBeInstanceOf(Map);
+ });
+
it('registers localized structured-reference table options', async () => {
const result = await commandService.executeCommand(SetSuperTableOptionMutation.id, {
tableOption: '数据',
diff --git a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
index e50bab0b3b..ffc0413b32 100644
--- a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
@@ -15,9 +15,9 @@
*/
import type { IMutation } from '@univerjs/core';
-import type { ISuperTable } from '../../basics/common';
-import type { ISuperTableOptionParam } from '../../services/super-table.service';
import { CommandType } from '@univerjs/core';
+import type { ISuperTable, ISuperTableData } from '../../basics/common';
+import type { ISuperTableOptionParam } from '../../services/super-table.service';
import { ISuperTableService } from '../../services/super-table.service';
export interface ISetSuperTableMutationSearchParam {
@@ -31,7 +31,8 @@ export interface IRemoveSuperTableMutationParam extends ISetSuperTableMutationSe
export interface ISetSuperTableMutationParam extends ISetSuperTableMutationSearchParam {
oldTableName?: string;
- reference: ISuperTable;
+ /** Plain column data for RPC; Map remains accepted for existing local callers. */
+ reference: ISuperTableData | ISuperTable;
}
/**
* In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.
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 377ebd12f7..c910529ddc 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
@@ -14,20 +14,155 @@
* limitations under the License.
*/
-import type { Injector } from '@univerjs/core';
-import type { FormulaDependencyTreeVirtual } from '../../dependency/dependency-tree';
+import type { ICellData, Injector } from '@univerjs/core';
+import { ObjectMatrix, Styles } from '@univerjs/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type {
+ IDirtyUnitDefinedNameMap,
+ IDirtyUnitSheetNameMap,
+ IDirtyUnitSuperTableMap,
+ IFormulaDatasetConfig,
+ IUnitExcludedCell,
+ IUnitSheetIdToNameMap,
+} from '../../../basics/common';
+import type { FormulaDependencyTreeVirtual } from '../../dependency/dependency-tree';
import { ErrorType } from '../../../basics/error-type';
+import { FUNCTION_NAMES_LOOKUP } from '../../../functions/lookup/function-names';
+import { Index } from '../../../functions/lookup/index';
+import { Indirect } from '../../../functions/lookup/indirect';
+import { Sum } from '../../../functions/math/sum';
+import { ICalculateFormulaService } from '../../../services/calculate-formula.service';
import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
+import { IDefinedNamesService } from '../../../services/defined-names.service';
+import { IDependencyManagerService } from '../../../services/dependency-manager.service';
import { IFeatureCalculationManagerService } from '../../../services/feature-calculation-manager.service';
+import { IFunctionService } from '../../../services/function.service';
import { IOtherFormulaManagerService } from '../../../services/other-formula-manager.service';
import { IFormulaRuntimeService } from '../../../services/runtime.service';
import { FormulaDependencyTree } from '../../dependency/dependency-tree';
import { IFormulaDependencyGenerator } from '../../dependency/formula-dependency';
import { Interpreter } from '../../interpreter/interpreter';
+import { FORMULA_AST_CACHE } from '../../utils/generate-ast-node';
import { ErrorValueObject } from '../../value-object/base-value-object';
import { createCommandTestBed } from './create-command-test-bed';
+describe('value-dependent reference ranges', () => {
+ it.each(['InputData', 'inputdata'])('rebinds %s after named-range expansion and later source edits', async (name) => {
+ FORMULA_AST_CACHE.clear();
+ const bed = createCommandTestBed();
+ try {
+ bed.get(IFunctionService).registerExecutors(new Sum('SUM'));
+ const cells = bed.sheetData[bed.sheetId].cellData;
+ for (let row = 0; row < 4; row++) {
+ cells.setValue(row, 0, { v: row + 1 });
+ }
+ const names = bed.get(IDefinedNamesService);
+ const setName = (end: number) => names.registerDefinedName(bed.unitId, {
+ id: 'input-data',
+ name: 'InputData',
+ formulaOrRefString: `Main!$A$1:$A$${end}`,
+ });
+ const service = bed.get(ICalculateFormulaService);
+ let actual: unknown;
+ service.executionCompleteListener$.subscribe((data) => {
+ actual = data.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 5)?.v;
+ });
+ const calculate = async (forceCalculate: boolean, nameChanged = false) => {
+ await service.execute({
+ formulaData: { [bed.unitId]: { [bed.sheetId]: { 0: { 5: { f: `=SUM(${name})` } } } } },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate,
+ dirtyRanges: forceCalculate
+ ? []
+ : [{ unitId: bed.unitId, sheetId: bed.sheetId, range: {
+ startRow: 3,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 0,
+ } }],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: nameChanged ? { [bed.unitId]: { InputData: 'Main!$A$1:$A$4' } } : {},
+ dirtySuperTableMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ clearDependencyTreeCache: {},
+ excludedCell: {},
+ unitSheetNameMap: { [bed.unitId]: { Main: bed.sheetId } },
+ allUnitData: { [bed.unitId]: bed.sheetData },
+ });
+ return actual;
+ };
+ setName(2);
+ expect(await calculate(true)).toBe(3);
+ setName(4);
+ expect(await calculate(true, true)).toBe(10);
+ cells.setValue(3, 0, { v: 40 });
+ expect(await calculate(false)).toBe(46);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+ it.each([
+ ['vertical', false],
+ ['vertical', true],
+ ['horizontal', false],
+ ['horizontal', true],
+ ] as const)('updates %s INDEX endpoints after a selector edit (forced: %s)', async (direction, forceSelector) => {
+ FORMULA_AST_CACHE.clear();
+ const bed = createCommandTestBed();
+ try {
+ bed.get(IFunctionService).registerExecutors(new Index('INDEX'), new Sum('SUM'));
+ const service = bed.get(ICalculateFormulaService);
+ const horizontal = direction === 'horizontal';
+ const formula = horizontal ? '=SUM(A1:INDEX(A1:D1,1,G1))' : '=SUM(A1:INDEX(A1:A4,D1))';
+ const selector = horizontal ? [0, 6] : [0, 3];
+ const last = horizontal ? [0, 3] : [3, 0];
+ let hostValue: number | undefined;
+ service.executionCompleteListener$.subscribe((data) => {
+ const value = data.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 5)?.v;
+ if (typeof value === 'number') {
+ hostValue = value;
+ }
+ });
+ const calculate = async (length: number, lastValue: number, dirty: number[], forceCalculate: boolean) => {
+ const cells = new ObjectMatrix<ICellData>({});
+ for (let index = 0; index < 4; index++) {
+ cells.setValue(horizontal ? 0 : index, horizontal ? index : 0, { v: index === 3 ? lastValue : index + 1 });
+ }
+ cells.setValue(selector[0], selector[1], { v: length });
+ cells.setValue(0, 5, { f: formula, v: hostValue });
+ await service.execute({
+ formulaData: { [bed.unitId]: { [bed.sheetId]: { 0: { 5: { f: formula } } } } },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate,
+ dirtyRanges: [{ unitId: bed.unitId, sheetId: bed.sheetId, range: { startRow: dirty[0], endRow: dirty[0], startColumn: dirty[1], endColumn: dirty[1] } }],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtySuperTableMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ clearDependencyTreeCache: {},
+ excludedCell: {},
+ unitSheetNameMap: { [bed.unitId]: { Main: bed.sheetId } },
+ unitStylesData: { [bed.unitId]: new Styles({}) },
+ allUnitData: { [bed.unitId]: { [bed.sheetId]: { cellData: cells, rowCount: 100, columnCount: 20, rowData: {}, columnData: {} } } },
+ } as IFormulaDatasetConfig);
+ return hostValue;
+ };
+ expect(await calculate(2, 4, selector, true)).toBe(3);
+ expect(await calculate(4, 4, selector, forceSelector)).toBe(10);
+ expect(await calculate(4, 40, last, false)).toBe(46);
+ expect(await calculate(1, 40, selector, false)).toBe(1);
+ expect(await calculate(1, 5, last, false)).toBe(1);
+ expect(await calculate(4, 5, selector, false)).toBe(11);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
+
describe('Test dependency', () => {
let get: Injector['get'];
let formulaDependencyGenerator: IFormulaDependencyGenerator;
@@ -380,4 +515,271 @@ describe('Test dependency', () => {
await expect(formulaDependencyGenerator.generate()).resolves.toHaveLength(1);
});
});
+
+ describe('dependency reuse', () => {
+ const load = (formula: string, options: {
+ forceCalculate?: boolean;
+ dirtyDefinedNameMap?: IDirtyUnitDefinedNameMap;
+ dirtyNameMap?: IDirtyUnitSheetNameMap;
+ dirtySuperTableMap?: IDirtyUnitSuperTableMap;
+ clearDependencyTreeCache?: IUnitSheetIdToNameMap;
+ excludedCell?: IUnitExcludedCell;
+ sheetData?: unknown;
+ sheetNameMap?: Record<string, string>;
+ } = {}) => {
+ formulaCurrentConfigService.load({
+ formulaData: {
+ [testUnitId]: {
+ [testSheetId]: {
+ 0: {
+ 2: { f: formula },
+ },
+ },
+ },
+ },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: options.forceCalculate ?? false,
+ dirtyRanges: [{
+ unitId: testUnitId,
+ sheetId: testSheetId,
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ }],
+ dirtyNameMap: options.dirtyNameMap ?? {},
+ dirtyDefinedNameMap: options.dirtyDefinedNameMap ?? {},
+ dirtySuperTableMap: options.dirtySuperTableMap ?? {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ clearDependencyTreeCache: options.clearDependencyTreeCache ?? {},
+ excludedCell: options.excludedCell ?? {},
+ unitSheetNameMap: { [testUnitId]: { Sheet1: testSheetId, ...options.sheetNameMap } },
+ unitStylesData: { [testUnitId]: new Styles({}) },
+ allUnitData: {
+ [testUnitId]: (options.sheetData ?? testSheetData) as never,
+ },
+ });
+ };
+
+ const spyRangeList = () => vi.spyOn(formulaDependencyGenerator as unknown as {
+ _getRangeListByNode: () => unknown;
+ }, '_getRangeListByNode');
+
+ const rTreeEntryCount = () => {
+ const dependencyManagerService = get(IDependencyManagerService) as unknown as {
+ _dependencyRTreeCache: { getTree: (unitId: string, sheetId: string) => { all: () => unknown[] } };
+ };
+ return dependencyManagerService._dependencyRTreeCache.getTree(testUnitId, testSheetId).all().length;
+ };
+
+ it('reuses the resolved ranges of an unchanged formula', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ expect(rTreeEntryCount()).toBe(1);
+
+ const spy = spyRangeList();
+ load('=SUM(A1:B10)');
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).not.toHaveBeenCalled();
+ // Reusing the ranges also means the index entry is left untouched.
+ expect(rTreeEntryCount()).toBe(1);
+ });
+
+ it('keeps the reused formula in the calculation when a referenced cell changes', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ // The dirty range from the helper covers A1, which the formula references.
+ load('=SUM(A1:B10)');
+ const treeList = await formulaDependencyGenerator.generate();
+
+ expect(spy).not.toHaveBeenCalled();
+ expect(treeList).toHaveLength(1);
+ });
+
+ it('recomputes when the formula text changes', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ get(IDependencyManagerService).removeFormulaDependency(testUnitId, testSheetId, 0, 2);
+
+ const spy = spyRangeList();
+ load('=SUM(A1:C10)');
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(rTreeEntryCount()).toBe(1);
+ });
+
+ it('recomputes when a sheet name is dirty', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=SUM(A1:B10)', { dirtyNameMap: { [testUnitId]: { [testSheetId]: 'Renamed' } } });
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('recomputes when the sheet size changes', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=SUM(A1:B10)', {
+ sheetData: {
+ ...(testSheetData as Record<string, Record<string, unknown>>),
+ [testSheetId]: {
+ ...(testSheetData as Record<string, Record<string, unknown>>)[testSheetId],
+ rowCount: 200,
+ },
+ },
+ });
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('recomputes when a referenced sheet is resized', async () => {
+ const sheetData = (rowCount: number) => ({
+ ...(testSheetData as Record<string, unknown>),
+ sheet2: {
+ cellData: new ObjectMatrix({ 0: { 0: { v: 1 } } }),
+ rowCount,
+ columnCount: 20,
+ },
+ });
+
+ load('=SUM(Sheet2!A:A)', {
+ forceCalculate: true,
+ sheetData: sheetData(100),
+ sheetNameMap: { Sheet2: 'sheet2' },
+ });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ // Only the referenced sheet is resized; the formula sheet and its AST are untouched,
+ // but an open-ended reference is clipped to the size of the sheet it points at.
+ load('=SUM(Sheet2!A:A)', {
+ sheetData: sheetData(200),
+ sheetNameMap: { Sheet2: 'sheet2' },
+ });
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('reuses the ranges but re-indexes after a forced calculation', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ // The ranges come from the still cached AST.
+ expect(spy).not.toHaveBeenCalled();
+ // The forced calculation reset the index, so the tree has to be written again.
+ expect(rTreeEntryCount()).toBe(1);
+ });
+
+ it('recomputes when the dependency tree cache is cleared', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=SUM(A1:B10)', { clearDependencyTreeCache: { [testUnitId]: { [testSheetId]: 'Sheet1' } } });
+ await formulaDependencyGenerator.generate();
+
+ // A cleared dependency cache also drops the resolved ranges, so they are rebuilt.
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(rTreeEntryCount()).toBe(1);
+ });
+
+ it('recomputes when a defined name change marks the formula dirty', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ // Dirty defined-name entries are keyed by the affected formula text; the AST cache
+ // rebuilds those formulas, so the range list is resolved again from a new AST.
+ load('=SUM(A1:B10)', { dirtyDefinedNameMap: { [testUnitId]: { 'SUM(A1:B10)': 'changed' } } });
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps reusing a formula that a super table change does not reference', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ // The dirty table is not referenced by this formula, so its AST (and the ranges
+ // resolved from it) stay valid.
+ load('=SUM(A1:B10)', { dirtySuperTableMap: { [testUnitId]: { table1: 'changed' } } });
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse a formula whose references resolve while executing', async () => {
+ // INDIRECT is only flagged as an address function when its executor is registered.
+ get(IFunctionService).registerExecutors(new Indirect(FUNCTION_NAMES_LOOKUP.INDIRECT));
+
+ load('=INDIRECT("A1")', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=INDIRECT("A1")');
+ await formulaDependencyGenerator.generate();
+
+ // The ranges are resolved again because the target only exists at execution time.
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it('does not reuse a cell excluded from the calculation', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=SUM(A1:B10)', {
+ excludedCell: {
+ [testUnitId]: {
+ [testSheetId]: new ObjectMatrix<boolean>({ 0: { 2: true } }),
+ },
+ },
+ });
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('recomputes after the AST cache is invalidated for a function', async () => {
+ load('=SUM(A1:B10)', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ // Unregistering a function removes its cached ASTs, so the next calculation parses
+ // the formula again and the range list is resolved from the new AST.
+ get(IFunctionService).deleteFormulaAstCacheKey('SUM' as never);
+ load('=SUM(A1:B10)');
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it('does not reuse a formula that failed to parse', async () => {
+ load('=1+', { forceCalculate: true });
+ await formulaDependencyGenerator.generate();
+
+ const spy = spyRangeList();
+ load('=1+');
+ await formulaDependencyGenerator.generate();
+
+ expect(spy).toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 830b249bf8..4ebb83157f 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -20,6 +20,15 @@ import type {
Nullable,
Workbook,
} from '@univerjs/core';
+import {
+ createIdentifier,
+ Disposable,
+ Inject,
+ IUniverInstanceService,
+ ObjectMatrix,
+ RTree,
+ UniverInstanceType,
+} from '@univerjs/core';
import type {
IFeatureDirtyRangeType,
IFormulaData,
@@ -45,15 +54,6 @@ import type {
IFormulaDependencyTreeJson,
IFormulaDependentsAndInRangeResults,
} from './dependency-tree';
-import {
- createIdentifier,
- Disposable,
- Inject,
- IUniverInstanceService,
- ObjectMatrix,
- RTree,
- UniverInstanceType,
-} from '@univerjs/core';
import { prefixToken, suffixToken } from '../../basics/token';
import { FUNCTION_NAMES_LOOKUP } from '../../functions/lookup/function-names';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
@@ -94,6 +94,10 @@ export interface IFormulaDependencyGenerator {
export const IFormulaDependencyGenerator = createIdentifier<IFormulaDependencyGenerator>('engine-formula.dependency-generator');
+function isEmptyRecord(record: Record<string, unknown> | null | undefined) {
+ return record == null || Object.keys(record).length === 0;
+}
+
export class FormulaDependencyGenerator extends Disposable implements IFormulaDependencyGenerator {
private _updateRangeFlattenCache = new Map<string, Map<string, IRange[]>>();
@@ -101,6 +105,15 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
protected _dependencyTreeCache = new Map<number, IFormulaDependencyTree>();
+ // Keyed by the AST instance the engine is already reusing, so the range list cannot
+ // outlive the AST it was resolved from.
+ private _reusableRanges = new WeakMap<BaseAstNode, IUnitRange[] | null>();
+
+ // Sheet sizes take part in resolving open-ended references (`A:A`, `A1:`), and the AST
+ // cache does not invalidate on a resize, so the resolved ranges are only reusable while
+ // every sheet keeps the size it had when they were resolved.
+ private _reusableSheetSignature: Nullable<string> = null;
+
constructor(
@IFormulaCurrentConfigService protected readonly _currentConfigService: IFormulaCurrentConfigService,
@IFormulaRuntimeService protected readonly _runtimeService: IFormulaRuntimeService,
@@ -688,6 +701,69 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
return false;
}
+ /**
+ * Whether the ranges resolved for this formula may be kept for a later calculation. This
+ * is independent of whether they may be reused right now: a forced calculation rebuilds
+ * the index but the ranges it resolves are still valid for the next one.
+ */
+ private _canShareRanges(tree: IFormulaDependencyTree, node: BaseAstNode, addressFunctionNodes: FunctionNode[]) {
+ if (addressFunctionNodes.length > 0) {
+ return false;
+ }
+
+ const excludedCell = this._currentConfigService.getExcludedRange()?.[tree.unitId]?.[tree.subUnitId];
+ if (excludedCell?.getValue(tree.row, tree.column) != null) {
+ return false;
+ }
+
+ const cached = this._reusableRanges.get(node);
+ if (cached !== undefined) {
+ return cached !== null;
+ }
+
+ const references: PreCalculateNodeType[] = [];
+ this._nodeTraversalRef(node, references);
+ if (references.some((reference) => !this._isStaticReference(reference))) {
+ // A stable AST can still resolve different ranges after an input value changes.
+ this._reusableRanges.set(node, null);
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * `A:A` and other open-ended references are clipped to the size of the sheet they point
+ * at, so any resize can change a resolved range list without touching the AST.
+ */
+ private _getSheetSignature(unitData: IUnitData) {
+ let signature = '';
+
+ for (const unitId of Object.keys(unitData)) {
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ signature += JSON.stringify(workbook?.getSheetOrders());
+ const sheets = unitData[unitId];
+ if (sheets == null) {
+ continue;
+ }
+
+ for (const sheetId of Object.keys(sheets)) {
+ const sheet = sheets[sheetId];
+ signature += `${unitId}:${sheetId}:${sheet.rowCount}:${sheet.columnCount};`;
+ }
+ }
+
+ return signature;
+ }
+
+ private _takeReusableRanges(node: BaseAstNode) {
+ return this._reusableRanges.get(node);
+ }
+
+ private _storeReusableRanges(node: BaseAstNode, rangeList: IUnitRange[]) {
+ this._reusableRanges.set(node, [...rangeList]);
+ }
+
/**
* Generate nodes for the dependency tree, where each node contains all the reference data ranges included in each formula.
* @param formulaData
@@ -715,6 +791,16 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
this._registerFeatureFormulas(treeList as FormulaDependencyTree[]);
+ const sheetSignature = this._getSheetSignature(unitData);
+
+ const canReuseRanges = this._reusableSheetSignature === sheetSignature
+ && isEmptyRecord(this._currentConfigService.getDirtyNameMap())
+ && isEmptyRecord(this._currentConfigService.getClearDependencyTreeCache());
+
+ if (!canReuseRanges) {
+ this._reusableRanges = new WeakMap();
+ }
+
for (let i = 0, len = treeList.length; i < len; i++) {
const tree = treeList[i];
@@ -744,14 +830,31 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
continue;
}
+ const canShare = this._canShareRanges(tree, node, addressFunctionNodes);
+ const cachedRangeList = canShare && canReuseRanges ? this._takeReusableRanges(node) : undefined;
+
+ if (cachedRangeList != null) {
+ (tree as FormulaDependencyTree).pushRangeList(cachedRangeList);
+ // The index entries survive only while the dependency index does. A forced
+ // calculation resets it, in which case the tree has to be inserted again.
+ tree.isCache = this._dependencyManagerService.hasDependencyRTreeCache(tree.treeId);
+ continue;
+ }
+
const rangeList = await this._getRangeListByNode({
node,
refOffsetX: tree.refOffsetX,
refOffsetY: tree.refOffsetY,
});
(tree as FormulaDependencyTree).pushRangeList(rangeList);
+
+ if (canShare) {
+ this._storeReusableRanges(node, rangeList);
+ }
}
+ this._reusableSheetSignature = sheetSignature;
+
for (let i = 0, len = treeList.length; i < len; i++) {
const tree = treeList[i];
if (tree.isCache) {
@@ -915,7 +1018,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
result.push(item as PreCalculateNodeType);
if (item.nodeType === NodeType.UNION) {
for (const unionChildItem of item.getChildren()) {
- if (unionChildItem.nodeType === NodeType.FUNCTION && (unionChildItem as FunctionNode).isAddress()) {
+ if (!this._isStaticReference(unionChildItem)) {
this._nodeTraversalRef(unionChildItem, result);
}
}
diff --git a/packages/engine-formula/src/engine/value-object/cube-value-object.ts b/packages/engine-formula/src/engine/value-object/cube-value-object.ts
index f629584b8d..f22457f916 100644
--- a/packages/engine-formula/src/engine/value-object/cube-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/cube-value-object.ts
@@ -14,13 +14,14 @@
* limitations under the License.
*/
+import type { BaseReferenceObject } from '../reference-object/base-reference-object';
import type { ArrayValueObject } from './array-value-object';
import { BaseValueObject } from './base-value-object';
import { NumberValueObject } from './primitive-object';
export class CubeValueObject extends BaseValueObject {
- static create(values: ArrayValueObject[]) {
- return new CubeValueObject(values);
+ static create(values: ArrayValueObject[], references?: BaseReferenceObject[]) {
+ return new CubeValueObject(values, references);
}
override isCube() {
@@ -29,7 +30,7 @@ export class CubeValueObject extends BaseValueObject {
private _values: ArrayValueObject[] = [];
- constructor(values: ArrayValueObject[]) {
+ constructor(values: ArrayValueObject[], private _references?: BaseReferenceObject[]) {
super();
this._values = values;
}
@@ -39,12 +40,17 @@ export class CubeValueObject extends BaseValueObject {
value.dispose();
});
this._values = [];
+ this._references = undefined;
}
getCubeValues(): ArrayValueObject[] {
return this._values;
}
+ getCubeReferences(): BaseReferenceObject[] | undefined {
+ return this._references;
+ }
+
getCubeCount(): number {
return this._values.length;
}
diff --git a/packages/engine-formula/src/functions/lookup/choose/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/choose/__tests__/index.spec.ts
index 65edf2e74e..93441ff197 100644
--- a/packages/engine-formula/src/functions/lookup/choose/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/choose/__tests__/index.spec.ts
@@ -27,6 +27,15 @@ describe('Test choose function', () => {
const testFunction = new Choose(FUNCTION_NAMES_LOOKUP.CHOOSE);
describe('Choose', () => {
+ it('keeps a one-element array selector as an array result', () => {
+ const result = testFunction.calculate(
+ ArrayValueObject.create('{2}'),
+ NumberValueObject.create(11),
+ NumberValueObject.create(22)
+ );
+ expect(result.isArray()).toBe(true);
+ expect(getObjectValue(result)).toEqual([[22]]);
+ });
it('Index num and value', async () => {
const indexNum = NumberValueObject.create(2);
const value1 = NumberValueObject.create(11);
diff --git a/packages/engine-formula/src/functions/lookup/choose/index.ts b/packages/engine-formula/src/functions/lookup/choose/index.ts
index 2420419440..39bc05d5be 100644
--- a/packages/engine-formula/src/functions/lookup/choose/index.ts
+++ b/packages/engine-formula/src/functions/lookup/choose/index.ts
@@ -40,7 +40,10 @@ export class Choose extends BaseFunction {
}
if (_indexNum.isReferenceObject()) {
- _indexNum = (_indexNum as BaseReferenceObject).toArrayValueObject();
+ const values = (_indexNum as BaseReferenceObject).toArrayValueObject();
+ _indexNum = values.getRowCount() === 1 && values.getColumnCount() === 1
+ ? values.get(0, 0) as BaseValueObject
+ : values;
}
if (!_indexNum.isArray()) {
diff --git a/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
index 0188ec40eb..3a402498c5 100644
--- a/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts
@@ -15,11 +15,11 @@
*/
import type { Injector, IWorkbookData } from '@univerjs/core';
-import type { LexerNode } from '../../../../engine/analysis/lexer-node';
-
-import type { BaseAstNode } from '../../../../engine/ast-node/base-ast-node';
import { CellValueType, LocaleType } from '@univerjs/core';
import { beforeEach, describe, expect, it } from 'vitest';
+import type { LexerNode } from '../../../../engine/analysis/lexer-node';
+import type { BaseAstNode } from '../../../../engine/ast-node/base-ast-node';
+import { createFunctionTestBed } from '../../../__tests__/create-function-test-bed';
import { ErrorType } from '../../../../basics/error-type';
import { Lexer } from '../../../../engine/analysis/lexer';
import { AstTreeBuilder } from '../../../../engine/analysis/parser';
@@ -28,7 +28,7 @@ import { generateExecuteAstNodeData } from '../../../../engine/utils/ast-node-to
import { IFormulaCurrentConfigService } from '../../../../services/current-data.service';
import { IFunctionService } from '../../../../services/function.service';
import { IFormulaRuntimeService } from '../../../../services/runtime.service';
-import { createFunctionTestBed } from '../../../__tests__/create-function-test-bed';
+import { Cube } from '../../../meta/cube';
import { getObjectValue } from '../../../util';
import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
import { Index } from '../index';
@@ -190,7 +190,8 @@ describe('Test index', () => {
);
functionService.registerExecutors(
- new Index(FUNCTION_NAMES_LOOKUP.INDEX)
+ new Index(FUNCTION_NAMES_LOOKUP.INDEX),
+ new Cube('CUBE')
);
calculate = (formula: string) => {
@@ -205,6 +206,13 @@ describe('Test index', () => {
});
describe('One row', () => {
+ it('selects the first and second reference areas without losing their addresses', () => {
+ expect(calculate('=INDEX((A1:A2,B1:B2),2,1,1)')).toStrictEqual([[3]]);
+ expect(calculate('=INDEX((A1:A2,B1:B2),2,1,2)')).toStrictEqual([[4]]);
+ expect(calculate('=INDEX((A1:A2,B1:B2),0,1,2)')).toStrictEqual([[2], [4]]);
+ expect(calculate('=INDEX((A1:A2,B1:B2),1,1,0)')).toBe(ErrorType.VALUE);
+ expect(calculate('=INDEX((A1:A2,B1:B2),1,1,3)')).toBe(ErrorType.REF);
+ });
it('Column number null, different row parameters', async () => {
// null
const result = await calculate('=INDEX(A6:B6,1)');
diff --git a/packages/engine-formula/src/functions/lookup/index/index.ts b/packages/engine-formula/src/functions/lookup/index/index.ts
index 0d1bdaf95a..1fb18c40b4 100644
--- a/packages/engine-formula/src/functions/lookup/index/index.ts
+++ b/packages/engine-formula/src/functions/lookup/index/index.ts
@@ -15,6 +15,7 @@
*/
import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
+import type { MultiAreaReferenceObject } from '../../../engine/reference-object/multi-area-reference-object';
import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import type { CubeValueObject } from '../../../engine/value-object/cube-value-object';
@@ -159,7 +160,7 @@ export class Index extends BaseFunction {
const areaNumValue = Math.floor(+_areaNum.getValue());
- if (areaNumValue < 0) {
+ if (areaNumValue < 1) {
return ErrorValueObject.create(ErrorType.VALUE);
}
@@ -192,10 +193,10 @@ export class Index extends BaseFunction {
return ErrorValueObject.create(ErrorType.REF);
}
- let _reference = reference;
+ const _reference = this._getReferenceArea(reference, areaNumValue);
- if (areaNumValue > 1) {
- _reference = (reference as CubeValueObject).getCubeValues()[areaNumValue - 1];
+ if (_reference.isError()) {
+ return _reference;
}
if (
@@ -215,6 +216,18 @@ export class Index extends BaseFunction {
return this._calculateArrayObject(_reference as BaseValueObject, rowNumValue, columnNumValue);
}
+ private _getReferenceArea(reference: FunctionVariantType, areaNum: number): FunctionVariantType {
+ if (reference.isReferenceObject()) {
+ if ((reference as BaseReferenceObject).isMultiArea()) {
+ return (reference as MultiAreaReferenceObject).getAreas().flat()[areaNum - 1];
+ }
+ } else if ((reference as BaseValueObject).isCube()) {
+ const cube = reference as CubeValueObject;
+ return cube.getCubeReferences()?.[areaNum - 1] ?? cube.getCubeValues()[areaNum - 1];
+ }
+ return reference;
+ }
+
private _getReferenceCounts(reference: FunctionVariantType): { rowCount: number; columnCount: number }[] {
let referenceRowColumnCounts = [
{
@@ -223,7 +236,14 @@ export class Index extends BaseFunction {
},
];
- if (reference.isReferenceObject()) {
+ if (reference.isReferenceObject() && (reference as BaseReferenceObject).isMultiArea()) {
+ referenceRowColumnCounts = (reference as MultiAreaReferenceObject).getAreas().flat().map((area) => {
+ if (area instanceof ErrorValueObject) {
+ return { rowCount: 1, columnCount: 1 };
+ }
+ return { rowCount: area.getRowCount(), columnCount: area.getColumnCount() };
+ });
+ } else if (reference.isReferenceObject()) {
referenceRowColumnCounts = [
{
rowCount: (reference as BaseReferenceObject).getRowCount(),
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
index 9f00e58866..1fe551acbb 100644
--- a/packages/engine-formula/src/functions/meta/cube/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/meta/cube/__tests__/index.spec.ts
@@ -16,15 +16,56 @@
import { describe, expect, it } from 'vitest';
import { ErrorType } from '../../../../basics/error-type';
+import { createCommandTestBed } from '../../../../engine/analysis/__tests__/create-command-test-bed';
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 { ICalculateFormulaService } from '../../../../services/calculate-formula.service';
+import { IFunctionService } from '../../../../services/function.service';
+import { Sumproduct } from '../../../math/sumproduct';
+import { Countif } from '../../../statistical/countif';
import { getObjectValue } from '../../../util';
import { FUNCTION_NAMES_META } from '../../function-names';
import { Cube } from '../index';
describe('Cube function', () => {
+ it.each([
+ ['=SUMPRODUCT((A1:A2,B1:B2))', ErrorType.VALUE],
+ ['=COUNTIF((A1:A2,B1:B2),">0")', ErrorType.VALUE],
+ ] as const)('preserves value semantics for %s while retaining reference areas', async (formula, expected) => {
+ const bed = createCommandTestBed();
+ try {
+ bed.get(IFunctionService).registerExecutors(
+ new Cube('CUBE'),
+ new Sumproduct('SUMPRODUCT'),
+ new Countif('COUNTIF')
+ );
+ const service = bed.get(ICalculateFormulaService);
+ let actual: unknown;
+ service.executionCompleteListener$.subscribe((data) => {
+ actual = data.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 5)?.v;
+ });
+ await service.execute({
+ formulaData: { [bed.unitId]: { [bed.sheetId]: { 0: { 5: { f: formula } } } } },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: true,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtySuperTableMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ clearDependencyTreeCache: {},
+ excludedCell: {},
+ allUnitData: { [bed.unitId]: bed.sheetData },
+ });
+ expect(actual).toBe(expected);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
const testFunction = new Cube(FUNCTION_NAMES_META.CUBE);
it('combines multiple array references into a cube value object', () => {
diff --git a/packages/engine-formula/src/functions/meta/cube/index.ts b/packages/engine-formula/src/functions/meta/cube/index.ts
index ebcadfa70a..7f350ab38c 100644
--- a/packages/engine-formula/src/functions/meta/cube/index.ts
+++ b/packages/engine-formula/src/functions/meta/cube/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorType } from '../../../basics/error-type';
@@ -22,15 +23,20 @@ import { CubeValueObject } from '../../../engine/value-object/cube-value-object'
import { BaseFunction } from '../../base-function';
export class Cube extends BaseFunction {
+ override needsReferenceObject = true;
override minParams = 1;
override maxParams = 255;
- override calculate(...variants: BaseValueObject[]) {
+ override calculate(...variants: FunctionVariantType[]) {
+ // Preserve addresses for reference-form INDEX without changing the cube's value semantics.
+ const references = variants.every((variant) => variant.isReferenceObject()) ? variants as BaseReferenceObject[] : undefined;
const values: ArrayValueObject[] = [];
for (let i = 0; i < variants.length; i++) {
- const variant = variants[i];
+ const variant = variants[i].isReferenceObject()
+ ? (variants[i] as BaseReferenceObject).toArrayValueObject()
+ : variants[i] as BaseValueObject;
if (variant.isError()) {
return variant;
@@ -43,6 +49,6 @@ export class Cube extends BaseFunction {
values.push(variant as ArrayValueObject);
}
- return CubeValueObject.create(values);
+ return CubeValueObject.create(values, references);
}
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index e2153ce64b..9cd880f7e9 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -45,7 +45,7 @@ export type {
export { BooleanValue } from './basics/common';
export { type IOtherFormulaData } from './basics/common';
-export type { IExprTreeNode, ISuperTable, IUnitRowData } from './basics/common';
+export type { IExprTreeNode, ISuperTable, ISuperTableData, IUnitRowData } from './basics/common';
export { isInDirtyRange } from './basics/dirty';
export { ERROR_TYPE_SET, ErrorType } from './basics/error-type';
export { type ISheetFormulaError } from './basics/error-type';
diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.ts
index a4fcbe2536..8934a0c626 100644
--- a/packages/engine-formula/src/plugin.ts
+++ b/packages/engine-formula/src/plugin.ts
@@ -15,8 +15,8 @@
*/
import type { Dependency } from '@univerjs/core';
-import type { IUniverEngineFormulaConfig } from './config/config';
import { IConfigService, Inject, Injector, merge, Plugin, touchDependencies } from '@univerjs/core';
+import type { IUniverEngineFormulaConfig } from './config/config';
import pkg from '../package.json';
import { defaultPluginConfig, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from './config/config';
import { CalculateController } from './controllers/calculate.controller';
@@ -48,12 +48,12 @@ import { FormulaDataModel } from './models/formula-data.model';
import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';
import { CalculateFormulaService, ICalculateFormulaService } from './services/calculate-formula.service';
import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './services/current-data.service';
+import { DefinedNamesService, IDefinedNamesService } from './services/defined-names.service';
+import { DependencyManagerService, IDependencyManagerService } from './services/dependency-manager.service';
import {
IFormulaExternalReferenceDataLoader,
NoopFormulaExternalReferenceDataLoader,
} from './services/external-reference-data-loader.service';
-import { DefinedNamesService, IDefinedNamesService } from './services/defined-names.service';
-import { DependencyManagerService, IDependencyManagerService } from './services/dependency-manager.service';
import {
FeatureCalculationManagerService,
IFeatureCalculationManagerService,
diff --git a/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts b/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts
index af8ece9c96..79eb527b2a 100644
--- a/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { AstRootNode } from '../../engine/ast-node';
import { Injector } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import type { AstRootNode } from '../../engine/ast-node';
import { FormulaDependencyTree } from '../../engine/dependency/dependency-tree';
import { DependencyManagerBaseService, DependencyManagerService, IDependencyManagerService } from '../dependency-manager.service';
@@ -73,6 +73,92 @@ function createService(): IDependencyManagerService {
}
describe('DependencyManagerService', () => {
+ it.each([false, true])('retains incoming dependencies when clearing many source-sheet formulas (point: %s)', (point) => {
+ const service = createService();
+ const range = { unitId: 'unit-1', sheetId: 'source', range: {
+ startRow: 0,
+ endRow: point ? 0 : 10,
+ startColumn: 0,
+ endColumn: 0,
+ } };
+ for (let id = 0; id < 512; id++) {
+ const tree = createTree(id, id + 10, 1);
+ tree.subUnitId = 'source';
+ tree.rangeList = [range];
+ service.addFormulaDependency('unit-1', 'source', id + 10, 1, tree);
+ service.addDependencyRTreeCache(tree);
+ }
+ const kept = createTree(10000, 0, 5);
+ kept.rangeList = [range];
+ service.addFormulaDependency('unit-1', 'sheet-1', 0, 5, kept);
+ service.addDependencyRTreeCache(kept);
+ service.openKdTree();
+ expect(service.searchDependency([range]).size).toBe(513);
+ service.clearFormulaDependency('unit-1', 'source');
+ expect(service.searchDependency([range])).toEqual(new Set([10000]));
+ expect(service.getFormulaDependency('unit-1', 'sheet-1', 0, 5)).toBe(10000);
+ expect(service.hasDependencyRTreeCache(1)).toBe(false);
+ service.closeKdTree();
+ service.dispose();
+ });
+ it('removes old bounds when a tree moves to a disjoint referenced range', () => {
+ const service = createService();
+ const tree = createTree(91, 0, 0);
+ const oldRange = tree.rangeList;
+ service.addDependencyRTreeCache(tree);
+ tree.rangeList = [{ ...oldRange[0], range: { startRow: 20, endRow: 21, startColumn: 4, endColumn: 5 } }];
+ service.addDependencyRTreeCache(tree);
+ expect(service.searchDependency(oldRange)).toEqual(new Set());
+ expect(service.searchDependency(tree.rangeList)).toEqual(new Set([91]));
+ });
+
+ it('does not search overlapping entries when indexing new trees', () => {
+ const service = createService();
+ const index = (service as unknown as { _dependencyRTreeCache: { remove: (...args: unknown[]) => void } })._dependencyRTreeCache;
+ const remove = vi.spyOn(index, 'remove');
+ for (let id = 0; id < 512; id++) {
+ service.addDependencyRTreeCache(createTree(id, 0, 0));
+ }
+ expect(remove).not.toHaveBeenCalled();
+ });
+
+ it.each(['formula', 'other', 'feature'] as const)('clears only the %s trees owned by the requested sheet', (kind) => {
+ const service = createService();
+ const kept = createTree(92, 0, 0);
+ const removed = createTree(93, 2, 2);
+ removed.subUnitId = 'sheet-2';
+ kept.rangeList[0].sheetId = 'sheet-2';
+ removed.rangeList[0].sheetId = 'sheet-3';
+ if (kind === 'formula') {
+ service.addFormulaDependency('unit-1', 'sheet-1', 0, 0, kept);
+ service.addFormulaDependency('unit-1', 'sheet-2', 2, 2, removed);
+ } else if (kind === 'other') {
+ service.addOtherFormulaDependency('unit-1', 'sheet-1', 'kept', kept);
+ service.addOtherFormulaDependency('unit-1', 'sheet-2', 'removed', removed);
+ } else {
+ service.addFeatureFormulaDependency('unit-1', 'sheet-1', 'kept', kept);
+ service.addFeatureFormulaDependency('unit-1', 'sheet-2', 'removed', removed);
+ }
+ service.addDependencyRTreeCache(kept);
+ service.addDependencyRTreeCache(removed);
+ const clear = (sheetId: string) => {
+ if (kind === 'formula') {
+ service.clearFormulaDependency('unit-1', sheetId);
+ } else if (kind === 'other') {
+ service.clearOtherFormulaDependency('unit-1', sheetId);
+ } else {
+ service.clearFeatureFormulaDependency('unit-1', sheetId);
+ }
+ };
+ clear('missing-sheet');
+ expect(service.searchDependency(kept.rangeList)).toEqual(new Set([92]));
+ expect(service.searchDependency(removed.rangeList)).toEqual(new Set([93]));
+ clear('sheet-2');
+ expect(service.searchDependency(kept.rangeList)).toEqual(new Set([92]));
+ expect(service.hasDependencyRTreeCache(92)).toBe(true);
+ expect(service.searchDependency(removed.rangeList)).toEqual(new Set());
+ expect(service.hasDependencyRTreeCache(93)).toBe(false);
+ });
it('should keep base dependency manager state through DI-created subclass', () => {
const injector = new Injector();
injector.add([DependencyManagerBaseService, { useClass: TestDependencyManagerBaseService }]);
@@ -150,6 +236,29 @@ describe('DependencyManagerService', () => {
expect(service.searchDependency(searchB)).toEqual(new Set());
});
+ it('keeps one index entry per tree after repeated registrations', () => {
+ const service = createService();
+ const tree = createTree(30, 0, 0);
+ const search = [{
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 },
+ }];
+
+ // A tree that cannot reuse its previous result is registered again on every
+ // recalculation; that must not append another copy of its ranges.
+ for (let i = 0; i < 5; i++) {
+ service.addDependencyRTreeCache(tree);
+ }
+
+ const rtree = (service as unknown as {
+ _dependencyRTreeCache: { getTree: (unitId: string, sheetId: string) => { all: () => unknown[] } };
+ })._dependencyRTreeCache;
+
+ expect(rtree.getTree('unit-1', 'sheet-1').all()).toHaveLength(1);
+ expect(service.searchDependency(search)).toEqual(new Set([30]));
+ });
+
it('should manage other-formula dependency matrices and main-data flag', () => {
const service = createService();
const tree = createTree(10, 0, 0);
diff --git a/packages/engine-formula/src/services/__tests__/super-table.service.spec.ts b/packages/engine-formula/src/services/__tests__/super-table.service.spec.ts
index 2819b3cf29..6e925a13c4 100644
--- a/packages/engine-formula/src/services/__tests__/super-table.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/super-table.service.spec.ts
@@ -29,9 +29,13 @@ describe('SuperTableService', () => {
});
it('registers workbook tables case-insensitively for structured references', () => {
- const table = { name: 'SalesTable' };
+ const table = {
+ sheetId: 'sheet-1',
+ titleMap: new Map([['Amount', 0]]),
+ range: { startRow: 0, endRow: 10, startColumn: 0, endColumn: 0 },
+ };
- service.registerTable('book-1', 'SalesTable', table as never);
+ service.registerTable('book-1', 'SalesTable', table);
expect(service.hasTable('book-1', 'salestable')).toBe(true);
expect(service.getTable('book-1', 'SalesTable')).toBe(table);
@@ -41,7 +45,11 @@ describe('SuperTableService', () => {
const changes: unknown[] = [];
service.update$.subscribe((change) => changes.push(change));
- service.registerTable('book-1', 'SalesTable', { name: 'SalesTable' } as never);
+ service.registerTable('book-1', 'SalesTable', {
+ sheetId: 'sheet-1',
+ titleMap: { Amount: 0 },
+ range: { startRow: 0, endRow: 10, startColumn: 0, endColumn: 0 },
+ });
service.remove('book-1', 'SalesTable');
expect(changes).toEqual([null, null]);
diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.ts
index 7fc841e1cb..c2b4876d5f 100644
--- a/packages/engine-formula/src/services/dependency-manager.service.ts
+++ b/packages/engine-formula/src/services/dependency-manager.service.ts
@@ -15,9 +15,9 @@
*/
import type { IRange, IRTreeItem, IUnitRange, Nullable } from '@univerjs/core';
+import { createIdentifier, Disposable, ObjectMatrix, RTree } from '@univerjs/core';
import type { AstRootNode } from '../engine/ast-node';
import type { FormulaDependencyTree, IFormulaDependencyTree } from '../engine/dependency/dependency-tree';
-import { createIdentifier, Disposable, ObjectMatrix, RTree } from '@univerjs/core';
export interface IDependencyManagerService {
dispose(): void;
@@ -45,6 +45,7 @@ export interface IDependencyManagerService {
addFormulaDependencyByDefinedName(tree: IFormulaDependencyTree, node: Nullable<AstRootNode>): void;
addDependencyRTreeCache(tree: IFormulaDependencyTree): void;
+ hasDependencyRTreeCache(treeId: number): boolean;
searchDependency(search: IUnitRange[], exceptTreeIds?: Set<number>): Set<number>;
getLastTreeId(): number;
@@ -182,6 +183,15 @@ export class DependencyManagerBaseService extends Disposable implements IDepende
this._addAllTreeMap(tree);
}
+ /**
+ * Whether this tree is currently present in the dependency index. A recalculation that
+ * reuses the ranges of an unchanged formula may skip the index write only while the entry
+ * it relies on still exists; a forced calculation resets the index and clears this state.
+ */
+ hasDependencyRTreeCache(treeId: number): boolean {
+ throw new Error('Method not implemented.');
+ }
+
getLastTreeId() {
const id = this._dependencyTreeIdLast;
this._dependencyTreeIdLast++;
@@ -238,6 +248,17 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
protected override _dependencyRTreeCache: RTree = new RTree(true); // true: open kd-tree search state
+ override hasDependencyRTreeCache(treeId: number) {
+ return this._allTreeMap.has(treeId);
+ }
+
+ override addDependencyRTreeCache(tree: IFormulaDependencyTree) {
+ // Replacement must use the old bounds; a new tree has no entries to remove.
+ this._removeDependencyRTreeCache(tree.treeId);
+ this._removeAllTreeMap(tree.treeId);
+ super.addDependencyRTreeCache(tree);
+ }
+
override reset() {
this._otherFormulaData.clear();
this._featureFormulaData.clear();
@@ -304,12 +325,15 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
}
override clearOtherFormulaDependency(unitId: string, sheetId?: string) {
+ const treeIds: number[] = [];
const unitMap = this._otherFormulaData.get(unitId);
+ if (sheetId && !unitMap?.has(sheetId)) {
+ return;
+ }
if (sheetId && unitMap && unitMap.has(sheetId)) {
const sheetMap = unitMap.get(sheetId)!;
- this._removeDependencyRTreeCacheById(unitId, sheetId);
for (const formulaId of sheetMap.keys()) {
const formulaTreeSet = sheetMap.get(formulaId);
if (formulaTreeSet == null) {
@@ -319,7 +343,7 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
formulaTreeSet.forValue((row, column, treeId) => {
const tree = this._allTreeMap.get(treeId);
if (tree) {
- this._removeAllTreeMap(treeId);
+ treeIds.push(treeId);
}
});
@@ -330,7 +354,6 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
} else if (unitMap) {
for (const sheetId of unitMap.keys()) {
const sheetMap = unitMap.get(sheetId)!;
- this._removeDependencyRTreeCacheById(unitId, sheetId);
for (const formulaId of sheetMap.keys()) {
const formulaTreeSet = sheetMap.get(formulaId);
if (formulaTreeSet == null) {
@@ -340,7 +363,7 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
formulaTreeSet.forValue((row, column, treeId) => {
const tree = this._allTreeMap.get(treeId);
if (tree) {
- this._removeAllTreeMap(treeId);
+ treeIds.push(treeId);
}
});
@@ -350,6 +373,7 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
this._otherFormulaData.delete(unitId); // Delete the data corresponding to the entire unitId
}
+ this._removeDependencyRTreeCaches(treeIds);
}
override addFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string, dependencyTree: FormulaDependencyTree) {
@@ -388,32 +412,35 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
}
override clearFeatureFormulaDependency(unitId: string, sheetId?: string) {
+ const treeIds: number[] = [];
const unitMap = this._featureFormulaData.get(unitId);
+ if (sheetId && !unitMap?.has(sheetId)) {
+ return;
+ }
if (sheetId && unitMap && unitMap.has(sheetId)) {
const sheetMap = unitMap.get(sheetId)!;
- this._removeDependencyRTreeCacheById(unitId, sheetId);
sheetMap.forEach((featureTreeId) => {
if (featureTreeId == null) {
return;
}
- this._removeAllTreeMap(featureTreeId);
+ treeIds.push(featureTreeId);
});
sheetMap.clear(); // Clear the formula dependent data corresponding to the sheetId
} else if (unitMap) {
unitMap.forEach((sheetMap, sheetId) => {
- this._removeDependencyRTreeCacheById(unitId, sheetId);
sheetMap.forEach((featureTreeId) => {
if (featureTreeId == null) {
return;
}
- this._removeAllTreeMap(featureTreeId);
+ treeIds.push(featureTreeId);
});
});
this._featureFormulaData.delete(unitId); // Delete the data corresponding to the entire unitId
}
+ this._removeDependencyRTreeCaches(treeIds);
}
override addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: IFormulaDependencyTree) {
@@ -449,60 +476,60 @@ export class DependencyManagerService extends DependencyManagerBaseService imple
}
override clearFormulaDependency(unitId: string, sheetId?: string) {
+ const treeIds: number[] = [];
const unitMap = this._formulaData.get(unitId);
+ if (sheetId && !unitMap?.has(sheetId)) {
+ return;
+ }
if (sheetId && unitMap && unitMap.has(sheetId)) {
const sheetMatrix = unitMap.get(sheetId)!;
- this._removeDependencyRTreeCacheById(unitId, sheetId);
-
sheetMatrix.forValue((row, column, treeId) => {
if (treeId == null) {
return true;
}
- this._removeAllTreeMap(treeId);
+ treeIds.push(treeId);
});
sheetMatrix.reset();
} else if (unitMap) {
unitMap.forEach((sheetMatrix, sheetId) => {
- this._removeDependencyRTreeCacheById(unitId, sheetId);
-
sheetMatrix.forValue((row, column, treeId) => {
if (treeId == null) {
return true;
}
- this._removeAllTreeMap(treeId);
+ treeIds.push(treeId);
});
});
this._formulaData.delete(unitId); // Delete the data of the entire unitId
}
+ this._removeDependencyRTreeCaches(treeIds);
}
private _removeDependencyRTreeCache(treeId: Nullable<number>) {
- if (treeId == null) {
- return;
+ if (treeId != null) {
+ this._removeDependencyRTreeCaches([treeId]);
}
+ }
- const treeRangeMap = this._allTreeMap.get(treeId);
-
- if (treeRangeMap) {
- const searchRanges: IRTreeItem[] = [];
+ private _removeDependencyRTreeCaches(treeIds: number[]) {
+ const searchRanges: IRTreeItem[] = [];
+ for (const treeId of treeIds) {
+ const treeRangeMap = this._allTreeMap.get(treeId);
+ if (!treeRangeMap) {
+ continue;
+ }
for (const [unitId, sheetMap] of treeRangeMap) {
for (const [sheetId, range] of sheetMap) {
- searchRanges.push({
- unitId,
- sheetId,
- range,
- id: treeId,
- });
+ searchRanges.push({ unitId, sheetId, range, id: treeId });
}
}
-
- this._dependencyRTreeCache.bulkRemove(searchRanges);
+ this._allTreeMap.delete(treeId);
}
+ this._dependencyRTreeCache.bulkRemove(searchRanges);
}
override removeFormulaDependencyByDefinedName(unitId: string, definedName: string) {
diff --git a/packages/engine-formula/src/services/super-table.service.ts b/packages/engine-formula/src/services/super-table.service.ts
index 434b0baf39..75cde8f6e1 100644
--- a/packages/engine-formula/src/services/super-table.service.ts
+++ b/packages/engine-formula/src/services/super-table.service.ts
@@ -16,9 +16,9 @@
import type { Nullable } from '@univerjs/core';
import type { Observable } from 'rxjs';
-import type { ISuperTable } from '../basics/common';
import { createIdentifier, Disposable } from '@univerjs/core';
import { Subject } from 'rxjs';
+import type { ISuperTable, ISuperTableData } from '../basics/common';
import { TableOptionType } from '../basics/common';
export interface ISuperTableOptionParam {
@@ -31,7 +31,7 @@ export interface ISuperTableService {
getTableOptionMap(): Map<string, TableOptionType>;
- registerTable(unitId: string, tableName: string, reference: ISuperTable): void;
+ registerTable(unitId: string, tableName: string, reference: ISuperTable | ISuperTableData): void;
registerTableOptionMap(tableOption: string, tableOptionType: TableOptionType): void;
@@ -83,11 +83,14 @@ export class SuperTableService extends Disposable implements ISuperTableService
return this._tableOptionMap;
}
- registerTable(unitId: string, tableName: string, reference: ISuperTable) {
+ registerTable(unitId: string, tableName: string, reference: ISuperTable | ISuperTableData) {
if (this._tableMap.get(unitId) == null) {
this._tableMap.set(unitId, new Map());
}
- this._tableMap.get(unitId)?.set(tableName, reference);
+ const table = reference.titleMap instanceof Map
+ ? reference as ISuperTable
+ : { ...reference, titleMap: new Map(Object.entries(reference.titleMap)) };
+ this._tableMap.get(unitId)?.set(tableName, table);
this._update();
}
diff --git a/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts b/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts
index e9f5e738e2..3f0a18a99b 100644
--- a/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts
+++ b/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-import type { IConditionFormattingRule } from '../type';
+import { Injector } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import type { IConditionFormattingRule } from '../type';
import { CFRuleType, CFSubRuleType, CFTextOperator } from '../../base/const';
import { ConditionalFormattingRangeIndexModel } from '../conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from '../conditional-formatting-rule-model';
@@ -36,6 +37,32 @@ function createRule(cfId: string, startRow: number, endRow: number, startColumn:
}
describe('ConditionalFormattingRangeIndexModel', () => {
+ it('replaces and deletes multiple rule ranges without removing overlapping rules or other workbooks', () => {
+ const injector = new Injector([[ConditionalFormattingRuleModel], [ConditionalFormattingRangeIndexModel]]);
+ const rules = injector.get(ConditionalFormattingRuleModel);
+ const index = injector.get(ConditionalFormattingRangeIndexModel);
+ const multiple = createRule('a', 0, 2, 0, 2);
+ multiple.ranges.push({ startRow: 10, endRow: 12, startColumn: 10, endColumn: 12 });
+ try {
+ rules.addRule('unit', 'sheet', multiple);
+ rules.addRule('unit', 'sheet', createRule('b', 0, 2, 0, 2));
+ rules.addRule('other', 'sheet', multiple);
+ const replacement = createRule('a', 20, 21, 20, 21);
+ replacement.ranges.push({ startRow: 30, endRow: 31, startColumn: 30, endColumn: 31 });
+ rules.setRule('unit', 'sheet', replacement, 'a');
+ expect(index.getRuleIdsByCell('unit', 'sheet', 1, 1)).toEqual(new Set(['b']));
+ expect(index.getRuleIdsByCell('unit', 'sheet', 11, 11)).toEqual(new Set());
+ expect(index.getRuleIdsByCell('unit', 'sheet', 20, 20)).toEqual(new Set(['a']));
+ expect(index.getRuleIdsByCell('unit', 'sheet', 30, 30)).toEqual(new Set(['a']));
+ expect(index.getRuleIdsByCell('other', 'sheet', 11, 11)).toEqual(new Set(['a']));
+ rules.deleteRule('unit', 'sheet', 'a');
+ expect(index.getRuleIdsByCell('unit', 'sheet', 20, 20)).toEqual(new Set());
+ expect(index.getRuleIdsByCell('unit', 'sheet', 30, 30)).toEqual(new Set());
+ expect(index.getRuleIdsByCell('unit', 'sheet', 1, 1)).toEqual(new Set(['b']));
+ } finally {
+ injector.dispose();
+ }
+ });
it('queries rule ids by cell and range through rule model changes', () => {
const ruleModel = new ConditionalFormattingRuleModel();
const rangeIndex = new ConditionalFormattingRangeIndexModel(ruleModel);
diff --git a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
index 8e7f8ff716..a11ee6cc7f 100644
--- a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
@@ -17,7 +17,6 @@
import type { Dependency, ICommandInfo, IWorkbookData } from '@univerjs/core';
import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
import type { IInsertSheetMutationParams, IRemoveRowsMutationParams } from '@univerjs/sheets';
-import type { ITestBed } from '../../facade/__tests__/create-test-bed';
import { LocaleType } from '@univerjs/core';
import {
ActiveDirtyManagerService,
@@ -37,8 +36,10 @@ import {
SetRowHiddenMutation,
SetStyleCommand,
SetWorkbookCalculationSettingsMutation,
+ SetWorksheetOrderMutation,
} from '@univerjs/sheets';
import { afterEach, describe, expect, it } from 'vitest';
+import type { ITestBed } from '../../facade/__tests__/create-test-bed';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
import { ActiveDirtyController } from '../active-dirty.controller';
@@ -93,6 +94,17 @@ describe('ActiveDirtyController', () => {
testBed?.univer.dispose();
});
+ it('rebuilds dependencies across the workbook when sheet order changes', () => {
+ testBed = createControllerTestBed();
+ testBed.injector.get(ActiveDirtyController);
+ const dirty = getDirtyData(testBed, {
+ id: SetWorksheetOrderMutation.id,
+ params: { unitId: 'test', subUnitId: 'sheet1', fromOrder: 0, toOrder: 0 },
+ });
+ expect(dirty.forceCalculation).toBe(true);
+ expect(dirty.clearDependencyTreeCache).toEqual({ test: { sheet1: 'Sheet1' } });
+ });
+
it('marks iteration-sensitive workbooks without making every sheet dirty', () => {
testBed = createControllerTestBed();
testBed.injector.get(ActiveDirtyController);
diff --git a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts
index fe21f2da06..f07b788b77 100644
--- a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts
@@ -53,7 +53,7 @@ import {
RemoteSyncPrimaryService,
WebWorkerRemoteInstanceService,
} from '@univerjs/rpc';
-import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService, UniverSheetsPlugin } from '@univerjs/sheets';
+import { INTERCEPTOR_POINT, SetRangeValuesMutation, SetWorksheetOrderMutation, SheetInterceptorService, UniverSheetsPlugin } from '@univerjs/sheets';
import { ReplaySubject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
@@ -272,7 +272,7 @@ function createWorkerWorkbookData(): IWorkbookData {
};
}
-function createWorkerFormulaTestBed() {
+function createWorkerFormulaTestBed(workbookData = createWorkerWorkbookData()) {
const [mainProtocol, workerProtocol] = createPairedMessageProtocols();
class MainRPCPlugin extends Plugin {
@@ -357,7 +357,7 @@ function createWorkerFormulaTestBed() {
mainInjector.get(ILogService).setLogLevel(LogLevel.SILENT);
workerInjector.get(ILogService).setLogLevel(LogLevel.SILENT);
- const sheet = mainUniver.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkerWorkbookData());
+ const sheet = mainUniver.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData);
return {
commandService: mainCommandService,
@@ -435,6 +435,36 @@ describe('ArrayFormulaCellInterceptorController with remote calculation', () =>
});
}
+ it('should synchronize worksheet moves to a formula-only replica before recalculation', async () => {
+ const data = createWorkerWorkbookData();
+ data.sheetOrder = [subUnitId, 'start', 'end', 'middle'];
+ data.sheets[subUnitId].cellData = { 0: { 0: { f: '=SUM(Start:End!A1)' } } };
+ for (const [id, name, value] of [['start', 'Start', 1], ['end', 'End', 2], ['middle', 'Middle', 3]] as const) {
+ data.sheets[id] = { id, name, rowCount: 20, columnCount: 20, cellData: { 0: { 0: { v: value, t: CellValueType.NUMBER } } } };
+ }
+ testBed = createWorkerFormulaTestBed(data);
+ commandService = testBed.commandService;
+ const sync = testBed.mainUniver.__getInjector().get(DataSyncPrimaryController);
+ await sync.waitForPendingMutations();
+ await calculateInWorker();
+ const replica = testBed.workerInstanceService.getUnit<Workbook>(unitId)!;
+ expect(testBed.sheet.getSheetBySheetId(subUnitId)!.getCellRaw(0, 0)?.v).toBe(3);
+
+ for (const [fromOrder, toOrder, total] of [[3, 2, 6], [2, 3, 3]]) {
+ expect(commandService.syncExecuteCommand(SetWorksheetOrderMutation.id, {
+ unitId,
+ subUnitId: 'middle',
+ fromOrder,
+ toOrder,
+ }, { onlyLocal: true })).toBe(true);
+ await sync.waitForPendingMutations();
+ expect(replica.getSheetOrders()).toEqual(testBed.sheet.getSheetOrders());
+ await calculateInWorker();
+ expect(replica.getSheetBySheetId(subUnitId)!.getCellRaw(0, 0)?.v).toBe(total);
+ expect(testBed.sheet.getSheetBySheetId(subUnitId)!.getCellRaw(0, 0)?.v).toBe(total);
+ }
+ });
+
it('should preserve multiple real blockers inside a spilled array reference formula', async () => {
testBed = createWorkerFormulaTestBed();
testBed.mainUniver.__getInjector().get(ArrayFormulaCellInterceptorController);
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index 4b3fcb9c09..f609b6a608 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -57,6 +57,7 @@ import {
SetRowVisibleMutation,
SetStyleCommand,
SetWorkbookCalculationSettingsMutation,
+ SetWorksheetOrderMutation,
} from '@univerjs/sheets';
export class ActiveDirtyController extends Disposable {
@@ -268,6 +269,21 @@ export class ActiveDirtyController extends Disposable {
}
private _initialSheet() {
+ this._activeDirtyManagerService.register(SetWorksheetOrderMutation.id, {
+ commandId: SetWorksheetOrderMutation.id,
+ getDirtyData: (command: ICommandInfo) => {
+ const { unitId } = command.params as { unitId: string };
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const sheets: Record<string, string> = Object.create(null);
+ for (const sheet of workbook?.getSheets() ?? []) {
+ sheets[sheet.getSheetId()] = sheet.getName();
+ }
+ return {
+ forceCalculation: true,
+ clearDependencyTreeCache: { [unitId]: sheets },
+ };
+ },
+ });
this._activeDirtyManagerService.register(RemoveSheetMutation.id, {
commandId: RemoveSheetMutation.id,
getDirtyData: (command: ICommandInfo) => {
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts
index 573358b1fc..7c9b100ea9 100644
--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts
@@ -89,9 +89,9 @@ describe('SheetTableFormulaController', () => {
}),
}), { onlyLocal: true });
- const titleMap = executeCommand.mock.calls[0][1].reference.titleMap as Map<string, number>;
- expect(titleMap.get('id')).toBe(0);
- expect(titleMap.get('amount')).toBe(1);
+ const params = executeCommand.mock.calls[0][1];
+ expect(params.reference.titleMap).toEqual({ id: 0, amount: 1 });
+ expect(JSON.parse(JSON.stringify(params))).toEqual(params);
tableRangeChanged$.next({ unitId: 'u1', tableId: 't1' });
expect(executeCommand).toHaveBeenCalledTimes(2);
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
index fe66c04cf7..df41bb28b5 100644
--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
@@ -510,11 +510,22 @@ describe('Sheet table formula integration', () => {
});
it('should sync table formulas when a table is renamed, undone, and redone', async () => {
+ let tableParams: unknown;
+ const listener = commandService.onCommandExecuted((command) => {
+ if (command.id === SetSuperTableMutation.id) {
+ tableParams = command.params;
+ }
+ });
expect(await commandService.executeCommand(SetSheetTableCommand.id, {
unitId: 'test',
tableId: 'orders-table',
name: 'Sales',
})).toBe(true);
+ listener.dispose();
+
+ const wireParams = JSON.parse(JSON.stringify(tableParams));
+ expect(wireParams.reference.titleMap).toEqual({ product: 0, amount: 1, tax: 2 });
+ expect(commandService.syncExecuteCommand(SetSuperTableMutation.id, wireParams)).toBe(true);
expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(Sales[amount])');
expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Sales[amount])');
diff --git a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
index 67612d372f..7478f597a6 100644
--- a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
@@ -15,10 +15,10 @@
*/
import type { IRemoveSuperTableMutationParam, ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from '@univerjs/engine-formula';
-import type { ISetSheetTableParams } from '../commands/mutations/set-table-filter.mutation';
-import type { Table } from '../models/table';
import { Disposable, ICommandService, Inject, toDisposable } from '@univerjs/core';
import { IActiveDirtyManagerService, RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';
+import type { ISetSheetTableParams } from '../commands/mutations/set-table-filter.mutation';
+import type { Table } from '../models/table';
import { SetSheetTableFilterMutation } from '../commands/mutations/set-table-filter.mutation';
import { TableManager } from '../models/table-manager';
@@ -112,10 +112,7 @@ export class SheetTableFormulaController extends Disposable {
const tableInfo = table.getTableInfo();
const name = tableInfo.name;
const columns = tableInfo.columns;
- const titleMap = new Map<string, number>();
- columns.forEach((column, index) => {
- titleMap.set(column.displayName, index);
- });
+ const titleMap = Object.fromEntries(columns.map((column, index) => [column.displayName, index]));
this._commandService.executeCommand<ISetSuperTableMutationParam>(SetSuperTableMutation.id, {
unitId,
tableName: name,
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index b40acf3b7b..4342aedf4b 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -216,6 +216,7 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetWorkbookCalculationSettingsMutation,
SetWorkbookNameMutation,
SetWorksheetNameMutation,
+ SetWorksheetOrderMutation,
SetNumfmtMutation,
ReorderRangeMutation,
EmptyMutation,
@@ -325,7 +326,6 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetWorksheetHideMutation,
SetWorksheetNameCommand,
SetWorksheetOrderCommand,
- SetWorksheetOrderMutation,
SetWorksheetRowAutoHeightMutation,
SetWorksheetRowHeightMutation,