Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheets): preserve formula parity and reduce recalculation overhead (#7704)
Univer2babd398a222
diff --git a/packages/core/src/shared/__tests__/range.spec.ts b/packages/core/src/shared/__tests__/range.spec.tsindex c65c846a7d..cf0fdac5af 100644--- a/packages/core/src/shared/__tests__/range.spec.ts+++ b/packages/core/src/shared/__tests__/range.spec.ts@@ -454,6 +454,30 @@ describe('mergeVerticalRanges', () => {});describe('mergeRanges', () => {+ it('matches grid union for overlapping, nested, adjacent and sparse ranges', () => {+ let seed = 20260918;+ const next = () => {+ seed = (seed * 1664525 + 1013904223) >>> 0;+ return seed % 12;+ };+ for (let example = 0; example < 100; example++) {+ const ranges = Array.from({ length: 20 }, () => {+ const startRow = next();+ const startColumn = next();+ return { startRow, startColumn, endRow: startRow + next(), endColumn: startColumn + next() };+ });+ const before = JSON.stringify(ranges);+ const expected = mergeVerticalRanges(mergeHorizontalRanges(splitIntoGrid(ranges.map((range) => ({ ...range })))));+ expect(stringifyRanges(mergeRanges(ranges))).toEqual(stringifyRanges(expected));+ expect(JSON.stringify(ranges)).toBe(before);+ }+ });++ it('keeps sparse validation ranges separated across thousands of boundaries', () => {+ const ranges = Array.from({ length: 5000 }, (_, index) => ({ startRow: index * 2, endRow: index * 2, startColumn: index * 2, endColumn: index * 2 }));+ expect(mergeRanges(ranges)).toEqual(ranges);+ });+it('should merge ranges correctly', () => {const input: IRange[] = [{ startColumn: 1, endColumn: 5, startRow: 1, endRow: 2 },diff --git a/packages/core/src/shared/range.ts b/packages/core/src/shared/range.tsindex 5b658c794d..41f5a49d38 100644--- a/packages/core/src/shared/range.ts+++ b/packages/core/src/shared/range.ts@@ -243,8 +243,41 @@ export function mergeVerticalRanges(ranges: IRange[]): IRange[] {* @returns ranges*/export function mergeRanges(ranges: IRange[]): IRange[] {- const split = splitIntoGrid(ranges);- const horizontalMerged = mergeHorizontalRanges(split);+ // Sweep row boundaries and merge the occupied column intervals directly.+ // Building every grid cell first makes sparse validation ranges cubic in+ // the number of row/column boundaries and source ranges.+ const events = new Map<number, Array<{ range: IRange; add: boolean }>>();+ for (const range of ranges) {+ for (const [row, add] of [[range.startRow, true], [range.endRow + 1, false]] as const) {+ const entries = events.get(row) ?? [];+ entries.push({ range, add });+ events.set(row, entries);+ }+ }+ const rows = [...events.keys()].sort((a, b) => a - b);+ const active = new Set<IRange>();+ const horizontalMerged: IRange[] = [];+ for (let index = 0; index < rows.length - 1; index++) {+ const startRow = rows[index];+ const endRow = rows[index + 1] - 1;+ for (const { range, add } of events.get(startRow)!) {+ if (add) {+ active.add(range);+ } else {+ active.delete(range);+ }+ }+ const intervals = [...active].sort((a, b) => a.startColumn - b.startColumn || a.endColumn - b.endColumn);+ let current: IRange | undefined;+ for (const range of intervals) {+ if (current && range.startColumn <= current.endColumn + 1) {+ current.endColumn = Math.max(current.endColumn, range.endColumn);+ } else {+ current = { startRow, endRow, startColumn: range.startColumn, endColumn: range.endColumn };+ horizontalMerged.push(current);+ }+ }+ }return mergeVerticalRanges(horizontalMerged);}@@ -322,10 +355,10 @@ function getOverlap1D(end2: number): [number, number] | null {// Treat NaN as unbounded (-Infinity to +Infinity)- const s1 = isNaN(start1) ? -Infinity : start1;- const e1 = isNaN(end1) ? Infinity : end1;- const s2 = isNaN(start2) ? -Infinity : start2;- const e2 = isNaN(end2) ? Infinity : end2;+ const s1 = Number.isNaN(start1) ? -Infinity : start1;+ const e1 = Number.isNaN(end1) ? Infinity : end1;+ const s2 = Number.isNaN(start2) ? -Infinity : start2;+ const e2 = Number.isNaN(end2) ? Infinity : end2;const start = Math.max(s1, s2);const end = Math.min(e1, e2);@@ -397,8 +430,8 @@ function inferRangeType(startColumn: number,endColumn: number): RANGE_TYPE {- const hasRow = !isNaN(startRow) && !isNaN(endRow);- const hasColumn = !isNaN(startColumn) && !isNaN(endColumn);+ const hasRow = !Number.isNaN(startRow) && !Number.isNaN(endRow);+ const hasColumn = !Number.isNaN(startColumn) && !Number.isNaN(endColumn);if (hasRow && hasColumn) {return RANGE_TYPE.NORMAL;diff --git a/packages/engine-formula/src/basics/__tests__/inverted-index-cache.spec.ts b/packages/engine-formula/src/basics/__tests__/inverted-index-cache.spec.tsindex 2051e1c738..337afe6ea6 100644--- a/packages/engine-formula/src/basics/__tests__/inverted-index-cache.spec.ts+++ b/packages/engine-formula/src/basics/__tests__/inverted-index-cache.spec.ts@@ -15,9 +15,138 @@*/import { describe, expect, it } from 'vitest';-import { InvertedIndexCache } from '../inverted-index-cache';+import { DEFAULT_EMPTY_CELL_KEY, InvertedIndexCache } from '../inverted-index-cache';describe('InvertedIndexCache', () => {+ it('keeps updates correct as distinct values grow, shrink and grow again', () => {+ const cache = new InvertedIndexCache();+ for (let row = 0; row < 100; row++) {+ cache.set('unit', 'sheet', 0, row, row);+ }+ cache.setContinueBuildingCache('unit', 'sheet', 0, 0, 99);+ for (let cycle = 0; cycle < 3; cycle++) {+ for (let row = 99; row >= 0; row--) {+ cache.set('unit', 'sheet', 0, 'same', row, true);+ }+ expect(cache.getCellValuePositions('unit', 'sheet', 0)?.size).toBe(1);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'same', [[0, 99]])?.matchingRows).toHaveLength(100);+ for (let row = 0; row < 100; row++) {+ cache.set('unit', 'sheet', 0, row, row, true);+ expect(cache.getCellPositions('unit', 'sheet', 0, row, [[0, 99]])?.matchingRows).toEqual([row]);+ }+ expect(cache.getCellPositions('unit', 'sheet', 0, 'same', [[0, 99]])?.matchingRows).toEqual([]);+ }+ });++ it('replaces repeated uncovered writes and drops obsolete value buckets', () => {+ const cache = new InvertedIndexCache();+ cache.set('unit', 'sheet', 0, 'A', 0);+ cache.set('unit', 'sheet', 0, 'B', 0);+ cache.set('unit', 'sheet', 0, 'C', 0, true);+ expect([...cache.getCellValuePositions('unit', 'sheet', 0)!.keys()]).toEqual(['c']);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'C', [[0, 0]])?.matchingRows).toEqual([0]);+ });++ it('keeps out-of-order range builds and later updates consistent', () => {+ const cache = new InvertedIndexCache();+ for (const row of [10, 11, 3, 4, 7, 8]) {+ cache.set('unit', 'sheet', 0, row, row);+ }+ cache.set('unit', 'sheet', 0, 'changed', 4, true);+ expect(cache.getCellPositions('unit', 'sheet', 0, 4, [[0, 20]])?.matchingRows).toEqual([]);+ for (const row of [10, 11, 3, 7, 8]) {+ expect(cache.getCellPositions('unit', 'sheet', 0, row, [[0, 20]])?.matchingRows).toEqual([row]);+ }+ expect(cache.getCellPositions('unit', 'sheet', 0, 'changed', [[0, 20]])?.matchingRows).toEqual([4]);+ });++ it('uses the same linguistic equality for indexed text and lookup text', () => {+ const cache = new InvertedIndexCache();+ cache.set('unit', 'sheet', 0, 'straße', 0);+ cache.set('unit', 'sheet', 0, 'é', 1);+ cache.set('unit', 'sheet', 0, 'Infinity', 2);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'STRASSE', [[0, 1]])?.matchingRows).toEqual([0]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'e\u0301', [[0, 1]])?.matchingRows).toEqual([1]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'e', [[0, 1]])?.matchingRows).toEqual([]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'INFINITY', [[0, 2]])?.matchingRows).toEqual([2]);+ });++ it('replaces every supported value kind without leaving a row in its previous bucket', () => {+ const values = [undefined, null, '', 0, -0, '0', 12, '12', '012', 'OLD', 'old', true, false, '#REF!', '#VALUE!'];+ const keys = [DEFAULT_EMPTY_CELL_KEY, DEFAULT_EMPTY_CELL_KEY, DEFAULT_EMPTY_CELL_KEY, 0, 0, 0, 12, 12, '012', 'old', 'old', true, false, '#ref!', '#value!'];+ for (const initial of values) {+ for (let index = 0; index < values.length; index++) {+ const cache = new InvertedIndexCache();+ cache.set('unit', 'sheet', 0, initial, 4);+ cache.set('unit', 'sheet', 0, initial, 7);+ cache.setContinueBuildingCache('unit', 'sheet', 0, 4, 7);+ cache.set('unit', 'sheet', 0, values[index], 4, true);+ const buckets = cache.getCellValuePositions('unit', 'sheet', 0)!;+ expect([...buckets].filter(([, rows]) => rows.has(4)).map(([key]) => key)).toEqual([keys[index]]);+ expect([...buckets.values()].filter((rows) => rows.has(7))).toHaveLength(1);+ }+ }+ });++ it('keeps forced writes correct while coverage expands and ignores ordinary writes to covered rows', () => {+ const cache = new InvertedIndexCache();+ cache.set('unit', 'sheet', 0, 'old', 2, true);+ cache.set('unit', 'sheet', 0, 'old', 2);+ cache.setContinueBuildingCache('unit', 'sheet', 0, 0, 3);+ cache.set('unit', 'sheet', 0, 'ignored', 2);+ cache.set('unit', 'sheet', 0, 'next', 2, true);+ cache.set('unit', 'sheet', 0, 'tail', 4);+ cache.setContinueBuildingCache('unit', 'sheet', 0, 2, 5);+ expect(cache.canUseCache('unit', 'sheet', 0, 0, 7)).toEqual({ rowsInCache: [[0, 5]], rowsNotInCache: [[6, 7]] });+ expect(cache.getCellPositions('unit', 'sheet', 0, 'old', [[0, 7]])?.matchingRows).toEqual([]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'ignored', [[0, 7]])?.matchingRows).toEqual([]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'next', [[0, 7]])?.matchingRows).toEqual([2]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'tail', [[0, 3]])?.matchingRows).toEqual([]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'tail', [[4, 7]])?.matchingRows).toEqual([4]);+ });++ it('isolates row updates by workbook, sheet and column across cache rebuilds', () => {+ const cache = new InvertedIndexCache();+ const scopes: [string, string, number][] = [['a', 'a', 0], ['b', 'a', 0], ['a', 'b', 0], ['a', 'a', 1]];+ for (let cycle = 0; cycle < 3; cycle++) {+ for (const [unit, sheet, column] of scopes) {+ cache.set(unit, sheet, column, 'old', 0);+ cache.setContinueBuildingCache(unit, sheet, column, 0, 0);+ }+ for (let index = 0; index < scopes.length; index++) {+ const [unit, sheet, column] = scopes[index];+ cache.set(unit, sheet, column, 'new', 0, true);+ for (let other = 0; other < scopes.length; other++) {+ const [otherUnit, otherSheet, otherColumn] = scopes[other];+ const expected = other <= index ? 'new' : 'old';+ expect(cache.getCellPositions(otherUnit, otherSheet, otherColumn, expected, [[0, 0]])?.matchingRows).toEqual([0]);+ }+ }+ cache.clear();+ expect(cache.getCellValuePositions('a', 'a', 0)).toBeUndefined();+ expect(cache.canUseCache('a', 'a', 0, 0, 0).rowsInCache).toEqual([]);+ }+ });++ it('moves updated rows between normalized value buckets and resets them on clear', () => {+ const cache = new InvertedIndexCache();+ const rows: [number, number][] = [[0, 3]];+ cache.set('unit', 'sheet', 0, 'OLD', 0);+ cache.set('unit', 'sheet', 0, 'old', 1);+ cache.setContinueBuildingCache('unit', 'sheet', 0, 0, 3);+ cache.set('unit', 'sheet', 0, 0, 0, true);+ cache.set('unit', 'sheet', 0, null, 0, true);+ cache.set('unit', 'sheet', 0, 'NEW', 0, true);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'old', rows)?.matchingRows).toEqual([1]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 0, rows)?.matchingRows).toEqual([]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'new', rows)?.matchingRows).toEqual([0]);+ cache.set('unit', 'other', 0, 'old', 0, true);+ expect(cache.getCellPositions('unit', 'other', 0, 'old', rows)?.matchingRows).toEqual([0]);+ cache.clear();+ cache.set('unit', 'sheet', 0, 'fresh', 0, true);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'new', rows)?.matchingRows).toEqual([]);+ expect(cache.getCellPositions('unit', 'sheet', 0, 'fresh', rows)?.matchingRows).toEqual([0]);+ });it('keeps empty string lookups distinct from numeric zero lookups', () => {const cache = new InvertedIndexCache();const unitId = 'unit';diff --git a/packages/engine-formula/src/basics/inverted-index-cache.ts b/packages/engine-formula/src/basics/inverted-index-cache.tsindex 7ebcc4575b..d750ee5653 100644--- a/packages/engine-formula/src/basics/inverted-index-cache.ts+++ b/packages/engine-formula/src/basics/inverted-index-cache.ts@@ -18,6 +18,7 @@ import type { NumericTuple } from '@flatten-js/interval-tree';import type { ErrorType } from './error-type';import IntervalTree from '@flatten-js/interval-tree';import { isRealNum } from '@univerjs/core';+import { normalizeTextForComparison } from '../engine/utils/compare';import { ERROR_TYPE_SET } from './error-type';type ValueType = string | number | boolean;@@ -38,12 +39,12 @@ function normalizeValue(value: ValueTypeWithNullUndefined): ValueTypeWithSymbolif (value === null || value === undefined || value === '') {_value = DEFAULT_EMPTY_CELL_KEY;- } else if (isRealNum(value) && Number(value).toString() === value.toString()) {+ } else if (isRealNum(value) && Number.isFinite(Number(value)) && Number(value).toString() === value.toString()) {// Number string that can be converted to number will be converted to number and stored in the inverted index cache, but '12a' or '012' will not be converted to number, because they are not pure number string._value = Number(value) === 0 ? 0 : Number(value);} else if (typeof value === 'string') {// For string value, we will convert it to lower case to make the compare operation case-insensitive.- _value = value.toLowerCase();+ _value = normalizeTextForComparison(value);} else {_value = value;}@@ -67,6 +68,11 @@ export class InvertedIndexCache {*/private _cache: Map<string, Map<string, Map<number, Map<ValueTypeWithSymbol, Set<number>>>>> = new Map();+ private _rowValues = new WeakMap<Map<ValueTypeWithSymbol, Set<number>>, {+ lastRow: number;+ values?: Map<number, ValueTypeWithSymbol>;+ }>();+private _continueBuildingCache: Map<string, Map<string, Map<number, IntervalTree<NumericTuple>>>> = new Map();set(unitId: string, sheetId: string, column: number, value: ValueTypeWithNullUndefined, row: number, isForceUpdate: boolean = false) {@@ -92,12 +98,40 @@ export class InvertedIndexCache {sheetMap.set(column, columnMap);}- // If is force update, we need to remove the old value from the map- if (isForceUpdate) {- for (const [_, _cellList] of columnMap) {- if (_cellList.has(row)) {- _cellList.delete(row);- break;+ let rowIndex = this._rowValues.get(columnMap);+ if (rowIndex == null) {+ rowIndex = { lastRow: -1 };+ this._rowValues.set(columnMap, rowIndex);+ }++ // Ascending scans cannot overwrite an indexed row. For low-cardinality+ // columns, bounded bucket scans avoid allocating a map entry per row.+ if (!rowIndex.values && (isForceUpdate || row <= rowIndex.lastRow)) {+ if (columnMap.size <= 32) {+ for (const [key, rows] of columnMap) {+ if (rows.delete(row)) {+ if (rows.size === 0) {+ columnMap.delete(key);+ }+ break;+ }+ }+ } else {+ rowIndex.values = new Map();+ for (const [key, rows] of columnMap) {+ for (const indexedRow of rows) {+ rowIndex.values.set(indexedRow, key);+ }+ }+ }+ }+ if (rowIndex.values) {+ const oldValue = rowIndex.values.get(row);+ if (oldValue !== undefined) {+ const oldRows = columnMap.get(oldValue)!;+ oldRows.delete(row);+ if (oldRows.size === 0) {+ columnMap.delete(oldValue);}}}@@ -111,6 +145,8 @@ export class InvertedIndexCache {}cellList.add(row);+ rowIndex.values?.set(row, _value);+ rowIndex.lastRow = Math.max(rowIndex.lastRow, row);}getCellValuePositions(unitId: string, sheetId: string, column: number) {diff --git a/packages/engine-formula/src/engine/ast-node/prefix-node.ts b/packages/engine-formula/src/engine/ast-node/prefix-node.tsindex f6e6e78b2b..5ea6bde3ab 100644--- a/packages/engine-formula/src/engine/ast-node/prefix-node.ts+++ b/packages/engine-formula/src/engine/ast-node/prefix-node.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { Nullable } from '@univerjs/core';+import type { IUnitRange, Nullable } from '@univerjs/core';import type { BaseFunction } from '../../functions/base-function';import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';import type { BaseValueObject } from '../value-object/base-value-object';@@ -34,6 +34,12 @@ import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-astimport { NODE_ORDER_MAP, NodeType } from './node-type';export class PrefixNode extends BaseAstNode {+ private _referenceRanges: IUnitRange[] | null = null;++ getReferenceRanges(): IUnitRange[] | null {+ return this._referenceRanges;+ }+constructor(private _runtimeService: IFormulaRuntimeService,private _operatorString: string,@@ -47,6 +53,7 @@ export class PrefixNode extends BaseAstNode {}override execute(dateSystem: DateSystem = DateSystem.Date1900) {+ this._referenceRanges = null;const children = this.getChildren();let value = children[0].getValue();let result: FunctionVariantType;@@ -81,9 +88,10 @@ export class PrefixNode extends BaseAstNode {}const currentValue = value as BaseReferenceObject;+ this._referenceRanges = [];if (currentValue.isCell()) {- return currentValue.getCellByPosition();+ return this._getReferencedCell(currentValue);}if (this._preserveAtRangeForFormula2LookupArray()) {@@ -109,18 +117,35 @@ export class PrefixNode extends BaseAstNode {// @ projection to currentif (endRow === startRow && currentColumn >= startColumn && currentColumn <= endColumn) {- return currentValue.getCellByColumn(currentColumn);+ return this._getReferencedCell(currentValue, undefined, currentColumn);} else if (startColumn === endColumn && currentRow >= startRow && currentRow <= endRow) {- return currentValue.getCellByRow(currentRow);+ return this._getReferencedCell(currentValue, currentRow);}if (currentValue.isTable()) {- return currentValue.getCellByPosition(currentRow);+ return this._getReferencedCell(currentValue, currentRow);}return ErrorValueObject.create(ErrorType.VALUE);}+ private _getReferencedCell(reference: BaseReferenceObject, row?: number, column?: number) {+ const position = reference.getRangePosition();+ const selectedRow = row ?? position.startRow;+ const selectedColumn = column ?? position.startColumn;+ this._referenceRanges = reference.toUnitRanges().map((range) => ({+ unitId: range.unitId,+ sheetId: range.sheetId,+ range: {+ startRow: selectedRow,+ endRow: selectedRow,+ startColumn: selectedColumn,+ endColumn: selectedColumn,+ },+ }));+ return reference.getCellByPosition(selectedRow, selectedColumn);+ }+private _preserveAtRangeForFormula2LookupArray(): boolean {let node: BaseAstNode = this;let parent = node.getParent();diff --git a/packages/engine-formula/src/engine/dependency/__tests__/formula-dependency.spec.ts b/packages/engine-formula/src/engine/dependency/__tests__/formula-dependency.spec.tsnew file mode 100644index 0000000000..5ccecbdf4b--- /dev/null+++ b/packages/engine-formula/src/engine/dependency/__tests__/formula-dependency.spec.ts@@ -0,0 +1,76 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { LexerNode } from '../../analysis/lexer-node';+import type { BaseAstNode } from '../../ast-node/base-ast-node';+import { describe, expect, it } from 'vitest';+import { If } from '../../../functions/logical/if';+import { Index } from '../../../functions/lookup/index/index';+import { Sum } from '../../../functions/math/sum';+import { IFormulaCurrentConfigService } from '../../../services/current-data.service';+import { IFunctionService } from '../../../services/function.service';+import { IFormulaRuntimeService } from '../../../services/runtime.service';+import { createCommandTestBed } from '../../analysis/__tests__/create-command-test-bed';+import { Lexer } from '../../analysis/lexer';+import { AstTreeBuilder } from '../../analysis/parser';+import { FormulaDependencyGenerator } from '../formula-dependency';++class TestFormulaDependencyGenerator extends FormulaDependencyGenerator {+ collectRanges(node: BaseAstNode) {+ return this._getRangeListByNode({ node, refOffsetX: 0, refOffsetY: 0 });+ }+}++describe('Implicit intersection dependencies', () => {+ it.each([+ ['=@SUM(A1:A3)', [0, 2]],+ ['=@IF(A1,INDEX({"Su";"M"},A2),"")', [0, 1]],+ ['=@SUM(@SUM(A1:A3))', [0, 2]],+ ['=@A1:A3', [1, 1]],+ ['=@INDEX(A1:A3,2)', [1, 1]],+ ] as const)('collects scalar inputs but preserves reference intersections: %s', async (formula, expectedRows) => {+ const bed = createCommandTestBed(undefined, [+ [TestFormulaDependencyGenerator],+ ]);+ try {+ bed.get(IFunctionService).registerExecutors(new Sum('SUM'), new If('IF'), new Index('INDEX'));+ bed.get(IFormulaCurrentConfigService).load({+ formulaData: { [bed.unitId]: { [bed.sheetId]: { 1: { 5: { f: formula } } } } },+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: true,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ excludedCell: {},+ allUnitData: { [bed.unitId]: bed.sheetData },+ });+ const sheet = bed.sheetData[bed.sheetId];+ bed.get(IFormulaRuntimeService).setCurrent(1, 5, sheet.rowCount, sheet.columnCount, bed.sheetId, bed.unitId);+ const lexerNode = bed.get(Lexer).treeBuilder(formula) as LexerNode;+ const node = bed.get(AstTreeBuilder).parse(lexerNode) as BaseAstNode;+ const generator = bed.get(TestFormulaDependencyGenerator);+ const ranges = (await generator.collectRanges(node)).map((item) => item.range);+ expect(Math.min(...ranges.map((range) => range.startRow))).toBe(expectedRows[0]);+ expect(Math.max(...ranges.map((range) => range.endRow))).toBe(expectedRows[1]);+ expect(ranges.every((range) => range.startColumn === 0 && range.endColumn === 0)).toBe(true);+ } finally {+ bed.univer.dispose();+ }+ });+});diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex ec86fab4f1..c362abcc2e 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -32,8 +32,10 @@ import type {IFeatureCalculationManagerParam,} from '../../services/feature-calculation-manager.service';import type { IAllRuntimeData } from '../../services/runtime.service';-import type { FunctionNode, PrefixNode, SuffixNode } from '../ast-node';import type { BaseAstNode } from '../ast-node/base-ast-node';+import type { FunctionNode } from '../ast-node/function-node';+import type { PrefixNode } from '../ast-node/prefix-node';+import type { SuffixNode } from '../ast-node/suffix-node';import type { FunctionVariantType } from '../reference-object/base-reference-object';import type { IExecuteAstNodeData } from '../utils/ast-node-tool';import type { PreCalculateNodeType } from '../utils/node-type';@@ -961,7 +963,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe* including references and location functions (such as OFFSET, INDIRECT, INDEX, etc.).* @param node*/- protected async _getRangeListByNode(nodeData: IExecuteAstNodeData) {+ protected async _getRangeListByNode(nodeData: IExecuteAstNodeData): Promise<IUnitRange[]> {// ref function in offset indirect INDEXconst preCalculateNodeList: PreCalculateNodeType[] = [];@@ -983,6 +985,11 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDeif (value != null) {rangeList.push(...value.toUnitRanges());+ } else if (node.nodeType === NodeType.PREFIX) {+ const intersectionRanges = (node as PrefixNode).getReferenceRanges();+ // Preserve the selected cell for reference operands; scalar expressions+ // instead depend on the references inside their expression.+ rangeList.push(...intersectionRanges ?? await this._getRangeListByNode({ node, refOffsetX, refOffsetY }));}node.setValue(null);diff --git a/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts b/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.tsindex 32d69e5024..625a3eefed 100644--- a/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts+++ b/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts@@ -20,6 +20,14 @@ import { CellReferenceObject } from '../cell-reference-object';import { RangeReferenceObject } from '../range-reference-object';describe('CellReferenceObject', () => {+ it('distinguishes forced error-looking text from a calculated error', () => {+ const reference = new CellReferenceObject('A1');+ const text = reference.getCellValueObject({ v: '#REF!', t: CellValueType.FORCE_STRING });+ const error = reference.getCellValueObject({ v: '#REF!', t: CellValueType.STRING });+ expect(text.isString()).toBe(true);+ expect(error.isError()).toBe(true);+ });+it('should allow blank cells inside the Excel grid even when they are outside snapshot row data', () => {const reference = new CellReferenceObject('Sheet2!A151');diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.tsindex 68b8405cd2..d7b1e1a566 100644--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts@@ -467,7 +467,7 @@ export class BaseReferenceObject extends ObjectClassType {getCellValueObject(cell: ICellData) {const value = getCellValue(cell);const cellValueType = Number(cell.t);- if (ERROR_TYPE_SET.has(value as ErrorType)) {+ if (cellValueType !== CellValueType.FORCE_STRING && ERROR_TYPE_SET.has(value as ErrorType)) {return ErrorValueObject.create(value as ErrorType);}diff --git a/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.tsindex 0966ac1f63..867bb0b18f 100644--- a/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts+++ b/packages/engine-formula/src/engine/utils/__tests__/value-object.spec.ts@@ -29,6 +29,39 @@ import { valueObjectCompare } from '../object-compare';import { convertTonNumber, filterSameValueObjectResult, isSingleValueObject, objectValueToCellValue } from '../value-object';describe('Test object cover', () => {+ it('preserves error-looking text through runtime serialization', () => {+ expect(objectValueToCellValue(StringValueObject.create('#REF!'))).toEqual({ v: '#REF!', t: CellValueType.FORCE_STRING });+ expect(objectValueToCellValue(ErrorValueObject.create(ErrorType.REF))).toEqual({ v: '#REF!', t: CellValueType.STRING });+ });++ it.each([+ ['1', '<>1', false, true],+ ['01', '<>1', false, true],+ ['1', '01', true, true],+ ['1', '1.0', true, true],+ ['1e0', '=1', true, true],+ ['1', '>0', true, false],+ ['\t1', '=1', true, false],+ ['\t1', '\t1', false, true],+ ['0x10', '0x10', false, true],+ ['Infinity', '<>Infinity', true, false],+ ['2026-1-1', '<>2026-1-1', true, true],+ ])('matches Excel numeric and text criteria: %s, %s', (text, criteria, numericMatch, textMatch) => {+ const range = ArrayValueObject.create({+ calculateValueList: [[NumberValueObject.create(1)], [StringValueObject.create(text)]],+ rowCount: 2,+ columnCount: 1,+ unitId: '',+ sheetId: '',+ row: -1,+ column: -1,+ });+ const criterion = StringValueObject.create(criteria);+ const comparison = valueObjectCompare(range, criterion) as ArrayValueObject;+ const result = filterSameValueObjectResult(comparison, range, criterion);+ expect(result.toValue()).toEqual([[numericMatch], [textMatch]]);+ });+it('Function convertTonNumber', () => {expect(convertTonNumber(BooleanValueObject.create(true)).getValue()).toBe(1);expect(convertTonNumber(BooleanValueObject.create(false)).getValue()).toBe(0);diff --git a/packages/engine-formula/src/engine/utils/compare.ts b/packages/engine-formula/src/engine/utils/compare.tsindex 37159413fe..d82bedc2a1 100644--- a/packages/engine-formula/src/engine/utils/compare.ts+++ b/packages/engine-formula/src/engine/utils/compare.ts@@ -47,6 +47,28 @@ export function isWildcard(str: string) {return str.indexOf('*') > -1 || str.indexOf('?') > -1;}+const TEXT_LIGATURES: Record<string, string> = {+ ß: 'ss',+ æ: 'ae',+ œ: 'oe',+ ff: 'ff',+ fi: 'fi',+ fl: 'fl',+ ffi: 'ffi',+ ffl: 'ffl',+ ſt: 'st',+ st: 'st',+};++export function normalizeTextForComparison(value: string): string {+ const lower = value.toLowerCase();+ // Excel's literal comparisons equate linguistic ligatures, while retaining+ // accents and the distinction between dotted/dotless I.+ return /[\u0080-\uFFFF]/.test(lower)+ ? lower.normalize('NFC').replace(/[ßæœff-st]/g, (character) => TEXT_LIGATURES[character])+ : lower;+}+export function isMatchWildcard(currentValue: string, value: string) {const pattern = escapeRegExpForWildcard(value).replace(/~?[*?]/g, (match) => {if (match.startsWith('~')) {@@ -60,7 +82,7 @@ export function isMatchWildcard(currentValue: string, value: string) {}return match;});- const regex = new RegExp(`^${pattern}$`);+ const regex = new RegExp(`^${pattern}$`, 's');return regex.test(currentValue);}@@ -73,25 +95,42 @@ export function replaceWildcard(value: string) {});}-export function compareWithWildcard(currentValue: string, value: string, operator: compareToken) {+export function compareWithWildcard(currentValue: string, value: string, operator: compareToken, isCaseSensitive = true) {+ let currentText = currentValue;+ let pattern = value;+ if (!isCaseSensitive) {+ // Wildcards count UTF-16 characters in Excel. Folding must not expand+ // a character (for example, İ into i plus a combining dot, or ß into ss).+ const fold = (text: string) => {+ if (!/[\u0080-\uFFFF]/.test(text)) {+ return text.toLowerCase();+ }+ return text.replace(/[\s\S]/g, (character) => {+ const lower = character.toLowerCase();+ return lower.length === 1 ? lower : character;+ });+ };+ currentText = fold(currentText);+ pattern = fold(pattern);+ }let result = false;switch (operator) {case compareToken.EQUALS:- result = isMatchWildcard(currentValue, value);+ result = isMatchWildcard(currentText, pattern);break;case compareToken.NOT_EQUAL:- result = !isMatchWildcard(currentValue, value);+ result = !isMatchWildcard(currentText, pattern);break;case compareToken.GREATER_THAN:case compareToken.GREATER_THAN_OR_EQUAL:- result = isMatchWildcard(currentValue, value) || currentValue > replaceWildcard(value);+ result = isMatchWildcard(currentText, pattern) || currentText > replaceWildcard(pattern);break;case compareToken.LESS_THAN:case compareToken.LESS_THAN_OR_EQUAL:- result = currentValue < replaceWildcard(value);+ result = currentText < replaceWildcard(pattern);break;default:diff --git a/packages/engine-formula/src/engine/utils/object-compare.ts b/packages/engine-formula/src/engine/utils/object-compare.tsindex ec742f61aa..0b28bd4edf 100644--- a/packages/engine-formula/src/engine/utils/object-compare.ts+++ b/packages/engine-formula/src/engine/utils/object-compare.ts@@ -17,11 +17,31 @@import type { DateSystem } from '@univerjs/core';import type { ArrayValueObject } from '../value-object/array-value-object';import type { BaseValueObject } from '../value-object/base-value-object';+import { isRealNum } from '@univerjs/core';import { compareToken } from '../../basics/token';import { ValueObjectFactory } from '../value-object/array-value-object';-import { BooleanValueObject, createBooleanValueObjectByRawValue } from '../value-object/primitive-object';+import {+ BooleanValueObject,+ createBooleanValueObjectByRawValue,+ NumberValueObject,+ StringValueObject,+} from '../value-object/primitive-object';import { expandArrayValueObject } from './array-object';+export function createCriteriaValueObject(content: string, dateSystem?: DateSystem): BaseValueObject {+ if (isRealNum(content)) {+ const number = Number(content);+ // Excel accepts decimal/scientific notation and spaces, but not JS+ // radix prefixes, control whitespace or infinities.+ if (!/^ *[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)? *$/i.test(content) || !Number.isFinite(number)) {+ return StringValueObject.create(content);+ }+ // Excel flushes subnormal decimal values to zero.+ return NumberValueObject.create(Math.abs(number) < 2 ** -1022 ? 0 : number);+ }+ return ValueObjectFactory.create(content, false, dateSystem);+}+export function findCompareToken(str: string, dateSystem?: DateSystem): [compareToken, BaseValueObject] {const comparisonTokens: compareToken[] = [compareToken.EQUALS,@@ -32,14 +52,19 @@ export function findCompareToken(str: string, dateSystem?: DateSystem): [comparecompareToken.LESS_THAN,];+ let operator = compareToken.EQUALS;+ let content = str;for (const token of comparisonTokens) {if (str.startsWith(token)) {- const content = str.substring(token.length);- return [token, ValueObjectFactory.create(content, false, dateSystem) as BaseValueObject];+ operator = token;+ content = str.substring(token.length);+ break;}}- return [compareToken.EQUALS, ValueObjectFactory.create(str, false, dateSystem) as BaseValueObject];+ // Criteria accept numeric text such as "01" and "1.0" even though a+ // worksheet cell containing that text must retain its string type.+ return [operator, createCriteriaValueObject(content, dateSystem)];}/**diff --git a/packages/engine-formula/src/engine/utils/value-object.ts b/packages/engine-formula/src/engine/utils/value-object.tsindex 55b2e41126..03c35c5af3 100644--- a/packages/engine-formula/src/engine/utils/value-object.ts+++ b/packages/engine-formula/src/engine/utils/value-object.ts@@ -18,7 +18,7 @@ import type { ICellData, Nullable } from '@univerjs/core';import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';import type { BaseValueObject } from '../value-object/base-value-object';import { CellValueType } from '@univerjs/core';-import { ErrorType } from '../../basics/error-type';+import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';import { compareToken } from '../../basics/token';import { CellReferenceObject } from '../reference-object/cell-reference-object';import { ColumnReferenceObject } from '../reference-object/column-reference-object';@@ -28,7 +28,12 @@ import { ErrorValueObject } from '../value-object/base-value-object';import { BooleanValueObject, NumberValueObject } from '../value-object/primitive-object';import { expandArrayValueObject } from './array-object';import { isWildcard } from './compare';-import { booleanObjectIntersection, findCompareToken, valueObjectCompare } from './object-compare';+import {+ booleanObjectIntersection,+ createCriteriaValueObject,+ findCompareToken,+ valueObjectCompare,+} from './object-compare';export function convertTonNumber(valueObject: BaseValueObject) {const currentValue = valueObject.getValue();@@ -124,12 +129,11 @@ export function objectValueToCellValue(objectValue: Nullable<BaseValueObject>):...cellWithCustomData,};}- // String "00"- // =IF(1,"0") evaluates to "0", which should be a normal string (regardless of whether it is a number or not). Forced strings only appear when preceded by single quotes+ // Error-looking text must remain distinct from actual errors when read back.if (vo.isString()) {return {v,- t: CellValueType.STRING,+ t: ERROR_TYPE_SET.has(v as ErrorType) ? CellValueType.FORCE_STRING : CellValueType.STRING,...cellWithStyle,...cellWithCustomData,};@@ -496,14 +500,14 @@ export function filterSameValueObjectResult(}if (rangeValueObject?.isNumber() && criteriaObject.isString()) {- const criteriaNumber = criteriaObject.convertToNumberObjectValue();+ const criteriaNumber = createCriteriaValueObject(`${criteriaObject.getValue()}`, criteriaObject.getDateSystem());if (criteriaNumber.isNumber()) {return rangeValueObject.compare(criteriaNumber, operator);}}- if (criteriaObject.isNumber() && criteriaObject.isDateFormat() && rangeValueObject?.isString()) {+ if (operator !== compareToken.NOT_EQUAL && criteriaObject.isNumber() && criteriaObject.isDateFormat() && rangeValueObject?.isString()) {const rangeNumber = rangeValueObject.convertToNumberObjectValue();if (rangeNumber.isNumber()) {@@ -520,7 +524,8 @@ export function filterSameValueObjectResult(}/**- * If the operator is '=' or '<>', we can compare string numbers against numeric criteria directly in COUNTIF, COUNTIFS, SUMIF, SUMIFS, etc.+ * Equality criteria coerce numeric text; numeric inequality criteria+ * retain the distinction between text cells and numeric cells.* Other operators require both valueObjects to be of the same type.* For example:* | A1 | B1 |@@ -532,8 +537,8 @@ export function filterSameValueObjectResult(* =COUNTIF(A1:B1, '<=123') will return 1*/if (operator === compareToken.EQUALS || operator === compareToken.NOT_EQUAL) {- if (criteriaObject.isNumber() && rangeValueObject?.isString()) {- const rangeNumber = rangeValueObject.convertToNumberObjectValue();+ if (operator === compareToken.EQUALS && criteriaObject.isNumber() && rangeValueObject?.isString()) {+ const rangeNumber = createCriteriaValueObject(`${rangeValueObject.getValue()}`, rangeValueObject.getDateSystem());if (rangeNumber.isNumber()) {return rangeNumber.compare(criteriaObject, operator);diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.tsindex eb5acf7c90..5cfad3ac4e 100644--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts@@ -19,12 +19,47 @@ import type { BaseValueObject } from '../base-value-object';import { DateSystem } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { ErrorType } from '../../../basics/error-type';+import { CELL_INVERTED_INDEX_CACHE } from '../../../basics/inverted-index-cache';+import { compareToken } from '../../../basics/token';import { getObjectValue } from '../../../functions/util';import { ArrayValueObject, transformToValueObject, ValueObjectFactory } from '../array-value-object';import { ErrorValueObject } from '../base-value-object';import { BooleanValueObject, NumberValueObject, StringValueObject } from '../primitive-object';describe('arrayValueObject test', () => {+ it('matches uncached comparisons after repeated formula-result updates', () => {+ const values = [[1], [3], [5], [7], [9]];+ const createArray = (useInvertedIndexCache: boolean): ArrayValueObject => ArrayValueObject.create({+ calculateValueList: transformToValueObject(values),+ rowCount: values.length,+ columnCount: 1,+ unitId: 'updated-formulas',+ sheetId: 'sheet',+ row: 10,+ column: 2,+ useInvertedIndexCache,+ });+ CELL_INVERTED_INDEX_CACHE.clear();+ try {+ createArray(true).compare(NumberValueObject.create(3), compareToken.EQUALS);+ for (let update = 0; update < 100; update++) {+ const row = update % values.length;+ values[row][0] = (update * 7) % 11;+ CELL_INVERTED_INDEX_CACHE.set('updated-formulas', 'sheet', 2, values[row][0], row + 10, true);+ for (const operator of Object.values(compareToken)) {+ const criterion = NumberValueObject.create(update % 11);+ const cached = createArray(true).compare(criterion, operator);+ const uncached = createArray(false).compare(criterion, operator);+ for (let index = 0; index < values.length; index++) {+ expect(cached.getValueOrDefault(index, 0)!.getValue()).toEqual(uncached.getValueOrDefault(index, 0)!.getValue());+ }+ }+ }+ } finally {+ CELL_INVERTED_INDEX_CACHE.clear();+ }+ });+const originArrayValueObject = ArrayValueObject.create({calculateValueList: transformToValueObject([[1, 2, 3, 4, 5],diff --git a/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.tsindex 2ec106f359..c409e4fc60 100644--- a/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts+++ b/packages/engine-formula/src/engine/value-object/__tests__/primitive-object.spec.ts@@ -16,9 +16,36 @@import { DateSystem } from '@univerjs/core';import { describe, expect, it } from 'vitest';+import { compareToken } from '../../../basics/token';import { NumberValueObject, StringValueObject } from '../primitive-object';describe('StringValueObject', () => {+ it.each([+ ['ß', 'SS', true],+ ['ẞ', 'ss', true],+ ['straße', 'STRASSE', true],+ ['æ', 'ae', true],+ ['œ', 'oe', true],+ ['ff', 'ff', true],+ ['é', 'e\u0301', true],+ ['é', 'e', false],+ ['İ', 'i', false],+ ['ı', 'i', false],+ ['İ', '?', true],+ ['ß', '?', true],+ ['ß', 'ss*', false],+ ['ẞ', 'ß*', true],+ ['😀', '?', false],+ ['😀', '??', true],+ ['a\nb', '*', true],+ ])('matches Excel text comparison for %s and %s', (value, criterion, expected) => {+ expect(StringValueObject.create(value).compare(StringValueObject.create(criterion), compareToken.EQUALS).getValue()).toBe(expected);+ });++ it('keeps case-sensitive wildcard matching case-sensitive', () => {+ expect(StringValueObject.create('ABC').compare(StringValueObject.create('a*'), compareToken.EQUALS, true).getValue()).toBe(false);+ });+it('binds the date system in place for scalar values', () => {const value = NumberValueObject.create(1);diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.tsindex 8b9b651725..66ce993916 100644--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts@@ -20,7 +20,7 @@ import { reverseCompareOperator } from '../../basics/calculate';import { BooleanValue, ConcatenateType } from '../../basics/common';import { ErrorType } from '../../basics/error-type';import { compareToken } from '../../basics/token';-import { compareWithWildcard, isWildcard } from '../utils/compare';+import { compareWithWildcard, isWildcard, normalizeTextForComparison } from '../utils/compare';import { ceil, divide, equals, floor, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals, minus, mod, multiply, plus, pow, round, sqrt } from '../utils/math-kit';import { BaseValueObject, ErrorValueObject } from './base-value-object';@@ -1532,10 +1532,6 @@ export class StringValueObject extends BaseValueObject {override compare(valueObject: BaseValueObject, operator: compareToken, isCaseSensitive?: boolean): BaseValueObject {if (valueObject.isArray()) {- // const o = valueObject.getReciprocal();- // if (o.isError()) {- // return o;- // }return valueObject.compare(this, reverseCompareOperator(operator), isCaseSensitive);}return this.compareBy(valueObject.getValue(), operator, isCaseSensitive);@@ -1546,17 +1542,16 @@ export class StringValueObject extends BaseValueObject {let result = false;if (typeof value === 'string') {+ if (isWildcard(value)) {+ return this._checkWildcard(value, operator, isCaseSensitive);+ }// Case sensitivity needs to be considered, most functions are case-insensitive, like VLOOKUP/HLOOKUP/XLOOKUP/MATCH/COUNTIF/COUNTIFS/SUMIF/SUMIFS/SEARCH/FIND(in SUBSTITUTE)// A few functions are case-sensitive, like EXACT/FIND/FINDB/REPLACE/REPLACEB/MIDBlet _value = value;if (!isCaseSensitive) {- currentValue = currentValue.toLocaleLowerCase();- _value = _value.toLocaleLowerCase();- }-- if (isWildcard(_value)) {- return this._checkWildcard(_value, operator);+ currentValue = normalizeTextForComparison(currentValue);+ _value = normalizeTextForComparison(_value);}result = this._compareString(currentValue, _value, operator);@@ -1638,9 +1633,8 @@ export class StringValueObject extends BaseValueObject {return BooleanValueObject.create(true);}- private _checkWildcard(value: string, operator: compareToken) {- const currentValue = this.getValue().toLocaleLowerCase();- const result = compareWithWildcard(currentValue, value, operator);+ private _checkWildcard(value: string, operator: compareToken, isCaseSensitive: boolean) {+ const result = compareWithWildcard(this.getValue(), value, operator, isCaseSensitive);return BooleanValueObject.create(result);}diff --git a/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.tsindex 6bf03c37f7..4553d9fa31 100644--- a/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/hlookup/__tests__/index.spec.ts@@ -180,3 +180,27 @@ describe('Test hlookup', () => {});});});++describe('Excel lookup error precedence', () => {+ it.each([+ [1, 0, '#N/A', '#N/A'],+ [1, 2, '#N/A', '#N/A'],+ [8, 0, '#VALUE!', '#VALUE!'],+ [8, -1, '#VALUE!', '#VALUE!'],+ [8, 2, '#REF!', '#REF!'],+ [8, 2.9, '#REF!', '#REF!'],+ [9, 2, '#N/A', '#REF!'],+ [20, 2, '#N/A', '#REF!'],+ ])('looks up %s before validating index %s', (key, index, exact, approximate) => {+ const fn = new Hlookup(FUNCTION_NAMES_LOOKUP.HLOOKUP);+ for (const [mode, expected] of [[0, exact], [1, approximate]] as const) {+ const result = fn.calculate(+ NumberValueObject.create(key as number),+ ArrayValueObject.create('{8,10,12}'),+ NumberValueObject.create(index as number),+ NumberValueObject.create(mode)+ );+ expect(result.getValue()).toBe(expected);+ }+ });+});diff --git a/packages/engine-formula/src/functions/lookup/hlookup/index.ts b/packages/engine-formula/src/functions/lookup/hlookup/index.tsindex 9038c87c71..a0d35da3d8 100644--- a/packages/engine-formula/src/functions/lookup/hlookup/index.ts+++ b/packages/engine-formula/src/functions/lookup/hlookup/index.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';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';@@ -45,7 +46,7 @@ export class Hlookup extends BaseFunction {}if (rowIndexNum.isError()) {- return ErrorValueObject.create(ErrorType.NA);+ return rowIndexNum;}if (rangeLookup?.isError()) {@@ -61,30 +62,38 @@ export class Hlookup extends BaseFunction {const rowIndexNumValue = this.getIndexNumValue(rowIndexNum);if (rowIndexNumValue instanceof ErrorValueObject) {- return rowIndexNumValue;+ return ErrorValueObject.create(ErrorType.VALUE);}+ const rowIndex = Math.floor(rowIndexNumValue);+const searchArray = (tableArray as ArrayValueObject).slice([0, 1]);- const resultArray = (tableArray as ArrayValueObject).slice([rowIndexNumValue - 1, rowIndexNumValue]);+ const resultArray = (tableArray as ArrayValueObject).slice([rowIndex - 1, rowIndex]);- if (searchArray == null || resultArray == null) {+ if (searchArray == null) {return ErrorValueObject.create(ErrorType.REF);}if (lookupValue.isArray()) {- return lookupValue.map((value) => this._handleSingleObject(value, searchArray, resultArray, rangeLookupValue));+ return lookupValue.map((value) => this._handleSingleObject(value, searchArray, resultArray, rangeLookupValue, rowIndex));}- return this._handleSingleObject(lookupValue, searchArray, resultArray, rangeLookupValue);+ return this._handleSingleObject(lookupValue, searchArray, resultArray, rangeLookupValue, rowIndex);}private _handleSingleObject(value: BaseValueObject,searchArray: ArrayValueObject,- resultArray: ArrayValueObject,- rangeLookupValue: number- ) {+ resultArray: Nullable<ArrayValueObject>,+ rangeLookupValue: number,+ rowIndex: number+ ): BaseValueObject {+ if (resultArray == null || rowIndex < 1) {+ const match = this._handleSingleObject(value, searchArray, searchArray, rangeLookupValue, 1);+ return match.isError() ? match : ErrorValueObject.create(rowIndex < 1 ? ErrorType.VALUE : ErrorType.REF);+ }+if (rangeLookupValue === 0) {return this._blankResultAsZero(this.equalSearch(value, searchArray, resultArray));}diff --git a/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.tsindex a6b7b26c9e..11ca68a82d 100644--- a/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/vlookup/__tests__/index.spec.ts@@ -200,7 +200,7 @@ describe('Test vlookup', () => {}`),NumberValueObject.create(0)) as BaseValueObject;- expect(getObjectValue(resultObject)).toStrictEqual(ErrorType.REF); // Excel reports #N/A+ expect(getObjectValue(resultObject)).toStrictEqual(ErrorType.NA);});it('LookupValue is single cell, colIndexNum is array and gets rangeLookup error', async () => {@@ -239,7 +239,7 @@ describe('Test vlookup', () => {}`)) as BaseValueObject;expect(getObjectValue(resultObject)).toStrictEqual([- [ErrorType.REF],+ [ErrorType.NA],[ErrorType.REF],]); // Excel reports [[ErrorType.NA], [ErrorType.REF]]});@@ -400,3 +400,27 @@ describe('Test vlookup', () => {});});});++describe('Excel lookup error precedence', () => {+ it.each([+ [1, 0, '#N/A', '#N/A'],+ [1, 2, '#N/A', '#N/A'],+ [8, 0, '#VALUE!', '#VALUE!'],+ [8, -1, '#VALUE!', '#VALUE!'],+ [8, 2, '#REF!', '#REF!'],+ [8, 2.9, '#REF!', '#REF!'],+ [9, 2, '#N/A', '#REF!'],+ [20, 2, '#N/A', '#REF!'],+ ])('looks up %s before validating index %s', (key, index, exact, approximate) => {+ const fn = new Vlookup(FUNCTION_NAMES_LOOKUP.VLOOKUP);+ for (const [mode, expected] of [[0, exact], [1, approximate]] as const) {+ const result = fn.calculate(+ NumberValueObject.create(key as number),+ ArrayValueObject.create('{8;10;12}'),+ NumberValueObject.create(index as number),+ NumberValueObject.create(mode)+ );+ expect(getObjectValue(result)).toEqual([[expected]]);+ }+ });+});diff --git a/packages/engine-formula/src/functions/lookup/vlookup/index.ts b/packages/engine-formula/src/functions/lookup/vlookup/index.tsindex 3694bce3f9..124139b168 100644--- a/packages/engine-formula/src/functions/lookup/vlookup/index.ts+++ b/packages/engine-formula/src/functions/lookup/vlookup/index.ts@@ -161,15 +161,11 @@ export class Vlookup extends BaseFunction {let colIndexNumValue = this.getIndexNumValue(colIndexNum);if (colIndexNumValue instanceof ErrorValueObject) {- return colIndexNumValue;+ return ErrorValueObject.create(ErrorType.VALUE);}colIndexNumValue = Math.floor(colIndexNumValue);- if (colIndexNumValue < 1) {- return ErrorValueObject.create(ErrorType.VALUE);- }-const searchArray = (tableArray as ArrayValueObject).slice(undefined, [0, 1]);if (searchArray == null) {@@ -178,10 +174,9 @@ export class Vlookup extends BaseFunction {const resultArray = (tableArray as ArrayValueObject).slice(undefined, [colIndexNumValue - 1, colIndexNumValue]);- // The error reporting priority of lookupValue in Excel is higher than colIndexNum. It is required to execute the query from the first column first, and then take the value of colIndexNum column from the query result.- // Here we will first throw the colIndexNum error to avoid unnecessary queries and improve performance.- if (resultArray == null) {- return ErrorValueObject.create(ErrorType.REF);+ if (resultArray == null || colIndexNumValue < 1) {+ const match = this._handleSingleObject(lookupValue, searchArray, searchArray, rangeLookupValue);+ return match.isError() ? match : ErrorValueObject.create(colIndexNumValue < 1 ? ErrorType.VALUE : ErrorType.REF);}return this._handleSingleObject(lookupValue, searchArray, resultArray, rangeLookupValue);diff --git a/packages/engine-formula/src/functions/statistical/countif/__tests__/index.spec.ts b/packages/engine-formula/src/functions/statistical/countif/__tests__/index.spec.tsindex 86f274168c..f3a4627626 100644--- a/packages/engine-formula/src/functions/statistical/countif/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/statistical/countif/__tests__/index.spec.ts@@ -292,6 +292,11 @@ describe('Test countif function', () => {expect(result).toBe(0);});+ it('Treats blank referenced array criteria as zero without changing empty strings', async () => {+ expect(await calculate('=COUNTIF(F1:F3,F1:F2)')).toStrictEqual([[2], [0]]);+ expect(await calculate('=COUNTIF(F1:F3,{"";0})')).toStrictEqual([[2], [0]]);+ });+it('Does not match incomplete inequality criteria', async () => {expect(await calculate('=COUNTIF(F1:F3,">")')).toBe(0);expect(await calculate('=COUNTIF(F1:F3,">=")')).toBe(0);diff --git a/packages/engine-formula/src/functions/statistical/countif/index.ts b/packages/engine-formula/src/functions/statistical/countif/index.tsindex 3f64d6688e..de18e7f2c4 100644--- a/packages/engine-formula/src/functions/statistical/countif/index.ts+++ b/packages/engine-formula/src/functions/statistical/countif/index.ts@@ -47,7 +47,10 @@ export class Countif extends BaseFunction {}if (_criteria.isArray()) {- const resultArray = (_criteria as ArrayValueObject).mapValue((criteriaObject) => this._handleSingleObject(range, criteriaObject));+ const resultArray = (_criteria as ArrayValueObject).mapValue((criteriaObject) => this._handleSingleObject(+ range,+ criteria.isReferenceObject() && criteriaObject.isNull() ? NumberValueObject.create(0) : criteriaObject+ ));if ((resultArray as ArrayValueObject).getRowCount() === 1 && (resultArray as ArrayValueObject).getColumnCount() === 1) {return (resultArray as ArrayValueObject).get(0, 0) as BaseValueObject;diff --git a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.tsindex 19251aae27..dd34185bc6 100644--- a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts@@ -14,8 +14,9 @@* limitations under the License.*/-import type { ICommandInfo, ICommandService, IExecutionOptions } from '@univerjs/core';-import { CommandType } from '@univerjs/core';+import type { ICommandInfo, IExecutionOptions } from '@univerjs/core';+import type { IDirtyConversionManagerParams } from '../active-dirty-manager.service';+import { CommandType, ICommandService, Univer } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {SetFormulaCalculationNotificationMutation,@@ -23,27 +24,27 @@ import {SetFormulaCalculationStopMutation,SetTriggerFormulaCalculationStartMutation,} from '../../commands/mutations/set-formula-calculation.mutation';-import { ActiveDirtyManagerService } from '../active-dirty-manager.service';+import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../active-dirty-manager.service';import { FormulaCalculationTriggerService } from '../formula-calculation-trigger.service';import { FormulaExecutedStateType } from '../runtime.service';function createTestBed(start = true) {- let listener: ((command: ICommandInfo, options?: IExecutionOptions) => void) | undefined;+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);+ injector.add([FormulaCalculationTriggerService]);const executed: Array<{ id: string; params: unknown; options: unknown }> = [];- const activeDirtyManagerService = new ActiveDirtyManagerService();+ const activeDirtyManagerService = injector.get(IActiveDirtyManagerService);const conversions = activeDirtyManagerService.getDirtyConversionMap();- const commandService = {- onCommandExecuted: vi.fn((callback: typeof listener) => {- listener = callback;- return { dispose: vi.fn() };- }),- executeCommand: vi.fn(async (id: string, params: unknown, options?: IExecutionOptions) => {+ const commandService = injector.get(ICommandService);+ for (const id of [SetFormulaCalculationStartMutation.id, SetFormulaCalculationStopMutation.id]) {+ commandService.registerCommand({ id, type: CommandType.MUTATION, handler: (_accessor, params, options) => {executed.push({ id, params, options });- listener?.({ id, params } as ICommandInfo, options);return true;- }),- } as unknown as ICommandService;- const service = new FormulaCalculationTriggerService(commandService, activeDirtyManagerService);+ } });+ }+ const service = injector.get(FormulaCalculationTriggerService);+ service.disposeWithMe(() => univer.dispose());if (start) {service.start();}@@ -52,7 +53,12 @@ function createTestBed(start = true) {service,executed,conversions,- emit: (command: ICommandInfo, options?: IExecutionOptions) => listener?.(command, options),+ emit: (command: ICommandInfo, options?: IExecutionOptions) => {+ if (!commandService.hasCommand(command.id)) {+ commandService.registerCommand({ id: command.id, type: CommandType.MUTATION, handler: () => true });+ }+ commandService.syncExecuteCommand(command.id, command.params, options);+ },};}@@ -63,6 +69,39 @@ describe('FormulaCalculationTriggerService', () => {vi.restoreAllMocks();});+ it('batches formula registrations without changing payloads or completed session maps', async () => {+ const testBed = createTestBed();+ const payload = Object.freeze({+ dirtyUnitOtherFormulaMap: Object.freeze({+ unit: Object.freeze({ sheet: Object.freeze({ first: true }) }),+ }),+ });+ testBed.conversions.set('register-formula', {+ commandId: 'register-formula',+ getDirtyData: (command) => command.params as ReturnType<IDirtyConversionManagerParams['getDirtyData']>,+ });+ testBed.emit({ id: 'register-formula', params: payload });+ for (let index = 0; index < 2000; index++) {+ testBed.emit({ id: 'register-formula', params: {+ dirtyUnitOtherFormulaMap: { unit: { sheet: { [`formula-${index}`]: true } } },+ } });+ }+ await vi.advanceTimersByTimeAsync(10);+ const first = testBed.executed[0].params;+ expect(first).toMatchObject(payload);+ expect(first).toHaveProperty('dirtyUnitOtherFormulaMap.unit.sheet.formula-1999', true);+ testBed.emit({ id: SetFormulaCalculationNotificationMutation.id, params: {+ functionsExecutedState: FormulaExecutedStateType.SUCCESS,+ } });+ testBed.emit({ id: 'register-formula', params: {+ dirtyUnitOtherFormulaMap: { unit: { sheet: { next: true } } },+ } });+ await vi.advanceTimersByTimeAsync(10);+ expect(first).not.toHaveProperty('dirtyUnitOtherFormulaMap.unit.sheet.next');+ expect(testBed.executed[1].params).toHaveProperty('dirtyUnitOtherFormulaMap.unit.sheet', { next: true });+ testBed.service.dispose();+ });+it('collects changeset dirty data before start and merges it with the initial trigger', async () => {const testBed = createTestBed(false);testBed.conversions.set('sheet-dirty', {diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.tsindex 329a3a8021..3126e6941a 100644--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts@@ -17,6 +17,7 @@import type { ICellData, Nullable } from '@univerjs/core';import type { BaseAstNode } from '../../engine/ast-node/base-ast-node';import {+ CellValueType,ContextService,DesktopLogService,IContextService,@@ -29,6 +30,7 @@ import {} from '@univerjs/core';import { describe, expect, it } from 'vitest';import { ErrorType } from '../../basics/error-type';+import { CELL_INVERTED_INDEX_CACHE } from '../../basics/inverted-index-cache';import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { createNewArray } from '../../engine/utils/array-object';import { NullValueObject, NumberValueObject, StringValueObject } from '../../engine/value-object/primitive-object';@@ -94,6 +96,25 @@ function createRuntimeService() {}describe('FormulaRuntimeService', () => {+ it('indexes scalar and spilled null results as blanks, consistently with reference scans', () => {+ const { injector, runtime } = createRuntimeService();+ CELL_INVERTED_INDEX_CACHE.clear();+ try {+ runtime.setCurrent(2, 3, 20, 20, 'sheet', 'unit');+ runtime.setRuntimeData(NumberValueObject.create(7));+ CELL_INVERTED_INDEX_CACHE.setContinueBuildingCache('unit', 'sheet', 3, 0, 19);+ runtime.setRuntimeData(NullValueObject.create());+ expect(runtime.getUnitData().unit?.sheet?.getValue(2, 3)?.v).toBeNull();+ expect(CELL_INVERTED_INDEX_CACHE.getCellPositions('unit', 'sheet', 3, '', [[0, 19]])?.matchingRows).toEqual([2]);+ runtime.setCurrent(4, 3, 20, 20, 'sheet', 'unit');+ runtime.setRuntimeData(createNewArray([[NullValueObject.create()], [NumberValueObject.create(1)]], 2, 1));+ expect(CELL_INVERTED_INDEX_CACHE.getCellPositions('unit', 'sheet', 3, '', [[0, 19]])?.matchingRows).toEqual([2, 4]);+ } finally {+ CELL_INVERTED_INDEX_CACHE.clear();+ injector.dispose();+ }+ });+it.each(['__proto__', 'constructor', 'prototype', 'toString'])('isolates runtime writes for special identifiers (%s)', (key) => {const { injector, runtime } = createRuntimeService();const marker = '__formula_pollution__';@@ -363,6 +384,32 @@ describe('FormulaRuntimeService', () => {expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(3, 4)?.v).toBe(12);});+ it.each([+ { cell: { v: '12', t: CellValueType.NUMBER }, blocked: false },+ { cell: { v: '1.2e1', t: CellValueType.NUMBER }, blocked: false },+ { cell: { v: '13', t: CellValueType.NUMBER }, blocked: true },+ { cell: { v: '12', t: CellValueType.STRING }, blocked: true },+ { cell: { v: '12', t: CellValueType.FORCE_STRING }, blocked: true },+ { cell: { v: 'invalid', t: CellValueType.NUMBER }, blocked: true },+ ])('recognizes imported numeric array results without overwriting real blockers: $cell', ({ cell, blocked }) => {+ const { injector, runtime, unitDataMatrix, arrayFormulaCellData, arrayFormulaRange } = createRuntimeService();+ try {+ arrayFormulaRange.unit.sheet = {+ 3: { 3: { startRow: 3, startColumn: 3, endRow: 3, endColumn: 4 } },+ };+ unitDataMatrix.setValue(3, 4, { ...cell });+ arrayFormulaCellData.setValue(3, 4, { v: 12, t: CellValueType.NUMBER });+ runtime.setCurrent(3, 3, 10, 10, 'sheet', 'unit');+ runtime.setRuntimeData(createNewArray([[NumberValueObject.create(11), NumberValueObject.create(12)]], 1, 2));+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 3)?.v).toBe(blocked ? ErrorType.SPILL : 11);+ if (blocked) {+ expect(unitDataMatrix.getValue(3, 4)).toEqual(cell);+ }+ } finally {+ injector.dispose();+ }+ });+it('should return #SPILL when a real value is entered into the previous array formula range', () => {const { runtime, unitDataMatrix, arrayFormulaCellData, arrayFormulaRange } = createRuntimeService();arrayFormulaRange.unit.sheet = {diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.tsindex f6d4f4aebb..c2a8a79c72 100644--- a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts@@ -16,7 +16,9 @@import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';import type { IDirtyUnitFeatureMap } from '../basics/common';-import type { ISetFormulaCalculationNotificationMutation } from '../commands/mutations/set-formula-calculation.mutation';+import type {+ ISetFormulaCalculationNotificationMutation,+} from '../commands/mutations/set-formula-calculation.mutation';import type { IFormulaDirtyData } from './current-data.service';import { Disposable, ICommandService, Rectangle } from '@univerjs/core';import {@@ -186,10 +188,15 @@ export class FormulaCalculationTriggerService extends Disposable {}private _generateDirty(commands: ICommandInfo[]): IFormulaDirtyData {- return commands.reduce<IFormulaDirtyData>((result, command) => {+ const result = createEmptyDirtyData();+ const rangeKeys = new Set<string>();+ for (const command of commands) {const conversion = this._activeDirtyManagerService.get(command.id);- return conversion ? mergeDirtyData(result, conversion.getDirtyData(command)) : result;- }, createEmptyDirtyData());+ if (conversion) {+ appendDirtyData(result, conversion.getDirtyData(command), rangeKeys);+ }+ }+ return result;}}@@ -197,32 +204,36 @@ function createEmptyDirtyData(): IFormulaDirtyData {return {forceCalculation: false,dirtyRanges: [],- dirtyNameMap: {},- dirtyDefinedNameMap: {},- dirtySuperTableMap: {},- dirtyUnitFeatureMap: {},- dirtyUnitOtherFormulaMap: {},- clearDependencyTreeCache: {},+ dirtyNameMap: Object.create(null),+ dirtyDefinedNameMap: Object.create(null),+ dirtySuperTableMap: Object.create(null),+ dirtyUnitFeatureMap: Object.create(null),+ dirtyUnitOtherFormulaMap: Object.create(null),+ clearDependencyTreeCache: Object.create(null),};}function mergeDirtyData(left: IFormulaDirtyData, right: Partial<IFormulaDirtyData>): IFormulaDirtyData {- const dirtyRanges = [...left.dirtyRanges];- mergeDirtyRanges(dirtyRanges, right.dirtyRanges ?? []);- return {- dirtyRanges,- dirtyNameMap: mergeDirtyUnitStringMap(left.dirtyNameMap, right.dirtyNameMap),- dirtyDefinedNameMap: mergeDirtyUnitStringMap(left.dirtyDefinedNameMap, right.dirtyDefinedNameMap),- dirtySuperTableMap: mergeDirtyUnitStringMap(left.dirtySuperTableMap ?? {}, right.dirtySuperTableMap),- dirtyUnitFeatureMap: mergeDirtyUnitNestedMap(left.dirtyUnitFeatureMap, right.dirtyUnitFeatureMap),- dirtyUnitOtherFormulaMap: mergeDirtyUnitNestedMap(left.dirtyUnitOtherFormulaMap, right.dirtyUnitOtherFormulaMap),- clearDependencyTreeCache: mergeDirtyUnitStringMap(left.clearDependencyTreeCache, right.clearDependencyTreeCache),- forceCalculation: left.forceCalculation || Boolean(right.forceCalculation),- };+ const result = createEmptyDirtyData();+ const rangeKeys = new Set<string>();+ appendDirtyData(result, left, rangeKeys);+ appendDirtyData(result, right, rangeKeys);+ return result;+}++// The accumulator owns its nested maps; command payloads and running sessions stay unchanged.+function appendDirtyData(target: IFormulaDirtyData, source: Partial<IFormulaDirtyData>, rangeKeys: Set<string>): void {+ mergeDirtyRanges(target.dirtyRanges, source.dirtyRanges ?? [], rangeKeys);+ mergeDirtyUnitStringMap(target.dirtyNameMap, source.dirtyNameMap);+ mergeDirtyUnitStringMap(target.dirtyDefinedNameMap, source.dirtyDefinedNameMap);+ mergeDirtyUnitStringMap(target.dirtySuperTableMap ??= Object.create(null), source.dirtySuperTableMap);+ mergeDirtyUnitNestedMap(target.dirtyUnitFeatureMap, source.dirtyUnitFeatureMap);+ mergeDirtyUnitNestedMap(target.dirtyUnitOtherFormulaMap, source.dirtyUnitOtherFormulaMap);+ mergeDirtyUnitStringMap(target.clearDependencyTreeCache, source.clearDependencyTreeCache);+ target.forceCalculation = target.forceCalculation || Boolean(source.forceCalculation);}-function mergeDirtyRanges(target: IUnitRange[], source: IUnitRange[]): void {- const keys = new Set(target.map(getDirtyRangeKey));+function mergeDirtyRanges(target: IUnitRange[], source: IUnitRange[], keys: Set<string>): void {source.forEach((range) => {const key = getDirtyRangeKey(range);if (!keys.has(key)) {@@ -236,24 +247,19 @@ function getDirtyRangeKey({ unitId, sheetId, range }: IUnitRange): string {return JSON.stringify([unitId, sheetId, range.startRow, range.startColumn, range.endRow, range.endColumn, range.rangeType]);}-function mergeDirtyUnitStringMap(left: IDirtyUnitStringMap, right?: IDirtyUnitStringMap): IDirtyUnitStringMap {- const result: IDirtyUnitStringMap = { ...left };+function mergeDirtyUnitStringMap(target: IDirtyUnitStringMap, right?: IDirtyUnitStringMap): void {Object.entries(right ?? {}).forEach(([unitId, values]) => {- result[unitId] = { ...result[unitId], ...values };+ Object.assign(target[unitId] ??= Object.create(null), values);});- return result;}-function mergeDirtyUnitNestedMap(left: IDirtyUnitFeatureMap, right?: IDirtyUnitFeatureMap): IDirtyUnitFeatureMap {- const result: IDirtyUnitFeatureMap = { ...left };+function mergeDirtyUnitNestedMap(target: IDirtyUnitFeatureMap, right?: IDirtyUnitFeatureMap): void {Object.entries(right ?? {}).forEach(([unitId, sheets]) => {- const unitResult: NonNullable<IDirtyUnitFeatureMap[string]> = { ...result[unitId] };+ const unitResult = target[unitId] ??= Object.create(null);Object.entries(sheets ?? {}).forEach(([sheetId, values]) => {- unitResult[sheetId] = { ...unitResult[sheetId], ...values };+ Object.assign(unitResult[sheetId] ??= Object.create(null), values);});- result[unitId] = unitResult;});- return result;}function hasDirtyData(dirtyData: IFormulaDirtyData): boolean {diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.tsindex 7fd198bcdd..582b362a93 100644--- a/packages/engine-formula/src/services/runtime.service.ts+++ b/packages/engine-formula/src/services/runtime.service.ts@@ -15,7 +15,6 @@*/import type { ICellData, IRange, Nullable } from '@univerjs/core';-import type {IArrayFormulaEmbeddedMap,IArrayFormulaRangeType,@@ -30,7 +29,7 @@ import type { BaseReferenceObject, FunctionVariantType } from '../engine/referenimport type { ArrayValueObject } from '../engine/value-object/array-value-object';import type { BaseValueObject } from '../engine/value-object/base-value-object';import type { StringValueObject } from '../engine/value-object/primitive-object';-import { createIdentifier, Disposable, isNullCell, ObjectMatrix } from '@univerjs/core';+import { CellValueType, createIdentifier, Disposable, isNullCell, isRealNum, ObjectMatrix } from '@univerjs/core';import { isInDirtyRange } from '../basics/dirty';import { ErrorType } from '../basics/error-type';import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';@@ -710,7 +709,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeunitId,sheetId,column - startColumn + columnIndex,- !valueObject ? 0 : valueObject.getValue(),+ valueObject == null || valueObject.isNull() ? null : valueObject.getValue(),row - startRow + rowIndex,true);@@ -758,7 +757,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeunitId,sheetId,column,- (functionVariant as BaseValueObject).getValue(),+ (functionVariant as BaseValueObject).isNull() ? null : (functionVariant as BaseValueObject).getValue(),row,true);@@ -1020,7 +1019,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime}private _isSameCellValue(cell: Nullable<ICellData>, arrayDataCell: Nullable<ICellData>) {- return cell?.v === arrayDataCell?.v && cell?.t === arrayDataCell?.t;+ if (cell?.t !== arrayDataCell?.t) {+ return false;+ }+ if (cell?.v === arrayDataCell?.v) {+ return true;+ }+ // Imported numeric caches may store strings; calculation results store numbers.+ return cell?.t === CellValueType.NUMBER &&+ isRealNum(cell.v) && isRealNum(arrayDataCell?.v) &&+ Number(cell.v) === Number(arrayDataCell?.v);}private _checkIfArrayFormulaExceeded(rowCount: number, columnCount: number, arrayRange: IRange) {diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.highlight.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.highlight.spec.tsindex d083cd4cb2..2859fe6e0e 100644--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.highlight.spec.ts+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/calculate.highlight.spec.ts@@ -14,7 +14,15 @@* limitations under the License.*/-import type { IAverageHighlightCell, IConditionFormattingRule, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell } from '../../type';+import type { ICellData, Workbook } from '@univerjs/core';+import type {+ IAverageHighlightCell,+ IConditionFormattingRule,+ INumberHighlightCell,+ IRankHighlightCell,+ ITextHighlightCell,+} from '../../type';+import { CellValueType } from '@univerjs/core';import { beforeEach, describe, expect, it } from 'vitest';import { CFNumberOperator, CFRuleType, CFSubRuleType, CFTextOperator } from '../../../base/const';import { createTestBed } from './test.util';@@ -29,6 +37,41 @@ describe('Test conditional formatting highlight', () => {});describe('Test Number', async () => {+ // Expected results recorded with Excel COM DisplayFormat for cellIs rules.+ it.each<{ name: string; cell: ICellData; matches: boolean[] }>([+ { name: 'blank', cell: {}, matches: [true, false, true, false, false, true, true, true] },+ { name: 'formula empty string', cell: { f: '=IF(TRUE,"",1)', v: '', t: CellValueType.STRING }, matches: [false, true, false, true, true, false, true, false] },+ { name: 'text', cell: { v: 'abc', t: CellValueType.STRING }, matches: [false, true, false, true, true, false, true, false] },+ { name: 'numeric text', cell: { v: '5', t: CellValueType.FORCE_STRING }, matches: [false, true, false, true, true, false, true, false] },+ { name: 'zero', cell: { v: 0, t: CellValueType.NUMBER }, matches: [true, false, true, false, false, true, true, true] },+ { name: 'five', cell: { v: 5, t: CellValueType.NUMBER }, matches: [true, false, false, true, true, true, true, true] },+ { name: 'true', cell: { v: 1, t: CellValueType.BOOLEAN }, matches: [false, true, false, true, true, false, true, false] },+ { name: 'false', cell: { v: 0, t: CellValueType.BOOLEAN }, matches: [false, true, false, true, true, false, true, false] },+ { name: 'error', cell: { f: '=1/0', v: '#DIV/0!', t: CellValueType.STRING }, matches: [false, false, false, false, false, false, false, false] },+ ])('matches Excel number comparisons for $name', ({ cell, matches }) => {+ const comparisons: [CFNumberOperator, number | [number, number]][] = [+ [CFNumberOperator.between, [0, 10]],+ [CFNumberOperator.notBetween, [0, 10]],+ [CFNumberOperator.equal, 0],+ [CFNumberOperator.notEqual, 0],+ [CFNumberOperator.greaterThan, 0],+ [CFNumberOperator.lessThan, 10],+ [CFNumberOperator.greaterThanOrEqual, 0],+ [CFNumberOperator.lessThanOrEqual, 10],+ ];+ for (const [column, [operator, value]] of comparisons.entries()) {+ (testBed.workbook as Workbook).getSheetBySheetId(testBed.subUnitId)!.getCellMatrix().setValue(0, column, cell);+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, {+ ranges: [{ startRow: 0, endRow: 0, startColumn: column, endColumn: column }],+ cfId: `comparison-${column}`,+ stopIfTrue: false,+ rule: { type: CFRuleType.highlightCell, subType: CFSubRuleType.number, operator, value, style: { bl: 1 } } as INumberHighlightCell,+ });+ expect(testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 0, column))+ .toEqual({ style: matches[column] ? { bl: 1 } : {} });+ }+ });+it('Should apply higher-priority rule style when multiple rules are matched', () => {const lowerPriorityRule: IConditionFormattingRule<INumberHighlightCell> = {ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.tsindex 9ab8c3d796..f733efd0d8 100644--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts@@ -15,14 +15,29 @@*/import type { IStyleData, Nullable } from '@univerjs/core';-import type { IAverageHighlightCell, IFormulaHighlightCell, IHighlightCell, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell, ITimePeriodHighlightCell } from '../type';+import type {+ IAverageHighlightCell,+ IFormulaHighlightCell,+ IHighlightCell,+ INumberHighlightCell,+ IRankHighlightCell,+ ITextHighlightCell,+ ITimePeriodHighlightCell,+} from '../type';import type { IContext } from './base-calculate-unit';import { CellValueType, dateKit, Range, Tools } from '@univerjs/core';import { ERROR_TYPE_SET, FormulaResultStatus } from '@univerjs/engine-formula';import { CFNumberOperator, CFSubRuleType, CFTextOperator, CFTimePeriodOperator } from '../../base/const';import { ConditionalFormattingFormulaService } from '../../services/conditional-formatting-formula.service';import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';-import { compareWithNumber, filterRange, getCellValue, isFloatsEqual, isNullable, serialTimeToTimestamp } from './utils';+import {+ compareWithNumber,+ filterRange,+ getCellValue,+ isFloatsEqual,+ isNullable,+ serialTimeToTimestamp,+} from './utils';interface IConfig {value: any;@@ -240,21 +255,17 @@ export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConfconst run = () => {switch (ruleConfig.subType) {case CFSubRuleType.number: {- const v = cellValue && Number(cellValue.v);- const isNumber = cellValue?.t === CellValueType.NUMBER;const subRuleConfig = ruleConfig as INumberHighlightCell;- if (!isNumber) {- if ([CFNumberOperator.notEqual, CFNumberOperator.notBetween].includes(subRuleConfig.operator)) {- return true;- }+ const value = cellValue?.v;+ if (cellValue?.t !== CellValueType.FORCE_STRING && (ERROR_TYPE_SET as Set<unknown>).has(value)) {return false;}-- if (isNullable(v) || Number.isNaN(v)) {- return;+ // Excel compares an empty cell as zero. Text (including a formula's+ // empty string) and booleans sort above numbers without coercion.+ if (value != null && (cellValue?.t === CellValueType.BOOLEAN || (cellValue?.t !== CellValueType.NUMBER && typeof value !== 'number'))) {+ return [CFNumberOperator.notEqual, CFNumberOperator.notBetween, CFNumberOperator.greaterThan, CFNumberOperator.greaterThanOrEqual].includes(subRuleConfig.operator);}-- return compareWithNumber({ operator: subRuleConfig.operator, value: subRuleConfig.value || 0 }, v || 0);+ return compareWithNumber({ operator: subRuleConfig.operator, value: subRuleConfig.value ?? 0 }, Number(value ?? 0));}case CFSubRuleType.text: {const subRuleConfig = ruleConfig as ITextHighlightCell;diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.tsindex 39c1c13b65..bcffed23fe 100644--- a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts@@ -15,6 +15,7 @@*/import type { Dependency, ICellData, IWorkbookData, Nullable, Workbook } from '@univerjs/core';+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import { CellValueType, ICommandService, IConfigService, IUniverInstanceService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';import {FormulaDataModel,@@ -697,6 +698,49 @@ describe('UpdateFormulaController', () => {expect(getCellFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');});+ it.each(['0', '1', 'TRUE'])('preserves text %s when replaying formula edits and undo on a replica', async (text) => {+ const replica = createFacadeTestBed(createWorkbookData());+ const replicaCommands = replica.injector.get(ICommandService);+ replicaCommands.registerCommand(SetRangeValuesMutation);+ const mutations: ISetRangeValuesMutationParams[] = [];+ const subscription = commandService.onCommandExecuted((command) => {+ if (command.id === SetRangeValuesMutation.id) {+ mutations.push(structuredClone(command.params as ISetRangeValuesMutationParams));+ }+ });+ const getCell = (bed: typeof testBed): Nullable<ICellData> => bed.injector+ .get(IUniverInstanceService)+ .getUnit<Workbook>('test')+ ?.getSheetBySheetId('sheet1')+ ?.getCellMatrix()+ .getValue(5, 2);+ const replay = (): void => {+ for (const params of mutations.splice(0)) {+ replicaCommands.syncExecuteCommand(SetRangeValuesMutation.id, params, { onlyLocal: true });+ }+ expect(getCell(replica)).toEqual(getCell(testBed));+ };++ try {+ await commandService.executeCommand(SetRangeValuesCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 5, endRow: 5, startColumn: 2, endColumn: 2 },+ value: { v: text, t: CellValueType.STRING, f: null, si: null },+ });+ replay();+ expect(getCell(replica)).toMatchObject({ v: text, t: CellValueType.STRING });+ await commandService.executeCommand(UndoCommand.id);+ replay();+ await commandService.executeCommand(RedoCommand.id);+ replay();+ expect(getCell(replica)).toMatchObject({ v: text, t: CellValueType.STRING });+ } finally {+ subscription.dispose();+ replica.univer.dispose();+ }+ });+it('should sync formula data for value mutations and ignore style-only updates', async () => {const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex 42bea8113d..cc5e97076c 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -164,8 +164,8 @@ export class UpdateFormulaController extends Disposable {},};- // update core snapshot- this._commandService.executeCommand(+ // Finish this nested mutation before the caller so replicas replay the same write order.+ this._commandService.syncExecuteCommand(SetRangeValuesMutation.id,{unitId,diff --git a/packages/ui/src/views/progress-bar/ProgressBar.tsx b/packages/ui/src/views/progress-bar/ProgressBar.tsxindex 4f17c5669f..cc3612fe91 100644--- a/packages/ui/src/views/progress-bar/ProgressBar.tsx+++ b/packages/ui/src/views/progress-bar/ProgressBar.tsx@@ -30,27 +30,27 @@ export function ProgressBar(props: IProgressBarProps) {const { count, done, label = '' } = progress;const progressBarInnerRef = useRef<HTMLDivElement>(null!);- const [visible, setVisible] = useState(false);+ const [completedProgress, setCompletedProgress] = useState<IProgressBarProps['progress']>();+ const visible = count > 0 && completedProgress !== progress;useEffect(() => {const progressBarInner = progressBarInnerRef.current;+ let animationFrame: number | undefined;// Hide immediately if both count and done are zeroif (count === 0 && done === 0) {- setVisible(false);progressBarInner.style.width = '0%';return;}// Update the width of the progress bar- else if (count > 0) {- setVisible(true);+ if (count > 0) {const width = Math.floor((done / count) * 100);// Trigger the animation to prevent the progress bar from not being closed due to reaching 100% too quickly without animationif (done === count) {- requestAnimationFrame(() => {+ animationFrame = requestAnimationFrame(() => {progressBarInner.style.width = `${width - 1}%`; // Set a width slightly smaller than the target- requestAnimationFrame(() => {+ animationFrame = requestAnimationFrame(() => {progressBarInner.style.width = `${width}%`; // Then set the target width});});@@ -64,7 +64,7 @@ export function ProgressBar(props: IProgressBarProps) {const handleTransitionEnd = () => {if (done === count) {// Hide the progress bar after the animation finishes- setVisible(false);+ setCompletedProgress(progress);// Notify the parent component to reset the progress after the animation ends// After the progress bar is completed 100%, the upper props data source may not be reset, resulting in count and done still being the previous values (displaying 100%) when the progress bar is triggered next time, so a message is reported here to trigger clearing.@@ -76,9 +76,12 @@ export function ProgressBar(props: IProgressBarProps) {// Clean up the event listener on unmount or when dependencies changereturn () => {+ if (animationFrame !== undefined) {+ cancelAnimationFrame(animationFrame);+ }progressBarInner.removeEventListener('transitionend', handleTransitionEnd);};- }, [count, done]);+ }, [count, done, progress, onClearProgress]);return (<divdiff --git a/packages/ui/src/views/progress-bar/__tests__/ProgressBar.spec.tsx b/packages/ui/src/views/progress-bar/__tests__/ProgressBar.spec.tsxnew file mode 100644index 0000000000..3b8c247cd0--- /dev/null+++ b/packages/ui/src/views/progress-bar/__tests__/ProgressBar.spec.tsx@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++// @vitest-environment happy-dom++import { cleanup, fireEvent, render } from '@testing-library/react';+import { Profiler } from 'react';+import { afterEach, describe, expect, it } from 'vitest';+import { ProgressBar } from '../ProgressBar';++afterEach(cleanup);++describe('ProgressBar', () => {+ it('does not schedule a nested React update when calculation progress arrives', () => {+ const phases: string[] = [];+ const view = (done: number, count: number) => (+ <Profiler id="progress" onRender={(_id, phase) => phases.push(phase)}>+ <ProgressBar progress={{ done, count }} />+ </Profiler>+ );+ const result = render(view(0, 0));+ phases.length = 0;+ for (let done = 0; done < 100; done++) {+ result.rerender(view(done, 100));+ }+ expect(phases).toHaveLength(100);+ expect(phases).not.toContain('nested-update');+ expect(result.container.firstElementChild?.classList.contains('univer-hidden')).toBe(false);+ result.rerender(view(0, 0));+ expect(result.container.firstElementChild?.classList.contains('univer-hidden')).toBe(true);+ });++ it('hides completed progress and shows a subsequent calculation', () => {+ let cleared = 0;+ const result = render(<ProgressBar progress={{ done: 1, count: 1 }} onClearProgress={() => cleared++} />);+ fireEvent.transitionEnd(result.container.querySelector('.univer-transition-\\[width\\]')!);+ expect(cleared).toBe(1);+ expect(result.container.firstElementChild?.classList.contains('univer-hidden')).toBe(true);+ result.rerender(<ProgressBar progress={{ done: 0, count: 3 }} />);+ expect(result.container.firstElementChild?.classList.contains('univer-hidden')).toBe(false);+ });+});