@odoo/o-spreadsheet 16.3.1 → 16.4.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1114,6 +1114,21 @@
1114
1114
  }
1115
1115
  }
1116
1116
  return true;
1117
+ }
1118
+ class JetSet extends Set {
1119
+ add(...iterable) {
1120
+ for (const element of iterable) {
1121
+ super.add(element);
1122
+ }
1123
+ return this;
1124
+ }
1125
+ delete(...iterable) {
1126
+ let deleted = false;
1127
+ for (const element of iterable) {
1128
+ deleted ||= super.delete(element);
1129
+ }
1130
+ return deleted;
1131
+ }
1117
1132
  }
1118
1133
 
1119
1134
  const RBA_REGEX = /rgba?\(|\s+|\)/gi;
@@ -2884,6 +2899,14 @@
2884
2899
  }
2885
2900
  return positions;
2886
2901
  }
2902
+ function forEachPositionsInZone(zone, callback) {
2903
+ const { left, right, top, bottom } = zone;
2904
+ for (let col = left; col <= right; col++) {
2905
+ for (let row = top; row <= bottom; row++) {
2906
+ callback(col, row);
2907
+ }
2908
+ }
2909
+ }
2887
2910
  /**
2888
2911
  * This function returns a zone with coordinates modified according to the change
2889
2912
  * applied to the zone. It may be possible to change the zone by resizing or moving
@@ -4184,6 +4207,11 @@
4184
4207
  "INSERT_CELL",
4185
4208
  "UNDO",
4186
4209
  "REDO",
4210
+ "ADD_MERGE",
4211
+ ]);
4212
+ const invalidateDependenciesCommands = new Set([
4213
+ ...invalidateEvaluationCommands,
4214
+ "MOVE_RANGES",
4187
4215
  ]);
4188
4216
  const invalidateCFEvaluationCommands = new Set([
4189
4217
  ...invalidateEvaluationCommands,
@@ -4401,6 +4429,9 @@
4401
4429
  })(exports.CommandResult || (exports.CommandResult = {}));
4402
4430
 
4403
4431
  const borderStyles = ["thin", "medium", "thick", "dashed", "dotted"];
4432
+ function isMatrix(x) {
4433
+ return Array.isArray(x) && Array.isArray(x[0]);
4434
+ }
4404
4435
  var DIRECTION;
4405
4436
  (function (DIRECTION) {
4406
4437
  DIRECTION["UP"] = "up";
@@ -10366,7 +10397,7 @@
10366
10397
  ],
10367
10398
  returns: ["NUMBER"],
10368
10399
  computeFormat: (factor1) => {
10369
- return Array.isArray(factor1) ? factor1[0][0]?.format : factor1?.format;
10400
+ return Array.isArray(factor1?.format) ? factor1.format[0][0] : factor1?.format;
10370
10401
  },
10371
10402
  compute: function (...factors) {
10372
10403
  let count = 0;
@@ -10592,7 +10623,7 @@
10592
10623
  ],
10593
10624
  returns: ["NUMBER"],
10594
10625
  computeFormat: (value1) => {
10595
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
10626
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
10596
10627
  },
10597
10628
  compute: function (...values) {
10598
10629
  return reduceNumbers(values, (acc, a) => acc + a, 0);
@@ -10864,7 +10895,7 @@
10864
10895
  ],
10865
10896
  returns: ["NUMBER"],
10866
10897
  computeFormat: (value1) => {
10867
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
10898
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
10868
10899
  },
10869
10900
  compute: function (...values) {
10870
10901
  let count = 0;
@@ -10892,7 +10923,7 @@
10892
10923
  ],
10893
10924
  returns: ["NUMBER"],
10894
10925
  computeFormat: (values) => {
10895
- return Array.isArray(values) ? values[0][0]?.format : values?.format;
10926
+ return Array.isArray(values?.format) ? values.format[0][0] : values?.format;
10896
10927
  },
10897
10928
  compute: function (...values) {
10898
10929
  let sum = 0;
@@ -10950,7 +10981,7 @@
10950
10981
  ],
10951
10982
  returns: ["NUMBER"],
10952
10983
  computeFormat: (value1) => {
10953
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
10984
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
10954
10985
  },
10955
10986
  compute: function (...values) {
10956
10987
  let count = 0;
@@ -11123,7 +11154,7 @@
11123
11154
  ],
11124
11155
  returns: ["NUMBER"],
11125
11156
  computeFormat: (data) => {
11126
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11157
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11127
11158
  },
11128
11159
  compute: function (data, n) {
11129
11160
  const _n = Math.trunc(toNumber(n));
@@ -11159,7 +11190,7 @@
11159
11190
  ],
11160
11191
  returns: ["NUMBER"],
11161
11192
  computeFormat: (value1) => {
11162
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
11193
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
11163
11194
  },
11164
11195
  compute: function (...values) {
11165
11196
  const result = reduceNumbers(values, (acc, a) => (acc < a ? a : acc), -Infinity);
@@ -11178,7 +11209,7 @@
11178
11209
  ],
11179
11210
  returns: ["NUMBER"],
11180
11211
  computeFormat: (value1) => {
11181
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
11212
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
11182
11213
  },
11183
11214
  compute: function (...values) {
11184
11215
  const maxa = reduceNumbersTextAs0(values, (acc, a) => {
@@ -11224,7 +11255,7 @@
11224
11255
  ],
11225
11256
  returns: ["NUMBER"],
11226
11257
  computeFormat: (value1) => {
11227
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
11258
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
11228
11259
  },
11229
11260
  compute: function (...values) {
11230
11261
  let data = [];
@@ -11246,7 +11277,7 @@
11246
11277
  ],
11247
11278
  returns: ["NUMBER"],
11248
11279
  computeFormat: (value1) => {
11249
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
11280
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
11250
11281
  },
11251
11282
  compute: function (...values) {
11252
11283
  const result = reduceNumbers(values, (acc, a) => (a < acc ? a : acc), Infinity);
@@ -11265,7 +11296,7 @@
11265
11296
  ],
11266
11297
  returns: ["NUMBER"],
11267
11298
  computeFormat: (value1) => {
11268
- return Array.isArray(value1) ? value1[0][0]?.format : value1?.format;
11299
+ return Array.isArray(value1?.format) ? value1.format[0][0] : value1?.format;
11269
11300
  },
11270
11301
  compute: function (...values) {
11271
11302
  const mina = reduceNumbersTextAs0(values, (acc, a) => {
@@ -11311,7 +11342,7 @@
11311
11342
  ],
11312
11343
  returns: ["NUMBER"],
11313
11344
  computeFormat: (data) => {
11314
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11345
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11315
11346
  },
11316
11347
  compute: function (data, percentile) {
11317
11348
  return PERCENTILE_INC.compute(data, percentile);
@@ -11329,7 +11360,7 @@
11329
11360
  ],
11330
11361
  returns: ["NUMBER"],
11331
11362
  computeFormat: (data) => {
11332
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11363
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11333
11364
  },
11334
11365
  compute: function (data, percentile) {
11335
11366
  return centile([data], percentile, false);
@@ -11347,7 +11378,7 @@
11347
11378
  ],
11348
11379
  returns: ["NUMBER"],
11349
11380
  computeFormat: (data) => {
11350
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11381
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11351
11382
  },
11352
11383
  compute: function (data, percentile) {
11353
11384
  return centile([data], percentile, true);
@@ -11365,7 +11396,7 @@
11365
11396
  ],
11366
11397
  returns: ["NUMBER"],
11367
11398
  computeFormat: (data) => {
11368
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11399
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11369
11400
  },
11370
11401
  compute: function (data, quartileNumber) {
11371
11402
  return QUARTILE_INC.compute(data, quartileNumber);
@@ -11383,7 +11414,7 @@
11383
11414
  ],
11384
11415
  returns: ["NUMBER"],
11385
11416
  computeFormat: (data) => {
11386
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11417
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11387
11418
  },
11388
11419
  compute: function (data, quartileNumber) {
11389
11420
  const _quartileNumber = Math.trunc(toNumber(quartileNumber));
@@ -11402,7 +11433,7 @@
11402
11433
  ],
11403
11434
  returns: ["NUMBER"],
11404
11435
  computeFormat: (data) => {
11405
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11436
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11406
11437
  },
11407
11438
  compute: function (data, quartileNumber) {
11408
11439
  const _quartileNumber = Math.trunc(toNumber(quartileNumber));
@@ -11421,7 +11452,7 @@
11421
11452
  ],
11422
11453
  returns: ["NUMBER"],
11423
11454
  computeFormat: (data) => {
11424
- return Array.isArray(data) ? data[0][0]?.format : data?.format;
11455
+ return Array.isArray(data?.format) ? data.format[0][0] : data?.format;
11425
11456
  },
11426
11457
  compute: function (data, n) {
11427
11458
  const _n = Math.trunc(toNumber(n));
@@ -16208,17 +16239,11 @@
16208
16239
  return undefined;
16209
16240
  }
16210
16241
  if (typeof arg === "function") {
16211
- return () => _extractArgValuesFromArgs(arg());
16242
+ return () => arg()?.value;
16212
16243
  }
16213
- return _extractArgValuesFromArgs(arg);
16244
+ return arg.value;
16214
16245
  });
16215
16246
  }
16216
- function _extractArgValuesFromArgs(arg) {
16217
- if (Array.isArray(arg)) {
16218
- return arg.map((col) => col.map((simpleArg) => simpleArg?.value));
16219
- }
16220
- return arg?.value;
16221
- }
16222
16247
  const functionRegistry = new FunctionRegistry();
16223
16248
  for (let category of categories) {
16224
16249
  const fns = category.functions;
@@ -20758,7 +20783,7 @@
20758
20783
  argToFocus: Number,
20759
20784
  };
20760
20785
 
20761
- const functions$2 = functionRegistry.content;
20786
+ const functions$3 = functionRegistry.content;
20762
20787
  const ASSISTANT_WIDTH = 300;
20763
20788
  const selectionIndicatorClass = "selector-flag";
20764
20789
  const selectionIndicatorColor = "#a9a9a9";
@@ -21260,7 +21285,7 @@
21260
21285
  // initialize Formula Assistant
21261
21286
  const tokenContext = tokenAtCursor.functionContext;
21262
21287
  const parentFunction = tokenContext.parent.toUpperCase();
21263
- const description = functions$2[parentFunction];
21288
+ const description = functions$3[parentFunction];
21264
21289
  const argPosition = tokenContext.argPosition;
21265
21290
  this.functionDescriptionState.functionName = parentFunction;
21266
21291
  this.functionDescriptionState.functionDescription = description;
@@ -22131,6 +22156,21 @@
22131
22156
  onFigureDeleted: Function,
22132
22157
  };
22133
22158
 
22159
+ /**
22160
+ * Manages an event listener on a ref. Useful for hooks that want to manage
22161
+ * event listeners, especially more than one. Prefer using t-on directly in
22162
+ * components. If your hook only needs a single event listener, consider simply
22163
+ * returning it from the hook and letting the user attach it with t-on.
22164
+ *
22165
+ * Adapted from Odoo Community - See https://github.com/odoo/odoo/blob/saas-16.2/addons/web/static/src/core/utils/hooks.js
22166
+ */
22167
+ function useRefListener(ref, ...listener) {
22168
+ owl.useEffect((el) => {
22169
+ el?.addEventListener(...listener);
22170
+ return () => el?.removeEventListener(...listener);
22171
+ }, () => [ref.el]);
22172
+ }
22173
+
22134
22174
  /**
22135
22175
  * Repeatedly calls a callback function with a time delay between calls.
22136
22176
  */
@@ -22193,20 +22233,10 @@
22193
22233
  setPosition(undefined, undefined);
22194
22234
  }
22195
22235
  }
22196
- owl.onMounted(() => {
22197
- const grid = gridRef.el;
22198
- grid.addEventListener("mousemove", updateMousePosition);
22199
- grid.addEventListener("mouseleave", pause);
22200
- grid.addEventListener("mouseenter", resume);
22201
- grid.addEventListener("mousedown", recompute);
22202
- });
22203
- owl.onWillUnmount(() => {
22204
- const grid = gridRef.el;
22205
- grid.removeEventListener("mousemove", updateMousePosition);
22206
- grid.removeEventListener("mouseleave", pause);
22207
- grid.removeEventListener("mouseenter", resume);
22208
- grid.removeEventListener("mousedown", recompute);
22209
- });
22236
+ useRefListener(gridRef, "mousemove", updateMousePosition);
22237
+ useRefListener(gridRef, "mouseleave", pause);
22238
+ useRefListener(gridRef, "mouseenter", resume);
22239
+ useRefListener(gridRef, "mousedown", recompute);
22210
22240
  function setPosition(col, row) {
22211
22241
  if (col !== hoveredPosition.col || row !== hoveredPosition.row) {
22212
22242
  hoveredPosition.col = col;
@@ -22245,16 +22275,9 @@
22245
22275
  x = currentX;
22246
22276
  y = currentY;
22247
22277
  }
22248
- owl.onMounted(() => {
22249
- gridRef.el.addEventListener("touchstart", onTouchStart);
22250
- gridRef.el.addEventListener("touchend", onTouchEnd);
22251
- gridRef.el.addEventListener("touchmove", onTouchMove);
22252
- });
22253
- owl.onWillUnmount(() => {
22254
- gridRef.el.removeEventListener("touchstart", onTouchStart);
22255
- gridRef.el.removeEventListener("touchend", onTouchEnd);
22256
- gridRef.el.removeEventListener("touchmove", onTouchMove);
22257
- });
22278
+ useRefListener(gridRef, "touchstart", onTouchStart);
22279
+ useRefListener(gridRef, "touchend", onTouchEnd);
22280
+ useRefListener(gridRef, "touchmove", onTouchMove);
22258
22281
  }
22259
22282
  class GridOverlay extends owl.Component {
22260
22283
  static template = "o-spreadsheet-GridOverlay";
@@ -25105,7 +25128,7 @@
25105
25128
  * is useful for the composer, which needs to be able to work with incomplete
25106
25129
  * formulas.
25107
25130
  */
25108
- const functions$1 = functionRegistry.content;
25131
+ const functions$2 = functionRegistry.content;
25109
25132
  const POSTFIX_UNARY_OPERATORS = ["%"];
25110
25133
  const OPERATORS = "+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(POSTFIX_UNARY_OPERATORS);
25111
25134
  function tokenize(str) {
@@ -25228,7 +25251,7 @@
25228
25251
  }
25229
25252
  if (result.length) {
25230
25253
  const value = result;
25231
- const isFunction = value.toUpperCase() in functions$1;
25254
+ const isFunction = value.toUpperCase() in functions$2;
25232
25255
  if (isFunction) {
25233
25256
  return { type: "FUNCTION", value };
25234
25257
  }
@@ -25698,7 +25721,7 @@
25698
25721
  return result;
25699
25722
  }
25700
25723
 
25701
- const functions = functionRegistry.content;
25724
+ const functions$1 = functionRegistry.content;
25702
25725
  const OPERATOR_MAP = {
25703
25726
  "=": "EQ",
25704
25727
  "+": "ADD",
@@ -25761,56 +25784,32 @@
25761
25784
  * between a cell value and a non cell value.
25762
25785
  */
25763
25786
  function compileFunctionArgs(ast) {
25764
- const functionDefinition = functions[ast.value.toUpperCase()];
25765
- const currentFunctionArguments = ast.args;
25766
- // check if arguments are supplied in the correct quantities
25767
- const nbrArg = currentFunctionArguments.length;
25768
- if (nbrArg < functionDefinition.minArgRequired) {
25769
- throw new BadExpressionError(_lt("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.", ast.value.toUpperCase(), functionDefinition.minArgRequired.toString(), nbrArg.toString()));
25770
- }
25771
- if (nbrArg > functionDefinition.maxArgPossible) {
25772
- throw new BadExpressionError(_lt("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.", ast.value.toUpperCase(), functionDefinition.maxArgPossible.toString(), nbrArg.toString()));
25773
- }
25774
- const repeatingArg = functionDefinition.nbrArgRepeating;
25775
- if (repeatingArg > 1) {
25776
- const argBeforeRepeat = functionDefinition.args.length - repeatingArg;
25777
- const nbrRepeatingArg = nbrArg - argBeforeRepeat;
25778
- if (nbrRepeatingArg % repeatingArg !== 0) {
25779
- throw new BadExpressionError(_lt("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments", ast.value.toUpperCase(), argBeforeRepeat.toString(), repeatingArg.toString()));
25780
- }
25781
- }
25782
- let compiledArgs = [];
25783
- for (let i = 0; i < nbrArg; i++) {
25784
- const argPosition = functionDefinition.getArgToFocus(i + 1) - 1;
25785
- if (0 <= argPosition && argPosition < functionDefinition.args.length) {
25786
- const currentArg = currentFunctionArguments[i];
25787
- const argDefinition = functionDefinition.args[argPosition];
25788
- const argTypes = argDefinition.type || [];
25789
- // detect when an argument need to be evaluated as a meta argument
25790
- const isMeta = argTypes.includes("META");
25791
- // detect when an argument need to be evaluated as a lazy argument
25792
- const isLazy = argDefinition.lazy;
25793
- const hasRange = argTypes.some((t) => t === "RANGE" ||
25794
- t === "RANGE<BOOLEAN>" ||
25795
- t === "RANGE<DATE>" ||
25796
- t === "RANGE<NUMBER>" ||
25797
- t === "RANGE<STRING>");
25798
- const isRangeOnly = argTypes.every((t) => t === "RANGE" ||
25799
- t === "RANGE<BOOLEAN>" ||
25800
- t === "RANGE<DATE>" ||
25801
- t === "RANGE<NUMBER>" ||
25802
- t === "RANGE<STRING>");
25803
- if (isRangeOnly) {
25804
- if (currentArg.type !== "REFERENCE") {
25805
- throw new BadExpressionError(_lt("Function %s expects the parameter %s to be reference to a cell or range, not a %s.", ast.value.toUpperCase(), (i + 1).toString(), currentArg.type.toLowerCase()));
25806
- }
25787
+ const { args } = ast;
25788
+ const functionName = ast.value.toUpperCase();
25789
+ const functionDefinition = functions$1[functionName];
25790
+ assertEnoughArgs(ast);
25791
+ const compiledArgs = [];
25792
+ for (let i = 0; i < args.length; i++) {
25793
+ const argToFocus = functionDefinition.getArgToFocus(i + 1) - 1;
25794
+ const argDefinition = functionDefinition.args[argToFocus];
25795
+ const currentArg = args[i];
25796
+ const argTypes = argDefinition.type || [];
25797
+ // detect when an argument need to be evaluated as a meta argument
25798
+ const isMeta = argTypes.includes("META");
25799
+ // detect when an argument need to be evaluated as a lazy argument
25800
+ const isLazy = argDefinition.lazy;
25801
+ const hasRange = argTypes.some((t) => isRangeType(t));
25802
+ const isRangeOnly = argTypes.every((t) => isRangeType(t));
25803
+ if (isRangeOnly) {
25804
+ if (!isRangeInput(currentArg)) {
25805
+ throw new BadExpressionError(_lt("Function %s expects the parameter %s to be reference to a cell or range, not a %s.", functionName, (i + 1).toString(), currentArg.type.toLowerCase()));
25807
25806
  }
25808
- const compiledAST = compileAST(currentArg, isMeta, hasRange, {
25809
- functionName: ast.value.toUpperCase(),
25810
- paramIndex: i + 1,
25811
- });
25812
- compiledArgs.push(isLazy ? compiledAST.wrapInClosure() : compiledAST);
25813
25807
  }
25808
+ const compiledAST = compileAST(currentArg, isMeta, hasRange, {
25809
+ functionName,
25810
+ paramIndex: i + 1,
25811
+ });
25812
+ compiledArgs.push(isLazy ? compiledAST.wrapInClosure() : compiledAST);
25814
25813
  }
25815
25814
  return compiledArgs;
25816
25815
  }
@@ -25954,6 +25953,41 @@
25954
25953
  dependencies,
25955
25954
  constantValues,
25956
25955
  };
25956
+ }
25957
+ /**
25958
+ * Check if arguments are supplied in the correct quantities
25959
+ */
25960
+ function assertEnoughArgs(ast) {
25961
+ const nbrArg = ast.args.length;
25962
+ const functionName = ast.value.toUpperCase();
25963
+ const functionDefinition = functions$1[functionName];
25964
+ if (nbrArg < functionDefinition.minArgRequired) {
25965
+ throw new BadExpressionError(_lt("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.", functionName, functionDefinition.minArgRequired.toString(), nbrArg.toString()));
25966
+ }
25967
+ if (nbrArg > functionDefinition.maxArgPossible) {
25968
+ throw new BadExpressionError(_lt("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.", functionName, functionDefinition.maxArgPossible.toString(), nbrArg.toString()));
25969
+ }
25970
+ const repeatableArgs = functionDefinition.nbrArgRepeating;
25971
+ if (repeatableArgs > 1) {
25972
+ const unrepeatableArgs = functionDefinition.args.length - repeatableArgs;
25973
+ const repeatingArgs = nbrArg - unrepeatableArgs;
25974
+ if (repeatingArgs % repeatableArgs !== 0) {
25975
+ throw new BadExpressionError(_lt("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments", functionName, unrepeatableArgs.toString(), repeatableArgs.toString()));
25976
+ }
25977
+ }
25978
+ }
25979
+ function isRangeType(type) {
25980
+ return type.startsWith("RANGE");
25981
+ }
25982
+ function isRangeInput(arg) {
25983
+ if (arg.type === "REFERENCE") {
25984
+ return true;
25985
+ }
25986
+ if (arg.type === "FUNCALL") {
25987
+ const fnDef = functions$1[arg.value.toUpperCase()];
25988
+ return fnDef && isRangeType(fnDef.returns[0]);
25989
+ }
25990
+ return false;
25957
25991
  }
25958
25992
 
25959
25993
  /**
@@ -26070,16 +26104,6 @@
26070
26104
  // -------------------------------------
26071
26105
  // WORKSHEET HELPERS
26072
26106
  // -------------------------------------
26073
- function getCellType(value) {
26074
- switch (typeof value) {
26075
- case "boolean":
26076
- return "b";
26077
- case "string":
26078
- return "str";
26079
- case "number":
26080
- return "n";
26081
- }
26082
- }
26083
26107
  function convertHeightToExcel(height) {
26084
26108
  return Math.round(HEIGHT_FACTOR * height * 100) / 100;
26085
26109
  }
@@ -29766,23 +29790,7 @@
29766
29790
  */
29767
29791
  createFormulaCellWithDependencies(id, compiledFormula, format, style, sheetId) {
29768
29792
  const dependencies = compiledFormula.dependencies.map((xc) => this.getters.getRangeFromSheetXC(sheetId, xc));
29769
- const buildFormulaContent = this.buildFormulaContent.bind(this);
29770
- // Only for formulas with dependencies because
29771
- // **the closure is expensive memory-wise**
29772
- return {
29773
- id,
29774
- get content() {
29775
- return buildFormulaContent(sheetId, {
29776
- dependencies: this.dependencies,
29777
- compiledFormula: this.compiledFormula,
29778
- });
29779
- },
29780
- style,
29781
- format,
29782
- isFormula: true,
29783
- compiledFormula,
29784
- dependencies,
29785
- };
29793
+ return new FormulaCellWithDependencies(id, compiledFormula, format, style, dependencies, sheetId, this.buildFormulaContent.bind(this));
29786
29794
  }
29787
29795
  createErrorFormula(id, content, format, style, error) {
29788
29796
  return {
@@ -29808,6 +29816,31 @@
29808
29816
  const sheetZone = this.getters.getSheetZone(sheetId);
29809
29817
  return isInside(col, row, sheetZone) ? 0 /* CommandResult.Success */ : 18 /* CommandResult.TargetOutOfSheet */;
29810
29818
  }
29819
+ }
29820
+ class FormulaCellWithDependencies {
29821
+ id;
29822
+ compiledFormula;
29823
+ format;
29824
+ style;
29825
+ dependencies;
29826
+ sheetId;
29827
+ buildFormulaContent;
29828
+ isFormula = true;
29829
+ constructor(id, compiledFormula, format, style, dependencies, sheetId, buildFormulaContent) {
29830
+ this.id = id;
29831
+ this.compiledFormula = compiledFormula;
29832
+ this.format = format;
29833
+ this.style = style;
29834
+ this.dependencies = dependencies;
29835
+ this.sheetId = sheetId;
29836
+ this.buildFormulaContent = buildFormulaContent;
29837
+ }
29838
+ get content() {
29839
+ return this.buildFormulaContent(this.sheetId, {
29840
+ dependencies: this.dependencies,
29841
+ compiledFormula: this.compiledFormula,
29842
+ });
29843
+ }
29811
29844
  }
29812
29845
 
29813
29846
  class ChartPlugin extends CorePlugin {
@@ -33099,6 +33132,931 @@
33099
33132
  drawGrid(ctx, layer) { }
33100
33133
  }
33101
33134
 
33135
+ const functionMap = functionRegistry.mapping;
33136
+ /**
33137
+ * Return all functions necessary to properly evaluate a formula:
33138
+ * - a refFn function to read any reference, cell or range of a normalized formula
33139
+ * - a range function to convert any reference to a proper value array
33140
+ * - an evaluation context
33141
+ */
33142
+ function buildCompilationParameters(context, getters, computeCell) {
33143
+ const builder = new CompilationParametersBuilder(context, getters, computeCell);
33144
+ return builder.getParameters();
33145
+ }
33146
+ class CompilationParametersBuilder {
33147
+ getters;
33148
+ computeCell;
33149
+ evalContext;
33150
+ constructor(context, getters, computeCell) {
33151
+ this.getters = getters;
33152
+ this.computeCell = computeCell;
33153
+ this.evalContext = Object.assign(Object.create(functionMap), context, {
33154
+ getters: this.getters,
33155
+ });
33156
+ }
33157
+ getParameters() {
33158
+ return [this.refFn.bind(this), this.range.bind(this), this.evalContext];
33159
+ }
33160
+ /**
33161
+ * Returns the value of the cell(s) used in reference
33162
+ *
33163
+ * @param range the references used
33164
+ * @param isMeta if a reference is supposed to be used in a `meta` parameter as described in the
33165
+ * function for which this parameter is used, we just return the string of the parameter.
33166
+ * The `compute` of the formula's function must process it completely
33167
+ */
33168
+ refFn(range, isMeta, functionName, paramNumber) {
33169
+ if (isMeta) {
33170
+ // Use zoneToXc of zone instead of getRangeString to avoid sending unbounded ranges
33171
+ return { value: zoneToXc(range.zone) };
33172
+ }
33173
+ if (!isZoneValid(range.zone)) {
33174
+ throw new InvalidReferenceError();
33175
+ }
33176
+ // if the formula definition could have accepted a range, we would pass through the _range function and not here
33177
+ if (range.zone.bottom !== range.zone.top || range.zone.left !== range.zone.right) {
33178
+ throw new Error(paramNumber
33179
+ ? _lt("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.", functionName.toString(), paramNumber.toString())
33180
+ : _lt("Function %s expects its parameters to be single values or single cell references, not ranges.", functionName.toString()));
33181
+ }
33182
+ if (range.invalidSheetName) {
33183
+ throw new Error(_lt("Invalid sheet name: %s", range.invalidSheetName));
33184
+ }
33185
+ return this.readCell(range);
33186
+ }
33187
+ readCell(range) {
33188
+ if (!this.getters.tryGetSheet(range.sheetId)) {
33189
+ throw new Error(_lt("Invalid sheet name"));
33190
+ }
33191
+ const position = { sheetId: range.sheetId, col: range.zone.left, row: range.zone.top };
33192
+ const evaluatedCell = this.getEvaluatedCellIfNotEmpty(position);
33193
+ if (evaluatedCell === undefined) {
33194
+ return { value: null, format: this.getters.getCell(position)?.format };
33195
+ }
33196
+ return evaluatedCell;
33197
+ }
33198
+ getEvaluatedCellIfNotEmpty(position) {
33199
+ const evaluatedCell = this.getEvaluatedCell(position);
33200
+ if (evaluatedCell.type === CellValueType.empty) {
33201
+ const cell = this.getters.getCell(position);
33202
+ if (!cell || cell.content === "") {
33203
+ return undefined;
33204
+ }
33205
+ }
33206
+ return evaluatedCell;
33207
+ }
33208
+ getEvaluatedCell(position) {
33209
+ const evaluatedCell = this.computeCell(position);
33210
+ if (evaluatedCell.type === CellValueType.error) {
33211
+ throw evaluatedCell.error;
33212
+ }
33213
+ return evaluatedCell;
33214
+ }
33215
+ /**
33216
+ * Return the values of the cell(s) used in reference, but always in the format of a range even
33217
+ * if a single cell is referenced. It is a list of col values. This is useful for the formulas that describe parameters as
33218
+ * range<number> etc.
33219
+ *
33220
+ * Note that each col is possibly sparse: it only contain the values of cells
33221
+ * that are actually present in the grid.
33222
+ */
33223
+ range({ sheetId, zone }) {
33224
+ if (!isZoneValid(zone)) {
33225
+ throw new InvalidReferenceError();
33226
+ }
33227
+ // Performance issue: Avoid fetching data on positions that are out of the spreadsheet
33228
+ // e.g. A1:ZZZ9999 in a sheet with 10 cols and 10 rows should ignore everything past J10 and return a 10x10 array
33229
+ const sheetZone = this.getters.getSheetZone(sheetId);
33230
+ const _zone = intersection(zone, sheetZone);
33231
+ if (!_zone) {
33232
+ return { value: [[]], format: [[]] };
33233
+ }
33234
+ const height = _zone.bottom - _zone.top + 1;
33235
+ const width = _zone.right - _zone.left + 1;
33236
+ const value = Array.from({ length: width }, () => Array.from({ length: height }));
33237
+ const format = Array.from({ length: width }, () => Array.from({ length: height }));
33238
+ // Performance issue: nested loop is faster than a map here
33239
+ for (let col = _zone.left; col <= _zone.right; col++) {
33240
+ for (let row = _zone.top; row <= _zone.bottom; row++) {
33241
+ const evaluatedCell = this.getEvaluatedCellIfNotEmpty({ sheetId: sheetId, col, row });
33242
+ if (evaluatedCell) {
33243
+ const colIndex = col - _zone.left;
33244
+ const rowIndex = row - _zone.top;
33245
+ value[colIndex][rowIndex] = evaluatedCell.value;
33246
+ if (evaluatedCell.format !== undefined) {
33247
+ format[colIndex][rowIndex] = evaluatedCell.format;
33248
+ }
33249
+ }
33250
+ }
33251
+ }
33252
+ return { value, format };
33253
+ }
33254
+ }
33255
+
33256
+ /**
33257
+ * This class is an implementation of a dependency Graph.
33258
+ * The graph is used to evaluate the cells in the correct
33259
+ * order, and should be updated each time a cell's content is modified
33260
+ *
33261
+ */
33262
+ class FormulaDependencyGraph {
33263
+ /**
33264
+ * Internal structure:
33265
+ * - key: a cell position (encoded as an integer)
33266
+ * - value: a set of cell positions that depends on the key
33267
+ *
33268
+ * Given
33269
+ * - A1:"= B1 + SQRT(B2)"
33270
+ * - C1:"= B1";
33271
+ * - C2:"= C1"
33272
+ *
33273
+ * we will have something like:
33274
+ * - B1 ---> (A1, C1) meaning A1 and C1 depends on B1
33275
+ * - B2 ---> (A1) meaning A1 depends on B2
33276
+ * - C1 ---> (C2) meaning C2 depends on C1
33277
+ */
33278
+ inverseDependencies = new Map();
33279
+ dependencies = new Map();
33280
+ removeAllDependencies(formulaPositionId) {
33281
+ const dependencies = this.dependencies.get(formulaPositionId);
33282
+ if (!dependencies) {
33283
+ return;
33284
+ }
33285
+ for (const dependency of dependencies) {
33286
+ this.inverseDependencies.get(dependency)?.delete(formulaPositionId);
33287
+ }
33288
+ this.dependencies.delete(formulaPositionId);
33289
+ }
33290
+ addDependencies(formulaPositionId, dependencies) {
33291
+ for (const dependency of dependencies) {
33292
+ const inverseDependencies = this.inverseDependencies.get(dependency);
33293
+ if (inverseDependencies) {
33294
+ inverseDependencies.add(formulaPositionId);
33295
+ }
33296
+ else {
33297
+ this.inverseDependencies.set(dependency, new Set([formulaPositionId]));
33298
+ }
33299
+ }
33300
+ const existingDependencies = this.dependencies.get(formulaPositionId);
33301
+ if (existingDependencies) {
33302
+ existingDependencies.push(...dependencies);
33303
+ }
33304
+ else {
33305
+ this.dependencies.set(formulaPositionId, dependencies);
33306
+ }
33307
+ }
33308
+ /**
33309
+ * Return the cell and all cells that depend on it,
33310
+ * in the correct order they should be evaluated.
33311
+ * This is called a topological ordering (excluding cycles)
33312
+ */
33313
+ getCellsDependingOn(positionIds) {
33314
+ const visited = new JetSet();
33315
+ const queue = Array.from(positionIds);
33316
+ while (queue.length > 0) {
33317
+ const node = queue.shift();
33318
+ visited.add(node);
33319
+ const adjacentNodes = this.inverseDependencies.get(node) || new Set();
33320
+ for (const adjacentNode of adjacentNodes) {
33321
+ if (!visited.has(adjacentNode)) {
33322
+ queue.push(adjacentNode);
33323
+ }
33324
+ }
33325
+ }
33326
+ visited.delete(...positionIds);
33327
+ return visited;
33328
+ }
33329
+ }
33330
+
33331
+ /**
33332
+ * Contains, for each cell, the array
33333
+ * formulas that could potentially spread on it
33334
+ * This is essentially a two way mapping between array formulas
33335
+ * and their results.
33336
+ *
33337
+ * As we don't allow two array formulas to spread on the same cell, this structure
33338
+ * is used to force the reevaluation of the potential spreaders of a cell when the
33339
+ * content of this cell is modified. This structure should be updated each time
33340
+ * an array formula is evaluated and try to spread on another cell.
33341
+ *
33342
+ */
33343
+ class SpreadingRelation {
33344
+ /**
33345
+ * Internal structure:
33346
+ * For something like
33347
+ * - A2:'=SPLIT("KAYAK", "A")'
33348
+ * - B1:'=TRANSPOSE(SPLIT("COYOTE", "O"))'
33349
+ *
33350
+ * Resulting in:
33351
+ * ```
33352
+ * -----------------
33353
+ * | | A | B | C |
33354
+ * |---+---+---+---|
33355
+ * | 1 | | C | |
33356
+ * | 2 | K | Y | K |
33357
+ * | 3 | | T | |
33358
+ * | 4 | | E | |
33359
+ * -----------------
33360
+ * ```
33361
+ * We will have `resultsToArrayFormulas` looking like:
33362
+ * - (B2) --> (A2, B1) meaning B2 can be the result of A2 OR B1
33363
+ * - (C2) --> (A2) meaning C2 is the result of A2
33364
+ * - (B3) --> (B1) meaning B3 is the result of B1
33365
+ * - (B4) --> (B1) meaning B4 is the result of B1
33366
+ *
33367
+ * We will have `arrayFormulasToResults` looking like:
33368
+ * - (A2) --> (B2, C2) meaning A2 spreads on B2 and C2
33369
+ * - (B1) --> (B2, B3, B4) meaning B1 spreads on B2, B3 and B4
33370
+ *
33371
+ */
33372
+ resultsToArrayFormulas = new Map();
33373
+ arrayFormulasToResults = new Map();
33374
+ getFormulaPositionsSpreadingOn(resultPositionId) {
33375
+ return this.resultsToArrayFormulas.get(resultPositionId) || EMPTY_ARRAY;
33376
+ }
33377
+ getArrayResultPositionIds(formulasPositionId) {
33378
+ return this.arrayFormulasToResults.get(formulasPositionId) || EMPTY_ARRAY;
33379
+ }
33380
+ /**
33381
+ * Remove a node, also remove it from other nodes adjacency list
33382
+ */
33383
+ removeNode(positionId) {
33384
+ this.resultsToArrayFormulas.delete(positionId);
33385
+ this.arrayFormulasToResults.delete(positionId);
33386
+ }
33387
+ /**
33388
+ * Create a spreading relation between two cells
33389
+ */
33390
+ addRelation({ arrayFormulaPositionId, resultPositionId, }) {
33391
+ if (!this.resultsToArrayFormulas.has(resultPositionId)) {
33392
+ this.resultsToArrayFormulas.set(resultPositionId, new Set());
33393
+ }
33394
+ this.resultsToArrayFormulas.get(resultPositionId)?.add(arrayFormulaPositionId);
33395
+ if (!this.arrayFormulasToResults.has(arrayFormulaPositionId)) {
33396
+ this.arrayFormulasToResults.set(arrayFormulaPositionId, new Set());
33397
+ }
33398
+ this.arrayFormulasToResults.get(arrayFormulaPositionId)?.add(resultPositionId);
33399
+ }
33400
+ hasArrayFormulaResult(positionId) {
33401
+ return this.resultsToArrayFormulas.has(positionId);
33402
+ }
33403
+ isArrayFormula(positionId) {
33404
+ return this.arrayFormulasToResults.has(positionId);
33405
+ }
33406
+ }
33407
+ const EMPTY_ARRAY = [];
33408
+
33409
+ const MAX_ITERATION = 30;
33410
+ class Evaluator {
33411
+ getters;
33412
+ compilationParams;
33413
+ positionEncoder = new PositionBitsEncoder();
33414
+ evaluatedCells = new Map();
33415
+ formulaDependencies = lazy(new FormulaDependencyGraph());
33416
+ blockedArrayFormulas = new Set();
33417
+ spreadingRelations = new SpreadingRelation();
33418
+ constructor(context, getters) {
33419
+ this.getters = getters;
33420
+ this.compilationParams = buildCompilationParameters(context, getters, (position) => this.computeCell(this.encodePosition(position)));
33421
+ }
33422
+ getEvaluatedCell(position) {
33423
+ return this.evaluatedCells.get(this.encodePosition(position)) || createEvaluatedCell("");
33424
+ }
33425
+ getArrayFormulaSpreadingOn(position) {
33426
+ const positionId = this.encodePosition(position);
33427
+ const formulaPosition = this.getArrayFormulaSpreadingOnId(positionId);
33428
+ return formulaPosition !== undefined ? this.decodePosition(formulaPosition) : undefined;
33429
+ }
33430
+ getEvaluatedPositions() {
33431
+ return [...this.evaluatedCells.keys()].map(this.decodePosition.bind(this));
33432
+ }
33433
+ getArrayFormulaSpreadingOnId(positionId) {
33434
+ if (!this.spreadingRelations.hasArrayFormulaResult(positionId)) {
33435
+ return undefined;
33436
+ }
33437
+ const arrayFormulas = this.spreadingRelations.getFormulaPositionsSpreadingOn(positionId);
33438
+ return Array.from(arrayFormulas).find((positionId) => !this.blockedArrayFormulas.has(positionId));
33439
+ }
33440
+ updateDependencies(position) {
33441
+ const positionId = this.encodePosition(position);
33442
+ this.formulaDependencies().removeAllDependencies(positionId);
33443
+ const dependencies = this.getDirectDependencies(positionId);
33444
+ this.formulaDependencies().addDependencies(positionId, dependencies);
33445
+ }
33446
+ evaluateCells(positions) {
33447
+ const cells = positions.map(this.encodePosition.bind(this));
33448
+ const cellsToCompute = new JetSet(cells);
33449
+ const arrayFormulas = this.getArrayFormulasImpactedByChangesOf(cells);
33450
+ cellsToCompute.add(...this.getCellsDependingOn(cells));
33451
+ cellsToCompute.add(...arrayFormulas);
33452
+ cellsToCompute.add(...this.getCellsDependingOn(arrayFormulas));
33453
+ this.evaluate(cellsToCompute);
33454
+ }
33455
+ getArrayFormulasImpactedByChangesOf(positionIds) {
33456
+ const impactedPositionIds = new JetSet();
33457
+ for (const positionId of positionIds) {
33458
+ const content = this.getCell(positionId)?.content;
33459
+ const arrayFormulaPositionId = this.getArrayFormulaSpreadingOnId(positionId);
33460
+ if (arrayFormulaPositionId !== undefined) {
33461
+ // take into account new collisions.
33462
+ impactedPositionIds.add(arrayFormulaPositionId);
33463
+ }
33464
+ if (!content) {
33465
+ // The previous content could have blocked some array formulas
33466
+ impactedPositionIds.add(...this.getArrayFormulasBlockedByOrSpreadingOn(positionId));
33467
+ }
33468
+ }
33469
+ return impactedPositionIds;
33470
+ }
33471
+ buildDependencyGraph() {
33472
+ this.blockedArrayFormulas = new Set();
33473
+ this.spreadingRelations = new SpreadingRelation();
33474
+ this.formulaDependencies = lazy(() => {
33475
+ const dependencyGraph = new FormulaDependencyGraph();
33476
+ for (const positionId of this.getAllCells()) {
33477
+ const dependencies = this.getDirectDependencies(positionId);
33478
+ dependencyGraph.addDependencies(positionId, dependencies);
33479
+ }
33480
+ return dependencyGraph;
33481
+ });
33482
+ }
33483
+ evaluateAllCells() {
33484
+ this.evaluatedCells = new Map();
33485
+ this.evaluate(this.getAllCells());
33486
+ }
33487
+ getAllCells() {
33488
+ const positionIds = new JetSet();
33489
+ for (const sheetId of this.getters.getSheetIds()) {
33490
+ const cellIds = this.getters.getCells(sheetId);
33491
+ for (const cellId in cellIds) {
33492
+ positionIds.add(this.encodePosition(this.getters.getCellPosition(cellId)));
33493
+ }
33494
+ }
33495
+ return positionIds;
33496
+ }
33497
+ getArrayFormulasBlockedByOrSpreadingOn(positionId) {
33498
+ if (!this.spreadingRelations.hasArrayFormulaResult(positionId)) {
33499
+ return [];
33500
+ }
33501
+ const arrayFormulas = this.spreadingRelations.getFormulaPositionsSpreadingOn(positionId);
33502
+ const cells = new JetSet(arrayFormulas);
33503
+ cells.add(...this.getCellsDependingOn(arrayFormulas));
33504
+ return cells;
33505
+ }
33506
+ nextPositionsToUpdate = new JetSet();
33507
+ cellsBeingComputed = new Set();
33508
+ evaluate(cells) {
33509
+ this.cellsBeingComputed = new Set();
33510
+ this.nextPositionsToUpdate = cells;
33511
+ let currentIteration = 0;
33512
+ while (this.nextPositionsToUpdate.size && currentIteration++ < MAX_ITERATION) {
33513
+ const positionIds = Array.from(this.nextPositionsToUpdate);
33514
+ this.nextPositionsToUpdate.clear();
33515
+ for (let i = 0; i < positionIds.length; ++i) {
33516
+ const cell = positionIds[i];
33517
+ this.evaluatedCells.delete(cell);
33518
+ }
33519
+ for (let i = 0; i < positionIds.length; ++i) {
33520
+ const cell = positionIds[i];
33521
+ this.setEvaluatedCell(cell, this.computeCell(cell));
33522
+ }
33523
+ }
33524
+ }
33525
+ setEvaluatedCell(positionId, evaluatedCell) {
33526
+ if (this.nextPositionsToUpdate.has(positionId)) {
33527
+ this.nextPositionsToUpdate.delete(positionId);
33528
+ }
33529
+ this.evaluatedCells.set(positionId, evaluatedCell);
33530
+ }
33531
+ computeCell(positionId) {
33532
+ const evaluation = this.evaluatedCells.get(positionId);
33533
+ if (evaluation) {
33534
+ return evaluation; // already computed
33535
+ }
33536
+ if (!this.blockedArrayFormulas.has(positionId)) {
33537
+ this.invalidateSpreading(positionId);
33538
+ }
33539
+ const cell = this.getCell(positionId);
33540
+ if (cell === undefined) {
33541
+ return createEvaluatedCell("");
33542
+ }
33543
+ const cellId = cell.id;
33544
+ try {
33545
+ if (this.cellsBeingComputed.has(cellId)) {
33546
+ throw new CircularDependencyError();
33547
+ }
33548
+ this.cellsBeingComputed.add(cellId);
33549
+ return cell.isFormula
33550
+ ? this.computeFormulaCell(cell)
33551
+ : evaluateLiteral(cell.content, cell.format);
33552
+ }
33553
+ catch (e) {
33554
+ return this.handleError(e, cell);
33555
+ }
33556
+ finally {
33557
+ this.cellsBeingComputed.delete(cellId);
33558
+ }
33559
+ }
33560
+ handleError(e, cell) {
33561
+ if (!(e instanceof Error)) {
33562
+ e = new Error(e);
33563
+ }
33564
+ const msg = e?.errorType || CellErrorType.GenericError;
33565
+ // apply function name
33566
+ const __lastFnCalled = this.compilationParams[2].__lastFnCalled || "";
33567
+ const error = new EvaluationError(msg, e.message.replace("[[FUNCTION_NAME]]", __lastFnCalled), e.logLevel !== undefined ? e.logLevel : CellErrorLevel.error);
33568
+ return errorCell(cell.content, error);
33569
+ }
33570
+ computeFormulaCell(cellData) {
33571
+ const cellId = cellData.id;
33572
+ this.compilationParams[2].__originCellXC = () => {
33573
+ // compute the value lazily for performance reasons
33574
+ const position = this.compilationParams[2].getters.getCellPosition(cellId);
33575
+ return toXC(position.col, position.row);
33576
+ };
33577
+ const formulaReturn = cellData.compiledFormula.execute(cellData.dependencies, ...this.compilationParams);
33578
+ assertFormulaReturnHasConsistentDimensions(formulaReturn);
33579
+ const { value: computedValue, format: computedFormat } = formulaReturn;
33580
+ if (!isMatrix(computedValue)) {
33581
+ return createEvaluatedCell(computedValue, cellData.format || computedFormat);
33582
+ }
33583
+ const formulaPosition = this.getters.getCellPosition(cellId);
33584
+ this.assertSheetHasEnoughSpaceToSpreadFormulaResult(formulaPosition, computedValue);
33585
+ forEachSpreadPositionInMatrix(computedValue, this.updateSpreadRelation(formulaPosition));
33586
+ forEachSpreadPositionInMatrix(computedValue, this.checkCollision(formulaPosition));
33587
+ forEachSpreadPositionInMatrix(computedValue,
33588
+ // due the isMatrix check above, we know that formulaReturn is MatrixFunctionReturn
33589
+ this.spreadValues(formulaPosition, formulaReturn));
33590
+ const formatFromPosition = formatFromPositionAccess(computedFormat);
33591
+ return createEvaluatedCell(computedValue[0][0], cellData.format || formatFromPosition(0, 0));
33592
+ }
33593
+ assertSheetHasEnoughSpaceToSpreadFormulaResult({ sheetId, col, row }, matrixResult) {
33594
+ const numberOfCols = this.getters.getNumberCols(sheetId);
33595
+ const numberOfRows = this.getters.getNumberRows(sheetId);
33596
+ const enoughCols = col + matrixResult.length <= numberOfCols;
33597
+ const enoughRows = row + matrixResult[0].length <= numberOfRows;
33598
+ if (enoughCols && enoughRows) {
33599
+ return;
33600
+ }
33601
+ if (enoughCols) {
33602
+ throw new Error(_lt("Result couldn't be automatically expanded. Please insert more rows."));
33603
+ }
33604
+ if (enoughRows) {
33605
+ throw new Error(_lt("Result couldn't be automatically expanded. Please insert more columns."));
33606
+ }
33607
+ throw new Error(_lt("Result couldn't be automatically expanded. Please insert more columns and rows."));
33608
+ }
33609
+ updateSpreadRelation({ sheetId, col, row, }) {
33610
+ const arrayFormulaPositionId = this.encodePosition({ sheetId, col, row });
33611
+ return (i, j) => {
33612
+ const position = { sheetId, col: i + col, row: j + row };
33613
+ const resultPositionId = this.encodePosition(position);
33614
+ this.spreadingRelations.addRelation({ resultPositionId, arrayFormulaPositionId });
33615
+ };
33616
+ }
33617
+ checkCollision({ sheetId, col, row }) {
33618
+ const formulaPositionId = this.encodePosition({ sheetId, col, row });
33619
+ return (i, j) => {
33620
+ const position = { sheetId: sheetId, col: i + col, row: j + row };
33621
+ const rawCell = this.getters.getCell(position);
33622
+ if (rawCell?.content ||
33623
+ this.getters.getEvaluatedCell(position).type !== CellValueType.empty) {
33624
+ this.blockedArrayFormulas.add(formulaPositionId);
33625
+ throw new Error(_lt("Array result was not expanded because it would overwrite data in %s.", toXC(position.col, position.row)));
33626
+ }
33627
+ this.blockedArrayFormulas.delete(formulaPositionId);
33628
+ };
33629
+ }
33630
+ spreadValues({ sheetId, col, row }, matrixResult) {
33631
+ const formatFromPosition = formatFromPositionAccess(matrixResult.format);
33632
+ return (i, j) => {
33633
+ const position = { sheetId, col: i + col, row: j + row };
33634
+ const cell = this.getters.getCell(position);
33635
+ const format = cell?.format;
33636
+ const evaluatedCell = createEvaluatedCell(matrixResult.value[i][j], format || formatFromPosition(i, j));
33637
+ const positionId = this.encodePosition(position);
33638
+ this.setEvaluatedCell(positionId, evaluatedCell);
33639
+ // check if formula dependencies present in the spread zone
33640
+ // if so, they need to be recomputed
33641
+ this.nextPositionsToUpdate.add(...this.getCellsDependingOn([positionId]));
33642
+ };
33643
+ }
33644
+ invalidateSpreading(positionId) {
33645
+ if (!this.spreadingRelations.isArrayFormula(positionId)) {
33646
+ return;
33647
+ }
33648
+ for (const child of this.spreadingRelations.getArrayResultPositionIds(positionId)) {
33649
+ const content = this.getCell(child)?.content;
33650
+ if (content) {
33651
+ // there's no point at re-evaluating overlapping array formulas,
33652
+ // there's still a collision
33653
+ continue;
33654
+ }
33655
+ this.evaluatedCells.delete(child);
33656
+ this.nextPositionsToUpdate.add(...this.getCellsDependingOn([child]));
33657
+ this.nextPositionsToUpdate.add(...this.getArrayFormulasBlockedByOrSpreadingOn(child));
33658
+ }
33659
+ this.spreadingRelations.removeNode(positionId);
33660
+ }
33661
+ // ----------------------------------------------------------
33662
+ // COMMON FUNCTIONALITY
33663
+ // ----------------------------------------------------------
33664
+ getDirectDependencies(positionId) {
33665
+ const cell = this.getCell(positionId);
33666
+ if (!cell?.isFormula) {
33667
+ return [];
33668
+ }
33669
+ const dependencies = [];
33670
+ for (const range of cell.dependencies) {
33671
+ if (range.invalidSheetName || range.invalidXc) {
33672
+ continue;
33673
+ }
33674
+ const sheetId = range.sheetId;
33675
+ forEachPositionsInZone(range.zone, (col, row) => {
33676
+ dependencies.push(this.encodePosition({ sheetId, col, row }));
33677
+ });
33678
+ }
33679
+ return dependencies;
33680
+ }
33681
+ getCellsDependingOn(positionIds) {
33682
+ return this.formulaDependencies().getCellsDependingOn(positionIds);
33683
+ }
33684
+ getCell(positionId) {
33685
+ return this.getters.getCell(this.decodePosition(positionId));
33686
+ }
33687
+ encodePosition(position) {
33688
+ return this.positionEncoder.encode(position);
33689
+ }
33690
+ decodePosition(positionId) {
33691
+ return this.positionEncoder.decode(positionId);
33692
+ }
33693
+ }
33694
+ function forEachSpreadPositionInMatrix(matrix, callback) {
33695
+ for (let i = 0; i < matrix.length; ++i) {
33696
+ for (let j = 0; j < matrix[i].length; ++j) {
33697
+ if (i === 0 && j === 0) {
33698
+ continue;
33699
+ }
33700
+ callback(i, j);
33701
+ }
33702
+ }
33703
+ }
33704
+ function formatFromPositionAccess(format) {
33705
+ return isMatrix(format) ? (i, j) => format[i][j] : () => format;
33706
+ }
33707
+ function assertFormulaReturnHasConsistentDimensions(formulaReturn) {
33708
+ const { value: computedValue, format: computedFormat } = formulaReturn;
33709
+ if (!isMatrix(computedValue)) {
33710
+ if (isMatrix(computedFormat)) {
33711
+ throw new Error("A format matrix should never be associated with a scalar value");
33712
+ }
33713
+ return;
33714
+ }
33715
+ if (isMatrix(computedFormat)) {
33716
+ const sameDimensions = computedValue.length === computedFormat.length &&
33717
+ computedValue[0].length === computedFormat[0].length;
33718
+ if (!sameDimensions) {
33719
+ throw new Error("Formats and values should have the same dimensions!");
33720
+ }
33721
+ }
33722
+ }
33723
+ /**
33724
+ * Encode (and decode) cell positions { sheetId, col, row }
33725
+ * to a single integer.
33726
+ *
33727
+ * `col` and `row` values are encoded on 21 bits each (max 2^21 = 2_097_152),
33728
+ * An incremental integer id is assigned to each different sheet id, starting at 0.
33729
+ *
33730
+ * e.g.
33731
+ * Given { col: 10, row: 4, sheetId: "abcde" }
33732
+ * we have:
33733
+ * - row "4" encoded on 21 bits: 000000000000000000100
33734
+ * - col "10" encoded on 21 bits: 000000000000000001010
33735
+ * - sheetId: let's say it's the 4th sheetId met, encoded to: 11
33736
+ *
33737
+ * The final encoded value is found by concatenating the 3 bit sequences:
33738
+ *
33739
+ * sheetId: 11
33740
+ * col: 000000000000000001010
33741
+ * row: 000000000000000000100
33742
+ * => 11000000000000000001010000000000000000000100
33743
+ *
33744
+ * this binary sequence is the integer 13194160504836
33745
+ */
33746
+ class PositionBitsEncoder {
33747
+ sheetMapping = {};
33748
+ inverseSheetMapping = new Map();
33749
+ constructor() {
33750
+ try {
33751
+ // @ts-ignore
33752
+ o_spreadsheet.__DEBUG__ = o_spreadsheet.__DEBUG__ || {};
33753
+ // @ts-ignore
33754
+ o_spreadsheet.__DEBUG__.decodePosition = this.decode.bind(this);
33755
+ // @ts-ignore
33756
+ o_spreadsheet.__DEBUG__.encodePosition = this.encode.bind(this);
33757
+ }
33758
+ catch (error) { }
33759
+ }
33760
+ /**
33761
+ * Encode a cell position to a single integer.
33762
+ */
33763
+ encode({ sheetId, col, row }) {
33764
+ return (this.encodeSheet(sheetId) << 42n) | (BigInt(col) << 21n) | BigInt(row);
33765
+ }
33766
+ decode(id) {
33767
+ // keep only the last 21 bits by AND-ing the bit sequence with 21 ones
33768
+ const row = Number(id & 2097151n);
33769
+ const col = Number((id >> 21n) & 2097151n);
33770
+ const sheetId = this.decodeSheet(id >> 42n);
33771
+ return { sheetId, col, row };
33772
+ }
33773
+ encodeSheet(sheetId) {
33774
+ const sheetKey = this.sheetMapping[sheetId];
33775
+ if (sheetKey === undefined) {
33776
+ const newSheetKey = BigInt(Object.keys(this.sheetMapping).length);
33777
+ this.sheetMapping[sheetId] = newSheetKey;
33778
+ this.inverseSheetMapping.set(newSheetKey, sheetId);
33779
+ return newSheetKey;
33780
+ }
33781
+ return sheetKey;
33782
+ }
33783
+ decodeSheet(sheetKey) {
33784
+ const sheetId = this.inverseSheetMapping.get(sheetKey);
33785
+ if (sheetId === undefined) {
33786
+ throw new Error("Sheet id not found");
33787
+ }
33788
+ return sheetId;
33789
+ }
33790
+ }
33791
+
33792
+ const functions = functionRegistry.content;
33793
+ //#region
33794
+ // ---------------------------------------------------------------------------
33795
+ // INTRODUCTION
33796
+ // ---------------------------------------------------------------------------
33797
+ // The evaluation plugin is in charge of computing the values of the cells.
33798
+ // This is a fairly complex task for several reasons:
33799
+ // Reason n°1: Cells can contain formulas that must be interpreted to know
33800
+ // the final value of the cell. And these formulas can depend on other cells.
33801
+ // ex A1:"=SUM(B1:B2)" we have to evaluate B1:B2 first to be able to evaluate A1.
33802
+ // We say here that we have a 'formula dependency' between A1 and B1:B2.
33803
+ // Reason n°2: A cell can assign value to other cells that haven't content.
33804
+ // This concerns cells containing a formula that returns an array of values.
33805
+ // ex A1:"=SPLIT('Odoo','d')" Evaluating A1 must assign the value "O" to A1 and
33806
+ // "oo" to B1. We say here that we have a 'spread relation' between A1 and B1.
33807
+ // B1 have a spread value from A1.
33808
+ // Note that a cell can contain a formula which depends on other cells which
33809
+ // themselves can:
33810
+ // - contain formulas which depends on other cells (and so on).
33811
+ // - contain a spread value from other formulas which depends on other cells
33812
+ // (and so on).
33813
+ // I - How to build the evaluation ?
33814
+ // If we had only formulas dependencies to treat, the evaluation would be
33815
+ // simple: the formulas dependencies are directly deduced from the content
33816
+ // of the formulas. With the dependencies we are able to calculate which
33817
+ // formula must be evaluated before another.
33818
+ // Cycles
33819
+ // ------
33820
+ // We can also easily detect if the cells are included in reference cycles
33821
+ // and return an error in this case. ex: A1:"=B1" B1:"=C1" C1:"=A1"
33822
+ // The "#CYCLE" error must be returned for
33823
+ // all three cells.
33824
+ // But there's more! There are formulas referring to other cells but never
33825
+ // use them. This is the case for example
33826
+ // with the "IF" formula. ex:
33827
+ // A1:"=IF(D1,A2,B1)"
33828
+ // A2:"=A1"
33829
+ // In this case it is obvious that we have a cyclic dependency. But in practice
33830
+ // this will only exist if D1 is true.
33831
+ // For this reason, we believe that the evaluation should be **partly recursive**:
33832
+ // The function computing a formula cell starts by marking them as 'being evaluated'
33833
+ // and then call itself on the dependencies of the concerned cell. This allows
33834
+ // to evaluate the dependencies before the cell itself and to detect
33835
+ // if the cell that is being evaluated isn't part of a cycle.
33836
+ // II - The spread relation anticipation problem
33837
+ // The biggest difficulty to solve with the evaluation lies in the fact that
33838
+ // we cannot anticipate the spread relations: cells impacted by the result array
33839
+ // of a formula are only determined after the array formula has been
33840
+ // evaluated. In the case where the impacted cells are used in other formulas,
33841
+ // this will require to re-evaluation other formulas (and so on...). ex:
33842
+ // A1:"=B2"
33843
+ // A2:"=SPLIT('Odoo','d')"
33844
+ // in the example above, A2 spreads on B2, but we will know it only after
33845
+ // the evaluation of A2. To be able to evaluate A1 correctly, we must therefore
33846
+ // reevaluate A1 after the evaluation of A2.
33847
+ // We could evaluate which formula spreads first. Except that the array formulas
33848
+ // can themselves depend on the spreads of other formulas. ex:
33849
+ // A1:"=SPLIT(B3,'d')"
33850
+ // A2:="odoo odoo"
33851
+ // A3:"=SPLIT(A2,' ')"
33852
+ // In the example above, A3 must be evaluated before A1 because A1 needs B3 which
33853
+ // can be modified by A3.
33854
+ // Therefore, there would be a spatial evaluation order to be respected between
33855
+ // the array formulas. We could imagine that, when an array formula depends
33856
+ // on a cell, then we evaluate the first formula that spreads located in the upper
33857
+ // left corner of this cell.
33858
+ // Although this possibility has been explored, it remains complicated to spatially
33859
+ // predict which formula should be evaluated before another, especially when
33860
+ // the array formulas are located in different sheets or when the array formulas
33861
+ // depends on the spreads of each other. ex:
33862
+ //
33863
+ // A1:"=ARRAY_FORMULA_ALPHA(B2)"
33864
+ // A2:"=ARRAY_FORMULA_BETA(B1)"
33865
+ // In the example above, ARRAY_FORMULA_ALPHA and ARRAY_FORMULA_BETA are some
33866
+ // formulas that could spread depending on the value of B2 and B1. This could be a
33867
+ // cyclic dependency that we cannot anticipate.
33868
+ // And as with the "IF" formula, array formulas may not use their dependency.
33869
+ // It then becomes very difficult to manage...
33870
+ // Also, if we have a cycle, that doesn't mean it's bad. The cycle can converge to
33871
+ // a stable state at the scale of the sheets. Functionally, we don't want to forbid
33872
+ // convergent cycles. It is an interesting feature but which requires to re-evaluate
33873
+ // the cycle as many times as convergence is not reached.
33874
+ // Thus, in order to respect the relations between the cells (formula dependencies and
33875
+ // spread relations), the evaluation of the cells must:
33876
+ // - respect a precise order (cells values used by another must be evaluated first) : As
33877
+ // we cannot anticipate which dependencies are really used by the formulas, we must
33878
+ // evaluate the cells in a recursive way;
33879
+ // - be done as many times as necessary to ensure that all the cells have been correctly
33880
+ // evaluated in the correct order (in case of, for example, spreading relation cycles).
33881
+ // The chosen solution is to reevaluate the formulas impacted by spreads as many times
33882
+ // as necessary in several iterations, where evaluated cells can trigger the evaluation
33883
+ // of other cells depending on it, at the next iteration.
33884
+ //#endregion
33885
+ class EvaluationPlugin extends UIPlugin {
33886
+ static getters = [
33887
+ "evaluateFormula",
33888
+ "getRangeFormattedValues",
33889
+ "getRangeValues",
33890
+ "getRangeFormats",
33891
+ "getEvaluatedCell",
33892
+ "getEvaluatedCells",
33893
+ "getEvaluatedCellsInZone",
33894
+ ];
33895
+ shouldRebuildDependenciesGraph = true;
33896
+ evaluator;
33897
+ compilationParams;
33898
+ positionsToUpdate = [];
33899
+ constructor(config) {
33900
+ super(config);
33901
+ this.evaluator = new Evaluator(config.custom, this.getters);
33902
+ this.compilationParams = buildCompilationParameters(config.custom, this.getters, (position) => this.evaluator.getEvaluatedCell(position));
33903
+ }
33904
+ // ---------------------------------------------------------------------------
33905
+ // Command Handling
33906
+ // ---------------------------------------------------------------------------
33907
+ beforeHandle(cmd) {
33908
+ if (invalidateDependenciesCommands.has(cmd.type)) {
33909
+ this.shouldRebuildDependenciesGraph = true;
33910
+ }
33911
+ }
33912
+ handle(cmd) {
33913
+ switch (cmd.type) {
33914
+ case "UPDATE_CELL":
33915
+ if (!("content" in cmd || "format" in cmd) || this.shouldRebuildDependenciesGraph) {
33916
+ return;
33917
+ }
33918
+ this.positionsToUpdate.push(cmd);
33919
+ if ("content" in cmd) {
33920
+ this.evaluator.updateDependencies(cmd);
33921
+ }
33922
+ break;
33923
+ case "EVALUATE_CELLS":
33924
+ this.evaluator.evaluateAllCells();
33925
+ break;
33926
+ }
33927
+ }
33928
+ finalize() {
33929
+ if (this.shouldRebuildDependenciesGraph) {
33930
+ this.evaluator.buildDependencyGraph();
33931
+ this.evaluator.evaluateAllCells();
33932
+ this.shouldRebuildDependenciesGraph = false;
33933
+ }
33934
+ else if (this.positionsToUpdate.length) {
33935
+ this.evaluator.evaluateCells(this.positionsToUpdate);
33936
+ }
33937
+ this.positionsToUpdate = [];
33938
+ }
33939
+ // ---------------------------------------------------------------------------
33940
+ // Getters
33941
+ // ---------------------------------------------------------------------------
33942
+ evaluateFormula(formulaString, sheetId = this.getters.getActiveSheetId()) {
33943
+ const compiledFormula = compile(formulaString);
33944
+ const ranges = [];
33945
+ for (let xc of compiledFormula.dependencies) {
33946
+ ranges.push(this.getters.getRangeFromSheetXC(sheetId, xc));
33947
+ }
33948
+ return compiledFormula.execute(ranges, ...this.compilationParams).value;
33949
+ }
33950
+ /**
33951
+ * Return the value of each cell in the range as they are displayed in the grid.
33952
+ */
33953
+ getRangeFormattedValues(range) {
33954
+ const sheet = this.getters.tryGetSheet(range.sheetId);
33955
+ if (sheet === undefined)
33956
+ return [];
33957
+ return this.getters
33958
+ .getEvaluatedCellsInZone(sheet.id, range.zone)
33959
+ .map((cell) => cell.formattedValue);
33960
+ }
33961
+ /**
33962
+ * Return the value of each cell in the range.
33963
+ */
33964
+ getRangeValues(range) {
33965
+ const sheet = this.getters.tryGetSheet(range.sheetId);
33966
+ if (sheet === undefined)
33967
+ return [];
33968
+ return this.getters.getEvaluatedCellsInZone(sheet.id, range.zone).map((cell) => cell.value);
33969
+ }
33970
+ /**
33971
+ * Return the format of each cell in the range.
33972
+ */
33973
+ getRangeFormats(range) {
33974
+ const sheet = this.getters.tryGetSheet(range.sheetId);
33975
+ if (sheet === undefined)
33976
+ return [];
33977
+ return this.getters.getEvaluatedCellsInZone(sheet.id, range.zone).map((cell) => cell.format);
33978
+ }
33979
+ getEvaluatedCell(position) {
33980
+ return this.evaluator.getEvaluatedCell(position);
33981
+ }
33982
+ getEvaluatedCells(sheetId) {
33983
+ const rawCells = this.getters.getCells(sheetId) || {};
33984
+ const record = {};
33985
+ for (let cellId of Object.keys(rawCells)) {
33986
+ const position = this.getters.getCellPosition(cellId);
33987
+ record[cellId] = this.getEvaluatedCell(position);
33988
+ }
33989
+ return record;
33990
+ }
33991
+ getEvaluatedCellsInZone(sheetId, zone) {
33992
+ return positions(zone).map(({ col, row }) => this.getters.getEvaluatedCell({ sheetId, col, row }));
33993
+ }
33994
+ // ---------------------------------------------------------------------------
33995
+ // Export
33996
+ // ---------------------------------------------------------------------------
33997
+ exportForExcel(data) {
33998
+ for (const position of this.evaluator.getEvaluatedPositions()) {
33999
+ const evaluatedCell = this.evaluator.getEvaluatedCell(position);
34000
+ const xc = toXC(position.col, position.row);
34001
+ const value = evaluatedCell.value;
34002
+ let isFormula = false;
34003
+ let newContent = undefined;
34004
+ let newFormat = undefined;
34005
+ let isExported = true;
34006
+ const formulaCell = this.getCorrespondingFormulaCell(position);
34007
+ if (formulaCell) {
34008
+ isExported = formulaCell.compiledFormula.tokens
34009
+ .filter((tk) => tk.type === "FUNCTION")
34010
+ .every((tk) => functions[tk.value.toUpperCase()].isExported);
34011
+ isFormula = isExported;
34012
+ if (!isExported) {
34013
+ newContent = value.toString();
34014
+ newFormat = evaluatedCell.format;
34015
+ }
34016
+ }
34017
+ const exportedSheetData = data.sheets.find((sheet) => sheet.id === position.sheetId);
34018
+ const exportedCellData = exportedSheetData.cells[xc] || {};
34019
+ const format = newFormat
34020
+ ? getItemId(newFormat, data.formats)
34021
+ : exportedCellData.format;
34022
+ const content = !isExported ? newContent : exportedCellData.content;
34023
+ exportedSheetData.cells[xc] = { ...exportedCellData, value, isFormula, content, format };
34024
+ }
34025
+ }
34026
+ /**
34027
+ * Returns the corresponding formula cell of a given cell
34028
+ * It could be the formula present in the cell itself or the
34029
+ * formula of the array formula that spreads to the cell
34030
+ */
34031
+ getCorrespondingFormulaCell(position) {
34032
+ const cell = this.getters.getCell(position);
34033
+ if (cell && cell.content) {
34034
+ if (cell.isFormula && !isBadExpression(cell.content)) {
34035
+ return cell;
34036
+ }
34037
+ return undefined;
34038
+ }
34039
+ const spreadingFormulaPosition = this.evaluator.getArrayFormulaSpreadingOn(position);
34040
+ if (spreadingFormulaPosition === undefined) {
34041
+ return undefined;
34042
+ }
34043
+ const spreadingFormulaCell = this.getters.getCell(spreadingFormulaPosition);
34044
+ if (spreadingFormulaCell?.isFormula) {
34045
+ return spreadingFormulaCell;
34046
+ }
34047
+ return undefined;
34048
+ }
34049
+ }
34050
+ function isBadExpression(formula) {
34051
+ try {
34052
+ compile(formula);
34053
+ return false;
34054
+ }
34055
+ catch (error) {
34056
+ return true;
34057
+ }
34058
+ }
34059
+
33102
34060
  /**
33103
34061
  * https://tomekdev.com/posts/sorting-colors-in-js
33104
34062
  */
@@ -33249,329 +34207,6 @@
33249
34207
  }
33250
34208
  }
33251
34209
 
33252
- const functionMap = functionRegistry.mapping;
33253
- class EvaluationPlugin extends UIPlugin {
33254
- static getters = [
33255
- "evaluateFormula",
33256
- "getRangeFormattedValues",
33257
- "getRangeValues",
33258
- "getRangeFormats",
33259
- "getEvaluatedCell",
33260
- "getEvaluatedCells",
33261
- "getColEvaluatedCells",
33262
- "getEvaluatedCellsInZone",
33263
- ];
33264
- isUpToDate = false;
33265
- evaluatedCells = {};
33266
- evalContext;
33267
- lazyEvaluation;
33268
- constructor(config) {
33269
- super(config);
33270
- this.evalContext = config.custom;
33271
- this.lazyEvaluation = config.lazyEvaluation;
33272
- }
33273
- // ---------------------------------------------------------------------------
33274
- // Command Handling
33275
- // ---------------------------------------------------------------------------
33276
- handle(cmd) {
33277
- if (invalidateEvaluationCommands.has(cmd.type)) {
33278
- this.isUpToDate = false;
33279
- }
33280
- switch (cmd.type) {
33281
- case "UPDATE_CELL":
33282
- if ("content" in cmd || "format" in cmd) {
33283
- this.isUpToDate = false;
33284
- }
33285
- break;
33286
- case "EVALUATE_CELLS":
33287
- this.evaluate();
33288
- break;
33289
- }
33290
- }
33291
- finalize() {
33292
- if (!this.isUpToDate) {
33293
- this.evaluate();
33294
- this.isUpToDate = true;
33295
- }
33296
- }
33297
- // ---------------------------------------------------------------------------
33298
- // Getters
33299
- // ---------------------------------------------------------------------------
33300
- evaluateFormula(formulaString, sheetId = this.getters.getActiveSheetId()) {
33301
- const compiledFormula = compile(formulaString);
33302
- const params = this.getCompilationParameters((cell) => this.getEvaluatedCell(this.getters.getCellPosition(cell.id)));
33303
- const ranges = [];
33304
- for (let xc of compiledFormula.dependencies) {
33305
- ranges.push(this.getters.getRangeFromSheetXC(sheetId, xc));
33306
- }
33307
- return compiledFormula.execute(ranges, ...params).value;
33308
- }
33309
- /**
33310
- * Return the value of each cell in the range as they are displayed in the grid.
33311
- */
33312
- getRangeFormattedValues(range) {
33313
- const sheet = this.getters.tryGetSheet(range.sheetId);
33314
- if (sheet === undefined)
33315
- return [];
33316
- return this.getters
33317
- .getEvaluatedCellsInZone(sheet.id, range.zone)
33318
- .map((cell) => cell.formattedValue);
33319
- }
33320
- /**
33321
- * Return the value of each cell in the range.
33322
- */
33323
- getRangeValues(range) {
33324
- const sheet = this.getters.tryGetSheet(range.sheetId);
33325
- if (sheet === undefined)
33326
- return [];
33327
- return this.getters.getEvaluatedCellsInZone(sheet.id, range.zone).map((cell) => cell.value);
33328
- }
33329
- /**
33330
- * Return the format of each cell in the range.
33331
- */
33332
- getRangeFormats(range) {
33333
- const sheet = this.getters.tryGetSheet(range.sheetId);
33334
- if (sheet === undefined)
33335
- return [];
33336
- return this.getters.getEvaluatedCellsInZone(sheet.id, range.zone).map((cell) => cell.format);
33337
- }
33338
- getEvaluatedCell({ sheetId, col, row }) {
33339
- const cell = this.getters.getCell({ sheetId, col, row });
33340
- if (cell === undefined) {
33341
- return createEvaluatedCell("");
33342
- }
33343
- // the cell might have been created by a command in the current
33344
- // dispatch but the evaluation is not done yet.
33345
- return this.evaluatedCells[sheetId]?.[col]?.[row]?.() || createEvaluatedCell("");
33346
- }
33347
- getEvaluatedCells(sheetId) {
33348
- const rawCells = this.getters.getCells(sheetId) || {};
33349
- const record = {};
33350
- for (let cellId of Object.keys(rawCells)) {
33351
- const position = this.getters.getCellPosition(cellId);
33352
- record[cellId] = this.getEvaluatedCell(position);
33353
- }
33354
- return record;
33355
- }
33356
- /**
33357
- * Returns all the evaluated cells of a col
33358
- */
33359
- getColEvaluatedCells(sheetId, col) {
33360
- return Object.values(this.evaluatedCells[sheetId]?.[col] || [])
33361
- .filter(isDefined$1)
33362
- .map((lazyCell) => lazyCell());
33363
- }
33364
- getEvaluatedCellsInZone(sheetId, zone) {
33365
- return positions(zone).map(({ col, row }) => this.getters.getEvaluatedCell({ sheetId, col, row }));
33366
- }
33367
- // ---------------------------------------------------------------------------
33368
- // Evaluator
33369
- // ---------------------------------------------------------------------------
33370
- setEvaluatedCell(cellId, evaluatedCell) {
33371
- const { col, row, sheetId } = this.getters.getCellPosition(cellId);
33372
- if (!this.evaluatedCells[sheetId]) {
33373
- this.evaluatedCells[sheetId] = {};
33374
- }
33375
- if (!this.evaluatedCells[sheetId][col]) {
33376
- this.evaluatedCells[sheetId][col] = {};
33377
- }
33378
- this.evaluatedCells[sheetId][col][row] = evaluatedCell;
33379
- if (!this.lazyEvaluation) {
33380
- this.evaluatedCells[sheetId][col][row]();
33381
- }
33382
- }
33383
- *getAllCells() {
33384
- // use a generator function to avoid re-building a new object
33385
- for (const sheetId of this.getters.getSheetIds()) {
33386
- const cells = this.getters.getCells(sheetId);
33387
- for (const cellId in cells) {
33388
- yield cells[cellId];
33389
- }
33390
- }
33391
- }
33392
- evaluate() {
33393
- this.evaluatedCells = {};
33394
- const cellsBeingComputed = new Set();
33395
- const computeCell = (cell) => {
33396
- const cellId = cell.id;
33397
- const { col, row, sheetId } = this.getters.getCellPosition(cellId);
33398
- const lazyEvaluation = this.evaluatedCells[sheetId]?.[col]?.[row];
33399
- if (lazyEvaluation) {
33400
- return lazyEvaluation; // already computed
33401
- }
33402
- return lazy(() => {
33403
- try {
33404
- switch (cell.isFormula) {
33405
- case true:
33406
- return computeFormulaCell(cell);
33407
- case false:
33408
- return evaluateLiteral(cell.content, cell.format);
33409
- }
33410
- }
33411
- catch (e) {
33412
- return handleError(e, cell);
33413
- }
33414
- });
33415
- };
33416
- const handleError = (e, cell) => {
33417
- if (!(e instanceof Error)) {
33418
- e = new Error(e);
33419
- }
33420
- const msg = e?.errorType || CellErrorType.GenericError;
33421
- // apply function name
33422
- const __lastFnCalled = compilationParameters[2].__lastFnCalled || "";
33423
- const error = new EvaluationError(msg, e.message.replace("[[FUNCTION_NAME]]", __lastFnCalled), e.logLevel !== undefined ? e.logLevel : CellErrorLevel.error);
33424
- return errorCell(cell.content, error);
33425
- };
33426
- const computeFormulaCell = (cellData) => {
33427
- const cellId = cellData.id;
33428
- if (cellsBeingComputed.has(cellId)) {
33429
- throw new CircularDependencyError();
33430
- }
33431
- compilationParameters[2].__originCellXC = () => {
33432
- // compute the value lazily for performance reasons
33433
- const position = compilationParameters[2].getters.getCellPosition(cellId);
33434
- return toXC(position.col, position.row);
33435
- };
33436
- cellsBeingComputed.add(cellId);
33437
- const computedCell = cellData.compiledFormula.execute(cellData.dependencies, ...compilationParameters);
33438
- cellsBeingComputed.delete(cellId);
33439
- if (Array.isArray(computedCell.value)) {
33440
- // if a value returns an array (like =A1:A3)
33441
- throw new Error(_lt("This formula depends on invalid values"));
33442
- }
33443
- return createEvaluatedCell(computedCell.value, cellData.format || computedCell.format);
33444
- };
33445
- const compilationParameters = this.getCompilationParameters((cell) => computeCell(cell)());
33446
- for (const cell of this.getAllCells()) {
33447
- this.setEvaluatedCell(cell.id, computeCell(cell));
33448
- }
33449
- }
33450
- /**
33451
- * Return all functions necessary to properly evaluate a formula:
33452
- * - a refFn function to read any reference, cell or range of a normalized formula
33453
- * - a range function to convert any reference to a proper value array
33454
- * - an evaluation context
33455
- */
33456
- getCompilationParameters(computeCell) {
33457
- const evalContext = Object.assign(Object.create(functionMap), this.evalContext, {
33458
- getters: this.getters,
33459
- });
33460
- const getters = this.getters;
33461
- function readCell(range) {
33462
- let cell;
33463
- if (!getters.tryGetSheet(range.sheetId)) {
33464
- throw new Error(_lt("Invalid sheet name"));
33465
- }
33466
- cell = getters.getCell({ sheetId: range.sheetId, col: range.zone.left, row: range.zone.top });
33467
- if (!cell || cell.content === "") {
33468
- // magic "empty" value
33469
- // Returning {value: null} instead of undefined will ensure that we don't
33470
- // fall back on the default value of the argument provided to the formula's compute function
33471
- return { value: null, format: cell?.format };
33472
- }
33473
- return getEvaluatedCell(cell);
33474
- }
33475
- const getEvaluatedCell = (cell) => {
33476
- const evaluatedCell = computeCell(cell);
33477
- if (evaluatedCell.type === CellValueType.error) {
33478
- throw evaluatedCell.error;
33479
- }
33480
- return evaluatedCell;
33481
- };
33482
- /**
33483
- * Return the values of the cell(s) used in reference, but always in the format of a range even
33484
- * if a single cell is referenced. It is a list of col values. This is useful for the formulas that describe parameters as
33485
- * range<number> etc.
33486
- *
33487
- * Note that each col is possibly sparse: it only contain the values of cells
33488
- * that are actually present in the grid.
33489
- */
33490
- function range(range) {
33491
- const sheetId = range.sheetId;
33492
- if (!isZoneValid(range.zone)) {
33493
- throw new InvalidReferenceError();
33494
- }
33495
- // Performance issue: Avoid fetching data on positions that are out of the spreadsheet
33496
- // e.g. A1:ZZZ9999 in a sheet with 10 cols and 10 rows should ignore everything past J10 and return a 10x10 array
33497
- const sheetZone = getters.getSheetZone(sheetId);
33498
- const result = [];
33499
- const zone = intersection(range.zone, sheetZone);
33500
- if (!zone) {
33501
- result.push([]);
33502
- return result;
33503
- }
33504
- // Performance issue: nested loop is faster than a map here
33505
- for (let col = zone.left; col <= zone.right; col++) {
33506
- const rowValues = [];
33507
- for (let row = zone.top; row <= zone.bottom; row++) {
33508
- const cell = evalContext.getters.getCell({ sheetId: range.sheetId, col, row });
33509
- rowValues.push(cell ? getEvaluatedCell(cell) : undefined);
33510
- }
33511
- result.push(rowValues);
33512
- }
33513
- return result;
33514
- }
33515
- /**
33516
- * Returns the value of the cell(s) used in reference
33517
- *
33518
- * @param range the references used
33519
- * @param isMeta if a reference is supposed to be used in a `meta` parameter as described in the
33520
- * function for which this parameter is used, we just return the string of the parameter.
33521
- * The `compute` of the formula's function must process it completely
33522
- */
33523
- function refFn(range, isMeta, functionName, paramNumber) {
33524
- if (isMeta) {
33525
- // Use zoneToXc of zone instead of getRangeString to avoid sending unbounded ranges
33526
- return { value: zoneToXc(range.zone) };
33527
- }
33528
- if (!isZoneValid(range.zone)) {
33529
- throw new InvalidReferenceError();
33530
- }
33531
- // if the formula definition could have accepted a range, we would pass through the _range function and not here
33532
- if (range.zone.bottom !== range.zone.top || range.zone.left !== range.zone.right) {
33533
- throw new Error(paramNumber
33534
- ? _lt("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.", functionName.toString(), paramNumber.toString())
33535
- : _lt("Function %s expects its parameters to be single values or single cell references, not ranges.", functionName.toString()));
33536
- }
33537
- if (range.invalidSheetName) {
33538
- throw new Error(_lt("Invalid sheet name: %s", range.invalidSheetName));
33539
- }
33540
- return readCell(range);
33541
- }
33542
- return [refFn, range, evalContext];
33543
- }
33544
- // ---------------------------------------------------------------------------
33545
- // Export
33546
- // ---------------------------------------------------------------------------
33547
- exportForExcel(data) {
33548
- for (let sheet of data.sheets) {
33549
- for (const xc in sheet.cells) {
33550
- const position = { sheetId: sheet.id, ...toCartesian(xc) };
33551
- const cell = this.getters.getCell(position);
33552
- if (cell) {
33553
- const exportedCellData = sheet.cells[xc];
33554
- const evaluatedCell = this.getEvaluatedCell(position);
33555
- exportedCellData.value = evaluatedCell.value;
33556
- exportedCellData.isFormula = cell.isFormula && !this.isBadExpression(cell.content);
33557
- if (cell.format !== evaluatedCell.format) {
33558
- exportedCellData.computedFormat = evaluatedCell.format;
33559
- }
33560
- }
33561
- }
33562
- }
33563
- }
33564
- isBadExpression(formula) {
33565
- try {
33566
- compile(formula);
33567
- return false;
33568
- }
33569
- catch (error) {
33570
- return true;
33571
- }
33572
- }
33573
- }
33574
-
33575
34210
  class EvaluationChartPlugin extends UIPlugin {
33576
34211
  static getters = ["getChartRuntime", "getBackgroundOfSingleCellChart"];
33577
34212
  charts = {};
@@ -45790,44 +46425,30 @@
45790
46425
 
45791
46426
  function addFormula(cell) {
45792
46427
  const formula = cell.content;
45793
- const functions = functionRegistry.content;
45794
- const tokens = tokenize(formula);
45795
46428
  const attrs = [];
45796
46429
  let node = escapeXml ``;
45797
- const isExported = tokens
45798
- .filter((tk) => tk.type === "FUNCTION")
45799
- .every((tk) => functions[tk.value.toUpperCase()].isExported);
45800
- if (isExported) {
45801
- let cycle = escapeXml ``;
45802
- const XlsxFormula = adaptFormulaToExcel(formula);
45803
- // hack for cycles : if we don't set a value (be it 0 or #VALUE!), it will appear as invisible on excel,
45804
- // Making it very hard for the client to find where the recursion is.
45805
- if (cell.value === CellErrorType.CircularDependency) {
45806
- attrs.push(["t", "str"]);
45807
- cycle = escapeXml /*xml*/ `<v>${cell.value}</v>`;
45808
- }
45809
- node = escapeXml /*xml*/ `
46430
+ let cycle = escapeXml ``;
46431
+ const XlsxFormula = adaptFormulaToExcel(formula);
46432
+ // hack for cycles : if we don't set a value (be it 0 or #VALUE!), it will appear as invisible on excel,
46433
+ // Making it very hard for the client to find where the recursion is.
46434
+ if (cell.value === CellErrorType.CircularDependency) {
46435
+ attrs.push(["t", "str"]);
46436
+ cycle = escapeXml /*xml*/ `<v>${cell.value}</v>`;
46437
+ }
46438
+ node = escapeXml /*xml*/ `
45810
46439
  <f>
45811
46440
  ${XlsxFormula}
45812
46441
  </f>
45813
46442
  ${cycle}
45814
46443
  `;
45815
- return { attrs, node };
45816
- }
45817
- else {
45818
- // Shouldn't we always output the value then ?
45819
- const value = cell.value;
45820
- const type = getCellType(value);
45821
- attrs.push(["t", type]);
45822
- node = escapeXml /*xml*/ `<v>${value}</v>`;
45823
- return { attrs, node };
45824
- }
46444
+ return { attrs, node };
45825
46445
  }
45826
46446
  function addContent(content, sharedStrings, forceString = false) {
45827
46447
  let value = content;
45828
46448
  const attrs = [];
45829
- if (!forceString && ["TRUE", "FALSE"].includes(value.trim())) {
45830
- value = value === "TRUE" ? "1" : "0";
46449
+ const clearValue = value.trim().toUpperCase();
46450
+ if (!forceString && ["TRUE", "FALSE"].includes(clearValue)) {
46451
+ value = clearValue === "TRUE" ? "1" : "0";
45831
46452
  attrs.push(["t", "b"]);
45832
46453
  }
45833
46454
  else if (forceString || !isNumber(value)) {
@@ -47218,7 +47839,6 @@
47218
47839
  moveClient: () => { },
47219
47840
  snapshotRequested: false,
47220
47841
  notifyUI: (payload) => this.trigger("notify-ui", payload),
47221
- lazyEvaluation: "lazyEvaluation" in config ? config.lazyEvaluation : true,
47222
47842
  };
47223
47843
  }
47224
47844
  setupCorePluginConfig() {
@@ -47241,7 +47861,6 @@
47241
47861
  moveClient: this.session.move.bind(this.session),
47242
47862
  custom: this.config.custom,
47243
47863
  uiActions: this.config,
47244
- lazyEvaluation: this.config.lazyEvaluation,
47245
47864
  session: this.session,
47246
47865
  };
47247
47866
  }
@@ -47582,9 +48201,9 @@
47582
48201
  Object.defineProperty(exports, '__esModule', { value: true });
47583
48202
 
47584
48203
 
47585
- __info__.version = '16.3.1';
47586
- __info__.date = '2023-05-25T13:00:27.320Z';
47587
- __info__.hash = 'b3cfd2c';
48204
+ __info__.version = '16.4.0-alpha.1';
48205
+ __info__.date = '2023-05-25T13:00:14.133Z';
48206
+ __info__.hash = '564c094';
47588
48207
 
47589
48208
 
47590
48209
  })(this.o_spreadsheet = this.o_spreadsheet || {}, owl);