@univerjs/engine-formula 1.0.0-beta.0 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1477,7 +1477,8 @@ const TABLE_NAME_REGEX = "((?![~!@#$%^&*()+<>?:,./;’,。、‘:“《》
1477
1477
  const TABLE_TITLE_REGEX = "\\[#.+\\]\\s*?,\\s*?";
1478
1478
  const TABLE_CONTENT_REGEX = "\\[[^#]*#?\\]";
1479
1479
  const TABLE_MULTIPLE_COLUMN_REGEX = `${TABLE_CONTENT_REGEX}${RANGE_SYMBOL}${TABLE_CONTENT_REGEX}`;
1480
- const TABLE_UNIT_QUALIFIER_REGEX = `(?:(?:${UNIT_NAME_REGEX}|'(?:[^']|'')+'|[^\\s!\\[\\]]+)!)?(?:${UNIT_NAME_REGEX})?`;
1480
+ const TABLE_BRACKETED_UNIT_QUALIFIER_REGEX = "\\[(?:[^\\]]|\\]\\])+\\]";
1481
+ const TABLE_UNIT_QUALIFIER_REGEX = `(?:(?:${TABLE_BRACKETED_UNIT_QUALIFIER_REGEX}|'(?:[^']|'')+'|[^\\s!\\[\\]]+)!)?(?:${TABLE_BRACKETED_UNIT_QUALIFIER_REGEX})?`;
1481
1482
  const REFERENCE_TABLE_ALL_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}$`;
1482
1483
  const REFERENCE_TABLE_SINGLE_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(${TABLE_CONTENT_REGEX}|\\[${TABLE_TITLE_REGEX}${TABLE_CONTENT_REGEX}\\])+$`;
1483
1484
  const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(\\[${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$|^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(\\[${TABLE_TITLE_REGEX}${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$`;
@@ -1934,8 +1935,13 @@ function splitTableStructuredRef(ref) {
1934
1935
  }
1935
1936
  quoteOpen = !quoteOpen;
1936
1937
  } else if (!quoteOpen && char === "[") bracketDepth++;
1937
- else if (!quoteOpen && char === "]") bracketDepth--;
1938
- else if (!quoteOpen && bracketDepth === 0 && char === "!") {
1938
+ else if (!quoteOpen && char === "]") {
1939
+ if (bracketDepth > 0 && tableRef[i + 1] === "]") {
1940
+ i++;
1941
+ continue;
1942
+ }
1943
+ bracketDepth--;
1944
+ } else if (!quoteOpen && bracketDepth === 0 && char === "!") {
1939
1945
  qualifierEnd = i;
1940
1946
  break;
1941
1947
  }
@@ -1943,8 +1949,10 @@ function splitTableStructuredRef(ref) {
1943
1949
  if (qualifierEnd >= 0) {
1944
1950
  unitQualifier = tableRef.slice(0, qualifierEnd).trim();
1945
1951
  tableRef = tableRef.slice(qualifierEnd + 1);
1946
- if (unitQualifier.startsWith("'") && unitQualifier.endsWith("'")) unitQualifier = unitQualifier.slice(1, -1);
1947
- if (unitQualifier.startsWith("[") && unitQualifier.endsWith("]")) unitQualifier = unitQualifier.slice(1, -1);
1952
+ const isQuotedQualifier = unitQualifier.startsWith("'") && unitQualifier.endsWith("'");
1953
+ const isBracketedQualifier = !isQuotedQualifier && unitQualifier.startsWith("[") && unitQualifier.endsWith("]");
1954
+ if (isQuotedQualifier) unitQualifier = unitQualifier.slice(1, -1);
1955
+ else if (isBracketedQualifier) unitQualifier = unitQualifier.slice(1, -1).replaceAll("]]", "]");
1948
1956
  unitQualifier = unquoteSheetName(unitQualifier);
1949
1957
  } else if (tableRef.startsWith("[")) {
1950
1958
  const legacyQualifierEnd = tableRef.indexOf("]");
@@ -5109,9 +5117,11 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5109
5117
  const unitId = base.getUnitId();
5110
5118
  formulaData[unitId] = {};
5111
5119
  const tables = Object.values(snapshot.tables);
5120
+ const formulaTableNames = (0, _univerjs_core.createBaseFormulaTableNameMap)(snapshot);
5112
5121
  for (let j = 0; j < tables.length; j++) {
5113
5122
  const table = tables[j];
5114
5123
  const tableFormulaData = {};
5124
+ const normalizedFormulaByFieldId = /* @__PURE__ */ new Map();
5115
5125
  const recordOrder = table.recordOrder;
5116
5126
  if (!recordOrder) {
5117
5127
  formulaData[unitId][table.id] = tableFormulaData;
@@ -5127,9 +5137,14 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5127
5137
  if (!field || field.type !== "formula") continue;
5128
5138
  const formula = String(((_field$config = field.config) === null || _field$config === void 0 ? void 0 : _field$config.formula) ?? "").trim();
5129
5139
  if (!formula) continue;
5140
+ let normalizedFormula = normalizedFormulaByFieldId.get(field.id);
5141
+ if (normalizedFormula == null) {
5142
+ normalizedFormula = normalizeBaseFormulaForEngine(formula, table, snapshot, formulaTableNames);
5143
+ normalizedFormulaByFieldId.set(field.id, normalizedFormula);
5144
+ }
5130
5145
  tableFormulaData[row] ??= {};
5131
5146
  tableFormulaData[row][col] = {
5132
- f: normalizeBaseFormulaForEngine(formula, table, snapshot),
5147
+ f: normalizedFormula,
5133
5148
  si: field.id
5134
5149
  };
5135
5150
  }
@@ -5257,6 +5272,7 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5257
5272
  };
5258
5273
  const baseData = {};
5259
5274
  const tableNameMap = {};
5275
+ const formulaTableNames = (0, _univerjs_core.createBaseFormulaTableNameMap)(snapshot);
5260
5276
  for (const table of Object.values(snapshot.tables)) {
5261
5277
  var _table$recordOrder;
5262
5278
  baseData[table.id] = {
@@ -5266,7 +5282,7 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5266
5282
  rowData: {},
5267
5283
  columnData: {}
5268
5284
  };
5269
- tableNameMap[table.name] = table.id;
5285
+ addEngineBaseTableNameMappings(tableNameMap, table, formulaTableNames);
5270
5286
  }
5271
5287
  allUnitData[unitId] = baseData;
5272
5288
  unitStylesData[unitId] = new _univerjs_core.Styles();
@@ -5610,28 +5626,47 @@ function initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix) {
5610
5626
  return { [unitId]: { [sheetId]: newSheetFormulaData } };
5611
5627
  }
5612
5628
  const BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g;
5613
- const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_]\w*)\[([^\]]+)\]/gi;
5614
- const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_\]\[])\[([^\]]+)\]/g;
5629
+ const BASE_TABLE_SCOPED_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi;
5630
+ const BASE_TABLE_CURRENT_ROW_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[@\[([^\]]+)\]\]/gi;
5631
+ const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[([^\[\]#]+)\]/gi;
5632
+ const BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w\[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi;
5633
+ const BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w\[])\[@\[([^\]]+)\]\](?!\])/g;
5634
+ const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^\w\[])\[@?([^\[\]#]+)\](?!\])/g;
5615
5635
  const BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi;
5616
5636
  const BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s!\[\]]+\[/g;
5617
- function normalizeBaseFormulaForEngine(formula, currentTable, snapshot) {
5637
+ function normalizeBaseFormulaForEngine(formula, currentTable, snapshot, formulaTableNames) {
5618
5638
  const refs = [];
5619
5639
  const hold = (ref) => {
5620
5640
  return `__BASE_FORMULA_REF_${refs.push(ref) - 1}__`;
5621
5641
  };
5622
- return protectBaseExternalReferences(formula, hold).replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5623
- const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
5624
- return targetTable ? hold(createEngineColumnRef(targetTable, fieldName, snapshot)) : `${sourceTableName}[${fieldName}]`;
5625
- }).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index) => refs[Number(index)] ?? "");
5642
+ return protectBaseFormulaParts(formula, hold).replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))).replace(BASE_TABLE_SCOPED_FIELD_REF_PATTERN, (_match, sourceTableName, scope, fieldName) => {
5643
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot, formulaTableNames);
5644
+ if (!targetTable) return `${sourceTableName}[[#${scope}],[${fieldName}]]`;
5645
+ return hold(scope.toLowerCase() === "data" ? createEngineColumnRef(targetTable, fieldName, formulaTableNames) : createEngineThisRowRef(targetTable, fieldName, formulaTableNames));
5646
+ }).replace(BASE_TABLE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5647
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot, formulaTableNames);
5648
+ return targetTable ? hold(createEngineThisRowRef(targetTable, fieldName, formulaTableNames)) : `${sourceTableName}[@[${fieldName}]]`;
5649
+ }).replace(BASE_SCOPED_FIELD_REF_PATTERN, (_match, prefix, scope, fieldName) => `${prefix}${hold(scope.toLowerCase() === "data" ? createEngineColumnRef(currentTable, fieldName, formulaTableNames) : createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5650
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot, formulaTableNames);
5651
+ if (targetTable) return hold(createEngineColumnRef(targetTable, fieldName, formulaTableNames));
5652
+ return `${sourceTableName}[${fieldName}]`;
5653
+ }).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index) => refs[Number(index)] ?? "");
5626
5654
  }
5627
5655
  function protectBaseExternalReferences(formula, replace) {
5628
5656
  return protectBaseExternalStructuredReferences(formula.replace(BASE_EXTERNAL_A1_REF_PATTERN, (reference, offset) => isInsideBaseFormulaString(formula, offset) ? reference : replace(reference)), replace);
5629
5657
  }
5658
+ function protectBaseFormulaParts(formula, replace) {
5659
+ return protectBaseFormulaStrings(protectBaseExternalReferences(formula, replace), replace);
5660
+ }
5661
+ function protectBaseFormulaStrings(formula, replace) {
5662
+ return formula.replace(/"(?:""|[^"])*"/g, replace);
5663
+ }
5630
5664
  function protectBaseExternalStructuredReferences(formula, replace) {
5631
5665
  const spans = [];
5632
5666
  BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex = 0;
5633
- let match;
5634
- while ((match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula)) != null) {
5667
+ while (true) {
5668
+ const match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula);
5669
+ if (match == null) break;
5635
5670
  if (isInsideBaseFormulaString(formula, match.index)) continue;
5636
5671
  const openBracket = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex - 1;
5637
5672
  let depth = 0;
@@ -5671,20 +5706,20 @@ function isInsideBaseFormulaString(formula, position) {
5671
5706
  }
5672
5707
  return inString;
5673
5708
  }
5674
- function createEngineThisRowRef(table, fieldName, snapshot) {
5675
- return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;
5709
+ function createEngineThisRowRef(table, fieldName, formulaTableNames) {
5710
+ return `${formulaTableNames.get(table.id) ?? (0, _univerjs_core.getBaseFormulaTableName)(table, { tables: { [table.id]: table } })}[[#This Row],[${fieldName}]]`;
5676
5711
  }
5677
- function createEngineColumnRef(table, fieldName, snapshot) {
5678
- return `${getEngineBaseTableName(table, snapshot)}[[#Data],[${fieldName}]]`;
5712
+ function createEngineColumnRef(table, fieldName, formulaTableNames) {
5713
+ return `${formulaTableNames.get(table.id) ?? (0, _univerjs_core.getBaseFormulaTableName)(table, { tables: { [table.id]: table } })}[[#Data],[${fieldName}]]`;
5679
5714
  }
5680
- function getEngineBaseTableName(table, snapshot) {
5681
- const tables = Object.values(snapshot.tables);
5682
- let sameNameCount = 0;
5683
- for (let i = 0; i < tables.length; i++) if (tables[i].name === table.name) {
5684
- sameNameCount++;
5685
- if (sameNameCount > 1) break;
5686
- }
5687
- return sameNameCount === 1 ? table.name : table.id;
5715
+ function addEngineBaseTableNameMappings(tableNameMap, table, formulaTableNames) {
5716
+ tableNameMap[formulaTableNames.get(table.id) ?? table.name] = table.id;
5717
+ }
5718
+ function createStableExcelTableName(tableId) {
5719
+ return `_T_${Array.from(tableId, (character) => {
5720
+ var _character$codePointA;
5721
+ return /[A-Za-z0-9]/.test(character) ? character : `_x${((_character$codePointA = character.codePointAt(0)) === null || _character$codePointA === void 0 ? void 0 : _character$codePointA.toString(16)) ?? "0"}_`;
5722
+ }).join("")}`;
5688
5723
  }
5689
5724
  function buildBaseRuntimeCellData(table) {
5690
5725
  const cellData = { ...table.cellData };
@@ -5772,11 +5807,13 @@ function isArrayConstantFormula(formula) {
5772
5807
  function isBaseCellData(value) {
5773
5808
  return !!value && typeof value === "object" && (Object.prototype.hasOwnProperty.call(value, "v") || Object.prototype.hasOwnProperty.call(value, "t") || Object.prototype.hasOwnProperty.call(value, "p") || Object.prototype.hasOwnProperty.call(value, "f") || Object.prototype.hasOwnProperty.call(value, "si"));
5774
5809
  }
5775
- function resolveBaseFormulaTable(tableName, currentTable, snapshot) {
5776
- if (!tableName || tableName === "table" || tableName === currentTable.id || tableName === currentTable.name) return currentTable;
5777
- const byId = snapshot.tables[tableName];
5778
- if (byId) return byId;
5779
- const matches = Object.values(snapshot.tables).filter((table) => table.name === tableName);
5810
+ function resolveBaseFormulaTable(tableName, currentTable, snapshot, formulaTableNames) {
5811
+ if (!tableName) return currentTable;
5812
+ const normalizedName = tableName.toLowerCase();
5813
+ const matches = Object.values(snapshot.tables).filter((table) => {
5814
+ var _formulaTableNames$ge;
5815
+ return table.id.toLowerCase() === normalizedName || table.name.toLowerCase() === normalizedName || ((_formulaTableNames$ge = formulaTableNames.get(table.id)) === null || _formulaTableNames$ge === void 0 ? void 0 : _formulaTableNames$ge.toLowerCase()) === normalizedName || createStableExcelTableName(table.id).toLowerCase() === normalizedName;
5816
+ });
5780
5817
  return matches.length === 1 ? matches[0] : void 0;
5781
5818
  }
5782
5819
 
@@ -8160,11 +8197,16 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
8160
8197
  * the sequential matching approach is only used for special matches in XLOOKUP and XMATCH.
8161
8198
  * For example, when match_mode is set to 1 and -1 for an exact match. If not found, it returns the next smaller item.
8162
8199
  */
8163
- orderSearch(valueObject, searchType = 1, isDesc = false, isFuzzyMatching = false) {
8200
+ orderSearch(valueObject, searchType = 1, isDesc = false, isFuzzyMatching = false, keepFirstNearest = false) {
8164
8201
  let result;
8165
8202
  let maxOrMin;
8166
8203
  let resultPosition;
8167
8204
  let maxOrMinPosition;
8205
+ const _isNearer = (itemValue, currentValue) => {
8206
+ const distance = itemValue.minus(valueObject).abs();
8207
+ const currentDistance = currentValue.minus(valueObject).abs();
8208
+ return keepFirstNearest ? distance.isLessThan(currentDistance).getValue() === true : distance.isLessThanOrEqual(currentDistance).getValue() === true;
8209
+ };
8168
8210
  const _handleMatch = (itemValue, row, column) => {
8169
8211
  if (itemValue == null || itemValue.isNull()) return true;
8170
8212
  let matchObject;
@@ -8181,7 +8223,7 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
8181
8223
  }
8182
8224
  if (searchType === 2) {
8183
8225
  if (itemValue.isGreaterThan(valueObject).getValue() === true) {
8184
- if (maxOrMin == null || itemValue.minus(valueObject).abs().isLessThanOrEqual(maxOrMin.minus(valueObject).abs()).getValue() === true) {
8226
+ if (maxOrMin == null || _isNearer(itemValue, maxOrMin)) {
8185
8227
  maxOrMin = itemValue;
8186
8228
  maxOrMinPosition = {
8187
8229
  row,
@@ -8191,7 +8233,7 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
8191
8233
  }
8192
8234
  } else if (searchType === 1) {
8193
8235
  if (itemValue.isLessThan(valueObject).getValue() === true) {
8194
- if (maxOrMin == null || itemValue.minus(valueObject).abs().isLessThanOrEqual(maxOrMin.minus(valueObject).abs()).getValue() === true) {
8236
+ if (maxOrMin == null || _isNearer(itemValue, maxOrMin)) {
8195
8237
  maxOrMin = itemValue;
8196
8238
  maxOrMinPosition = {
8197
8239
  row,
@@ -8694,11 +8736,12 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
8694
8736
  const sheetId = this.getSheetId();
8695
8737
  const startRow = this.getCurrentRow();
8696
8738
  const startColumn = this.getCurrentColumn();
8739
+ const isWildcardComparison = batchOperatorType === 5 && valueObject.isString() && isWildcard(String(valueObject.getValue()));
8697
8740
  /**
8698
8741
  * If comparison operations are conducted for a single numerical value,
8699
8742
  * then retrieve the judgment from the inverted index. This enhances performance.
8700
8743
  */
8701
- if (batchOperatorType === 5 && this._useInvertedIndexCache) {
8744
+ if (batchOperatorType === 5 && this._useInvertedIndexCache && !isWildcardComparison) {
8702
8745
  const { rowsInCache, rowsNotInCache } = CELL_INVERTED_INDEX_CACHE.canUseCache(unitId, sheetId, column + startColumn, startRow, startRow + rowCount - 1);
8703
8746
  if (rowsInCache.length > 0) {
8704
8747
  if (operator === "=" && !(valueObject.isString() && isWildcard(valueObject.getValue()))) {
@@ -9086,6 +9129,7 @@ var BaseReferenceObject = class extends ObjectClassType {
9086
9129
  }
9087
9130
  setForcedSheetId(sheetNameMap) {
9088
9131
  var _sheetNameMap$this$ge;
9132
+ if (!this._forcedSheetName) return;
9089
9133
  this._forcedSheetId = (_sheetNameMap$this$ge = sheetNameMap[this.getUnitId()]) === null || _sheetNameMap$this$ge === void 0 ? void 0 : _sheetNameMap$this$ge[this._forcedSheetName];
9090
9134
  }
9091
9135
  setForcedSheetIdDirect(sheetId) {
@@ -9486,7 +9530,7 @@ var CellReferenceObject = class extends BaseReferenceObject {
9486
9530
  unionBy(referenceObject) {
9487
9531
  if (!referenceObject.isCell()) return ErrorValueObject.create("#REF!");
9488
9532
  const cellReferenceObject = referenceObject;
9489
- const newRangeData = this.unionRange(this.getRangeData(), cellReferenceObject.getRangeData());
9533
+ const newRangeData = this.unionRange(this.getRangePosition(), cellReferenceObject.getRangePosition());
9490
9534
  return this._createRange(newRangeData);
9491
9535
  }
9492
9536
  unionRange(rangeData1, rangeData2) {
@@ -9528,8 +9572,6 @@ var CellReferenceObject = class extends BaseReferenceObject {
9528
9572
  rangeReferenceObject.setArrayFormulaCellData(this.getArrayFormulaCellData());
9529
9573
  rangeReferenceObject.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData());
9530
9574
  rangeReferenceObject.setRuntimeFeatureCellData(this.getRuntimeFeatureCellData());
9531
- const { x, y } = this.getRefOffset();
9532
- rangeReferenceObject.setRefOffset(x, y);
9533
9575
  const forceSheetId = this.getForcedSheetId();
9534
9576
  rangeReferenceObject.setForcedSheetName(this.getForcedSheetName());
9535
9577
  if (forceSheetId != null) rangeReferenceObject.setForcedSheetIdDirect(forceSheetId);
@@ -10285,6 +10327,9 @@ let FormulaRuntimeService = class FormulaRuntimeService extends _univerjs_core.D
10285
10327
  this._functionRefInfoOverrideStack.pop();
10286
10328
  };
10287
10329
  }
10330
+ hasFunctionRefInfoOverride() {
10331
+ return this._functionRefInfoOverrideStack.length > 0;
10332
+ }
10288
10333
  clearFunctionDefinitionPrivacyVar() {
10289
10334
  this._functionDefinitionPrivacyVar.clear();
10290
10335
  }
@@ -10741,7 +10786,7 @@ var PrefixNode = class extends BaseAstNode {
10741
10786
  if (value instanceof ArrayValueObject) return value.get(0, 0) ?? ErrorValueObject.create("#VALUE!");
10742
10787
  if (!value.isReferenceObject()) return value;
10743
10788
  const currentValue = value;
10744
- if (currentValue.isCell()) return ErrorValueObject.create("#VALUE!");
10789
+ if (currentValue.isCell()) return currentValue.getCellByPosition();
10745
10790
  if (this._preserveAtRangeForFormula2LookupArray()) return currentValue;
10746
10791
  const runtimeService = this._runtimeService;
10747
10792
  const currentRow = runtimeService.currentRow || 0;
@@ -10906,6 +10951,7 @@ var FunctionNode = class extends BaseAstNode {
10906
10951
  if (!this._functionExecutor.returnsLegacyArrayAsScalar || !isTopLevel || !result.isArray()) return result;
10907
10952
  const array = result;
10908
10953
  if (array.getRowCount() <= 1 && array.getColumnCount() <= 1) return result;
10954
+ if (this._runtimeService.hasFunctionRefInfoOverride() && (this._runtimeService.currentRowCount > 1 || this._runtimeService.currentColumnCount > 1)) return result;
10909
10955
  return array.getFirstCell();
10910
10956
  }
10911
10957
  /**
@@ -11827,6 +11873,7 @@ var TableReferenceObject = class extends BaseReferenceObject {
11827
11873
  const tableStartRow = range.startRow;
11828
11874
  const tableEndRow = range.endRow;
11829
11875
  const dataStartRow = tableStartRow + (this._tableData.showHeader === false ? 0 : 1);
11876
+ const dataEndRow = tableEndRow - (this._tableData.showFooter === true ? 1 : 0);
11830
11877
  let startRow = -1;
11831
11878
  let endRow = -1;
11832
11879
  switch (type) {
@@ -11836,7 +11883,7 @@ var TableReferenceObject = class extends BaseReferenceObject {
11836
11883
  break;
11837
11884
  case "#Data":
11838
11885
  startRow = dataStartRow;
11839
- endRow = tableEndRow;
11886
+ endRow = dataEndRow;
11840
11887
  break;
11841
11888
  case "#Headers":
11842
11889
  if (this._tableData.showHeader === false) {
@@ -11852,14 +11899,14 @@ var TableReferenceObject = class extends BaseReferenceObject {
11852
11899
  endRow = tableEndRow;
11853
11900
  break;
11854
11901
  case "#This Row": {
11855
- const r = this._resolveThisRow(tableStartRow, tableEndRow);
11902
+ const r = this._resolveThisRow(dataStartRow, dataEndRow);
11856
11903
  startRow = r;
11857
11904
  endRow = r;
11858
11905
  break;
11859
11906
  }
11860
11907
  default:
11861
11908
  startRow = dataStartRow;
11862
- endRow = tableEndRow;
11909
+ endRow = dataEndRow;
11863
11910
  break;
11864
11911
  }
11865
11912
  this.setRangeData({
@@ -11886,7 +11933,8 @@ var TableReferenceObject = class extends BaseReferenceObject {
11886
11933
  getCellData(row, column) {
11887
11934
  if (this._isCurrentRowForRange) {
11888
11935
  const { startRow, endRow } = this._tableData.range;
11889
- if (row < startRow || row > endRow) return { v: "#N/A" };
11936
+ const lastCurrentRow = endRow - (this._tableData.showFooter === true ? 1 : 0);
11937
+ if (row < startRow || row > lastCurrentRow) return { v: "#N/A" };
11890
11938
  }
11891
11939
  return super.getCellData(row, column);
11892
11940
  }
@@ -12091,9 +12139,9 @@ var TableReferenceObject = class extends BaseReferenceObject {
12091
12139
  return -1;
12092
12140
  }
12093
12141
  /** Resolve #This Row's row number; takes first data row (tableStartRow+1) when no context available */
12094
- _resolveThisRow(tableStartRow, tableEndRow) {
12142
+ _resolveThisRow(dataStartRow, dataEndRow) {
12095
12143
  this._isCurrentRowForRange = true;
12096
- return Math.min(tableStartRow + 1, tableEndRow);
12144
+ return Math.min(dataStartRow, dataEndRow);
12097
12145
  }
12098
12146
  };
12099
12147
 
@@ -15576,13 +15624,13 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15576
15624
  this._activeDirtyManagerService = _activeDirtyManagerService;
15577
15625
  this._lifecycleService = _lifecycleService;
15578
15626
  _defineProperty(this, "_formulaCacheMap", /* @__PURE__ */ new Map());
15627
+ _defineProperty(this, "_mutationSyncHandler", void 0);
15579
15628
  _defineProperty(this, "_formulaChangeWithRange$", new rxjs.Subject());
15580
15629
  _defineProperty(this, "formulaChangeWithRange$", this._formulaChangeWithRange$.asObservable());
15581
15630
  _defineProperty(this, "_formulaResult$", new rxjs.Subject());
15582
15631
  _defineProperty(this, "formulaResult$", this._formulaResult$.asObservable());
15583
15632
  _defineProperty(this, "_otherFormulaResultApplied$", new rxjs.Subject());
15584
15633
  _defineProperty(this, "otherFormulaResultApplied$", this._otherFormulaResultApplied$.asObservable());
15585
- _defineProperty(this, "calculateStarted$", new rxjs.BehaviorSubject(false));
15586
15634
  this._initFormulaRegister();
15587
15635
  this._initFormulaCalculationResultChange();
15588
15636
  }
@@ -15591,7 +15639,6 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15591
15639
  this._formulaChangeWithRange$.complete();
15592
15640
  this._formulaResult$.complete();
15593
15641
  this._otherFormulaResultApplied$.complete();
15594
- this.calculateStarted$.complete();
15595
15642
  }
15596
15643
  _ensureCacheMap(unitId, subUnitId) {
15597
15644
  let unitMap = this._formulaCacheMap.get(unitId);
@@ -15617,6 +15664,7 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15617
15664
  }
15618
15665
  });
15619
15666
  const handleRegister = (option) => {
15667
+ var _this$_mutationSyncHa;
15620
15668
  const { unitId, subUnitId, formulaText, formulaId, ranges } = option;
15621
15669
  if (!this._ensureCacheMap(unitId, subUnitId).has(formulaId)) return;
15622
15670
  const params = {
@@ -15627,13 +15675,29 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15627
15675
  ranges
15628
15676
  } }
15629
15677
  };
15630
- this._commandService.executeCommand(SetOtherFormulaMutation.id, params, { onlyLocal: true }).then(() => {
15678
+ const waitForMutationSync = (_this$_mutationSyncHa = this._mutationSyncHandler) === null || _this$_mutationSyncHa === void 0 ? void 0 : _this$_mutationSyncHa.call(this, unitId);
15679
+ this._commandService.executeCommand(SetOtherFormulaMutation.id, params, { onlyLocal: true }).then(async () => {
15680
+ if (this._disposed) return;
15681
+ await (waitForMutationSync === null || waitForMutationSync === void 0 ? void 0 : waitForMutationSync());
15631
15682
  if (this._disposed) return;
15632
15683
  this._commandService.executeCommand(OtherFormulaMarkDirty.id, { [unitId]: { [subUnitId]: { [formulaId]: true } } }, { onlyLocal: true });
15633
15684
  });
15634
15685
  };
15635
- this.disposeWithMe(this._formulaChangeWithRange$.pipe((0, rxjs.bufferWhen)(() => this.calculateStarted$.pipe((0, rxjs.skip)(1), (0, rxjs.filter)((calculateStarted) => calculateStarted)))).subscribe((options) => options.forEach(handleRegister)));
15636
- this.disposeWithMe(this._formulaChangeWithRange$.pipe((0, rxjs.filter)(() => this.calculateStarted$.getValue())).subscribe(handleRegister));
15686
+ this.disposeWithMe(this._formulaChangeWithRange$.subscribe((option) => {
15687
+ if (this._commandService.hasCommand(SetOtherFormulaMutation.id) && this._commandService.hasCommand(OtherFormulaMarkDirty.id)) {
15688
+ handleRegister(option);
15689
+ return;
15690
+ }
15691
+ this._lifecycleService.onStage(_univerjs_core.LifecycleStages.Ready).then(() => {
15692
+ if (!this._disposed) handleRegister(option);
15693
+ });
15694
+ }));
15695
+ }
15696
+ setMutationSyncHandler(handler) {
15697
+ this._mutationSyncHandler = handler;
15698
+ return (0, _univerjs_core.toDisposable)(() => {
15699
+ if (this._mutationSyncHandler === handler) this._mutationSyncHandler = void 0;
15700
+ });
15637
15701
  }
15638
15702
  _initFormulaCalculationResultChange() {
15639
15703
  this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {
@@ -15705,11 +15769,13 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15705
15769
  return Object.fromEntries(Array.from(unitMap.entries(), ([subUnitId, formulas]) => [subUnitId, Object.fromEntries(Array.from(formulas.keys(), (formulaId) => [formulaId, true]))]));
15706
15770
  }
15707
15771
  deleteFormula(unitId, subUnitId, formulaIdList) {
15772
+ var _this$_mutationSyncHa2;
15708
15773
  const params = {
15709
15774
  unitId,
15710
15775
  subUnitId,
15711
15776
  formulaIdList
15712
15777
  };
15778
+ (_this$_mutationSyncHa2 = this._mutationSyncHandler) === null || _this$_mutationSyncHa2 === void 0 || _this$_mutationSyncHa2.call(this, unitId);
15713
15779
  this._commandService.executeCommand(RemoveOtherFormulaMutation.id, params, { onlyLocal: true });
15714
15780
  const cacheMap = this._ensureCacheMap(unitId, subUnitId);
15715
15781
  formulaIdList.forEach((id) => cacheMap.delete(id));
@@ -16598,8 +16664,8 @@ var BaseFunction = class {
16598
16664
  if (isFirst) return this._getOneFirstByRaw(resultArrayValue);
16599
16665
  return this._getOneLastByRaw(resultArrayValue);
16600
16666
  }
16601
- orderSearch(value, searchArray, resultArray, searchType = 1, isDesc = false) {
16602
- const position = searchArray.orderSearch(value, searchType, isDesc);
16667
+ orderSearch(value, searchArray, resultArray, searchType = 1, isDesc = false, keepFirstNearest = false) {
16668
+ const position = searchArray.orderSearch(value, searchType, isDesc, false, keepFirstNearest);
16603
16669
  if (position == null) return ErrorValueObject.create("#N/A");
16604
16670
  const resultValue = resultArray.get(position.row, position.column) || NullValueObject.create();
16605
16671
  if (resultValue.isNull()) return ErrorValueObject.create("#N/A");
@@ -16629,8 +16695,8 @@ var BaseFunction = class {
16629
16695
  if (axis === 0) return resultArray.slice([position.row, position.row + 1]);
16630
16696
  return resultArray.slice(void 0, [position.column, position.column + 1]);
16631
16697
  }
16632
- orderSearchExpand(value, searchArray, resultArray, searchType = 1, isDesc = false, axis = 0) {
16633
- const position = searchArray.orderSearch(value, searchType, isDesc);
16698
+ orderSearchExpand(value, searchArray, resultArray, searchType = 1, isDesc = false, axis = 0, keepFirstNearest = false) {
16699
+ const position = searchArray.orderSearch(value, searchType, isDesc, false, keepFirstNearest);
16634
16700
  if (position == null) return ErrorValueObject.create("#N/A");
16635
16701
  if (axis === 0) return resultArray.slice([position.row, position.row + 1]);
16636
16702
  return resultArray.slice(void 0, [position.column, position.column + 1]);
@@ -30430,20 +30496,72 @@ var Or = class extends BaseFunction {
30430
30496
  }
30431
30497
  };
30432
30498
 
30499
+ //#endregion
30500
+ //#region src/functions/math/sum/index.ts
30501
+ var Sum = class extends BaseFunction {
30502
+ constructor(..._args) {
30503
+ super(..._args);
30504
+ _defineProperty(this, "minParams", 1);
30505
+ _defineProperty(this, "maxParams", 255);
30506
+ }
30507
+ calculate(...variants) {
30508
+ let accumulatorAll = NumberValueObject.create(0);
30509
+ for (let i = 0; i < variants.length; i++) {
30510
+ let variant = variants[i];
30511
+ variant = this._legacyImplicitDerivedArray(variant);
30512
+ if (variant.isString()) variant = variant.convertToNumberObjectValue();
30513
+ if (variant.isError()) return variant;
30514
+ if (variant.isArray()) variant = variant.sum();
30515
+ if (variant.isError()) return variant;
30516
+ accumulatorAll = accumulatorAll.plus(variant);
30517
+ if (accumulatorAll.isError()) return accumulatorAll;
30518
+ }
30519
+ return accumulatorAll;
30520
+ }
30521
+ _legacyImplicitDerivedArray(variant) {
30522
+ if (!variant.isArray()) return variant;
30523
+ const array = variant;
30524
+ if (array.usesInvertedIndexCache() || !array.usesLegacyImplicitForAggregate()) return variant;
30525
+ const startRow = array.getCurrentRow();
30526
+ const startColumn = array.getCurrentColumn();
30527
+ if (startRow < 0 || startColumn < 0) return variant;
30528
+ const rowCount = array.getRowCount();
30529
+ const columnCount = array.getColumnCount();
30530
+ let rowIndex = -1;
30531
+ let columnIndex = -1;
30532
+ if (rowCount === 1) {
30533
+ rowIndex = 0;
30534
+ columnIndex = this.column - startColumn;
30535
+ } else if (columnCount === 1) {
30536
+ rowIndex = this.row - startRow;
30537
+ columnIndex = 0;
30538
+ } else {
30539
+ rowIndex = this.row - startRow;
30540
+ columnIndex = this.column - startColumn;
30541
+ }
30542
+ if (rowIndex < 0 || rowIndex >= rowCount || columnIndex < 0 || columnIndex >= columnCount) return variant;
30543
+ return array.get(rowIndex, columnIndex) || variant;
30544
+ }
30545
+ };
30546
+
30433
30547
  //#endregion
30434
30548
  //#region src/functions/logical/percentof/index.ts
30435
30549
  /**
30436
- * PERCENTOF is an Excel GROUPBY aggregator token. It is evaluated by GROUPBY's
30437
- * AST path, not as a standalone scalar function.
30550
+ * PERCENTOF is logically equivalent to SUM(dataSubset) / SUM(dataAll).
30551
+ * GROUPBY also consumes the function name as an aggregator token through its AST path.
30438
30552
  */
30439
- var Percentof = class extends BaseFunction {
30553
+ var Percentof = class extends Sum {
30440
30554
  constructor(..._args) {
30441
30555
  super(..._args);
30442
- _defineProperty(this, "minParams", 0);
30443
- _defineProperty(this, "maxParams", 0);
30556
+ _defineProperty(this, "minParams", 2);
30557
+ _defineProperty(this, "maxParams", 2);
30444
30558
  }
30445
- calculate(..._variants) {
30446
- return ErrorValueObject.create("#VALUE!");
30559
+ calculate(dataSubset, dataAll) {
30560
+ const subsetTotal = super.calculate(dataSubset);
30561
+ if (subsetTotal.isError()) return subsetTotal;
30562
+ const allTotal = super.calculate(dataAll);
30563
+ if (allTotal.isError()) return allTotal;
30564
+ return subsetTotal.divided(allTotal);
30447
30565
  }
30448
30566
  };
30449
30567
 
@@ -33011,8 +33129,8 @@ var Xlookup = class extends BaseFunction {
33011
33129
  return this.binarySearchExpand(value, searchArray, resultArray, axis, searchType, matchType);
33012
33130
  }
33013
33131
  if (matchModeValue === 2) return this.fuzzySearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
33014
- if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearchExpand(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1, axis);
33015
- return this.equalSearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
33132
+ if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearchExpand(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1, axis, true);
33133
+ return this._exactSearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
33016
33134
  }
33017
33135
  _handleSingleObject(value, searchArray, resultArray, matchModeValue, searchModeValue) {
33018
33136
  if ((searchModeValue === 2 || searchModeValue === -2) && matchModeValue !== 2) {
@@ -33021,8 +33139,38 @@ var Xlookup = class extends BaseFunction {
33021
33139
  return this.binarySearch(value, searchArray, resultArray, searchType, matchType);
33022
33140
  }
33023
33141
  if (matchModeValue === 2) return this.fuzzySearch(value, searchArray, resultArray, searchModeValue !== -1);
33024
- if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearch(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1);
33025
- return this.equalSearch(value, searchArray, resultArray, searchModeValue !== -1);
33142
+ if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearch(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1, true);
33143
+ return this._exactSearch(value, searchArray, resultArray, searchModeValue !== -1);
33144
+ }
33145
+ _exactSearch(value, searchArray, resultArray, isFirst) {
33146
+ const position = this._findExactPosition(value, searchArray, isFirst);
33147
+ if (position == null) return ErrorValueObject.create("#N/A");
33148
+ return resultArray.get(position.row, position.column) ?? ErrorValueObject.create("#N/A");
33149
+ }
33150
+ _exactSearchExpand(value, searchArray, resultArray, isFirst, axis) {
33151
+ const position = this._findExactPosition(value, searchArray, isFirst);
33152
+ if (position == null) return ErrorValueObject.create("#N/A");
33153
+ return axis === 0 ? resultArray.slice([position.row, position.row + 1]) ?? ErrorValueObject.create("#N/A") : resultArray.slice(void 0, [position.column, position.column + 1]) ?? ErrorValueObject.create("#N/A");
33154
+ }
33155
+ _findExactPosition(value, searchArray, isFirst) {
33156
+ let position;
33157
+ const find = (candidate, row, column) => {
33158
+ if (candidate != null && this._isExactMatch(candidate, value)) {
33159
+ position = {
33160
+ row,
33161
+ column
33162
+ };
33163
+ return false;
33164
+ }
33165
+ };
33166
+ if (isFirst) searchArray.iterator(find);
33167
+ else searchArray.iteratorReverse(find);
33168
+ return position;
33169
+ }
33170
+ _isExactMatch(candidate, value) {
33171
+ if (candidate.isError() || value.isError()) return candidate.isError() && value.isError() && candidate.getValue() === value.getValue();
33172
+ if (candidate.isNull() !== value.isNull() || candidate.isNumber() !== value.isNumber() || candidate.isString() !== value.isString() || candidate.isBoolean() !== value.isBoolean()) return false;
33173
+ return candidate.isEqual(value).getValue() === true;
33026
33174
  }
33027
33175
  _blankResultAsZero(value) {
33028
33176
  if (value.isNull()) return NumberValueObject.create(0);
@@ -35589,54 +35737,6 @@ var Subtotal = class extends BaseFunction {
35589
35737
  }
35590
35738
  };
35591
35739
 
35592
- //#endregion
35593
- //#region src/functions/math/sum/index.ts
35594
- var Sum = class extends BaseFunction {
35595
- constructor(..._args) {
35596
- super(..._args);
35597
- _defineProperty(this, "minParams", 1);
35598
- _defineProperty(this, "maxParams", 255);
35599
- }
35600
- calculate(...variants) {
35601
- let accumulatorAll = NumberValueObject.create(0);
35602
- for (let i = 0; i < variants.length; i++) {
35603
- let variant = variants[i];
35604
- variant = this._legacyImplicitDerivedArray(variant);
35605
- if (variant.isString()) variant = variant.convertToNumberObjectValue();
35606
- if (variant.isError()) return variant;
35607
- if (variant.isArray()) variant = variant.sum();
35608
- if (variant.isError()) return variant;
35609
- accumulatorAll = accumulatorAll.plus(variant);
35610
- if (accumulatorAll.isError()) return accumulatorAll;
35611
- }
35612
- return accumulatorAll;
35613
- }
35614
- _legacyImplicitDerivedArray(variant) {
35615
- if (!variant.isArray()) return variant;
35616
- const array = variant;
35617
- if (array.usesInvertedIndexCache() || !array.usesLegacyImplicitForAggregate()) return variant;
35618
- const startRow = array.getCurrentRow();
35619
- const startColumn = array.getCurrentColumn();
35620
- if (startRow < 0 || startColumn < 0) return variant;
35621
- const rowCount = array.getRowCount();
35622
- const columnCount = array.getColumnCount();
35623
- let rowIndex = -1;
35624
- let columnIndex = -1;
35625
- if (rowCount === 1) {
35626
- rowIndex = 0;
35627
- columnIndex = this.column - startColumn;
35628
- } else if (columnCount === 1) {
35629
- rowIndex = this.row - startRow;
35630
- columnIndex = 0;
35631
- } else {
35632
- rowIndex = this.row - startRow;
35633
- columnIndex = this.column - startColumn;
35634
- }
35635
- if (rowIndex < 0 || rowIndex >= rowCount || columnIndex < 0 || columnIndex >= columnCount) return variant;
35636
- return array.get(rowIndex, columnIndex) || variant;
35637
- }
35638
- };
35639
-
35640
35740
  //#endregion
35641
35741
  //#region src/functions/math/sumif/index.ts
35642
35742
  var Sumif = class extends BaseFunction {
@@ -43007,7 +43107,7 @@ function getObjectValue(result, isUseStrip = false) {
43007
43107
  //#endregion
43008
43108
  //#region package.json
43009
43109
  var name = "@univerjs/engine-formula";
43010
- var version = "1.0.0-beta.0";
43110
+ var version = "1.0.0-beta.1";
43011
43111
 
43012
43112
  //#endregion
43013
43113
  //#region src/services/global-computing-status.service.ts
@@ -43307,12 +43407,9 @@ function hasSameNestedKey(left, right) {
43307
43407
  * limitations under the License.
43308
43408
  */
43309
43409
  let FormulaCalculationTriggerController = class FormulaCalculationTriggerController extends _univerjs_core.Disposable {
43310
- constructor(formulaCalculationTriggerService, registerOtherFormulaService, lifecycleService) {
43410
+ constructor(formulaCalculationTriggerService, lifecycleService) {
43311
43411
  super();
43312
- const start = () => {
43313
- formulaCalculationTriggerService.start();
43314
- registerOtherFormulaService.calculateStarted$.next(true);
43315
- };
43412
+ const start = () => formulaCalculationTriggerService.start();
43316
43413
  if ((0, _univerjs_core.isNodeEnv)()) {
43317
43414
  start();
43318
43415
  return;
@@ -43320,11 +43417,7 @@ let FormulaCalculationTriggerController = class FormulaCalculationTriggerControl
43320
43417
  this.disposeWithMe(lifecycleService.lifecycle$.pipe((0, rxjs.filter)((stage) => stage >= _univerjs_core.LifecycleStages.Rendered), (0, rxjs.take)(1)).subscribe(start));
43321
43418
  }
43322
43419
  };
43323
- FormulaCalculationTriggerController = __decorate([
43324
- __decorateParam(0, (0, _univerjs_core.Inject)(FormulaCalculationTriggerService)),
43325
- __decorateParam(1, (0, _univerjs_core.Inject)(RegisterOtherFormulaService)),
43326
- __decorateParam(2, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))
43327
- ], FormulaCalculationTriggerController);
43420
+ FormulaCalculationTriggerController = __decorate([__decorateParam(0, (0, _univerjs_core.Inject)(FormulaCalculationTriggerService)), __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))], FormulaCalculationTriggerController);
43328
43421
 
43329
43422
  //#endregion
43330
43423
  //#region src/controllers/formula.controller.ts
@@ -43347,10 +43440,12 @@ let FormulaController = class FormulaController extends _univerjs_core.Disposabl
43347
43440
  _syncOtherFormulaUnits() {
43348
43441
  const dataSyncPrimaryController = this._dataSyncPrimaryController;
43349
43442
  if (!dataSyncPrimaryController) return;
43350
- this.disposeWithMe(this._registerOtherFormulaService.formulaChangeWithRange$.subscribe(({ unitId }) => {
43351
- if (this._syncedOtherFormulaUnits.has(unitId)) return;
43352
- this._syncedOtherFormulaUnits.add(unitId);
43353
- this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));
43443
+ this.disposeWithMe(this._registerOtherFormulaService.setMutationSyncHandler((unitId) => {
43444
+ if (!this._syncedOtherFormulaUnits.has(unitId)) {
43445
+ this._syncedOtherFormulaUnits.add(unitId);
43446
+ this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));
43447
+ }
43448
+ return () => dataSyncPrimaryController.waitForPendingMutations();
43354
43449
  }));
43355
43450
  }
43356
43451
  _registerCommands() {