@file-viewer/renderer-spreadsheet 3.2.2 → 3.3.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.
Files changed (30) hide show
  1. package/README.en.md +13 -3
  2. package/README.md +30 -20
  3. package/README.zh-CN.md +73 -0
  4. package/dist/spreadsheet/chartRenderer.js +5 -0
  5. package/dist/spreadsheet/chartSampling.d.ts +4 -0
  6. package/dist/spreadsheet/chartSampling.js +6 -0
  7. package/dist/spreadsheet/rangeNavigation.d.ts +2 -0
  8. package/dist/spreadsheet/rangeNavigation.js +4 -0
  9. package/dist/spreadsheet/state.d.ts +1 -0
  10. package/dist/spreadsheet/state.js +2 -0
  11. package/dist/spreadsheet/view.js +14 -2
  12. package/dist/spreadsheet/viewport.d.ts +1 -0
  13. package/dist/spreadsheet/viewport.js +4 -2
  14. package/dist/spreadsheet/worker/sheetjs/SheetJsModel.js +39 -15
  15. package/dist/spreadsheet/worker/sheetjs/chartParser.js +30 -0
  16. package/dist/spreadsheet/worker/sheetjs/color.js +10 -8
  17. package/dist/spreadsheet/worker/sheetjs/formulaValues.d.ts +5 -0
  18. package/dist/spreadsheet/worker/sheetjs/formulaValues.js +421 -0
  19. package/dist/spreadsheet/worker/sheetjs/parser.d.ts +1 -0
  20. package/dist/spreadsheet/worker/sheetjs/parser.js +89 -17
  21. package/dist/spreadsheet/worker/sheetjs/richDataParser.js +2 -0
  22. package/dist/spreadsheet/worker/sheetjs/richText.js +2 -1
  23. package/dist/spreadsheet/worker/sheetjs/sheetLayout.d.ts +13 -0
  24. package/dist/spreadsheet/worker/sheetjs/sheetLayout.js +68 -0
  25. package/dist/spreadsheet/worker/sheetjs/textEncoding.js +7 -0
  26. package/dist/spreadsheet/worker/type.d.ts +3 -0
  27. package/dist/spreadsheet.js +24 -0
  28. package/dist/worker/sheet.worker.js +48 -48
  29. package/dist/worker.THIRD_PARTY_LICENSES.txt +1 -1
  30. package/package.json +7 -2
@@ -1,10 +1,12 @@
1
1
  import { DOMParser } from '@xmldom/xmldom';
2
2
  import JSZip from 'jszip';
3
+ import { readStoredSheetLayout, readWorkbookDigitWidth } from './sheetLayout.js';
3
4
  import { extremaPointIndexes, MAX_TRANSFERRED_LINE_CHART_POINTS } from '../../chartSampling.js';
4
5
  const CHART_RELATIONSHIP_SUFFIX = '/chart';
5
6
  const DRAWING_RELATIONSHIP_SUFFIX = '/drawing';
6
7
  const WORKSHEET_RELATIONSHIP_SUFFIX = '/worksheet';
7
8
  const EMUS_PER_CSS_PIXEL = 9525;
9
+ // Bound cache indices and formula expansion before allocating producer-controlled arrays.
8
10
  const MAX_CHART_POINTS = 1048576;
9
11
  const CHART_TYPE_MAP = {
10
12
  areaChart: 'area',
@@ -115,6 +117,9 @@ const relationshipPartPath = (sourcePart) => {
115
117
  return `${directory ? `${directory}/` : ''}_rels/${filename}.rels`;
116
118
  };
117
119
  const parseXml = (xml) => {
120
+ // Some valid Office producers prefix relationship parts with a UTF-8 BOM.
121
+ // XML declarations must otherwise be the first character, and xmldom reports
122
+ // the BOM as content outside the root element before aborting chart parsing.
118
123
  return new DOMParser().parseFromString(xml.replace(/^[\uFEFF\s]+/, ''), 'application/xml');
119
124
  };
120
125
  export const loadXml = async (zip, path) => {
@@ -246,6 +251,8 @@ const parsePointValues = (element, workbook, formatted = true) => {
246
251
  if (!element) {
247
252
  return [];
248
253
  }
254
+ // Cache point idx is a logical source position, not the point's XML order.
255
+ // Select one cache/level; flattening nested caches mixes category hierarchies.
249
256
  const literal = firstChildByLocal(element, 'strLit') || firstChildByLocal(element, 'numLit');
250
257
  const reference = firstChildByLocal(element, 'strRef') || firstChildByLocal(element, 'numRef');
251
258
  const multiLevel = firstChildByLocal(firstChildByLocal(element, 'multiLvlStrRef'), 'multiLvlStrCache');
@@ -271,6 +278,9 @@ const parsePointValues = (element, workbook, formatted = true) => {
271
278
  const values = Array(count).fill('');
272
279
  for (const point of entries)
273
280
  values[point.index] = point.value;
281
+ // A declared domain with missing points is an intentional sparse cache.
282
+ // A zero-length reference cache supplies no domain; Office producers use
283
+ // it as a placeholder until Excel recalculates the worksheet formula.
274
284
  if (count || literal || !reference)
275
285
  return values;
276
286
  }
@@ -348,6 +358,8 @@ const parseSeries = (chartNode, workbook, blankMode = 'gap') => {
348
358
  spanBlankIndexes.push(pointIndex);
349
359
  return blankMode === 'zero' ? 0 : Number.NaN;
350
360
  }
361
+ // Empty cells and error values are not zero. Keep an error as a hard gap,
362
+ // even when blank cells are explicitly spanned or plotted as zero.
351
363
  const number = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(raw) ? Number(raw) : NaN;
352
364
  return Number.isFinite(number) ? number : Number.NaN;
353
365
  });
@@ -380,6 +392,7 @@ const parseSeries = (chartNode, workbook, blankMode = 'gap') => {
380
392
  };
381
393
  });
382
394
  };
395
+ /** DrawingML font sizes are hundredths of a point, not SVG viewport units. */
383
396
  const parseAxisFontSize = (axis, chartSpace) => {
384
397
  var _a;
385
398
  const size = (node) => {
@@ -469,6 +482,7 @@ const parseDrawingCharts = async (zip, drawingPart, workbook) => {
469
482
  return charts.filter((chart) => chart !== null);
470
483
  };
471
484
  export const parseSpreadsheetCharts = async (data, workbook) => {
485
+ var _a;
472
486
  const zip = await JSZip.loadAsync(data);
473
487
  const workbookPart = 'xl/workbook.xml';
474
488
  const [workbookDocument, workbookRelationships] = await Promise.all([
@@ -479,12 +493,28 @@ export const parseSpreadsheetCharts = async (data, workbook) => {
479
493
  if (!workbookDocument) {
480
494
  return result;
481
495
  }
496
+ const maximumDigitWidth = readWorkbookDigitWidth(workbook);
482
497
  for (const sheet of elementsByLocal(workbookDocument.documentElement, 'sheet')) {
483
498
  const name = sheet.getAttribute('name') || '';
484
499
  const worksheetRelationship = relationById(workbookRelationships, relationshipId(sheet));
485
500
  if (!name || !(worksheetRelationship === null || worksheetRelationship === void 0 ? void 0 : worksheetRelationship.type.endsWith(WORKSHEET_RELATIONSHIP_SUFFIX))) {
486
501
  continue;
487
502
  }
503
+ // A missing <col> uses the worksheet's stored/default geometry, rather
504
+ // than content auto-fit. Keep this metadata even when there are no charts.
505
+ const worksheet = (_a = workbook === null || workbook === void 0 ? void 0 : workbook.Sheets) === null || _a === void 0 ? void 0 : _a[name];
506
+ if (worksheet) {
507
+ worksheet['!fileViewerLayout'] = {};
508
+ worksheet['!fileViewerLayout'] = {
509
+ ...await readStoredSheetLayout(zip, worksheetRelationship.target),
510
+ maximumDigitWidth
511
+ };
512
+ }
513
+ // A worksheet can expand to hundreds of megabytes even when the drawing
514
+ // relationship part is only a few hundred bytes. Loading sheetN.xml as a
515
+ // string here duplicates the cell parser's work and can exceed V8's string
516
+ // limit before chart parsing starts. Drawing relationships already carry
517
+ // the typed targets needed by the chart parser, so discover them directly.
488
518
  const worksheetRelationships = await loadRelationships(zip, worksheetRelationship.target);
489
519
  const drawingParts = Array.from(new Set(worksheetRelationships
490
520
  .filter((relationship) => relationship.type.endsWith(DRAWING_RELATIONSHIP_SUFFIX))
@@ -1,16 +1,17 @@
1
1
  import tinycolor from 'tinycolor2';
2
2
  export const indexedColors = [
3
- 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF',
4
- 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF',
5
- 'FF800000', 'FF008000', 'FF000080', 'FF808000', 'FF800080', 'FF008080', 'FFC0C0C0', 'FF808080',
6
- 'FF9999FF', 'FF993366', 'FFFFFFCC', 'FFCCFFFF', 'FF660066', 'FFFF8080', 'FF0066CC', 'FFCCCCFF',
7
- 'FF000080', 'FFFF00FF', 'FFFFFF00', 'FF00FFFF', 'FF800080', 'FF800000', 'FF008080', 'FF0000FF',
8
- 'FF00CCFF', 'FFCCFFFF', 'FFCCFFCC', 'FFFFFF99', 'FF99CCFF', 'FFFF99CC', 'FFCC99FF', 'FFFFCC99',
9
- 'FF3366FF', 'FF33CCCC', 'FF99CC00', 'FFFFCC00', 'FFFF9900', 'FFFF6600', 'FF666699', 'FF969696',
10
- 'FF003366', 'FF339966', 'FF003300', 'FF333300', 'FF993300', 'FF993366', 'FF333399', 'FF333333'
3
+ 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF', // 0-7
4
+ 'FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF', 'FFFFFF00', 'FFFF00FF', 'FF00FFFF', // 8-15
5
+ 'FF800000', 'FF008000', 'FF000080', 'FF808000', 'FF800080', 'FF008080', 'FFC0C0C0', 'FF808080', // 16-23
6
+ 'FF9999FF', 'FF993366', 'FFFFFFCC', 'FFCCFFFF', 'FF660066', 'FFFF8080', 'FF0066CC', 'FFCCCCFF', // 24-31
7
+ 'FF000080', 'FFFF00FF', 'FFFFFF00', 'FF00FFFF', 'FF800080', 'FF800000', 'FF008080', 'FF0000FF', // 32-39
8
+ 'FF00CCFF', 'FFCCFFFF', 'FFCCFFCC', 'FFFFFF99', 'FF99CCFF', 'FFFF99CC', 'FFCC99FF', 'FFFFCC99', // 40-47
9
+ 'FF3366FF', 'FF33CCCC', 'FF99CC00', 'FFFFCC00', 'FFFF9900', 'FFFF6600', 'FF666699', 'FF969696', // 48-55
10
+ 'FF003366', 'FF339966', 'FF003300', 'FF333300', 'FF993300', 'FF993366', 'FF333399', 'FF333333' // 56-63
11
11
  ];
12
12
  const HLSMAX = 240;
13
13
  const RGBMAX = 0xFF;
14
+ // Excel 主题色的 tint 计算使用微软 HLS 取值范围,和浏览器 HSL 不是同一套刻度。
14
15
  function rgb2hls(r, g, b) {
15
16
  const maxc = Math.max(r, g, b);
16
17
  const minc = Math.min(r, g, b);
@@ -62,6 +63,7 @@ function tintLuminance(tint, lum) {
62
63
  }
63
64
  return Math.round(lum * (1.0 - tint) + (HLSMAX - HLSMAX * (1.0 - tint)));
64
65
  }
66
+ // 根据主题原始色和 tint 还原 Excel 实际显示色。
65
67
  export function getTintColor(hex, tint) {
66
68
  if (!hex) {
67
69
  return hex;
@@ -0,0 +1,5 @@
1
+ import type { WorkBook } from 'styled-exceljs';
2
+ export declare function recoverUncachedFormulaValues(workbook: WorkBook): {
3
+ calculated: number;
4
+ unavailable: number;
5
+ };
@@ -0,0 +1,421 @@
1
+ import { utils } from 'styled-exceljs';
2
+ const MAX_STEPS = 2000000;
3
+ const MAX_DEPTH = 128;
4
+ const ADDRESS = /^\$?([A-Z]{1,3})\$?([1-9][0-9]*)$/i;
5
+ const unavailable = () => {
6
+ throw new Error('Formula value unavailable');
7
+ };
8
+ function tokenize(formula) {
9
+ if (formula.length > 8192)
10
+ return unavailable();
11
+ const tokens = [];
12
+ let rest = formula.replace(/^=/, '');
13
+ while (rest.length) {
14
+ const space = /^\s+/.exec(rest);
15
+ if (space) {
16
+ rest = rest.slice(space[0].length);
17
+ continue;
18
+ }
19
+ const match = /^(?:"(?:[^"]|"")*"|'(?:[^']|'')*'|(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?|[\p{L}_$\\][\p{L}\p{N}_.$\\]*|<>|<=|>=|[+\-*/^&=<>%(),!:])/u.exec(rest);
20
+ if (!match || tokens.length >= 4096)
21
+ return unavailable();
22
+ const text = match[0];
23
+ tokens.push({
24
+ kind: text[0] === '"'
25
+ ? 'string'
26
+ : text[0] === "'"
27
+ ? 'quoted'
28
+ : /^[\d.]/.test(text)
29
+ ? 'number'
30
+ : /^[\p{L}_$\\]/u.test(text)
31
+ ? 'name'
32
+ : text,
33
+ text
34
+ });
35
+ rest = rest.slice(text.length);
36
+ }
37
+ tokens.push({ kind: 'eof', text: '' });
38
+ return tokens;
39
+ }
40
+ class FormulaParser {
41
+ constructor(tokens) {
42
+ this.tokens = tokens;
43
+ this.index = 0;
44
+ this.depth = 0;
45
+ }
46
+ current() {
47
+ return this.tokens[this.index];
48
+ }
49
+ take(kind) {
50
+ if (this.current().kind !== kind)
51
+ return false;
52
+ this.index++;
53
+ return true;
54
+ }
55
+ parse() {
56
+ const result = this.expression();
57
+ if (this.current().kind !== 'eof')
58
+ return unavailable();
59
+ return result;
60
+ }
61
+ expression(minimum = 0) {
62
+ var _a;
63
+ if (++this.depth > MAX_DEPTH)
64
+ return unavailable();
65
+ let left = this.primary();
66
+ const precedence = {
67
+ '=': 1,
68
+ '<>': 1,
69
+ '<': 1,
70
+ '>': 1,
71
+ '<=': 1,
72
+ '>=': 1,
73
+ '&': 2,
74
+ '+': 3,
75
+ '-': 3,
76
+ '*': 4,
77
+ '/': 4,
78
+ '^': 5
79
+ };
80
+ while (((_a = precedence[this.current().kind]) !== null && _a !== void 0 ? _a : -1) >= minimum) {
81
+ const op = this.tokens[this.index++].kind;
82
+ // Excel exponentiation is left associative.
83
+ left = { kind: 'binary', op, left, right: this.expression(precedence[op] + 1) };
84
+ }
85
+ this.depth--;
86
+ return left;
87
+ }
88
+ primary() {
89
+ const token = this.tokens[this.index++];
90
+ let result;
91
+ if (token.kind === '+' || token.kind === '-') {
92
+ result = { kind: 'unary', op: token.kind, value: this.expression(6) };
93
+ }
94
+ else if (token.kind === 'number') {
95
+ const value = Number(token.text);
96
+ if (!Number.isFinite(value))
97
+ return unavailable();
98
+ result = { kind: 'value', value };
99
+ }
100
+ else if (token.kind === 'string') {
101
+ result = { kind: 'value', value: token.text.slice(1, -1).replace(/""/g, '"') };
102
+ }
103
+ else if (token.kind === '(') {
104
+ result = this.expression();
105
+ if (!this.take(')'))
106
+ return unavailable();
107
+ }
108
+ else if (token.kind === 'name' || token.kind === 'quoted') {
109
+ if (token.kind === 'name' && this.take('(')) {
110
+ const args = [];
111
+ if (!this.take(')')) {
112
+ do {
113
+ args.push(this.expression());
114
+ } while (this.take(','));
115
+ if (!this.take(')'))
116
+ return unavailable();
117
+ }
118
+ result = { kind: 'call', name: token.text.toUpperCase(), args };
119
+ }
120
+ else {
121
+ let address = token.text;
122
+ let sheet;
123
+ if (this.take('!')) {
124
+ sheet = token.kind === 'quoted' ? token.text.slice(1, -1).replace(/''/g, "'") : token.text;
125
+ address = this.tokens[this.index++].text;
126
+ }
127
+ else if (/^(TRUE|FALSE)$/i.test(address)) {
128
+ return { kind: 'value', value: address.toUpperCase() === 'TRUE' };
129
+ }
130
+ if (!ADDRESS.test(address))
131
+ return unavailable();
132
+ let end;
133
+ if (this.take(':')) {
134
+ end = this.tokens[this.index++].text;
135
+ if (!ADDRESS.test(end))
136
+ return unavailable();
137
+ }
138
+ result = { kind: 'ref', sheet, address, end };
139
+ }
140
+ }
141
+ else
142
+ return unavailable();
143
+ while (this.take('%'))
144
+ result = { kind: 'unary', op: '%', value: result };
145
+ return result;
146
+ }
147
+ }
148
+ const position = (address) => {
149
+ const match = ADDRESS.exec(address);
150
+ if (!match)
151
+ return unavailable();
152
+ let col = 0;
153
+ for (const char of match[1].toUpperCase())
154
+ col = col * 26 + char.charCodeAt(0) - 64;
155
+ const row = Number(match[2]);
156
+ if (col > 16384 || row > 1048576)
157
+ return unavailable();
158
+ return { row: row - 1, col: col - 1 };
159
+ };
160
+ const key = (row, col) => `${row}:${col}`;
161
+ const numeric = (value) => {
162
+ if (value === null)
163
+ return 0;
164
+ if (typeof value === 'boolean')
165
+ return value ? 1 : 0;
166
+ // Blank cells use null. Empty strings and JavaScript-only hexadecimal text
167
+ // are not Excel arithmetic numbers and must not silently become 0 or 16.
168
+ if (typeof value === 'string' &&
169
+ !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?$/.test(value.trim()))
170
+ return unavailable();
171
+ const number = typeof value === 'string' ? Number(value.trim()) : value;
172
+ if (!Number.isFinite(number))
173
+ return unavailable();
174
+ return number;
175
+ };
176
+ const scalar = (value) => (Array.isArray(value) ? unavailable() : value);
177
+ const textValue = (value) => typeof value === 'boolean' ? (value ? 'TRUE' : 'FALSE') : String(value !== null && value !== void 0 ? value : '');
178
+ const needsValue = (cell) => !!cell.f && (cell.t === 'z' || cell.v === undefined || cell.v === null);
179
+ function cellsOf(sheet) {
180
+ const result = new Map();
181
+ const data = Array.isArray(sheet)
182
+ ? sheet
183
+ : sheet['!data'];
184
+ if (data) {
185
+ for (const rowKey of Object.keys(data)) {
186
+ const row = Number(rowKey);
187
+ if (!Number.isInteger(row) || row < 0 || !Array.isArray(data[row]))
188
+ continue;
189
+ for (const colKey of Object.keys(data[row])) {
190
+ const col = Number(colKey), cell = data[row][col];
191
+ if (Number.isInteger(col) && col >= 0 && cell && needsValue(cell))
192
+ result.set(key(row, col), cell);
193
+ }
194
+ }
195
+ }
196
+ else {
197
+ for (const address of Object.keys(sheet)) {
198
+ if (!ADDRESS.test(address))
199
+ continue;
200
+ const { row, col } = position(address);
201
+ if (sheet[address] && needsValue(sheet[address]))
202
+ result.set(key(row, col), sheet[address]);
203
+ }
204
+ }
205
+ return result;
206
+ }
207
+ export function recoverUncachedFormulaValues(workbook) {
208
+ var _a;
209
+ const sheets = new Map(workbook.SheetNames.map((name) => [
210
+ name.toLowerCase(),
211
+ { name, sheet: workbook.Sheets[name], cells: cellsOf(workbook.Sheets[name]) }
212
+ ]));
213
+ const results = new Map();
214
+ const failed = new Set();
215
+ const visiting = new Set();
216
+ let steps = 0;
217
+ const tick = () => {
218
+ if (++steps > MAX_STEPS)
219
+ return unavailable();
220
+ };
221
+ const resolveSheet = (name) => { var _a; return (_a = sheets.get(name.toLowerCase())) !== null && _a !== void 0 ? _a : unavailable(); };
222
+ const readCell = (name, row, col, depth) => {
223
+ var _a, _b;
224
+ tick();
225
+ if (depth > MAX_DEPTH)
226
+ return unavailable();
227
+ const { sheet } = resolveSheet(name);
228
+ const data = Array.isArray(sheet)
229
+ ? sheet
230
+ : sheet['!data'];
231
+ const cell = data
232
+ ? (_a = data[row]) === null || _a === void 0 ? void 0 : _a[col]
233
+ : sheet[utils.encode_cell({ r: row, c: col })];
234
+ if (!cell)
235
+ return null;
236
+ if (results.has(cell))
237
+ return results.get(cell);
238
+ if (failed.has(cell) || visiting.has(cell) || cell.t === 'e')
239
+ return unavailable();
240
+ if (!needsValue(cell)) {
241
+ if (cell.v instanceof Date)
242
+ return unavailable();
243
+ const value = (_b = cell.v) !== null && _b !== void 0 ? _b : null;
244
+ return typeof value === 'number' && !Number.isFinite(value) ? unavailable() : value;
245
+ }
246
+ visiting.add(cell);
247
+ try {
248
+ const tree = new FormulaParser(tokenize(cell.f)).parse();
249
+ const value = scalar(evaluate(tree, name, row, depth + 1));
250
+ if (typeof value === 'number' && !Number.isFinite(value))
251
+ return unavailable();
252
+ results.set(cell, value);
253
+ return value;
254
+ }
255
+ catch {
256
+ failed.add(cell);
257
+ return unavailable();
258
+ }
259
+ finally {
260
+ visiting.delete(cell);
261
+ }
262
+ };
263
+ const evaluate = (node, sheet, row, depth) => {
264
+ var _a, _b;
265
+ tick();
266
+ if (depth > MAX_DEPTH)
267
+ return unavailable();
268
+ const run = (child) => evaluate(child, sheet, row, depth + 1);
269
+ if (node.kind === 'value')
270
+ return node.value;
271
+ if (node.kind === 'ref') {
272
+ const start = position(node.address);
273
+ if (!node.end)
274
+ return readCell((_a = node.sheet) !== null && _a !== void 0 ? _a : sheet, start.row, start.col, depth + 1);
275
+ const end = position(node.end);
276
+ const minRow = Math.min(start.row, end.row), maxRow = Math.max(start.row, end.row);
277
+ const minCol = Math.min(start.col, end.col), maxCol = Math.max(start.col, end.col);
278
+ if ((maxRow - minRow + 1) * (maxCol - minCol + 1) > MAX_STEPS - steps)
279
+ return unavailable();
280
+ const values = [];
281
+ for (let r = minRow; r <= maxRow; r++)
282
+ for (let c = minCol; c <= maxCol; c++)
283
+ values.push(readCell((_b = node.sheet) !== null && _b !== void 0 ? _b : sheet, r, c, depth + 1));
284
+ return values;
285
+ }
286
+ if (node.kind === 'unary') {
287
+ const number = numeric(scalar(run(node.value)));
288
+ return node.op === '-' ? -number : node.op === '%' ? number / 100 : number;
289
+ }
290
+ if (node.kind === 'binary') {
291
+ const left = scalar(run(node.left)), right = scalar(run(node.right));
292
+ if (node.op === '&')
293
+ return textValue(left) + textValue(right);
294
+ if (['=', '<>', '<', '>', '<=', '>='].includes(node.op)) {
295
+ // Excel compares text without case sensitivity. Different value types
296
+ // are ordered number < text < logical; empty cells take the other type.
297
+ const normalize = (value, other) => value === null
298
+ ? typeof other === 'string'
299
+ ? ''
300
+ : typeof other === 'boolean'
301
+ ? false
302
+ : 0
303
+ : typeof value === 'string'
304
+ ? value.toUpperCase()
305
+ : value;
306
+ const a = normalize(left, right), b = normalize(right, left);
307
+ const rank = (value) => typeof value === 'number' ? 0 : typeof value === 'string' ? 1 : 2;
308
+ const comparison = typeof a === typeof b ? (a === b ? 0 : a < b ? -1 : 1) : rank(a) - rank(b);
309
+ return node.op === '='
310
+ ? comparison === 0
311
+ : node.op === '<>'
312
+ ? comparison !== 0
313
+ : node.op === '<'
314
+ ? comparison < 0
315
+ : node.op === '>'
316
+ ? comparison > 0
317
+ : node.op === '<='
318
+ ? comparison <= 0
319
+ : comparison >= 0;
320
+ }
321
+ const a = numeric(left), b = numeric(right);
322
+ if (node.op === '/' && b === 0)
323
+ return unavailable();
324
+ // Office POWER(0,0) is an error, unlike JavaScript's finite result1.
325
+ if (node.op === '^' && a === 0 && b === 0)
326
+ return unavailable();
327
+ const value = node.op === '+'
328
+ ? a + b
329
+ : node.op === '-'
330
+ ? a - b
331
+ : node.op === '*'
332
+ ? a * b
333
+ : node.op === '/'
334
+ ? a / b
335
+ : a ** b;
336
+ return Number.isFinite(value) ? value : unavailable();
337
+ }
338
+ if (node.name === 'IF' && (node.args.length === 2 || node.args.length === 3)) {
339
+ const condition = scalar(run(node.args[0]));
340
+ if (typeof condition === 'string' && !/^(TRUE|FALSE)$/i.test(condition))
341
+ return unavailable();
342
+ const truthy = typeof condition === 'string' ? condition.toUpperCase() === 'TRUE' : !!condition;
343
+ return truthy ? run(node.args[1]) : node.args[2] ? run(node.args[2]) : false;
344
+ }
345
+ if (node.name === 'ROW' && node.args.length <= 1) {
346
+ if (!node.args.length)
347
+ return row + 1;
348
+ const ref = node.args[0];
349
+ if (ref.kind !== 'ref')
350
+ return unavailable();
351
+ if (ref.sheet)
352
+ resolveSheet(ref.sheet);
353
+ return position(ref.address).row + 1;
354
+ }
355
+ if (node.name === 'ROUND' && node.args.length === 2) {
356
+ const value = numeric(scalar(run(node.args[0])));
357
+ const digits = Math.trunc(numeric(scalar(run(node.args[1]))));
358
+ if (Math.abs(digits) > 100)
359
+ return unavailable();
360
+ const scale = 10 ** digits, magnitude = Math.abs(value) * scale;
361
+ const rounded = Math.floor(magnitude + 0.5 + Number.EPSILON * magnitude) / scale;
362
+ return Number.isFinite(rounded) ? Math.sign(value) * rounded : unavailable();
363
+ }
364
+ if (node.name === 'SUM' && node.args.length > 0) {
365
+ let total = 0;
366
+ for (const arg of node.args) {
367
+ const value = run(arg);
368
+ if (Array.isArray(value)) {
369
+ for (const entry of value)
370
+ if (typeof entry === 'number')
371
+ total += entry;
372
+ }
373
+ else if (arg.kind === 'ref') {
374
+ if (typeof value === 'number')
375
+ total += value;
376
+ }
377
+ else
378
+ total += numeric(value);
379
+ }
380
+ return Number.isFinite(total) ? total : unavailable();
381
+ }
382
+ return unavailable();
383
+ };
384
+ let calculated = 0, unavailableCount = 0;
385
+ for (const { name, cells } of sheets.values())
386
+ for (const [location, cell] of cells) {
387
+ if (!needsValue(cell))
388
+ continue;
389
+ const [row, col] = location.split(':').map(Number);
390
+ try {
391
+ readCell(name, row, col, 0);
392
+ }
393
+ catch {
394
+ /* keep the original formula visible */
395
+ }
396
+ }
397
+ for (const { cells } of sheets.values())
398
+ for (const cell of cells.values()) {
399
+ if (!needsValue(cell))
400
+ continue;
401
+ if (results.has(cell)) {
402
+ const value = (_a = results.get(cell)) !== null && _a !== void 0 ? _a : 0;
403
+ cell.v = value;
404
+ cell.t = typeof value === 'boolean' ? 'b' : typeof value === 'string' ? 's' : 'n';
405
+ // The parser may have produced w="0" for an empty cached value.
406
+ delete cell.w;
407
+ try {
408
+ cell.w = utils.format_cell(cell);
409
+ }
410
+ catch {
411
+ /* plain value is still available */
412
+ }
413
+ calculated++;
414
+ }
415
+ else {
416
+ cell.w = `=${cell.f}`;
417
+ unavailableCount++;
418
+ }
419
+ }
420
+ return { calculated, unavailable: unavailableCount };
421
+ }
@@ -23,6 +23,7 @@ export interface SpreadsheetParserContext {
23
23
  cellImages: Record<string, SheetCellImage[]>;
24
24
  }
25
25
  export interface SpreadsheetWorkbookSource extends SpreadsheetTextSource {
26
+ /** Retain truly empty sheets only for the opt-in Excel viewport grid. */
26
27
  includeEmptySheets?: boolean;
27
28
  }
28
29
  export interface SpreadsheetWorkerRequest {