@univerjs-pro/engine-formula-rust 1.0.0-insiders.20260809-70eefdd → 1.0.0

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/es/index.js CHANGED
@@ -176,10 +176,12 @@ import { CommandType, Disposable, ICommandService, setDependencies } from "@univ
176
176
 
177
177
  // src/services/rust-formula-projection.service.ts
178
178
  import {
179
+ BooleanNumber,
179
180
  CellValueType,
181
+ FormulaType,
180
182
  ObjectMatrix
181
183
  } from "@univerjs/core";
182
- var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_PLUGIN", EXTERNAL_DATA_RESOURCE = "SHEET_EXTERNAL_DATA_PLUGIN", EXTERNAL_DATA_SIGNATURE = "external_data", RUST_UPSERT_REFERENCE_DATA_MUTATION_ID = "formula.mutation.upsert-reference-data", RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID = "formula.mutation.upsert-projection-workbook", RUST_FORMULA_RELEVANT_MUTATIONS = /* @__PURE__ */ new Set([
184
+ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_PLUGIN", EXTERNAL_DATA_RESOURCE = "SHEET_EXTERNAL_DATA_PLUGIN", EXTERNAL_DATA_SIGNATURE = "external_data", RUST_UPSERT_REFERENCE_DATA_MUTATION_ID = "formula.mutation.upsert-reference-data", RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID = "formula.mutation.upsert-projection-workbook", RUST_SET_SUPER_TABLES_MUTATION_ID = "formula.mutation.set-super-tables", RUST_FORMULA_RELEVANT_MUTATIONS = /* @__PURE__ */ new Set([
183
185
  "sheet.mutation.set-range-values",
184
186
  "sheet.mutation.insert-row",
185
187
  "sheet.mutation.insert-col",
@@ -195,6 +197,11 @@ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_P
195
197
  "sheet.mutation.set-col-visible",
196
198
  "sheet.mutation.set-row-hidden",
197
199
  "sheet.mutation.set-row-visible",
200
+ "sheet.mutation.set-table-filter",
201
+ "sheet.mutation.set-filter-range",
202
+ "sheet.mutation.set-filter-criteria",
203
+ "sheet.mutation.remove-filter",
204
+ "sheet.mutation.re-calc-filter",
198
205
  "sheet.mutation.set-worksheet-name",
199
206
  "sheet.mutation.reorder-range",
200
207
  "sheet.mutation.set-worksheet-row-count",
@@ -206,6 +213,7 @@ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_P
206
213
  "formula.mutation.set-image-formula-data",
207
214
  "formula.mutation.set-other-formula",
208
215
  "formula.mutation.set-super-table",
216
+ RUST_SET_SUPER_TABLES_MUTATION_ID,
209
217
  "formula.mutation.set-super-table-option",
210
218
  "formula.mutation.remove-defined-name",
211
219
  "formula.mutation.remove-feature-calculation",
@@ -267,11 +275,18 @@ function serializeRuntimeWorkbookSnapshots(workbooks) {
267
275
  }
268
276
  function serializeRuntimeWorkbookSnapshot(input) {
269
277
  let { snapshot } = input, sheetOrder = snapshot.sheetOrder?.length > 0 ? snapshot.sheetOrder : Object.keys(snapshot.sheets ?? {}), calculation = serializeCalculation(snapshot), precisionAsDisplayed = calculation?.fullPrecision === !1, sheets = sheetOrder.map(
270
- (sheetId) => serializeSheetSnapshot(sheetId, snapshot.sheets?.[sheetId], snapshot.styles, precisionAsDisplayed)
278
+ (sheetId) => serializeSheetSnapshot(
279
+ sheetId,
280
+ snapshot.sheets?.[sheetId],
281
+ snapshot.styles,
282
+ precisionAsDisplayed,
283
+ input.styleResolver
284
+ )
271
285
  ).filter((sheet) => sheet != null);
272
286
  return {
273
287
  unitId: input.unitId || snapshot.id,
274
288
  name: snapshot.name,
289
+ dateSystem: snapshot.dateSystem,
275
290
  sheets,
276
291
  ...calculation ? { calculation } : {},
277
292
  resources: serializeResources(snapshot),
@@ -339,13 +354,16 @@ function otherFormulaDataToUnitOtherData(otherFormulaData) {
339
354
  if (!colMap) return;
340
355
  let row = Number(rowKey), rowData = {};
341
356
  formulaData[row] = rowData, Object.entries(colMap).forEach(([colKey, value]) => {
342
- rowData[Number(colKey)] = [[cellDataFromRustValue(value)]];
357
+ rowData[Number(colKey)] = otherFormulaResultFromRustValue(value);
343
358
  });
344
359
  });
345
360
  });
346
361
  });
347
362
  }), unitOtherData;
348
363
  }
364
+ function otherFormulaResultFromRustValue(value) {
365
+ return Array.isArray(value) ? value.map((row) => (Array.isArray(row) ? row : [row]).map((cell) => cellDataFromRustValue(cell))) : [[cellDataFromRustValue(value)]];
366
+ }
349
367
  function createFormulaProjectionDesyncSignal(reason, error, mutationId) {
350
368
  return {
351
369
  reason,
@@ -441,13 +459,26 @@ var RustFormulaProjectionService = class {
441
459
  }
442
460
  };
443
461
  function normalizeRustEngineMutation(mutation) {
444
- let params = mutation.id === "formula.mutation.set-super-table" ? normalizeSetSuperTableMutationParams(mutation.params) : mutation.params ?? {};
462
+ let params = mutation.id === "formula.mutation.set-super-table" ? normalizeSetSuperTableMutationParams(mutation.params) : mutation.id === RUST_SET_SUPER_TABLES_MUTATION_ID ? normalizeSetSuperTablesMutationParams(mutation.params) : mutation.params ?? {};
445
463
  return {
446
464
  id: mutation.id,
447
465
  params,
448
466
  dirtyRanges: Array.isArray(mutation.dirtyRanges) ? mutation.dirtyRanges : []
449
467
  };
450
468
  }
469
+ function normalizeSetSuperTablesMutationParams(params) {
470
+ return !isRecord(params) || typeof params.unitId != "string" || !Array.isArray(params.tables) ? params ?? {} : {
471
+ ...params,
472
+ tables: params.tables.map((entry) => {
473
+ let normalized = normalizeSetSuperTableMutationParams(
474
+ isRecord(entry) ? { ...entry, unitId: params.unitId } : entry
475
+ );
476
+ if (!isRecord(normalized)) return normalized;
477
+ let { unitId: _unitId, ...table } = normalized;
478
+ return table;
479
+ })
480
+ };
481
+ }
451
482
  function normalizeSetSuperTableMutationParams(params) {
452
483
  if (!isRecord(params) || !isRecord(params.reference))
453
484
  return params ?? {};
@@ -866,19 +897,19 @@ function extractDefinedNames(snapshot) {
866
897
  }
867
898
  return {};
868
899
  }
869
- function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed) {
900
+ function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed, styleResolver) {
870
901
  return sheet ? {
871
902
  sheetId: sheet.id ?? sheetId,
872
903
  name: sheet.name,
873
904
  rowCount: sheet.rowCount ?? 0,
874
905
  columnCount: sheet.columnCount ?? 0,
875
906
  transitionEvaluation: sheet.transitionEvaluation === !0,
876
- cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed),
907
+ cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed, styleResolver),
877
908
  rowData: serializeVisibilityData(sheet.rowData),
878
909
  columnData: serializeVisibilityData(sheet.columnData)
879
910
  } : null;
880
911
  }
881
- function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
912
+ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1, styleResolver) {
882
913
  let result = {}, rawCellData = cellData instanceof ObjectMatrix ? cellData.getMatrix() : cellData;
883
914
  for (let [rowKey, row] of Object.entries(rawCellData ?? {})) {
884
915
  if (!row)
@@ -887,13 +918,15 @@ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
887
918
  for (let [colKey, cell] of Object.entries(row)) {
888
919
  if (!cell || typeof cell != "object")
889
920
  continue;
890
- let cellRecord = cell, value = {};
891
- if ("v" in cellRecord && (value.v = cellRecord.v), typeof cellRecord.t == "number" && (value.t = cellRecord.t), "p" in cellRecord && (value.p = cellRecord.p), typeof cellRecord.f == "string" && (value.f = cellRecord.f), typeof cellRecord.si == "string" && (value.si = cellRecord.si), typeof cellRecord.ref == "string") {
921
+ let cellRecord = cell, resolvedStyle = styleResolver?.getStyleByCell(cell), value = {};
922
+ if ("v" in cellRecord && (value.v = cellRecord.v), typeof cellRecord.t == "number" && (value.t = cellRecord.t), "p" in cellRecord && (value.p = cellRecord.p), typeof cellRecord.f == "string" && (value.f = cellRecord.f), typeof cellRecord.ft == "number" && (value.ft = cellRecord.ft), (cellRecord.fd === BooleanNumber.FALSE || cellRecord.fd === BooleanNumber.TRUE) && (value.fd = cellRecord.fd), typeof cellRecord.si == "string" && (value.si = cellRecord.si), typeof cellRecord.ref == "string") {
892
923
  let hasFormula = typeof cellRecord.f == "string" && cellRecord.f.length > 0;
893
924
  typeof cellRecord.si == "string" || hasFormula && isLegacyArrayFormulaCell(cellRecord) ? value.ref = cellRecord.ref : hasFormula && (value.dynamicArrayRef = cellRecord.ref);
894
925
  }
895
- if (typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s), precisionAsDisplayed && typeof cellRecord.f == "string") {
896
- let displayPrecision = inferDisplayPrecision(cellRecord.s, styles);
926
+ typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s);
927
+ let numberFormat = resolveNumberFormatPattern(cellRecord.s, styles, resolvedStyle);
928
+ if (numberFormat !== void 0 && (value.numberFormat = numberFormat), precisionAsDisplayed && typeof cellRecord.f == "string") {
929
+ let displayPrecision = inferDisplayPrecision(cellRecord.s, styles, resolvedStyle);
897
930
  displayPrecision !== void 0 && (value.displayPrecision = displayPrecision);
898
931
  }
899
932
  Object.keys(value).length > 0 && (serializedRow[Number(colKey)] = value);
@@ -916,23 +949,19 @@ function serializeCellDataInRanges(cellData, ranges) {
916
949
  return result;
917
950
  }
918
951
  function isLegacyArrayFormulaCell(cell) {
919
- let custom = cell.custom;
920
- if (!custom || typeof custom != "object")
921
- return !1;
922
- let xlsx = custom._xlsx;
923
- return xlsx != null && typeof xlsx == "object" && xlsx.legacyArrayFormula === !0;
952
+ return cell.ft === FormulaType.ARRAY && cell.fd !== BooleanNumber.TRUE;
924
953
  }
925
- function inferDisplayPrecision(styleId, styles) {
926
- if (typeof styleId != "string" || !styles || typeof styles != "object")
927
- return;
928
- let style = styles[styleId];
929
- if (!style || typeof style != "object")
930
- return;
954
+ function inferDisplayPrecision(styleId, styles, resolvedStyle) {
955
+ let pattern = resolveNumberFormatPattern(styleId, styles, resolvedStyle);
956
+ return pattern === void 0 ? void 0 : inferFixedNumberFormatPrecision(pattern);
957
+ }
958
+ function resolveNumberFormatPattern(styleRef, styles, resolvedStyle) {
959
+ let style = resolvedStyle ?? (typeof styleRef == "string" && styles && typeof styles == "object" ? styles[styleRef] : styleRef);
960
+ if (!style || typeof style != "object") return;
931
961
  let numberFormat = style.n;
932
- if (!numberFormat || typeof numberFormat != "object")
933
- return;
962
+ if (!numberFormat || typeof numberFormat != "object") return;
934
963
  let pattern = numberFormat.pattern;
935
- return typeof pattern == "string" ? inferFixedNumberFormatPrecision(pattern) : void 0;
964
+ return typeof pattern == "string" ? pattern : void 0;
936
965
  }
937
966
  function inferFixedNumberFormatPrecision(pattern) {
938
967
  let cleaned = (pattern.split(";")[0] ?? pattern).replace(/"[^"]*"/gu, "").replace(/\\./gu, "").replace(/_.|\*./gu, "");
@@ -1015,6 +1044,7 @@ var RustEngineSyncController = class extends Disposable {
1015
1044
  _nativeReady = !1;
1016
1045
  _snapshotLoaded = !1;
1017
1046
  _projectionLoadPromise = null;
1047
+ _projectionDeltaBarrier = Promise.resolve();
1018
1048
  _pendingMutations = [];
1019
1049
  _projectionManagedTableUnits = /* @__PURE__ */ new Set();
1020
1050
  _initialize() {
@@ -1035,6 +1065,13 @@ var RustEngineSyncController = class extends Disposable {
1035
1065
  }
1036
1066
  async waitForProjectionLoad() {
1037
1067
  await this._projectionLoadPromise;
1068
+ let barrier;
1069
+ do
1070
+ barrier = this._projectionDeltaBarrier, await barrier;
1071
+ while (barrier !== this._projectionDeltaBarrier);
1072
+ }
1073
+ setProjectionDeltaBarrier(barrier) {
1074
+ this._projectionDeltaBarrier = barrier;
1038
1075
  }
1039
1076
  async _loadProjection(workbooks) {
1040
1077
  await loadNativeBinding(), this._nativeReady = !0;
@@ -1066,7 +1103,7 @@ var RustEngineSyncController = class extends Disposable {
1066
1103
  }
1067
1104
  }
1068
1105
  dispose() {
1069
- if (super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, !this._nativeReady) {
1106
+ if (super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, this._projectionDeltaBarrier = Promise.resolve(), !this._nativeReady) {
1070
1107
  this._snapshotLoaded = !1;
1071
1108
  return;
1072
1109
  }
@@ -1202,12 +1239,14 @@ import { ICalculateFormulaService } from "@univerjs/engine-formula";
1202
1239
  import { UniverProFormulaEnginePlugin } from "@univerjs-pro/engine-formula";
1203
1240
 
1204
1241
  // package.json
1205
- var name = "@univerjs-pro/engine-formula-rust", version = "1.0.0-insiders.20260809-70eefdd";
1242
+ var name = "@univerjs-pro/engine-formula-rust", version = "1.0.0";
1206
1243
 
1207
1244
  // src/controllers/rust-same-runtime-projection.controller.ts
1208
1245
  import {
1209
1246
  CellValueType as CellValueType2,
1210
1247
  CommandType as CommandType2,
1248
+ createBaseFormulaTableReferenceNormalizer,
1249
+ createBaseFormulaTableNameMap,
1211
1250
  Disposable as Disposable2,
1212
1251
  ICommandService as ICommandService2,
1213
1252
  IUniverInstanceService,
@@ -1242,18 +1281,20 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1242
1281
  _activeDirtyManagerService;
1243
1282
  _initialProjectionLoad = Promise.resolve();
1244
1283
  _projectionDeltaQueue = Promise.resolve();
1284
+ _baseProjectionStructures = /* @__PURE__ */ new Map();
1245
1285
  _initialize() {
1246
1286
  for (let base of this._univerInstanceService.getAllUnitsForType(
1247
1287
  UniverInstanceType.UNIVER_BASE
1248
1288
  ))
1249
- this._rustEngineSyncController.setProjectionManagedTableUnit(base.getUnitId());
1289
+ this._rustEngineSyncController.setProjectionManagedTableUnit(base.getUnitId()), this._rememberBaseProjectionStructure(base.getSnapshot());
1250
1290
  this._initialProjectionLoad = this._loadAllWorkbookProjections(), this.disposeWithMe(
1251
1291
  toDisposable(
1252
1292
  this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_SHEET).subscribe(({ unit }) => {
1253
1293
  this._enqueueProjectionDelta(() => {
1254
1294
  this._rustEngineSyncController.upsertProjectionWorkbook({
1255
1295
  unitId: unit.getUnitId(),
1256
- snapshot: unit.getSnapshot()
1296
+ snapshot: unit.getSnapshot(),
1297
+ styleResolver: unit.getStyles()
1257
1298
  });
1258
1299
  });
1259
1300
  })
@@ -1261,7 +1302,7 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1261
1302
  ), this.disposeWithMe(
1262
1303
  toDisposable(
1263
1304
  this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_BASE).subscribe(({ unit }) => {
1264
- this._rustEngineSyncController.setProjectionManagedTableUnit(unit.getUnitId()), this._enqueueProjectionDelta(() => this._upsertBaseProjection(unit.getUnitId()));
1305
+ this._rustEngineSyncController.setProjectionManagedTableUnit(unit.getUnitId()), this._rememberBaseProjectionStructure(unit.getSnapshot()), this._enqueueProjectionDelta(() => this._upsertBaseProjection(unit.getUnitId()));
1265
1306
  })
1266
1307
  )
1267
1308
  ), this.disposeWithMe(
@@ -1271,7 +1312,7 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1271
1312
  ), this.disposeWithMe(
1272
1313
  toDisposable(
1273
1314
  this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_BASE).subscribe((base) => {
1274
- this._rustEngineSyncController.unsetProjectionManagedTableUnit(base.getUnitId()), this._enqueueProjectionDelta(
1315
+ this._baseProjectionStructures.delete(base.getUnitId()), this._rustEngineSyncController.unsetProjectionManagedTableUnit(base.getUnitId()), this._enqueueProjectionDelta(
1275
1316
  () => this._rustEngineSyncController.disposeProjectionWorkbook(base.getUnitId())
1276
1317
  );
1277
1318
  })
@@ -1295,7 +1336,7 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1295
1336
  if (!this._disposed)
1296
1337
  return task();
1297
1338
  }).catch(() => {
1298
- });
1339
+ }), this._rustEngineSyncController.setProjectionDeltaBarrier(this._projectionDeltaQueue);
1299
1340
  }
1300
1341
  async _syncBaseMutation(command) {
1301
1342
  if (!hasUnitId2(command.params)) return;
@@ -1304,7 +1345,65 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1304
1345
  this._applyBaseDirtyRanges(unitId, dirtyRanges);
1305
1346
  return;
1306
1347
  }
1307
- await this._upsertBaseProjection(unitId);
1348
+ hasStructureInvalidation && this._isBaseProjectionStructureUnchanged(unitId) || hasStructureInvalidation && this._applyBaseFieldInsertion(unitId, dirtyRanges) || await this._upsertBaseProjection(unitId);
1349
+ }
1350
+ _applyBaseFieldInsertion(unitId, dirtyRanges) {
1351
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE), previous = this._baseProjectionStructures.get(unitId);
1352
+ if (!base || !previous) return !1;
1353
+ let snapshot = base.getSnapshot(), insertion = findSingleBaseFieldInsertion(previous, snapshot);
1354
+ if (!insertion) return !1;
1355
+ let projectionData = this._getBaseProjectionData(unitId), sheet = projectionData?.calculationData.allUnitData[unitId]?.[insertion.tableId];
1356
+ if (!projectionData || !sheet) return !1;
1357
+ let formulaData = projectionData.formulaData[unitId]?.[insertion.tableId], cellValue = {};
1358
+ for (let row = 0; row < sheet.rowCount; row++) {
1359
+ let value = sheet.cellData.getValue(row, insertion.column), formula = formulaData?.[row]?.[insertion.column];
1360
+ cellValue[row] = {
1361
+ [insertion.column]: formula ? { ...value, ...formula } : value ?? null
1362
+ };
1363
+ }
1364
+ let insertedRange = {
1365
+ startRow: 0,
1366
+ endRow: Math.max(0, sheet.rowCount - 1),
1367
+ startColumn: insertion.column,
1368
+ endColumn: insertion.column
1369
+ };
1370
+ return this._rustEngineSyncController.applyProjectionMutation({
1371
+ id: "sheet.mutation.insert-col",
1372
+ params: {
1373
+ unitId,
1374
+ subUnitId: insertion.tableId,
1375
+ range: insertedRange
1376
+ },
1377
+ dirtyRanges: []
1378
+ }), this._rustEngineSyncController.applyProjectionMutation({
1379
+ id: "sheet.mutation.set-range-values",
1380
+ params: {
1381
+ unitId,
1382
+ subUnitId: insertion.tableId,
1383
+ cellValue
1384
+ },
1385
+ dirtyRanges: [
1386
+ {
1387
+ unitId,
1388
+ sheetId: insertion.tableId,
1389
+ range: insertedRange
1390
+ }
1391
+ ]
1392
+ }), this._rustEngineSyncController.applyProjectionMutation({
1393
+ id: RUST_SET_SUPER_TABLES_MUTATION_ID,
1394
+ params: {
1395
+ unitId,
1396
+ tables: this._getBaseTableEntries(
1397
+ insertion.tableId,
1398
+ snapshot,
1399
+ createBaseFormulaTableNameMap(snapshot)
1400
+ ).map(([tableName, reference]) => ({
1401
+ tableName,
1402
+ reference
1403
+ }))
1404
+ },
1405
+ dirtyRanges: []
1406
+ }), dirtyRanges.length > 0 && this._applyBaseDirtyRanges(unitId, dirtyRanges), this._rememberBaseProjectionStructure(snapshot), !0;
1308
1407
  }
1309
1408
  _applyBaseDirtyRanges(unitId, dirtyRanges) {
1310
1409
  let projectionData = this._getBaseProjectionData(unitId);
@@ -1346,6 +1445,15 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1346
1445
  formulaData
1347
1446
  );
1348
1447
  workbook && this._rustEngineSyncController.upsertProjectionWorkbook(workbook);
1448
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE);
1449
+ base && this._rememberBaseProjectionStructure(base.getSnapshot());
1450
+ }
1451
+ _rememberBaseProjectionStructure(snapshot) {
1452
+ this._baseProjectionStructures.set(snapshot.id, createBaseProjectionStructure(snapshot));
1453
+ }
1454
+ _isBaseProjectionStructureUnchanged(unitId) {
1455
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE), previous = this._baseProjectionStructures.get(unitId);
1456
+ return !!(base && previous && isSameBaseProjectionStructure(previous, createBaseProjectionStructure(base.getSnapshot())));
1349
1457
  }
1350
1458
  _getBaseProjectionData(unitId) {
1351
1459
  let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE);
@@ -1355,9 +1463,9 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1355
1463
  name: snapshot.name,
1356
1464
  unitType: UniverInstanceType.UNIVER_BASE
1357
1465
  }
1358
- }, formulaData = { [unitId]: {} };
1466
+ }, formulaData = { [unitId]: {} }, formulaTableNames = createBaseFormulaTableNameMap(snapshot), normalizeFormulaTableReferences = createBaseFormulaTableReferenceNormalizer(snapshot, formulaTableNames);
1359
1467
  for (let table of Object.values(snapshot.tables)) {
1360
- let fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] != null);
1468
+ let fieldOrder = table.fieldOrder;
1361
1469
  allUnitData[unitId][table.id] = {
1362
1470
  cellData: new ObjectMatrix2(
1363
1471
  buildBaseRuntimeCellData(table)
@@ -1366,18 +1474,25 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1366
1474
  columnCount: fieldOrder.length,
1367
1475
  rowData: {},
1368
1476
  columnData: {}
1369
- }, unitSheetNameMap[unitId][table.name] = table.id;
1370
- let tableFormulaData = {}, recordOrder = baseRecordOrder(table);
1477
+ }, unitSheetNameMap[unitId][formulaTableNames.get(table.id)] = table.id;
1478
+ let tableFormulaData = {}, normalizedFormulaByFieldId = /* @__PURE__ */ new Map(), recordOrder = baseRecordOrder(table);
1371
1479
  for (let row = 0; row < recordOrder.length; row++)
1372
1480
  if (table.records[recordOrder[row]])
1373
1481
  for (let column = 0; column < fieldOrder.length; column++) {
1374
1482
  let field = table.fields[fieldOrder[column]];
1375
1483
  if (!field || field.type !== "formula") continue;
1376
1484
  let formula = String(field.config?.formula ?? "").trim();
1377
- formula && ((tableFormulaData[row] ??= {})[column] = {
1378
- f: normalizeBaseFormulaForEngine(formula, table, snapshot),
1485
+ if (!formula) continue;
1486
+ let normalizedFormula = normalizedFormulaByFieldId.get(field.id);
1487
+ normalizedFormula == null && (normalizedFormula = normalizeBaseFormulaForEngine(
1488
+ formula,
1489
+ table,
1490
+ formulaTableNames,
1491
+ normalizeFormulaTableReferences
1492
+ ), normalizedFormulaByFieldId.set(field.id, normalizedFormula)), (tableFormulaData[row] ??= {})[column] = {
1493
+ f: normalizedFormula,
1379
1494
  si: field.id
1380
- });
1495
+ };
1381
1496
  }
1382
1497
  formulaData[unitId][table.id] = tableFormulaData;
1383
1498
  }
@@ -1393,7 +1508,8 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1393
1508
  async _loadAllWorkbookProjections() {
1394
1509
  let workbooks = this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_SHEET).map((workbook) => ({
1395
1510
  unitId: workbook.getUnitId(),
1396
- snapshot: workbook.getSnapshot()
1511
+ snapshot: workbook.getSnapshot(),
1512
+ styleResolver: workbook.getStyles()
1397
1513
  })), calculationData = this._formulaDataModel.getCalculateData(), formulaData = this._formulaDataModel.getFormulaData(), baseWorkbooks = this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_BASE).map(
1398
1514
  (base) => this._createBaseWorkbookProjection(
1399
1515
  base.getUnitId(),
@@ -1446,25 +1562,17 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1446
1562
  _createBaseTableResource(unitId) {
1447
1563
  let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE);
1448
1564
  if (base) {
1449
- let snapshot = base.getSnapshot(), tables = Object.values(snapshot.tables), data2 = {};
1450
- for (let table of tables) {
1451
- let recordCount = baseRecordOrder(table).length, fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] != null), tableNames = /* @__PURE__ */ new Set([table.id, getEngineBaseTableName(table, snapshot)]);
1452
- isUniqueBaseTableName(table, snapshot) && tableNames.add(table.name);
1453
- for (let name2 of tableNames)
1565
+ let snapshot = base.getSnapshot(), tables = Object.values(snapshot.tables), formulaTableNames = createBaseFormulaTableNameMap(snapshot), data2 = {};
1566
+ for (let table of tables)
1567
+ for (let [name2, reference] of this._getBaseTableEntries(table.id, snapshot, formulaTableNames)) {
1568
+ let columns = Array.from(reference.titleMap.entries()).toSorted((left, right) => left[1] - right[1]).map(([displayName]) => ({ displayName }));
1454
1569
  (data2[table.id] ??= { tables: [] }).tables.push({
1455
1570
  name: name2,
1456
- range: {
1457
- startRow: 0,
1458
- endRow: Math.max(0, recordCount - 1),
1459
- startColumn: 0,
1460
- endColumn: Math.max(0, fieldOrder.length - 1)
1461
- },
1462
- columns: fieldOrder.map((fieldId) => ({
1463
- displayName: table.fields[fieldId]?.name ?? fieldId
1464
- })),
1465
- options: { showHeader: !1 }
1571
+ range: reference.range,
1572
+ columns,
1573
+ options: { showHeader: reference.showHeader !== !1 }
1466
1574
  });
1467
- }
1575
+ }
1468
1576
  return [
1469
1577
  {
1470
1578
  name: "SHEET_TABLE_PLUGIN",
@@ -1491,6 +1599,22 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1491
1599
  }
1492
1600
  ];
1493
1601
  }
1602
+ _getBaseTableEntries(tableId, snapshot, formulaTableNames) {
1603
+ let table = snapshot.tables[tableId];
1604
+ if (!table) return [];
1605
+ let recordCount = baseRecordOrder(table).length, fieldOrder = table.fieldOrder, reference = {
1606
+ sheetId: table.id,
1607
+ range: {
1608
+ startRow: 0,
1609
+ endRow: Math.max(0, recordCount - 1),
1610
+ startColumn: 0,
1611
+ endColumn: Math.max(0, fieldOrder.length - 1)
1612
+ },
1613
+ titleMap: new Map(fieldOrder.map((fieldId, index) => [table.fields[fieldId]?.name ?? fieldId, index])),
1614
+ showHeader: !1
1615
+ };
1616
+ return [[formulaTableNames.get(table.id), reference]];
1617
+ }
1494
1618
  _rawCellData(cellData) {
1495
1619
  let raw = cellData.getMatrix(), result = {};
1496
1620
  for (let [row, values] of Object.entries(raw ?? {})) {
@@ -1501,16 +1625,58 @@ var RustSameRuntimeProjectionController = class extends Disposable2 {
1501
1625
  }
1502
1626
  return result;
1503
1627
  }
1504
- }, BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g, BASE_TABLE_REFERENCE_PREFIX = /\b[A-Z_][\w.]*\[/gi, BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi, BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w[])\[@\[([^\]]+)\]\](?!\])/g, BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_[\]])\[([^\]]+)\]/g, BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi, BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s![\]]+\[/g;
1505
- function normalizeBaseFormulaForEngine(formula, currentTable, snapshot) {
1506
- let references = [], hold = (reference) => `__BASE_FORMULA_REF_${references.push(reference) - 1}__`;
1507
- return protectBaseTableReferences(protectBaseExternalReferences(formula, hold), hold).replace(
1628
+ };
1629
+ function createBaseProjectionStructure(snapshot) {
1630
+ let formulaTableNames = createBaseFormulaTableNameMap(snapshot);
1631
+ return {
1632
+ unitName: snapshot.name,
1633
+ tables: Object.fromEntries(
1634
+ Object.values(snapshot.tables).map((table) => [
1635
+ table.id,
1636
+ {
1637
+ formulaName: formulaTableNames.get(table.id),
1638
+ fieldOrder: [...table.fieldOrder],
1639
+ recordOrder: baseRecordOrder(table),
1640
+ fieldSignatures: Object.fromEntries(
1641
+ Object.entries(table.fields).map(([fieldId, field]) => [fieldId, JSON.stringify(field)])
1642
+ )
1643
+ }
1644
+ ])
1645
+ )
1646
+ };
1647
+ }
1648
+ function isSameBaseProjectionStructure(left, right) {
1649
+ return JSON.stringify(left) === JSON.stringify(right);
1650
+ }
1651
+ function findSingleBaseFieldInsertion(previous, snapshot) {
1652
+ let current = createBaseProjectionStructure(snapshot), previousTableIds = Object.keys(previous.tables).toSorted(), currentTableIds = Object.keys(current.tables).toSorted();
1653
+ if (JSON.stringify(previousTableIds) !== JSON.stringify(currentTableIds)) return null;
1654
+ let insertion = null;
1655
+ for (let tableId of currentTableIds) {
1656
+ let before = previous.tables[tableId], after = current.tables[tableId];
1657
+ if (!before || !after || before.formulaName !== after.formulaName || JSON.stringify(before.recordOrder) !== JSON.stringify(after.recordOrder)) return null;
1658
+ for (let fieldId of before.fieldOrder)
1659
+ if (before.fieldSignatures[fieldId] !== after.fieldSignatures[fieldId]) return null;
1660
+ if (JSON.stringify(before.fieldOrder) === JSON.stringify(after.fieldOrder)) continue;
1661
+ if (insertion || after.fieldOrder.length !== before.fieldOrder.length + 1) return null;
1662
+ let column = after.fieldOrder.findIndex((fieldId, index) => fieldId !== before.fieldOrder[index]);
1663
+ if (column < 0) return null;
1664
+ let withoutInserted = after.fieldOrder.filter((_, index) => index !== column);
1665
+ if (JSON.stringify(withoutInserted) !== JSON.stringify(before.fieldOrder)) return null;
1666
+ insertion = { tableId, column };
1667
+ }
1668
+ return insertion;
1669
+ }
1670
+ var BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g, BASE_TABLE_REFERENCE_PREFIX = /\b[A-Z_][\w.]*\[/gi, BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi, BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w[])\[@\[([^\]]+)\]\](?!\])/g, BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_[\]])\[([^\]]+)\]/g, BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi, BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s![\]]+\[/g;
1671
+ function normalizeBaseFormulaForEngine(formula, currentTable, formulaTableNames, normalizeFormulaTableReferences) {
1672
+ let canonicalFormula = normalizeFormulaTableReferences(formula), references = [], hold = (reference) => `__BASE_FORMULA_REF_${references.push(reference) - 1}__`;
1673
+ return protectBaseTableReferences(protectBaseExternalReferences(canonicalFormula, hold), hold).replace(
1508
1674
  BASE_LEGACY_FIELD_REF_PATTERN,
1509
- (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))
1675
+ (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))
1510
1676
  ).replace(BASE_SCOPED_FIELD_REF_PATTERN, (_match, prefix, scope, fieldName) => {
1511
- let tableName = getEngineBaseTableName(currentTable, snapshot);
1677
+ let tableName = formulaTableNames.get(currentTable.id) ?? currentTable.name;
1512
1678
  return `${prefix}${hold(`${tableName}[[#${scope}],[${fieldName}]]`)}`;
1513
- }).replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(
1679
+ }).replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(
1514
1680
  /__BASE_FORMULA_REF_(\d+)__/g,
1515
1681
  (_match, index) => references[Number(index)] ?? ""
1516
1682
  );
@@ -1559,37 +1725,21 @@ function isInsideBaseFormulaString(formula, position) {
1559
1725
  }
1560
1726
  return inString;
1561
1727
  }
1562
- function createEngineThisRowRef(table, fieldName, snapshot) {
1563
- return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;
1564
- }
1565
- function getEngineBaseTableName(table, snapshot) {
1566
- return isUniqueBaseTableName(table, snapshot) && isExcelTableName(table.name) ? table.name : createStableExcelTableName(table.id);
1567
- }
1568
- function isUniqueBaseTableName(table, snapshot) {
1569
- let normalizedName = table.name.trim().toLowerCase();
1570
- return Object.values(snapshot.tables).filter((candidate) => candidate.name.trim().toLowerCase() === normalizedName).length === 1;
1571
- }
1572
- function isExcelTableName(name2) {
1573
- return name2.length === 0 || name2.length > 255 || !/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name2) ? !1 : !/^[RC]$/i.test(name2) && !/^[A-Za-z]{1,3}[1-9]\d*$/.test(name2) && !/^R(?:\d+)?C(?:\d+)?$/i.test(name2);
1574
- }
1575
- function createStableExcelTableName(tableId) {
1576
- return `_T_${Array.from(
1577
- tableId,
1578
- (character) => /[A-Za-z0-9]/.test(character) ? character : `_x${character.codePointAt(0)?.toString(16) ?? "0"}_`
1579
- ).join("")}`;
1728
+ function createEngineThisRowRef(table, fieldName, formulaTableNames) {
1729
+ return `${formulaTableNames.get(table.id) ?? table.name}[[#This Row],[${fieldName}]]`;
1580
1730
  }
1581
1731
  function baseRecordOrder(table) {
1582
1732
  return table.recordOrder ? table.recordOrder.filter((recordId) => table.records[recordId] != null) : Object.values(table.records ?? {}).toSorted((left, right) => left.orderKey.localeCompare(right.orderKey)).map((record) => record.id);
1583
1733
  }
1584
1734
  function buildBaseRuntimeCellData(table) {
1585
- let cellData = { ...table.cellData }, fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] != null), recordOrder = baseRecordOrder(table);
1735
+ let cellData = { ...table.cellData }, fieldOrder = table.fieldOrder, recordOrder = baseRecordOrder(table);
1586
1736
  for (let row = 0; row < recordOrder.length; row++) {
1587
1737
  let record = table.records[recordOrder[row]];
1588
1738
  if (record) {
1589
1739
  cellData[row] = { ...cellData[row] };
1590
1740
  for (let column = 0; column < fieldOrder.length; column++) {
1591
1741
  let fieldId = fieldOrder[column];
1592
- Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId) && (cellData[row][column] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]));
1742
+ table.fields[fieldId] && Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId) && (cellData[row][column] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]));
1593
1743
  }
1594
1744
  }
1595
1745
  }
@@ -1645,6 +1795,7 @@ import {
1645
1795
  FormulaExecuteStageType,
1646
1796
  IFeatureCalculationManagerService,
1647
1797
  IFormulaCurrentConfigService,
1798
+ IDefinedNamesService,
1648
1799
  IFormulaDependencyGenerator,
1649
1800
  IFormulaRuntimeService,
1650
1801
  IOtherFormulaManagerService,
@@ -1701,7 +1852,7 @@ function resultBatchSheetCounts(output) {
1701
1852
  return counts;
1702
1853
  }
1703
1854
  var RustCalculateFormulaService = class extends Disposable3 {
1704
- constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService) {
1855
+ constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService, _definedNamesService) {
1705
1856
  super();
1706
1857
  this._configService = _configService;
1707
1858
  this._currentConfigService = _currentConfigService;
@@ -1715,6 +1866,7 @@ var RustCalculateFormulaService = class extends Disposable3 {
1715
1866
  this._formulaReferenceDataService = _formulaReferenceDataService;
1716
1867
  this._excelExternalReferenceModel = _excelExternalReferenceModel;
1717
1868
  this._superTableService = _superTableService;
1869
+ this._definedNamesService = _definedNamesService;
1718
1870
  this._commandService.hasCommand(SetFormulaCalculationResultMutation2.id) || this.disposeWithMe(this._commandService.registerCommand(SetFormulaCalculationResultMutation2)), this._commandService.hasCommand(SetArrayFormulaDataMutation.id) || this.disposeWithMe(this._commandService.registerCommand(SetArrayFormulaDataMutation));
1719
1871
  }
1720
1872
  _configService;
@@ -1729,6 +1881,7 @@ var RustCalculateFormulaService = class extends Disposable3 {
1729
1881
  _formulaReferenceDataService;
1730
1882
  _excelExternalReferenceModel;
1731
1883
  _superTableService;
1884
+ _definedNamesService;
1732
1885
  _executionInProgressListener$ = new Subject();
1733
1886
  executionInProgressListener$ = this._executionInProgressListener$.asObservable();
1734
1887
  _executionCompleteListener$ = new Subject();
@@ -2226,16 +2379,23 @@ var RustCalculateFormulaService = class extends Disposable3 {
2226
2379
  if (!unitData) return result;
2227
2380
  for (let [unitId, sheets] of Object.entries(unitData)) {
2228
2381
  result[unitId] = {};
2382
+ let styles = this._currentConfigService.getUnitStylesData()[unitId], sheetNames = Object.fromEntries(
2383
+ Object.entries(this._currentConfigService.getSheetNameMap()[unitId] ?? {}).map(([name2, id]) => [
2384
+ id,
2385
+ name2
2386
+ ])
2387
+ );
2229
2388
  for (let [sheetId, sheet] of Object.entries(sheets))
2230
2389
  result[unitId][sheetId] = {
2231
- cellData: this._serializeCellData(sheet.cellData),
2390
+ name: sheetNames[sheetId],
2391
+ cellData: this._serializeCellData(sheet.cellData, styles),
2232
2392
  rowCount: sheet.rowCount ?? 0,
2233
2393
  columnCount: sheet.columnCount ?? 0
2234
2394
  };
2235
2395
  }
2236
2396
  return result;
2237
2397
  }
2238
- _serializeCellData(cellData) {
2398
+ _serializeCellData(cellData, styles) {
2239
2399
  let result = {};
2240
2400
  if (!cellData || typeof cellData != "object") return result;
2241
2401
  let data = typeof cellData.getMatrix == "function" ? cellData.getMatrix() : cellData;
@@ -2245,13 +2405,23 @@ var RustCalculateFormulaService = class extends Disposable3 {
2245
2405
  result[row] = {};
2246
2406
  for (let [colStr, cell] of Object.entries(cols)) {
2247
2407
  let col = Number(colStr);
2248
- Number.isFinite(col) && (result[row][col] = {
2408
+ if (!Number.isFinite(col))
2409
+ continue;
2410
+ result[row][col] = {
2249
2411
  v: cell?.v ?? null,
2250
2412
  t: cell?.t ?? void 0,
2251
2413
  p: cell?.p ?? void 0,
2252
2414
  f: cell?.f ?? void 0,
2253
2415
  s: cell?.s ?? void 0
2254
- });
2416
+ };
2417
+ let style = styles?.getStyleByCell(cell);
2418
+ if (style && typeof style == "object") {
2419
+ let numberFormat = style.n;
2420
+ if (numberFormat && typeof numberFormat == "object") {
2421
+ let pattern = numberFormat.pattern;
2422
+ typeof pattern == "string" && (result[row][col].numberFormat = pattern);
2423
+ }
2424
+ }
2255
2425
  }
2256
2426
  }
2257
2427
  }
@@ -2260,7 +2430,9 @@ var RustCalculateFormulaService = class extends Disposable3 {
2260
2430
  _applyRustOutput(_output) {
2261
2431
  }
2262
2432
  async _applyRustDependencyOutput(output) {
2263
- let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output), convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2433
+ let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output);
2434
+ this._mergeRuntimeUnitData(patch.unitData);
2435
+ let convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2264
2436
  return (patch.arrayFormulaRange || patch.arrayFormulaCellData) && (this._formulaDataModel.setArrayFormulaRange(patch.arrayFormulaRange ?? {}), this._formulaDataModel.setArrayFormulaCellData(patch.arrayFormulaCellData ?? {}), await this._commandService.executeCommand(
2265
2437
  SetArrayFormulaDataMutation.id,
2266
2438
  {
@@ -2287,6 +2459,20 @@ var RustCalculateFormulaService = class extends Disposable3 {
2287
2459
  commandMs: performance.now() - commandStartedAt
2288
2460
  };
2289
2461
  }
2462
+ _mergeRuntimeUnitData(unitData) {
2463
+ let runtimeUnitData = this._runtimeService.getUnitData();
2464
+ Object.entries(unitData).forEach(([unitId, sheetMap]) => {
2465
+ if (!sheetMap) return;
2466
+ let runtimeSheetMap = runtimeUnitData[unitId] ??= {};
2467
+ Object.entries(sheetMap).forEach(([sheetId, cellData]) => {
2468
+ if (!cellData) return;
2469
+ let runtimeMatrix = runtimeSheetMap[sheetId] ??= new ObjectMatrix3();
2470
+ new ObjectMatrix3(cellData).forValue((row, column, cell) => {
2471
+ runtimeMatrix.setValue(row, column, cell);
2472
+ });
2473
+ });
2474
+ });
2475
+ }
2290
2476
  async calculate(formulaString) {
2291
2477
  this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0);
2292
2478
  let unitId = "__rust_formula_calculate__", sheetId = "__sheet__", input = {
@@ -2314,13 +2500,25 @@ var RustCalculateFormulaService = class extends Disposable3 {
2314
2500
  }
2315
2501
  async executeFormulas(formulas, rowData) {
2316
2502
  this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._currentConfigService.loadDataLite(rowData);
2317
- let unitData = this._currentConfigService.getUnitData(), formulaData = this._formulaStringMapToFormulaData(formulas), input = {
2503
+ let unitData = this._currentConfigService.getUnitData(), definedNames = {};
2504
+ for (let [unitId, names] of Object.entries(this._definedNamesService.getAllDefinedNames()))
2505
+ for (let [id, name2] of Object.entries(names))
2506
+ definedNames[JSON.stringify([unitId, id])] = {
2507
+ unitId,
2508
+ localSheetId: name2.localSheetId === "AllDefaultWorkbook" ? void 0 : name2.localSheetId,
2509
+ name: name2.name,
2510
+ formula: name2.formulaOrRefString
2511
+ };
2512
+ let input = {
2318
2513
  config: { maxIteration: 1, intervalCount: DEFAULT_INTERVAL_COUNT },
2319
- formulaData,
2514
+ formulaData: {},
2515
+ queryFormulas: this._formulaStringMapToQueryData(formulas),
2320
2516
  unitData: this._serializeUnitData(unitData),
2321
2517
  dirtyRanges: [],
2322
- definedNames: {}
2518
+ definedNames
2323
2519
  }, output = JSON.parse(executeOnRust(JSON.stringify(input)));
2520
+ if (!output.queryResults)
2521
+ throw new Error("Native formula binding does not support independent formula queries");
2324
2522
  return this._formulaExecutionOutputToResultMap(formulas, output);
2325
2523
  }
2326
2524
  async getAllDependencyJson(_rowData) {
@@ -2363,7 +2561,7 @@ var RustCalculateFormulaService = class extends Disposable3 {
2363
2561
  ]);
2364
2562
  return { dependents, inRanges };
2365
2563
  }
2366
- _formulaStringMapToFormulaData(formulas) {
2564
+ _formulaStringMapToQueryData(formulas) {
2367
2565
  let formulaData = {};
2368
2566
  return Object.entries(formulas).forEach(([unitId, sheetMap]) => {
2369
2567
  sheetMap && (formulaData[unitId] = {}, Object.entries(sheetMap).forEach(([sheetId, rowMap]) => {
@@ -2371,8 +2569,7 @@ var RustCalculateFormulaService = class extends Disposable3 {
2371
2569
  if (!colMap) return;
2372
2570
  let row = Number(rowKey);
2373
2571
  formulaData[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2374
- let formula = Array.isArray(formulaList) ? formulaList[0] : void 0;
2375
- typeof formula == "string" && (formulaData[unitId][sheetId][row][Number(colKey)] = formula);
2572
+ Array.isArray(formulaList) && (formulaData[unitId][sheetId][row][Number(colKey)] = formulaList);
2376
2573
  });
2377
2574
  }));
2378
2575
  }));
@@ -2386,10 +2583,13 @@ var RustCalculateFormulaService = class extends Disposable3 {
2386
2583
  if (!colMap) return;
2387
2584
  let row = Number(rowKey);
2388
2585
  result[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2389
- let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [], value = normalizeFormulaResultValue(
2390
- output.runtimeData?.[unitId]?.[sheetId]?.[row]?.[col]
2391
- );
2392
- result[unitId][sheetId][row][col] = formulasForCell.map((formula) => ({ formula, value }));
2586
+ let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [];
2587
+ result[unitId][sheetId][row][col] = formulasForCell.map((formula, index) => ({
2588
+ formula,
2589
+ value: normalizeFormulaResultValue(
2590
+ output.queryResults?.[unitId]?.[sheetId]?.[row]?.[col]?.[index]?.value
2591
+ )
2592
+ }));
2393
2593
  });
2394
2594
  }));
2395
2595
  }));
@@ -2508,7 +2708,8 @@ setDependencies3(RustCalculateFormulaService, [
2508
2708
  FormulaDataModel2,
2509
2709
  IFormulaReferenceDataService,
2510
2710
  ExternalReferenceModel,
2511
- ISuperTableService2
2711
+ ISuperTableService2,
2712
+ IDefinedNamesService
2512
2713
  ]);
2513
2714
  function createRustProductExternalSyntheticUnitId(hostUnitId, referenceId) {
2514
2715
  return `external:product:${encodeURIComponent(hostUnitId)}:${encodeURIComponent(referenceId)}`;