@univerjs/engine-formula 1.0.0-alpha.3 → 1.0.0-alpha.5

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
@@ -1483,10 +1483,11 @@ const TABLE_NAME_REGEX = "((?![~!@#$%^&*()_+<>?:,./;’,。、‘:“《》
1483
1483
  const TABLE_TITLE_REGEX = "\\[#.+\\]\\s*?,\\s*?";
1484
1484
  const TABLE_CONTENT_REGEX = "\\[((?<!#)[\\s\\S])*\\]";
1485
1485
  const TABLE_MULTIPLE_COLUMN_REGEX = `${TABLE_CONTENT_REGEX}${RANGE_SYMBOL}${TABLE_CONTENT_REGEX}`;
1486
- const REFERENCE_TABLE_ALL_COLUMN_REGEX = `^(${UNIT_NAME_REGEX})?${TABLE_NAME_REGEX}$`;
1487
- const REFERENCE_TABLE_SINGLE_COLUMN_REGEX = `^(${UNIT_NAME_REGEX})?${TABLE_NAME_REGEX}(${TABLE_CONTENT_REGEX}|\\[${TABLE_TITLE_REGEX}${TABLE_CONTENT_REGEX}\\])+$`;
1488
- const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX = `^(${UNIT_NAME_REGEX})?${TABLE_NAME_REGEX}(\\[${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$|^${TABLE_NAME_REGEX}(\\[${TABLE_TITLE_REGEX}${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$`;
1489
- const REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX = `^(${UNIT_NAME_REGEX})?${TABLE_NAME_REGEX}\\[\\s*#([^\\]]+)\\s*\\]$`;
1486
+ const TABLE_UNIT_QUALIFIER_REGEX = `(?:(?:${UNIT_NAME_REGEX}|'(?:[^']|'')+'|[^\\s!\\[\\]]+)!)?(?:${UNIT_NAME_REGEX})?`;
1487
+ const REFERENCE_TABLE_ALL_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}$`;
1488
+ const REFERENCE_TABLE_SINGLE_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(${TABLE_CONTENT_REGEX}|\\[${TABLE_TITLE_REGEX}${TABLE_CONTENT_REGEX}\\])+$`;
1489
+ 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}\\])?$`;
1490
+ const REFERENCE_TABLE_TITLE_ONLY_ANY_HASH_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}\\[\\s*#([^\\]]+)\\s*\\]$`;
1490
1491
  const REFERENCE_TABLE_ALL_COLUMN_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_ALL_COLUMN_REGEX);
1491
1492
  const REFERENCE_TABLE_SINGLE_COLUMN_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_SINGLE_COLUMN_REGEX);
1492
1493
  const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX_PRECOMPILING = new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX);
@@ -1737,10 +1738,10 @@ function singleReferenceToGrid(refBody) {
1737
1738
  }
1738
1739
  function handleRefStringInfo(refString) {
1739
1740
  const unitIdMatch = UNIT_NAME_REGEX_PRECOMPILING.exec(refString);
1740
- let unitId = "";
1741
+ let unitQualifier = "";
1741
1742
  if (unitIdMatch != null) {
1742
- unitId = unitIdMatch[0].trim();
1743
- unitId = unquoteSheetName(unitId.slice(1, unitId.length - 1));
1743
+ unitQualifier = unitIdMatch[0].trim();
1744
+ unitQualifier = unquoteSheetName(unitQualifier.slice(1, unitQualifier.length - 1));
1744
1745
  refString = refString.replace(UNIT_NAME_REGEX_PRECOMPILING, "");
1745
1746
  }
1746
1747
  const sheetNameIndex = refString.indexOf("!");
@@ -1755,11 +1756,13 @@ function handleRefStringInfo(refString) {
1755
1756
  return {
1756
1757
  refBody,
1757
1758
  sheetName,
1758
- unitId
1759
+ unitQualifier,
1760
+ /** @deprecated Use unitQualifier. Kept for reference-grid compatibility. */
1761
+ unitId: unitQualifier
1759
1762
  };
1760
1763
  }
1761
1764
  function deserializeRangeWithSheet(refString) {
1762
- const { refBody, sheetName, unitId } = handleRefStringInfo(refString);
1765
+ const { refBody, sheetName, unitQualifier } = handleRefStringInfo(refString);
1763
1766
  const colonIndex = refBody.indexOf(":");
1764
1767
  if (colonIndex === -1) {
1765
1768
  const grid = singleReferenceToGrid(refBody);
@@ -1767,7 +1770,7 @@ function deserializeRangeWithSheet(refString) {
1767
1770
  const column = grid.column;
1768
1771
  const absoluteRefType = grid.absoluteRefType;
1769
1772
  return {
1770
- unitId,
1773
+ unitId: unitQualifier,
1771
1774
  sheetName,
1772
1775
  range: {
1773
1776
  startRow: row,
@@ -1791,7 +1794,7 @@ function deserializeRangeWithSheet(refString) {
1791
1794
  if (Number.isNaN(startRow) && Number.isNaN(endRow)) rangeType = _univerjs_core.RANGE_TYPE.COLUMN;
1792
1795
  else if (Number.isNaN(startColumn) && Number.isNaN(endColumn)) rangeType = _univerjs_core.RANGE_TYPE.ROW;
1793
1796
  return {
1794
- unitId,
1797
+ unitId: unitQualifier,
1795
1798
  sheetName,
1796
1799
  range: {
1797
1800
  startRow,
@@ -1925,14 +1928,49 @@ function startsWithNonAlphabetic(name) {
1925
1928
  return !/^\p{Letter}/u.test(name.charAt(0));
1926
1929
  }
1927
1930
  function splitTableStructuredRef(ref) {
1928
- const idx = ref.indexOf("[");
1931
+ let unitQualifier = "";
1932
+ let tableRef = ref.trim();
1933
+ let quoteOpen = false;
1934
+ let bracketDepth = 0;
1935
+ let qualifierEnd = -1;
1936
+ for (let i = 0; i < tableRef.length; i++) {
1937
+ const char = tableRef[i];
1938
+ if (char === "'") {
1939
+ if (quoteOpen && tableRef[i + 1] === "'") {
1940
+ i++;
1941
+ continue;
1942
+ }
1943
+ quoteOpen = !quoteOpen;
1944
+ } else if (!quoteOpen && char === "[") bracketDepth++;
1945
+ else if (!quoteOpen && char === "]") bracketDepth--;
1946
+ else if (!quoteOpen && bracketDepth === 0 && char === "!") {
1947
+ qualifierEnd = i;
1948
+ break;
1949
+ }
1950
+ }
1951
+ if (qualifierEnd >= 0) {
1952
+ unitQualifier = tableRef.slice(0, qualifierEnd).trim();
1953
+ tableRef = tableRef.slice(qualifierEnd + 1);
1954
+ if (unitQualifier.startsWith("'") && unitQualifier.endsWith("'")) unitQualifier = unitQualifier.slice(1, -1);
1955
+ if (unitQualifier.startsWith("[") && unitQualifier.endsWith("]")) unitQualifier = unitQualifier.slice(1, -1);
1956
+ unitQualifier = unquoteSheetName(unitQualifier);
1957
+ } else if (tableRef.startsWith("[")) {
1958
+ const legacyQualifierEnd = tableRef.indexOf("]");
1959
+ if (legacyQualifierEnd > 0) {
1960
+ unitQualifier = unquoteSheetName(tableRef.slice(1, legacyQualifierEnd));
1961
+ tableRef = tableRef.slice(legacyQualifierEnd + 1);
1962
+ }
1963
+ }
1964
+ const idx = tableRef.indexOf("[");
1929
1965
  if (idx === -1) return {
1930
- tableName: ref,
1931
- struct: ""
1966
+ unitQualifier,
1967
+ tableName: tableRef,
1968
+ columnStruct: ""
1932
1969
  };
1933
1970
  return {
1934
- tableName: ref.slice(0, idx),
1935
- columnStruct: ref.slice(idx)
1971
+ unitQualifier,
1972
+ tableName: tableRef.slice(0, idx),
1973
+ columnStruct: tableRef.slice(idx)
1936
1974
  };
1937
1975
  }
1938
1976
 
@@ -5160,8 +5198,13 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5160
5198
  const allUnitData = {};
5161
5199
  const unitStylesData = {};
5162
5200
  const unitSheetNameMap = {};
5201
+ const unitNameMap = {};
5163
5202
  for (const workbook of unitAllSheet) {
5164
5203
  const unitId = workbook.getUnitId();
5204
+ unitNameMap[unitId] = {
5205
+ name: workbook.name,
5206
+ unitType: _univerjs_core.UniverInstanceType.UNIVER_SHEET
5207
+ };
5165
5208
  const sheets = workbook.getSheets();
5166
5209
  const sheetData = {};
5167
5210
  const sheetNameMap = {};
@@ -5187,6 +5230,10 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5187
5230
  for (const base of unitAllBases) {
5188
5231
  const snapshot = base.getSnapshot();
5189
5232
  const unitId = base.getUnitId();
5233
+ unitNameMap[unitId] = {
5234
+ name: snapshot.name,
5235
+ unitType: _univerjs_core.UniverInstanceType.UNIVER_BASE
5236
+ };
5190
5237
  const baseData = {};
5191
5238
  const tableNameMap = {};
5192
5239
  for (const table of Object.values(snapshot.tables)) {
@@ -5207,7 +5254,8 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5207
5254
  return {
5208
5255
  allUnitData,
5209
5256
  unitStylesData,
5210
- unitSheetNameMap
5257
+ unitSheetNameMap,
5258
+ unitNameMap
5211
5259
  };
5212
5260
  }
5213
5261
  /**
@@ -5235,18 +5283,51 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5235
5283
  return rowData;
5236
5284
  }
5237
5285
  updateFormulaData(unitId, sheetId, cellValue) {
5286
+ var _this$_univerInstance, _formulaData$unitId$s, _formulaData$unitId;
5238
5287
  const cellMatrix = new _univerjs_core.ObjectMatrix(cellValue);
5239
- const formulaIdMap = this._getSheetFormulaIdMap(unitId, sheetId);
5240
- const deleteFormulaIdMap = /* @__PURE__ */ new Map();
5241
- const formulaData = this.getFormulaData();
5242
- if (formulaData[unitId] == null) formulaData[unitId] = {};
5243
- const workbookFormulaData = formulaData[unitId];
5244
- if (workbookFormulaData[sheetId] == null) workbookFormulaData[sheetId] = {};
5245
- const sheetFormulaDataMatrix = new _univerjs_core.ObjectMatrix(workbookFormulaData[sheetId] || {});
5246
5288
  const newSheetFormulaDataMatrix = new _univerjs_core.ObjectMatrix();
5289
+ const worksheetCellMatrix = (_this$_univerInstance = this._univerInstanceService.getUnit(unitId)) === null || _this$_univerInstance === void 0 || (_this$_univerInstance = _this$_univerInstance.getSheetBySheetId(sheetId)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getCellMatrix();
5290
+ const affectedFormulaIds = /* @__PURE__ */ new Set();
5247
5291
  cellMatrix.forValue((r, c, cell) => {
5292
+ const currentCell = worksheetCellMatrix === null || worksheetCellMatrix === void 0 ? void 0 : worksheetCellMatrix.getValue(r, c);
5293
+ const currentFormulaId = currentCell === null || currentCell === void 0 ? void 0 : currentCell.si;
5294
+ const formulaId = cell === null || cell === void 0 ? void 0 : cell.si;
5295
+ const hasCurrentFormulaId = (0, _univerjs_core.isFormulaId)(currentFormulaId);
5296
+ const hasFormulaId = (0, _univerjs_core.isFormulaId)(formulaId);
5297
+ const formulaString = cell === null || cell === void 0 ? void 0 : cell.f;
5298
+ if (hasCurrentFormulaId) affectedFormulaIds.add(String(currentFormulaId));
5299
+ if (hasFormulaId) affectedFormulaIds.add(String(formulaId));
5300
+ if (!hasCurrentFormulaId && !hasFormulaId) {
5301
+ if (typeof formulaString === "string" && (0, _univerjs_core.isFormulaString)(formulaString)) newSheetFormulaDataMatrix.setValue(r, c, { f: formulaString });
5302
+ else if ((0, _univerjs_core.isFormulaString)(currentCell === null || currentCell === void 0 ? void 0 : currentCell.f)) newSheetFormulaDataMatrix.setValue(r, c, null);
5303
+ }
5304
+ });
5305
+ if (affectedFormulaIds.size === 0) return newSheetFormulaDataMatrix.getMatrix();
5306
+ const formulaIdMap = {};
5307
+ const sharedFormulaCellMatrix = new _univerjs_core.ObjectMatrix();
5308
+ worksheetCellMatrix === null || worksheetCellMatrix === void 0 || worksheetCellMatrix.forValue((r, c, cell) => {
5309
+ const formulaId = cell === null || cell === void 0 ? void 0 : cell.si;
5310
+ if (!(0, _univerjs_core.isFormulaId)(formulaId) || !affectedFormulaIds.has(String(formulaId))) return;
5311
+ sharedFormulaCellMatrix.setValue(r, c, cell);
5312
+ if (typeof (cell === null || cell === void 0 ? void 0 : cell.f) === "string" && (0, _univerjs_core.isFormulaString)(cell.f)) formulaIdMap[String(formulaId)] = {
5313
+ f: cell.f,
5314
+ r,
5315
+ c
5316
+ };
5317
+ });
5318
+ const formulaData = {};
5319
+ initSheetFormulaData(formulaData, unitId, sheetId, sharedFormulaCellMatrix);
5320
+ const deleteFormulaIdMap = /* @__PURE__ */ new Map();
5321
+ const sheetFormulaDataMatrix = new _univerjs_core.ObjectMatrix((_formulaData$unitId$s = (_formulaData$unitId = formulaData[unitId]) === null || _formulaData$unitId === void 0 ? void 0 : _formulaData$unitId[sheetId]) !== null && _formulaData$unitId$s !== void 0 ? _formulaData$unitId$s : {});
5322
+ cellMatrix.forValue((r, c, cell) => {
5323
+ var _worksheetCellMatrix$;
5324
+ if (!(0, _univerjs_core.isFormulaId)(worksheetCellMatrix === null || worksheetCellMatrix === void 0 || (_worksheetCellMatrix$ = worksheetCellMatrix.getValue(r, c)) === null || _worksheetCellMatrix$ === void 0 ? void 0 : _worksheetCellMatrix$.si) && !(0, _univerjs_core.isFormulaId)(cell === null || cell === void 0 ? void 0 : cell.si)) return;
5248
5325
  updateFormulaDataByCellValue(sheetFormulaDataMatrix, newSheetFormulaDataMatrix, formulaIdMap, deleteFormulaIdMap, r, c, cell);
5249
5326
  });
5327
+ this._rebindSharedFormulaData(sheetFormulaDataMatrix, newSheetFormulaDataMatrix, formulaIdMap, deleteFormulaIdMap);
5328
+ return newSheetFormulaDataMatrix.getMatrix();
5329
+ }
5330
+ _rebindSharedFormulaData(sheetFormulaDataMatrix, newSheetFormulaDataMatrix, formulaIdMap, deleteFormulaIdMap) {
5250
5331
  sheetFormulaDataMatrix.forValue((r, c, cell) => {
5251
5332
  const formulaString = (cell === null || cell === void 0 ? void 0 : cell.f) || "";
5252
5333
  const formulaId = (cell === null || cell === void 0 ? void 0 : cell.si) || "";
@@ -5304,7 +5385,6 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5304
5385
  }
5305
5386
  }
5306
5387
  });
5307
- return newSheetFormulaDataMatrix.getMatrix();
5308
5388
  }
5309
5389
  updateArrayFormulaRange(unitId, sheetId, cellValue) {
5310
5390
  var _this$_arrayFormulaRa5;
@@ -5426,23 +5506,6 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5426
5506
  }
5427
5507
  return dirtyRanges;
5428
5508
  }
5429
- _getSheetFormulaIdMap(unitId, sheetId) {
5430
- const formulaIdMap = {};
5431
- const workbook = this._univerInstanceService.getUnit(unitId);
5432
- if (workbook == null) return formulaIdMap;
5433
- const worksheet = workbook.getSheetBySheetId(sheetId);
5434
- if (worksheet == null) return formulaIdMap;
5435
- worksheet.getCellMatrix().forValue((r, c, cell) => {
5436
- if (cell == null) return true;
5437
- const { f, si } = cell;
5438
- if ((0, _univerjs_core.isFormulaString)(f) && (0, _univerjs_core.isFormulaId)(si)) formulaIdMap[si] = {
5439
- f,
5440
- r,
5441
- c
5442
- };
5443
- });
5444
- return formulaIdMap;
5445
- }
5446
5509
  _initSheetArrayFormulaData(unitId, sheetId, cellMatrix) {
5447
5510
  let arrayFormulaRangeMatrix;
5448
5511
  let arrayFormulaCellDataMatrix;
@@ -5528,12 +5591,13 @@ function initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix) {
5528
5591
  const BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g;
5529
5592
  const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_]\w*)\[([^\]]+)\]/gi;
5530
5593
  const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_\]\[])\[([^\]]+)\]/g;
5594
+ const BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi;
5531
5595
  function normalizeBaseFormulaForEngine(formula, currentTable, snapshot) {
5532
5596
  const refs = [];
5533
5597
  const hold = (ref) => {
5534
5598
  return `__BASE_FORMULA_REF_${refs.push(ref) - 1}__`;
5535
5599
  };
5536
- return formula.replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5600
+ return formula.replace(BASE_EXTERNAL_A1_REF_PATTERN, (reference) => hold(reference)).replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5537
5601
  const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
5538
5602
  return targetTable ? hold(createEngineThisRowRef(targetTable, fieldName, snapshot)) : `${sourceTableName}[${fieldName}]`;
5539
5603
  }).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index) => {
@@ -5699,6 +5763,7 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5699
5763
  _defineProperty(this, "_arrayFormulaRange", {});
5700
5764
  _defineProperty(this, "_formulaData", {});
5701
5765
  _defineProperty(this, "_sheetNameMap", {});
5766
+ _defineProperty(this, "_unitNameMap", {});
5702
5767
  _defineProperty(this, "_forceCalculate", false);
5703
5768
  _defineProperty(this, "_clearDependencyTreeCache", {});
5704
5769
  _defineProperty(this, "_dirtyRanges", []);
@@ -5720,6 +5785,7 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5720
5785
  this._arrayFormulaRange = {};
5721
5786
  this._formulaData = {};
5722
5787
  this._sheetNameMap = {};
5788
+ this._unitNameMap = {};
5723
5789
  this._clearDependencyTreeCache = {};
5724
5790
  this._dirtyRanges = [];
5725
5791
  this._dirtyNameMap = {};
@@ -5763,6 +5829,9 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5763
5829
  getSheetNameMap() {
5764
5830
  return this._sheetNameMap;
5765
5831
  }
5832
+ getUnitNameMap() {
5833
+ return this._unitNameMap;
5834
+ }
5766
5835
  isForceCalculate() {
5767
5836
  return this._forceCalculate;
5768
5837
  }
@@ -5828,11 +5897,13 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5828
5897
  this._unitData = config.allUnitData;
5829
5898
  this._unitStylesData = config.unitStylesData;
5830
5899
  this._sheetNameMap = config.unitSheetNameMap;
5900
+ this._unitNameMap = config.unitNameMap || {};
5831
5901
  } else {
5832
- const { allUnitData, unitSheetNameMap, unitStylesData } = this._loadSheetData();
5902
+ const { allUnitData, unitNameMap, unitSheetNameMap, unitStylesData } = this._loadSheetData();
5833
5903
  this._unitData = allUnitData;
5834
5904
  this._unitStylesData = unitStylesData;
5835
5905
  this._sheetNameMap = unitSheetNameMap;
5906
+ this._unitNameMap = unitNameMap;
5836
5907
  }
5837
5908
  if (config.rowData) this._applyUnitRowData(config.rowData);
5838
5909
  this._formulaData = config.formulaData;
@@ -5850,10 +5921,11 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5850
5921
  this._mergeNameMap(this._sheetNameMap, this._dirtyNameMap);
5851
5922
  }
5852
5923
  loadDataLite(rowData) {
5853
- const { allUnitData, unitSheetNameMap, unitStylesData } = this._loadSheetData();
5924
+ const { allUnitData, unitNameMap, unitSheetNameMap, unitStylesData } = this._loadSheetData();
5854
5925
  this._unitData = allUnitData;
5855
5926
  this._unitStylesData = unitStylesData;
5856
5927
  this._sheetNameMap = unitSheetNameMap;
5928
+ this._unitNameMap = unitNameMap;
5857
5929
  this._formulaData = this._formulaDataModel.getFormulaData();
5858
5930
  this._arrayFormulaCellData = convertUnitDataToRuntime(this._formulaDataModel.getArrayFormulaCellData());
5859
5931
  this._arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
@@ -5888,6 +5960,9 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5888
5960
  registerSheetNameMap(sheetNameMap) {
5889
5961
  this._sheetNameMap = sheetNameMap;
5890
5962
  }
5963
+ registerUnitNameMap(unitNameMap) {
5964
+ this._unitNameMap = unitNameMap;
5965
+ }
5891
5966
  _mergeNameMap(unitSheetNameMap, dirtyNameMap) {
5892
5967
  Object.keys(dirtyNameMap).forEach((unitId) => {
5893
5968
  if (dirtyNameMap[unitId]) Object.keys(dirtyNameMap[unitId]).forEach((sheetId) => {
@@ -8506,6 +8581,7 @@ var BaseReferenceObject = class extends ObjectClassType {
8506
8581
  _defineProperty(this, "_filteredOutRows", []);
8507
8582
  _defineProperty(this, "_defaultUnitId", "");
8508
8583
  _defineProperty(this, "_forcedUnitId", "");
8584
+ _defineProperty(this, "_unitQualifier", "");
8509
8585
  _defineProperty(this, "_runtimeData", {});
8510
8586
  _defineProperty(this, "_arrayFormulaCellData", {});
8511
8587
  _defineProperty(this, "_arrayFormulaRange", {});
@@ -8612,6 +8688,12 @@ var BaseReferenceObject = class extends ObjectClassType {
8612
8688
  setForcedUnitIdDirect(unitId) {
8613
8689
  if (unitId.length > 0) this._forcedUnitId = unitId;
8614
8690
  }
8691
+ setUnitQualifier(unitQualifier) {
8692
+ this._unitQualifier = unitQualifier;
8693
+ }
8694
+ getUnitQualifier() {
8695
+ return this._unitQualifier;
8696
+ }
8615
8697
  getForcedUnitId() {
8616
8698
  return this._forcedUnitId;
8617
8699
  }
@@ -8999,6 +9081,7 @@ var CellReferenceObject = class extends BaseReferenceObject {
8999
9081
  constructor(token) {
9000
9082
  super(token);
9001
9083
  const grid = deserializeRangeWithSheetWithCache(token);
9084
+ this.setUnitQualifier(grid.unitId);
9002
9085
  this.setForcedUnitIdDirect(grid.unitId);
9003
9086
  this.setForcedSheetName(grid.sheetName);
9004
9087
  this.setRangeData(grid.range);
@@ -9074,6 +9157,7 @@ var ColumnReferenceObject = class extends BaseReferenceObject {
9074
9157
  constructor(token) {
9075
9158
  super(token);
9076
9159
  const grid = deserializeRangeWithSheetWithCache(token);
9160
+ this.setUnitQualifier(grid.unitId);
9077
9161
  this.setForcedUnitIdDirect(grid.unitId);
9078
9162
  this.setForcedSheetName(grid.sheetName);
9079
9163
  const range = {
@@ -9116,6 +9200,7 @@ var RowReferenceObject = class extends BaseReferenceObject {
9116
9200
  constructor(token) {
9117
9201
  super(token);
9118
9202
  const grid = deserializeRangeWithSheetWithCache(token);
9203
+ this.setUnitQualifier(grid.unitId);
9119
9204
  this.setForcedUnitIdDirect(grid.unitId);
9120
9205
  this.setForcedSheetName(grid.sheetName);
9121
9206
  const range = {
@@ -10491,6 +10576,49 @@ var FunctionService = class extends _univerjs_core.Disposable {
10491
10576
  }
10492
10577
  };
10493
10578
 
10579
+ //#endregion
10580
+ //#region src/services/unit-reference-resolver.service.ts
10581
+ const IFormulaUnitReferenceResolver = (0, _univerjs_core.createIdentifier)("univer.formula.unit-reference-resolver");
10582
+ const EXCEL_WORKBOOK_EXTENSION = /\.(?:xlsx|xlsm|xlsb|xltx|xltm|xls)$/i;
10583
+ function normalizeFormulaUnitName(name) {
10584
+ return name.replace(EXCEL_WORKBOOK_EXTENSION, "").toLowerCase();
10585
+ }
10586
+ let FormulaUnitReferenceResolver = class FormulaUnitReferenceResolver {
10587
+ constructor(_currentConfigService) {
10588
+ this._currentConfigService = _currentConfigService;
10589
+ }
10590
+ resolve({ hostUnitId, qualifier, referenceKind }) {
10591
+ const unitNameMap = this._currentConfigService.getUnitNameMap();
10592
+ const unitData = this._currentConfigService.getUnitData();
10593
+ const address = qualifier || hostUnitId;
10594
+ const direct = unitNameMap[address];
10595
+ if (direct || unitData[address]) return this._validateReferenceKind(hostUnitId, referenceKind, {
10596
+ unitId: address,
10597
+ unitType: direct === null || direct === void 0 ? void 0 : direct.unitType
10598
+ }, unitNameMap);
10599
+ if (!qualifier) return "#REF!";
10600
+ const namedUnits = Object.entries(unitNameMap).filter(([, item]) => item.name.length > 0);
10601
+ const normalizedQualifier = qualifier.toLowerCase();
10602
+ const exactMatches = namedUnits.filter(([, item]) => item.name.toLowerCase() === normalizedQualifier);
10603
+ const matches = exactMatches.length > 0 ? exactMatches : namedUnits.filter(([, item]) => normalizeFormulaUnitName(item.name) === normalizeFormulaUnitName(qualifier));
10604
+ if (matches.length !== 1) return "#REF!";
10605
+ const [unitId, item] = matches[0];
10606
+ return this._validateReferenceKind(hostUnitId, referenceKind, {
10607
+ unitId,
10608
+ unitType: item.unitType
10609
+ }, unitNameMap);
10610
+ }
10611
+ _validateReferenceKind(hostUnitId, referenceKind, resolution, unitNameMap) {
10612
+ var _unitNameMap$hostUnit;
10613
+ if (referenceKind !== "a1" || resolution.unitId === hostUnitId) return resolution;
10614
+ const hostType = (_unitNameMap$hostUnit = unitNameMap[hostUnitId]) === null || _unitNameMap$hostUnit === void 0 ? void 0 : _unitNameMap$hostUnit.unitType;
10615
+ if (resolution.unitType === _univerjs_core.UniverInstanceType.UNIVER_BASE) return "#REF!";
10616
+ if (hostType === _univerjs_core.UniverInstanceType.UNIVER_BASE && resolution.unitType !== _univerjs_core.UniverInstanceType.UNIVER_SHEET) return "#REF!";
10617
+ return resolution;
10618
+ }
10619
+ };
10620
+ FormulaUnitReferenceResolver = __decorate([__decorateParam(0, IFormulaCurrentConfigService)], FormulaUnitReferenceResolver);
10621
+
10494
10622
  //#endregion
10495
10623
  //#region src/engine/ast-node/prefix-node.ts
10496
10624
  var PrefixNode = class extends BaseAstNode {
@@ -10607,18 +10735,20 @@ function prefixHandler(tokenTrimParam, functionService, runtimeService) {
10607
10735
  //#endregion
10608
10736
  //#region src/engine/ast-node/function-node.ts
10609
10737
  var FunctionNode = class extends BaseAstNode {
10610
- constructor(token, _functionExecutor, _currentConfigService, _runtimeService, _definedNamesService, _formulaDataModel) {
10738
+ constructor(token, _functionExecutor, _currentConfigService, _runtimeService, _definedNamesService, _formulaDataModel, _unitReferenceResolver) {
10611
10739
  super(token);
10612
10740
  this._functionExecutor = _functionExecutor;
10613
10741
  this._currentConfigService = _currentConfigService;
10614
10742
  this._runtimeService = _runtimeService;
10615
10743
  this._definedNamesService = _definedNamesService;
10616
10744
  this._formulaDataModel = _formulaDataModel;
10745
+ this._unitReferenceResolver = _unitReferenceResolver;
10617
10746
  if (this._functionExecutor.isAsync()) this.setAsync();
10618
10747
  if (this._functionExecutor.isAddress()) this.setAddress();
10619
10748
  if (this._functionExecutor.needsLocale) this._setLocale();
10620
10749
  if (this._functionExecutor.needsSheetsInfo) this._setSheetsInfo();
10621
10750
  if (this._functionExecutor.needsFormulaDataModel) this._functionExecutor.setFormulaDataModel(this._formulaDataModel);
10751
+ if (this._functionExecutor.needsUnitReferenceResolver) this._functionExecutor.setUnitReferenceResolver(this._unitReferenceResolver);
10622
10752
  }
10623
10753
  get nodeType() {
10624
10754
  return 4;
@@ -10846,7 +10976,7 @@ var ErrorFunctionNode = class extends BaseAstNode {
10846
10976
  }
10847
10977
  };
10848
10978
  let FunctionNodeFactory = class FunctionNodeFactory extends BaseAstNodeFactory {
10849
- constructor(_functionService, _currentConfigService, _runtimeService, _definedNamesService, _injector, _formulaDataModel) {
10979
+ constructor(_functionService, _currentConfigService, _runtimeService, _definedNamesService, _injector, _formulaDataModel, _unitReferenceResolver) {
10850
10980
  super();
10851
10981
  this._functionService = _functionService;
10852
10982
  this._currentConfigService = _currentConfigService;
@@ -10854,6 +10984,7 @@ let FunctionNodeFactory = class FunctionNodeFactory extends BaseAstNodeFactory {
10854
10984
  this._definedNamesService = _definedNamesService;
10855
10985
  this._injector = _injector;
10856
10986
  this._formulaDataModel = _formulaDataModel;
10987
+ this._unitReferenceResolver = _unitReferenceResolver;
10857
10988
  }
10858
10989
  get zIndex() {
10859
10990
  return NODE_ORDER_MAP.get(4) || 100;
@@ -10864,7 +10995,7 @@ let FunctionNodeFactory = class FunctionNodeFactory extends BaseAstNodeFactory {
10864
10995
  console.error(`No function ${token}`);
10865
10996
  return ErrorNode.create("#NAME?");
10866
10997
  }
10867
- return new FunctionNode(token, functionExecutor, this._currentConfigService, this._runtimeService, this._definedNamesService, this._formulaDataModel);
10998
+ return new FunctionNode(token, functionExecutor, this._currentConfigService, this._runtimeService, this._definedNamesService, this._formulaDataModel, this._unitReferenceResolver);
10868
10999
  }
10869
11000
  checkAndCreateNodeType(param) {
10870
11001
  if (typeof param === "string") return;
@@ -10891,7 +11022,8 @@ FunctionNodeFactory = __decorate([
10891
11022
  __decorateParam(2, IFormulaRuntimeService),
10892
11023
  __decorateParam(3, IDefinedNamesService),
10893
11024
  __decorateParam(4, (0, _univerjs_core.Inject)(_univerjs_core.Injector)),
10894
- __decorateParam(5, (0, _univerjs_core.Inject)(FormulaDataModel))
11025
+ __decorateParam(5, (0, _univerjs_core.Inject)(FormulaDataModel)),
11026
+ __decorateParam(6, IFormulaUnitReferenceResolver)
10895
11027
  ], FunctionNodeFactory);
10896
11028
  function normalizeFunctionToken(token) {
10897
11029
  if (token === "REGEXTEST" || token === "_XLFN.REGEXTEST") return "REGEXMATCH";
@@ -11595,6 +11727,7 @@ var TableReferenceObject = class extends BaseReferenceObject {
11595
11727
  const { startColumn, endColumn, type } = this._parseStructuredRef(this._columnDataString, titleMap);
11596
11728
  const tableStartRow = range.startRow;
11597
11729
  const tableEndRow = range.endRow;
11730
+ const dataStartRow = tableStartRow + (this._tableData.showHeader === false ? 0 : 1);
11598
11731
  let startRow = -1;
11599
11732
  let endRow = -1;
11600
11733
  switch (type) {
@@ -11603,10 +11736,15 @@ var TableReferenceObject = class extends BaseReferenceObject {
11603
11736
  endRow = tableEndRow;
11604
11737
  break;
11605
11738
  case "#Data":
11606
- startRow = tableStartRow + 1;
11739
+ startRow = dataStartRow;
11607
11740
  endRow = tableEndRow;
11608
11741
  break;
11609
11742
  case "#Headers":
11743
+ if (this._tableData.showHeader === false) {
11744
+ startRow = -1;
11745
+ endRow = -1;
11746
+ break;
11747
+ }
11610
11748
  startRow = tableStartRow;
11611
11749
  endRow = tableStartRow;
11612
11750
  break;
@@ -11621,7 +11759,7 @@ var TableReferenceObject = class extends BaseReferenceObject {
11621
11759
  break;
11622
11760
  }
11623
11761
  default:
11624
- startRow = tableStartRow + 1;
11762
+ startRow = dataStartRow;
11625
11763
  endRow = tableEndRow;
11626
11764
  break;
11627
11765
  }
@@ -11646,6 +11784,13 @@ var TableReferenceObject = class extends BaseReferenceObject {
11646
11784
  }
11647
11785
  return rangeData;
11648
11786
  }
11787
+ getCellData(row, column) {
11788
+ if (this._isCurrentRowForRange) {
11789
+ const { startRow, endRow } = this._tableData.range;
11790
+ if (row < startRow || row > endRow) return { v: "#N/A" };
11791
+ }
11792
+ return super.getCellData(row, column);
11793
+ }
11649
11794
  getRefOffset() {
11650
11795
  return {
11651
11796
  x: 0,
@@ -11842,13 +11987,15 @@ var TableReferenceObject = class extends BaseReferenceObject {
11842
11987
  //#endregion
11843
11988
  //#region src/engine/ast-node/reference-node.ts
11844
11989
  var ReferenceNode = class extends BaseAstNode {
11845
- constructor(_currentConfigService, _runtimeService, operatorString, _referenceObjectType, _isPrepareMerge = false, _tableReferenceObject) {
11990
+ constructor(_currentConfigService, _runtimeService, operatorString, _referenceObjectType, _unitReferenceResolver, _superTableService, _isPrepareMerge = false, _tableReference) {
11846
11991
  super(operatorString);
11847
11992
  this._currentConfigService = _currentConfigService;
11848
11993
  this._runtimeService = _runtimeService;
11849
11994
  this._referenceObjectType = _referenceObjectType;
11995
+ this._unitReferenceResolver = _unitReferenceResolver;
11996
+ this._superTableService = _superTableService;
11850
11997
  this._isPrepareMerge = _isPrepareMerge;
11851
- this._tableReferenceObject = _tableReferenceObject;
11998
+ this._tableReference = _tableReference;
11852
11999
  _defineProperty(this, "_refOffsetX", 0);
11853
12000
  _defineProperty(this, "_refOffsetY", 0);
11854
12001
  }
@@ -11858,7 +12005,49 @@ var ReferenceNode = class extends BaseAstNode {
11858
12005
  execute() {
11859
12006
  const currentConfigService = this._currentConfigService;
11860
12007
  const runtimeService = this._runtimeService;
11861
- const referenceObject = this._tableReferenceObject || getReferenceObjectFromCache(this.getToken(), this._referenceObjectType);
12008
+ let referenceObject;
12009
+ if (this._tableReference) {
12010
+ var _Array$from$find;
12011
+ const { unitQualifier, tableName, columnStruct } = this._tableReference;
12012
+ const resolution = this._unitReferenceResolver.resolve({
12013
+ hostUnitId: runtimeService.currentUnitId,
12014
+ qualifier: unitQualifier,
12015
+ referenceKind: "table"
12016
+ });
12017
+ if (typeof resolution === "string") {
12018
+ this.setValue(ErrorValueObject.create(resolution));
12019
+ return;
12020
+ }
12021
+ const tableMap = this._superTableService.getTableMap(resolution.unitId);
12022
+ const tableData = (_Array$from$find = Array.from((tableMap === null || tableMap === void 0 ? void 0 : tableMap.entries()) || []).find(([name]) => name.toLocaleLowerCase() === tableName.toLocaleLowerCase())) === null || _Array$from$find === void 0 ? void 0 : _Array$from$find[1];
12023
+ if (!tableData) {
12024
+ this.setValue(ErrorValueObject.create("#REF!"));
12025
+ return;
12026
+ }
12027
+ referenceObject = new TableReferenceObject(this.getToken(), tableData, columnStruct, this._superTableService.getTableOptionMap());
12028
+ referenceObject.setUnitQualifier(unitQualifier);
12029
+ referenceObject.setForcedUnitIdDirect(resolution.unitId);
12030
+ } else {
12031
+ referenceObject = getReferenceObjectFromCache(this.getToken(), this._referenceObjectType);
12032
+ const unitQualifier = referenceObject.getUnitQualifier();
12033
+ if (unitQualifier) {
12034
+ const resolution = this._unitReferenceResolver.resolve({
12035
+ hostUnitId: runtimeService.currentUnitId,
12036
+ qualifier: unitQualifier,
12037
+ referenceKind: "a1"
12038
+ });
12039
+ if (typeof resolution === "string") {
12040
+ this.setValue(ErrorValueObject.create(resolution));
12041
+ return;
12042
+ }
12043
+ referenceObject.setForcedUnitIdDirect(resolution.unitId);
12044
+ }
12045
+ }
12046
+ this._configureReferenceObject(referenceObject, currentConfigService, runtimeService);
12047
+ if (!this._isPrepareMerge && referenceObject.isExceedRange()) this.setValue(ErrorValueObject.create("#NAME?"));
12048
+ else this.setValue(referenceObject);
12049
+ }
12050
+ _configureReferenceObject(referenceObject, currentConfigService, runtimeService) {
11862
12051
  referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
11863
12052
  referenceObject.setDefaultSheetId(runtimeService.currentSubUnitId);
11864
12053
  referenceObject.setForcedSheetId(currentConfigService.getSheetNameMap());
@@ -11870,13 +12059,9 @@ var ReferenceNode = class extends BaseAstNode {
11870
12059
  referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());
11871
12060
  referenceObject.setRuntimeArrayFormulaRange(runtimeService.getUnitArrayFormula());
11872
12061
  referenceObject.setRuntimeFeatureCellData(runtimeService.getRuntimeFeatureCellData());
11873
- const currentRow = runtimeService.currentRow;
11874
- const currentCol = runtimeService.currentColumn;
11875
- referenceObject.setCurrentRowAndColumn(currentRow, currentCol);
12062
+ referenceObject.setCurrentRowAndColumn(runtimeService.currentRow, runtimeService.currentColumn);
11876
12063
  const { x, y } = this.getRefOffset();
11877
12064
  referenceObject.setRefOffset(x, y);
11878
- if (!this._isPrepareMerge && referenceObject.isExceedRange()) this.setValue(ErrorValueObject.create("#NAME?"));
11879
- else this.setValue(referenceObject);
11880
12065
  }
11881
12066
  setRefOffset(x = 0, y = 0) {
11882
12067
  this._refOffsetX = x;
@@ -11890,12 +12075,13 @@ var ReferenceNode = class extends BaseAstNode {
11890
12075
  }
11891
12076
  };
11892
12077
  let ReferenceNodeFactory = class ReferenceNodeFactory extends BaseAstNodeFactory {
11893
- constructor(_currentConfigService, _formulaRuntimeService, _functionService, _superTableService) {
12078
+ constructor(_currentConfigService, _formulaRuntimeService, _functionService, _superTableService, _unitReferenceResolver) {
11894
12079
  super();
11895
12080
  this._currentConfigService = _currentConfigService;
11896
12081
  this._formulaRuntimeService = _formulaRuntimeService;
11897
12082
  this._functionService = _functionService;
11898
12083
  this._superTableService = _superTableService;
12084
+ this._unitReferenceResolver = _unitReferenceResolver;
11899
12085
  }
11900
12086
  get zIndex() {
11901
12087
  return NODE_ORDER_MAP.get(1) || 100;
@@ -11932,25 +12118,25 @@ let ReferenceNodeFactory = class ReferenceNodeFactory extends BaseAstNodeFactory
11932
12118
  var _tableMap$has;
11933
12119
  const currentConfigService = this._currentConfigService;
11934
12120
  const runtimeService = this._formulaRuntimeService;
11935
- const makeRef = (type) => new ReferenceNode(currentConfigService, runtimeService, tokenTrim, type, isPrepareMerge);
12121
+ const makeRef = (type) => new ReferenceNode(currentConfigService, runtimeService, tokenTrim, type, this._unitReferenceResolver, this._superTableService, isPrepareMerge);
11936
12122
  const tableMap = this._getTableMap();
11937
- if ((_tableMap$has = tableMap === null || tableMap === void 0 ? void 0 : tableMap.has(tokenTrim)) !== null && _tableMap$has !== void 0 ? _tableMap$has : false) return this._getTableReferenceNode(tokenTrim, isLexerNode, isPrepareMerge, true);
12123
+ if ((_tableMap$has = tableMap === null || tableMap === void 0 ? void 0 : tableMap.has(tokenTrim)) !== null && _tableMap$has !== void 0 ? _tableMap$has : false) return this._getTableReferenceNode(tokenTrim, isPrepareMerge, true);
11938
12124
  if (regexTestSingeRange(tokenTrim)) return makeRef(0);
11939
12125
  const parentIsUnion = isLexerNode && this._checkParentIsUnionOperator(param);
11940
12126
  if (parentIsUnion && regexTestSingleRow(tokenTrim)) return makeRef(2);
11941
12127
  if (parentIsUnion && regexTestSingleColumn(tokenTrim)) return makeRef(1);
11942
- return this._getTableReferenceNode(tokenTrim, isLexerNode, isPrepareMerge, false);
12128
+ return this._getTableReferenceNode(tokenTrim, isPrepareMerge, false);
11943
12129
  }
11944
- _getTableReferenceNode(tokenTrim, isLexerNode, isPrepareMerge, isSuperTableDirectly = false) {
12130
+ _getTableReferenceNode(tokenTrim, isPrepareMerge, isSuperTableDirectly = false) {
11945
12131
  if (!this._checkTokenIsTableReference(tokenTrim) && !isSuperTableDirectly) return;
11946
- const { tableName, columnStruct } = splitTableStructuredRef(tokenTrim);
12132
+ const { unitQualifier, tableName, columnStruct } = splitTableStructuredRef(tokenTrim);
11947
12133
  const tableMap = this._getTableMap();
11948
- if (!isLexerNode && (tableMap === null || tableMap === void 0 ? void 0 : tableMap.has(tableName))) {
11949
- const columnDataString = columnStruct;
11950
- const tableData = tableMap.get(tableName);
11951
- const tableOption = this._superTableService.getTableOptionMap();
11952
- return new ReferenceNode(this._currentConfigService, this._formulaRuntimeService, tokenTrim, 1, isPrepareMerge, new TableReferenceObject(tokenTrim, tableData, columnDataString, tableOption));
11953
- }
12134
+ const hasLocalTable = Array.from((tableMap === null || tableMap === void 0 ? void 0 : tableMap.keys()) || []).some((name) => name.toLocaleLowerCase() === tableName.toLocaleLowerCase());
12135
+ if (unitQualifier || hasLocalTable) return new ReferenceNode(this._currentConfigService, this._formulaRuntimeService, tokenTrim, 1, this._unitReferenceResolver, this._superTableService, isPrepareMerge, {
12136
+ unitQualifier,
12137
+ tableName,
12138
+ columnStruct
12139
+ });
11954
12140
  }
11955
12141
  _checkTokenIsTableReference(token) {
11956
12142
  return regexTestReferenceTableAllColumn(token) || regexTestReferenceTableSingleColumn(token) || regexTestReferenceTableMultipleColumn(token) || regexTestReferenceTableTitleOnlyAnyHash(token);
@@ -11964,7 +12150,8 @@ ReferenceNodeFactory = __decorate([
11964
12150
  __decorateParam(0, IFormulaCurrentConfigService),
11965
12151
  __decorateParam(1, IFormulaRuntimeService),
11966
12152
  __decorateParam(2, IFunctionService),
11967
- __decorateParam(3, ISuperTableService)
12153
+ __decorateParam(3, ISuperTableService),
12154
+ __decorateParam(4, IFormulaUnitReferenceResolver)
11968
12155
  ], ReferenceNodeFactory);
11969
12156
 
11970
12157
  //#endregion
@@ -14256,9 +14443,10 @@ let CalculateFormulaService = class CalculateFormulaService extends _univerjs_co
14256
14443
  this._executeLock.acquire("FORMULA_EXECUTION_LOCK", async () => {
14257
14444
  for (let i = 0; i < cycleReferenceCount; i++) {
14258
14445
  this._runtimeService.setFormulaCycleIndex(i);
14259
- await this._executeStep();
14446
+ const executed = await this._executeStep();
14260
14447
  FORMULA_REF_TO_ARRAY_CACHE.clear();
14261
- if (!this._runtimeService.isCycleDependency()) break;
14448
+ const isCycleDependency = this._runtimeService.isCycleDependency();
14449
+ if (!executed || !isCycleDependency) break;
14262
14450
  }
14263
14451
  this._runtimeService.setFormulaExecuteStage(8);
14264
14452
  this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
@@ -14369,7 +14557,6 @@ let CalculateFormulaService = class CalculateFormulaService extends _univerjs_co
14369
14557
  if (this._runtimeService.isStopExecution() || nodeData == null && getDirtyData == null) {
14370
14558
  this._runtimeService.setFormulaExecuteStage(0);
14371
14559
  this._runtimeService.markedAsStopFunctionsExecuted();
14372
- this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
14373
14560
  return;
14374
14561
  }
14375
14562
  }
@@ -14754,7 +14941,7 @@ function singleReference(refBody, currentRow = 0, currentColumn = 0) {
14754
14941
  };
14755
14942
  }
14756
14943
  function deserializeRangeForR1C1(refString, currentRow = 0, currentColumn = 0) {
14757
- const { refBody, sheetName, unitId } = handleRefStringInfo(refString);
14944
+ const { refBody, sheetName, unitQualifier } = handleRefStringInfo(refString);
14758
14945
  const colonIndex = refBody.indexOf(":");
14759
14946
  if (colonIndex === -1) {
14760
14947
  const grid = singleReference(refBody, currentRow, currentColumn);
@@ -14762,7 +14949,7 @@ function deserializeRangeForR1C1(refString, currentRow = 0, currentColumn = 0) {
14762
14949
  const column = grid.column;
14763
14950
  const absoluteRefType = grid.absoluteRefType;
14764
14951
  return {
14765
- unitId,
14952
+ unitId: unitQualifier,
14766
14953
  sheetName,
14767
14954
  range: {
14768
14955
  startRow: row,
@@ -14779,7 +14966,7 @@ function deserializeRangeForR1C1(refString, currentRow = 0, currentColumn = 0) {
14779
14966
  const startGrid = singleReference(refStartString, currentRow, currentColumn);
14780
14967
  const endGrid = singleReference(refEndString, currentRow, currentColumn);
14781
14968
  return {
14782
- unitId,
14969
+ unitId: unitQualifier,
14783
14970
  sheetName,
14784
14971
  range: {
14785
14972
  startRow: startGrid.row,
@@ -14809,6 +14996,91 @@ function getR1C1Ref(index, absoluteRefType = _univerjs_core.AbsoluteRefType.ALL,
14809
14996
  }
14810
14997
  }
14811
14998
 
14999
+ //#endregion
15000
+ //#region src/engine/utils/unit-qualifier.ts
15001
+ /**
15002
+ * Copyright 2023-present DreamNum Co., Ltd.
15003
+ *
15004
+ * Licensed under the Apache License, Version 2.0 (the "License");
15005
+ * you may not use this file except in compliance with the License.
15006
+ * You may obtain a copy of the License at
15007
+ *
15008
+ * http://www.apache.org/licenses/LICENSE-2.0
15009
+ *
15010
+ * Unless required by applicable law or agreed to in writing, software
15011
+ * distributed under the License is distributed on an "AS IS" BASIS,
15012
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15013
+ * See the License for the specific language governing permissions and
15014
+ * limitations under the License.
15015
+ */
15016
+ const A1_UNIT_QUALIFIER = /('?)\[([^\]]+)\]((?:[^']|'')+)\1!(?=\$?[A-Z]{1,3}\$?\d+)/gi;
15017
+ const TABLE_UNIT_QUALIFIER = /(^|[^\w.])(?:'((?:[^']|'')+)'|\[([^\]]+)\]|([A-Za-z0-9_.-]+))!(?=[^\s!\[\]]+\[)/g;
15018
+ const INDIRECT_LITERAL = /\bINDIRECT\s*\(\s*"((?:[^"]|"")*)"/gi;
15019
+ function equalsQualifier(actual, expected) {
15020
+ return actual.replace(/''/g, "'").toLocaleLowerCase() === expected.toLocaleLowerCase();
15021
+ }
15022
+ function quoteQualifier(name) {
15023
+ return /^[A-Za-z0-9_.-]+$/.test(name) ? name : `'${name.replace(/'/g, "''")}'`;
15024
+ }
15025
+ function refactorReferenceSegment(segment, oldName, newName) {
15026
+ return segment.replace(A1_UNIT_QUALIFIER, (token, quote, qualifier, sheetName) => {
15027
+ if (!equalsQualifier(qualifier, oldName)) return token;
15028
+ const escapedName = newName.replace(/'/g, "''");
15029
+ return quote ? `'[${escapedName}]${sheetName}'!` : `[${newName}]${sheetName}!`;
15030
+ }).replace(TABLE_UNIT_QUALIFIER, (token, boundary, quoted, bracketed, plain) => {
15031
+ var _ref, _ref2;
15032
+ if (!equalsQualifier((_ref = (_ref2 = quoted !== null && quoted !== void 0 ? quoted : bracketed) !== null && _ref2 !== void 0 ? _ref2 : plain) !== null && _ref !== void 0 ? _ref : "", oldName)) return token;
15033
+ if (quoted != null) return `${boundary}'${newName.replace(/'/g, "''")}'!`;
15034
+ if (bracketed != null) return `${boundary}[${newName}]!`;
15035
+ return `${boundary}${quoteQualifier(newName)}!`;
15036
+ });
15037
+ }
15038
+ function refactorOutsideStrings(formula, oldName, newName) {
15039
+ let result = "";
15040
+ let chunk = "";
15041
+ let inString = false;
15042
+ for (let index = 0; index < formula.length; index++) {
15043
+ const character = formula[index];
15044
+ if (character !== "\"") {
15045
+ chunk += character;
15046
+ continue;
15047
+ }
15048
+ if (inString && formula[index + 1] === "\"") {
15049
+ chunk += "\"\"";
15050
+ index++;
15051
+ continue;
15052
+ }
15053
+ result += inString ? chunk : refactorReferenceSegment(chunk, oldName, newName);
15054
+ result += "\"";
15055
+ chunk = "";
15056
+ inString = !inString;
15057
+ }
15058
+ return result + (inString ? chunk : refactorReferenceSegment(chunk, oldName, newName));
15059
+ }
15060
+ /** Refactors only parsed reference qualifiers and INDIRECT literal references, never arbitrary text. */
15061
+ function refactorFormulaUnitQualifier(formula, oldName, newName) {
15062
+ if (!oldName || oldName === newName) return formula;
15063
+ return refactorOutsideStrings(formula.replace(INDIRECT_LITERAL, (token, literal) => {
15064
+ const next = refactorReferenceSegment(literal.replace(/""/g, "\""), oldName, newName).replace(/"/g, "\"\"");
15065
+ return token.replace(literal, next);
15066
+ }), oldName, newName);
15067
+ }
15068
+ /**
15069
+ * Copyright 2023-present DreamNum Co., Ltd.
15070
+ *
15071
+ * Licensed under the Apache License, Version 2.0 (the "License");
15072
+ * you may not use this file except in compliance with the License.
15073
+ * You may obtain a copy of the License at
15074
+ *
15075
+ * http://www.apache.org/licenses/LICENSE-2.0
15076
+ *
15077
+ * Unless required by applicable law or agreed to in writing, software
15078
+ * distributed under the License is distributed on an "AS IS" BASIS,
15079
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15080
+ * See the License for the specific language governing permissions and
15081
+ * limitations under the License.
15082
+ */
15083
+
14812
15084
  //#endregion
14813
15085
  //#region src/engine/utils/check-variant-error.ts
14814
15086
  function checkVariantErrorIsArray(variant) {
@@ -14913,6 +15185,7 @@ var BaseFunction = class {
14913
15185
  _defineProperty(this, "_sheetOrder", void 0);
14914
15186
  _defineProperty(this, "_sheetNameMap", void 0);
14915
15187
  _defineProperty(this, "_formulaDataModel", void 0);
15188
+ _defineProperty(this, "_unitReferenceResolver", void 0);
14916
15189
  _defineProperty(this, "_rowCount", -1);
14917
15190
  _defineProperty(this, "_columnCount", -1);
14918
15191
  _defineProperty(
@@ -14955,6 +15228,12 @@ var BaseFunction = class {
14955
15228
  "needsFormulaDataModel",
14956
15229
  false
14957
15230
  );
15231
+ _defineProperty(
15232
+ this,
15233
+ /** Whether the function resolves external Unit qualifiers. */
15234
+ "needsUnitReferenceResolver",
15235
+ false
15236
+ );
14958
15237
  _defineProperty(
14959
15238
  this,
14960
15239
  /**
@@ -15063,6 +15342,9 @@ var BaseFunction = class {
15063
15342
  setFormulaDataModel(_formulaDataModel) {
15064
15343
  this._formulaDataModel = _formulaDataModel;
15065
15344
  }
15345
+ setUnitReferenceResolver(unitReferenceResolver) {
15346
+ this._unitReferenceResolver = unitReferenceResolver;
15347
+ }
15066
15348
  setSheetRowColumnCount(rowCount, columnCount) {
15067
15349
  this._rowCount = rowCount;
15068
15350
  this._columnCount = columnCount;
@@ -30224,6 +30506,7 @@ var Indirect = class extends BaseFunction {
30224
30506
  super(..._args);
30225
30507
  _defineProperty(this, "minParams", 1);
30226
30508
  _defineProperty(this, "maxParams", 2);
30509
+ _defineProperty(this, "needsUnitReferenceResolver", true);
30227
30510
  }
30228
30511
  isAddress() {
30229
30512
  return true;
@@ -30253,6 +30536,7 @@ var Indirect = class extends BaseFunction {
30253
30536
  if (a1Value === 0) {
30254
30537
  const { range, sheetName, unitId } = deserializeRangeForR1C1(refTextV);
30255
30538
  const rangeReferenceObject = new RangeReferenceObject(range);
30539
+ rangeReferenceObject.setUnitQualifier(unitId);
30256
30540
  rangeReferenceObject.setForcedUnitIdDirect(unitId);
30257
30541
  rangeReferenceObject.setForcedSheetName(sheetName);
30258
30542
  return this._setDefault(rangeReferenceObject);
@@ -30263,12 +30547,23 @@ var Indirect = class extends BaseFunction {
30263
30547
  const { range, sheetName, unitId } = deserializeRangeWithSheetWithCache(refTextV);
30264
30548
  if (Number.isNaN(range.startRow) || range.endRow + 1 > _univerjs_core.MAX_ROW_COUNT || Number.isNaN(range.startColumn) || range.endColumn + 1 > _univerjs_core.MAX_COLUMN_COUNT) return ErrorValueObject.create("#REF!");
30265
30549
  const rangeReferenceObject = new RangeReferenceObject(range);
30550
+ rangeReferenceObject.setUnitQualifier(unitId);
30266
30551
  rangeReferenceObject.setForcedUnitIdDirect(unitId);
30267
30552
  rangeReferenceObject.setForcedSheetName(sheetName);
30268
30553
  return this._setDefault(rangeReferenceObject);
30269
30554
  }
30270
30555
  _setDefault(object) {
30271
30556
  if (this.unitId == null || this.subUnitId == null) return ErrorValueObject.create("#REF!");
30557
+ const unitQualifier = object.getUnitQualifier();
30558
+ if (unitQualifier && this._unitReferenceResolver) {
30559
+ const resolution = this._unitReferenceResolver.resolve({
30560
+ hostUnitId: this.unitId,
30561
+ qualifier: unitQualifier,
30562
+ referenceKind: "a1"
30563
+ });
30564
+ if (typeof resolution === "string") return ErrorValueObject.create(resolution);
30565
+ object.setForcedUnitIdDirect(resolution.unitId);
30566
+ }
30272
30567
  object.setDefaultUnitId(this.unitId);
30273
30568
  object.setDefaultSheetId(this.subUnitId);
30274
30569
  return object;
@@ -41810,7 +42105,7 @@ function getObjectValue(result, isUseStrip = false) {
41810
42105
  //#endregion
41811
42106
  //#region package.json
41812
42107
  var name = "@univerjs/engine-formula";
41813
- var version = "1.0.0-alpha.3";
42108
+ var version = "1.0.0-alpha.5";
41814
42109
 
41815
42110
  //#endregion
41816
42111
  //#region src/services/global-computing-status.service.ts
@@ -41879,6 +42174,242 @@ let ComputingStatusReporterController = class ComputingStatusReporterController
41879
42174
  };
41880
42175
  ComputingStatusReporterController = __decorate([__decorateParam(0, _univerjs_core.ICommandService), __decorateParam(1, (0, _univerjs_core.Inject)(GlobalComputingStatusService))], ComputingStatusReporterController);
41881
42176
 
42177
+ //#endregion
42178
+ //#region src/services/formula-calculation-trigger.service.ts
42179
+ const LOCAL_ONLY = { onlyLocal: true };
42180
+ const CALCULATION_DEBOUNCE_TIME = 10;
42181
+ let FormulaCalculationTriggerService = class FormulaCalculationTriggerService extends _univerjs_core.Disposable {
42182
+ constructor(_commandService, _activeDirtyManagerService) {
42183
+ super();
42184
+ this._commandService = _commandService;
42185
+ this._activeDirtyManagerService = _activeDirtyManagerService;
42186
+ _defineProperty(this, "_waitingCommandQueue", []);
42187
+ _defineProperty(this, "_pendingDirtyData", createEmptyDirtyData());
42188
+ _defineProperty(this, "_runningDirtyData", createEmptyDirtyData());
42189
+ _defineProperty(this, "_timer", void 0);
42190
+ _defineProperty(this, "_started", false);
42191
+ _defineProperty(this, "_executionInProgress", false);
42192
+ _defineProperty(this, "_hasPendingCalculation", false);
42193
+ _defineProperty(this, "_stopRequested", false);
42194
+ this._initialize();
42195
+ }
42196
+ start() {
42197
+ if (this._started) return;
42198
+ this._started = true;
42199
+ this._scheduleFlush();
42200
+ }
42201
+ dispose() {
42202
+ clearTimeout(this._timer);
42203
+ this._waitingCommandQueue = [];
42204
+ this._pendingDirtyData = createEmptyDirtyData();
42205
+ this._runningDirtyData = createEmptyDirtyData();
42206
+ super.dispose();
42207
+ }
42208
+ _initialize() {
42209
+ this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
42210
+ var _conversion$shouldTri;
42211
+ if (command.id === SetFormulaCalculationStartMutation.id) {
42212
+ this._executionInProgress = true;
42213
+ return;
42214
+ }
42215
+ if (command.id === SetFormulaCalculationNotificationMutation.id) {
42216
+ this._handleCalculationNotification(command.params);
42217
+ return;
42218
+ }
42219
+ const conversion = this._activeDirtyManagerService.get(command.id);
42220
+ if (!conversion) return;
42221
+ if (((_conversion$shouldTri = conversion.shouldTrigger) === null || _conversion$shouldTri === void 0 ? void 0 : _conversion$shouldTri.call(conversion, command, options)) === false) return;
42222
+ this._waitingCommandQueue.push(command);
42223
+ this._scheduleFlush();
42224
+ }));
42225
+ }
42226
+ _scheduleFlush() {
42227
+ if (!this._started || this._waitingCommandQueue.length === 0 && !this._hasPendingCalculation) return;
42228
+ clearTimeout(this._timer);
42229
+ this._timer = setTimeout(() => this._flush(), CALCULATION_DEBOUNCE_TIME);
42230
+ }
42231
+ _flush() {
42232
+ const commands = this._waitingCommandQueue;
42233
+ const dirtyData = this._generateDirty(commands);
42234
+ this._waitingCommandQueue = [];
42235
+ this._timer = void 0;
42236
+ if (hasDirtyData(dirtyData) || commands.some(({ id }) => id === SetTriggerFormulaCalculationStartMutation.id)) {
42237
+ this._pendingDirtyData = mergeDirtyData(this._pendingDirtyData, dirtyData);
42238
+ this._hasPendingCalculation = true;
42239
+ }
42240
+ if (!this._hasPendingCalculation) return;
42241
+ if (this._executionInProgress) {
42242
+ if (!this._stopRequested && dirtyDataIntersects(this._runningDirtyData, this._pendingDirtyData)) {
42243
+ this._stopRequested = true;
42244
+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {}, LOCAL_ONLY);
42245
+ }
42246
+ return;
42247
+ }
42248
+ this._startCalculation();
42249
+ }
42250
+ _startCalculation() {
42251
+ this._runningDirtyData = this._pendingDirtyData;
42252
+ this._pendingDirtyData = createEmptyDirtyData();
42253
+ this._hasPendingCalculation = false;
42254
+ this._executionInProgress = true;
42255
+ this._stopRequested = false;
42256
+ this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, { ...this._runningDirtyData }, LOCAL_ONLY);
42257
+ }
42258
+ _handleCalculationNotification(params) {
42259
+ if (params.stageInfo != null) {
42260
+ this._executionInProgress = true;
42261
+ return;
42262
+ }
42263
+ const state = params.functionsExecutedState;
42264
+ if (state == null) return;
42265
+ if (!(state === 1 || state === 3 || state === 2) || !this._executionInProgress) return;
42266
+ this._executionInProgress = false;
42267
+ this._stopRequested = false;
42268
+ if (state === 1) this._pendingDirtyData = mergeDirtyData(this._runningDirtyData, this._pendingDirtyData);
42269
+ this._runningDirtyData = createEmptyDirtyData();
42270
+ if (this._hasPendingCalculation || this._waitingCommandQueue.length > 0) this._scheduleFlush();
42271
+ }
42272
+ _generateDirty(commands) {
42273
+ return commands.reduce((result, command) => {
42274
+ const conversion = this._activeDirtyManagerService.get(command.id);
42275
+ return conversion ? mergeDirtyData(result, conversion.getDirtyData(command)) : result;
42276
+ }, createEmptyDirtyData());
42277
+ }
42278
+ };
42279
+ FormulaCalculationTriggerService = __decorate([__decorateParam(0, _univerjs_core.ICommandService), __decorateParam(1, IActiveDirtyManagerService)], FormulaCalculationTriggerService);
42280
+ function createEmptyDirtyData() {
42281
+ return {
42282
+ forceCalculation: false,
42283
+ dirtyRanges: [],
42284
+ dirtyNameMap: {},
42285
+ dirtyDefinedNameMap: {},
42286
+ dirtySuperTableMap: {},
42287
+ dirtyUnitFeatureMap: {},
42288
+ dirtyUnitOtherFormulaMap: {},
42289
+ clearDependencyTreeCache: {}
42290
+ };
42291
+ }
42292
+ function mergeDirtyData(left, right) {
42293
+ var _right$dirtyRanges, _left$dirtySuperTable;
42294
+ const dirtyRanges = [...left.dirtyRanges];
42295
+ mergeDirtyRanges(dirtyRanges, (_right$dirtyRanges = right.dirtyRanges) !== null && _right$dirtyRanges !== void 0 ? _right$dirtyRanges : []);
42296
+ return {
42297
+ dirtyRanges,
42298
+ dirtyNameMap: mergeDirtyUnitStringMap(left.dirtyNameMap, right.dirtyNameMap),
42299
+ dirtyDefinedNameMap: mergeDirtyUnitStringMap(left.dirtyDefinedNameMap, right.dirtyDefinedNameMap),
42300
+ dirtySuperTableMap: mergeDirtyUnitStringMap((_left$dirtySuperTable = left.dirtySuperTableMap) !== null && _left$dirtySuperTable !== void 0 ? _left$dirtySuperTable : {}, right.dirtySuperTableMap),
42301
+ dirtyUnitFeatureMap: mergeDirtyUnitNestedMap(left.dirtyUnitFeatureMap, right.dirtyUnitFeatureMap),
42302
+ dirtyUnitOtherFormulaMap: mergeDirtyUnitNestedMap(left.dirtyUnitOtherFormulaMap, right.dirtyUnitOtherFormulaMap),
42303
+ clearDependencyTreeCache: mergeDirtyUnitStringMap(left.clearDependencyTreeCache, right.clearDependencyTreeCache),
42304
+ forceCalculation: left.forceCalculation || Boolean(right.forceCalculation)
42305
+ };
42306
+ }
42307
+ function mergeDirtyRanges(target, source) {
42308
+ const keys = new Set(target.map(getDirtyRangeKey));
42309
+ source.forEach((range) => {
42310
+ const key = getDirtyRangeKey(range);
42311
+ if (!keys.has(key)) {
42312
+ keys.add(key);
42313
+ target.push(range);
42314
+ }
42315
+ });
42316
+ }
42317
+ function getDirtyRangeKey({ unitId, sheetId, range }) {
42318
+ return JSON.stringify([
42319
+ unitId,
42320
+ sheetId,
42321
+ range.startRow,
42322
+ range.startColumn,
42323
+ range.endRow,
42324
+ range.endColumn,
42325
+ range.rangeType
42326
+ ]);
42327
+ }
42328
+ function mergeDirtyUnitStringMap(left, right) {
42329
+ const result = { ...left };
42330
+ Object.entries(right !== null && right !== void 0 ? right : {}).forEach(([unitId, values]) => {
42331
+ result[unitId] = {
42332
+ ...result[unitId],
42333
+ ...values
42334
+ };
42335
+ });
42336
+ return result;
42337
+ }
42338
+ function mergeDirtyUnitNestedMap(left, right) {
42339
+ const result = { ...left };
42340
+ Object.entries(right !== null && right !== void 0 ? right : {}).forEach(([unitId, sheets]) => {
42341
+ const unitResult = { ...result[unitId] };
42342
+ Object.entries(sheets !== null && sheets !== void 0 ? sheets : {}).forEach(([sheetId, values]) => {
42343
+ unitResult[sheetId] = {
42344
+ ...unitResult[sheetId],
42345
+ ...values
42346
+ };
42347
+ });
42348
+ result[unitId] = unitResult;
42349
+ });
42350
+ return result;
42351
+ }
42352
+ function hasDirtyData(dirtyData) {
42353
+ return dirtyData.forceCalculation || dirtyData.dirtyRanges.length > 0 || hasNestedValue(dirtyData.dirtyNameMap) || hasNestedValue(dirtyData.dirtyDefinedNameMap) || hasNestedValue(dirtyData.dirtySuperTableMap) || hasNestedValue(dirtyData.dirtyUnitFeatureMap) || hasNestedValue(dirtyData.dirtyUnitOtherFormulaMap) || hasNestedValue(dirtyData.clearDependencyTreeCache);
42354
+ }
42355
+ function hasNestedValue(value) {
42356
+ if (value == null) return false;
42357
+ if (typeof value !== "object") return true;
42358
+ return Object.values(value).some(hasNestedValue);
42359
+ }
42360
+ function dirtyDataIntersects(left, right) {
42361
+ if (left.forceCalculation || right.forceCalculation) return true;
42362
+ if (left.dirtyRanges.some((leftRange) => right.dirtyRanges.some((rightRange) => leftRange.unitId === rightRange.unitId && leftRange.sheetId === rightRange.sheetId && _univerjs_core.Rectangle.intersects(leftRange.range, rightRange.range))) || clearedSheetIntersects(left, right) || clearedSheetIntersects(right, left)) return true;
42363
+ return [
42364
+ [left.dirtyNameMap, right.dirtyNameMap],
42365
+ [left.dirtyDefinedNameMap, right.dirtyDefinedNameMap],
42366
+ [left.dirtySuperTableMap, right.dirtySuperTableMap],
42367
+ [left.dirtyUnitFeatureMap, right.dirtyUnitFeatureMap],
42368
+ [left.dirtyUnitOtherFormulaMap, right.dirtyUnitOtherFormulaMap],
42369
+ [left.clearDependencyTreeCache, right.clearDependencyTreeCache]
42370
+ ].some(([leftMap, rightMap]) => hasSameNestedKey(leftMap, rightMap));
42371
+ }
42372
+ function clearedSheetIntersects(cleared, dirty) {
42373
+ return Object.entries(cleared.clearDependencyTreeCache).some(([unitId, sheets]) => Object.keys(sheets !== null && sheets !== void 0 ? sheets : {}).some((sheetId) => {
42374
+ var _dirty$dirtyNameMap$u, _dirty$dirtyUnitFeatu, _dirty$dirtyUnitOther;
42375
+ return dirty.dirtyRanges.some((range) => range.unitId === unitId && range.sheetId === sheetId) || ((_dirty$dirtyNameMap$u = dirty.dirtyNameMap[unitId]) === null || _dirty$dirtyNameMap$u === void 0 ? void 0 : _dirty$dirtyNameMap$u[sheetId]) != null || ((_dirty$dirtyUnitFeatu = dirty.dirtyUnitFeatureMap[unitId]) === null || _dirty$dirtyUnitFeatu === void 0 ? void 0 : _dirty$dirtyUnitFeatu[sheetId]) != null || ((_dirty$dirtyUnitOther = dirty.dirtyUnitOtherFormulaMap[unitId]) === null || _dirty$dirtyUnitOther === void 0 ? void 0 : _dirty$dirtyUnitOther[sheetId]) != null;
42376
+ }));
42377
+ }
42378
+ function hasSameNestedKey(left, right) {
42379
+ if (left == null || right == null || typeof left !== "object" || typeof right !== "object") return left != null && right != null;
42380
+ const rightRecord = right;
42381
+ return Object.entries(left).some(([key, value]) => Object.prototype.hasOwnProperty.call(rightRecord, key) && hasSameNestedKey(value, rightRecord[key]));
42382
+ }
42383
+
42384
+ //#endregion
42385
+ //#region src/controllers/formula-calculation-trigger.controller.ts
42386
+ /**
42387
+ * Copyright 2023-present DreamNum Co., Ltd.
42388
+ *
42389
+ * Licensed under the Apache License, Version 2.0 (the "License");
42390
+ * you may not use this file except in compliance with the License.
42391
+ * You may obtain a copy of the License at
42392
+ *
42393
+ * http://www.apache.org/licenses/LICENSE-2.0
42394
+ *
42395
+ * Unless required by applicable law or agreed to in writing, software
42396
+ * distributed under the License is distributed on an "AS IS" BASIS,
42397
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
42398
+ * See the License for the specific language governing permissions and
42399
+ * limitations under the License.
42400
+ */
42401
+ let FormulaCalculationTriggerController = class FormulaCalculationTriggerController extends _univerjs_core.Disposable {
42402
+ constructor(formulaCalculationTriggerService, lifecycleService) {
42403
+ super();
42404
+ if ((0, _univerjs_core.isNodeEnv)()) {
42405
+ formulaCalculationTriggerService.start();
42406
+ return;
42407
+ }
42408
+ this.disposeWithMe(lifecycleService.lifecycle$.pipe((0, rxjs.filter)((stage) => stage >= _univerjs_core.LifecycleStages.Rendered), (0, rxjs.take)(1)).subscribe(() => formulaCalculationTriggerService.start()));
42409
+ }
42410
+ };
42411
+ FormulaCalculationTriggerController = __decorate([__decorateParam(0, (0, _univerjs_core.Inject)(FormulaCalculationTriggerService)), __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))], FormulaCalculationTriggerController);
42412
+
41882
42413
  //#endregion
41883
42414
  //#region src/controllers/formula.controller.ts
41884
42415
  let FormulaController = class FormulaController extends _univerjs_core.Disposable {
@@ -42100,153 +42631,6 @@ SetOtherFormulaController = __decorate([
42100
42631
  __decorateParam(2, IDependencyManagerService)
42101
42632
  ], SetOtherFormulaController);
42102
42633
 
42103
- //#endregion
42104
- //#region src/services/formula-calculation-trigger.service.ts
42105
- const LOCAL_ONLY = { onlyLocal: true };
42106
- const CALCULATION_DEBOUNCE_TIME = 100;
42107
- let FormulaCalculationTriggerService = class FormulaCalculationTriggerService extends _univerjs_core.Disposable {
42108
- constructor(_commandService, _activeDirtyManagerService) {
42109
- super();
42110
- this._commandService = _commandService;
42111
- this._activeDirtyManagerService = _activeDirtyManagerService;
42112
- _defineProperty(this, "_waitingCommandQueue", []);
42113
- _defineProperty(this, "_executingDirtyData", createEmptyDirtyData());
42114
- _defineProperty(this, "_timer", void 0);
42115
- _defineProperty(this, "_executionInProgress", false);
42116
- _defineProperty(this, "_restartCalculation", false);
42117
- this._initialize();
42118
- }
42119
- dispose() {
42120
- clearTimeout(this._timer);
42121
- this._waitingCommandQueue = [];
42122
- this._executingDirtyData = createEmptyDirtyData();
42123
- super.dispose();
42124
- }
42125
- _initialize() {
42126
- this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
42127
- var _conversion$shouldTri;
42128
- if (command.id === SetFormulaCalculationStartMutation.id) {
42129
- this._executionInProgress = true;
42130
- return;
42131
- }
42132
- if (command.id === SetFormulaCalculationNotificationMutation.id) {
42133
- this._handleCalculationNotification(command.params);
42134
- return;
42135
- }
42136
- const conversion = this._activeDirtyManagerService.get(command.id);
42137
- if (!conversion) return;
42138
- if (((_conversion$shouldTri = conversion.shouldTrigger) === null || _conversion$shouldTri === void 0 ? void 0 : _conversion$shouldTri.call(conversion, command, options)) === false) return;
42139
- this._waitingCommandQueue.push(command);
42140
- clearTimeout(this._timer);
42141
- this._timer = setTimeout(() => this._flush(), CALCULATION_DEBOUNCE_TIME);
42142
- }));
42143
- }
42144
- _flush() {
42145
- const dirtyData = this._generateDirty(this._waitingCommandQueue);
42146
- this._waitingCommandQueue = [];
42147
- this._timer = void 0;
42148
- if (!hasDirtyData(dirtyData)) return;
42149
- this._executingDirtyData = mergeDirtyData(this._executingDirtyData, dirtyData);
42150
- if (this._executionInProgress) {
42151
- this._restartCalculation = true;
42152
- this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {}, LOCAL_ONLY);
42153
- return;
42154
- }
42155
- this._startCalculation();
42156
- }
42157
- _startCalculation() {
42158
- this._executionInProgress = true;
42159
- this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, { ...this._executingDirtyData }, LOCAL_ONLY);
42160
- }
42161
- _handleCalculationNotification(params) {
42162
- if (params.stageInfo != null) {
42163
- this._executionInProgress = true;
42164
- return;
42165
- }
42166
- const state = params.functionsExecutedState;
42167
- if (state == null) return;
42168
- this._executionInProgress = false;
42169
- if (state === 1 && this._restartCalculation) {
42170
- this._restartCalculation = false;
42171
- this._startCalculation();
42172
- return;
42173
- }
42174
- this._restartCalculation = false;
42175
- this._executingDirtyData = createEmptyDirtyData();
42176
- }
42177
- _generateDirty(commands) {
42178
- return commands.reduce((result, command) => {
42179
- const conversion = this._activeDirtyManagerService.get(command.id);
42180
- return conversion ? mergeDirtyData(result, conversion.getDirtyData(command)) : result;
42181
- }, createEmptyDirtyData());
42182
- }
42183
- };
42184
- FormulaCalculationTriggerService = __decorate([__decorateParam(0, _univerjs_core.ICommandService), __decorateParam(1, IActiveDirtyManagerService)], FormulaCalculationTriggerService);
42185
- function createEmptyDirtyData() {
42186
- return {
42187
- forceCalculation: false,
42188
- dirtyRanges: [],
42189
- dirtyNameMap: {},
42190
- dirtyDefinedNameMap: {},
42191
- dirtySuperTableMap: {},
42192
- dirtyUnitFeatureMap: {},
42193
- dirtyUnitOtherFormulaMap: {},
42194
- clearDependencyTreeCache: {}
42195
- };
42196
- }
42197
- function mergeDirtyData(left, right) {
42198
- var _right$dirtyRanges, _left$dirtySuperTable;
42199
- const dirtyRanges = [...left.dirtyRanges];
42200
- mergeDirtyRanges(dirtyRanges, (_right$dirtyRanges = right.dirtyRanges) !== null && _right$dirtyRanges !== void 0 ? _right$dirtyRanges : []);
42201
- return {
42202
- dirtyRanges,
42203
- dirtyNameMap: mergeDirtyUnitStringMap(left.dirtyNameMap, right.dirtyNameMap),
42204
- dirtyDefinedNameMap: mergeDirtyUnitStringMap(left.dirtyDefinedNameMap, right.dirtyDefinedNameMap),
42205
- dirtySuperTableMap: mergeDirtyUnitStringMap((_left$dirtySuperTable = left.dirtySuperTableMap) !== null && _left$dirtySuperTable !== void 0 ? _left$dirtySuperTable : {}, right.dirtySuperTableMap),
42206
- dirtyUnitFeatureMap: mergeDirtyUnitNestedMap(left.dirtyUnitFeatureMap, right.dirtyUnitFeatureMap),
42207
- dirtyUnitOtherFormulaMap: mergeDirtyUnitNestedMap(left.dirtyUnitOtherFormulaMap, right.dirtyUnitOtherFormulaMap),
42208
- clearDependencyTreeCache: mergeDirtyUnitStringMap(left.clearDependencyTreeCache, right.clearDependencyTreeCache),
42209
- forceCalculation: left.forceCalculation || Boolean(right.forceCalculation)
42210
- };
42211
- }
42212
- function mergeDirtyRanges(target, source) {
42213
- source.forEach((range) => {
42214
- if (!target.some((item) => item.unitId === range.unitId && item.sheetId === range.sheetId && item.range.startRow === range.range.startRow && item.range.startColumn === range.range.startColumn && item.range.endRow === range.range.endRow && item.range.endColumn === range.range.endColumn)) target.push(range);
42215
- });
42216
- }
42217
- function mergeDirtyUnitStringMap(left, right) {
42218
- const result = { ...left };
42219
- Object.entries(right !== null && right !== void 0 ? right : {}).forEach(([unitId, values]) => {
42220
- result[unitId] = {
42221
- ...result[unitId],
42222
- ...values
42223
- };
42224
- });
42225
- return result;
42226
- }
42227
- function mergeDirtyUnitNestedMap(left, right) {
42228
- const result = { ...left };
42229
- Object.entries(right !== null && right !== void 0 ? right : {}).forEach(([unitId, sheets]) => {
42230
- const unitResult = { ...result[unitId] };
42231
- Object.entries(sheets !== null && sheets !== void 0 ? sheets : {}).forEach(([sheetId, values]) => {
42232
- unitResult[sheetId] = {
42233
- ...unitResult[sheetId],
42234
- ...values
42235
- };
42236
- });
42237
- result[unitId] = unitResult;
42238
- });
42239
- return result;
42240
- }
42241
- function hasDirtyData(dirtyData) {
42242
- return dirtyData.forceCalculation || dirtyData.dirtyRanges.length > 0 || hasNestedValue(dirtyData.dirtyNameMap) || hasNestedValue(dirtyData.dirtyDefinedNameMap) || hasNestedValue(dirtyData.dirtySuperTableMap) || hasNestedValue(dirtyData.dirtyUnitFeatureMap) || hasNestedValue(dirtyData.dirtyUnitOtherFormulaMap) || hasNestedValue(dirtyData.clearDependencyTreeCache);
42243
- }
42244
- function hasNestedValue(value) {
42245
- if (value == null) return false;
42246
- if (typeof value !== "object") return true;
42247
- return Object.values(value).some(hasNestedValue);
42248
- }
42249
-
42250
42634
  //#endregion
42251
42635
  //#region src/services/formula-common.ts
42252
42636
  let FormulaResultStatus = /* @__PURE__ */ function(FormulaResultStatus) {
@@ -42447,7 +42831,11 @@ let UniverFormulaEnginePlugin = class UniverFormulaEnginePlugin extends _univerj
42447
42831
  }
42448
42832
  onReady() {
42449
42833
  var _this$_config;
42450
- (0, _univerjs_core.touchDependencies)(this._injector, [[FormulaController], [SuperTableActiveDirtyController]]);
42834
+ (0, _univerjs_core.touchDependencies)(this._injector, [
42835
+ [FormulaController],
42836
+ [FormulaCalculationTriggerController],
42837
+ [SuperTableActiveDirtyController]
42838
+ ]);
42451
42839
  if (!((_this$_config = this._config) === null || _this$_config === void 0 ? void 0 : _this$_config.notExecuteFormula)) (0, _univerjs_core.touchDependencies)(this._injector, [
42452
42840
  [SetOtherFormulaController],
42453
42841
  [SetFeatureCalculationController],
@@ -42473,6 +42861,7 @@ let UniverFormulaEnginePlugin = class UniverFormulaEnginePlugin extends _univerj
42473
42861
  [GlobalComputingStatusService],
42474
42862
  [FormulaDataModel],
42475
42863
  [FormulaController],
42864
+ [FormulaCalculationTriggerController],
42476
42865
  [SuperTableActiveDirtyController],
42477
42866
  [ComputingStatusReporterController]
42478
42867
  ];
@@ -42485,7 +42874,8 @@ let UniverFormulaEnginePlugin = class UniverFormulaEnginePlugin extends _univerj
42485
42874
  if (!((_this$_config3 = this._config) === null || _this$_config3 === void 0 ? void 0 : _this$_config3.notExecuteFormula)) [
42486
42875
  [ICalculateFormulaService, { useClass: CalculateFormulaService }],
42487
42876
  [IDependencyManagerService, { useClass: DependencyManagerService }],
42488
- [IFormulaDependencyGenerator, { useClass: FormulaDependencyGenerator }]
42877
+ [IFormulaDependencyGenerator, { useClass: FormulaDependencyGenerator }],
42878
+ [IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }]
42489
42879
  ].forEach((dependency) => this._injector.add(dependency));
42490
42880
  }
42491
42881
  };
@@ -42603,6 +42993,12 @@ Object.defineProperty(exports, 'FormulaRuntimeService', {
42603
42993
  return FormulaRuntimeService;
42604
42994
  }
42605
42995
  });
42996
+ Object.defineProperty(exports, 'FormulaUnitReferenceResolver', {
42997
+ enumerable: true,
42998
+ get: function () {
42999
+ return FormulaUnitReferenceResolver;
43000
+ }
43001
+ });
42606
43002
  Object.defineProperty(exports, 'FunctionNodeFactory', {
42607
43003
  enumerable: true,
42608
43004
  get: function () {
@@ -42626,6 +43022,7 @@ exports.IFeatureCalculationManagerService = IFeatureCalculationManagerService;
42626
43022
  exports.IFormulaCurrentConfigService = IFormulaCurrentConfigService;
42627
43023
  exports.IFormulaDependencyGenerator = IFormulaDependencyGenerator;
42628
43024
  exports.IFormulaRuntimeService = IFormulaRuntimeService;
43025
+ exports.IFormulaUnitReferenceResolver = IFormulaUnitReferenceResolver;
42629
43026
  exports.IFunctionService = IFunctionService;
42630
43027
  exports.IHyperlinkEngineFormulaService = IHyperlinkEngineFormulaService;
42631
43028
  exports.IOtherFormulaManagerService = IOtherFormulaManagerService;
@@ -42787,10 +43184,12 @@ exports.isReferenceStrings = isReferenceStrings;
42787
43184
  exports.matchRefDrawToken = matchRefDrawToken;
42788
43185
  exports.matchToken = matchToken;
42789
43186
  exports.needsQuoting = needsQuoting;
43187
+ exports.normalizeFormulaUnitName = normalizeFormulaUnitName;
42790
43188
  exports.normalizeSheetName = normalizeSheetName;
42791
43189
  exports.operatorToken = operatorToken;
42792
43190
  exports.prefixToken = prefixToken;
42793
43191
  exports.quoteSheetName = quoteSheetName;
43192
+ exports.refactorFormulaUnitQualifier = refactorFormulaUnitQualifier;
42794
43193
  exports.sequenceNodeType = sequenceNodeType;
42795
43194
  exports.serializeRange = serializeRange;
42796
43195
  exports.serializeRangeToRefString = serializeRangeToRefString;