@file-viewer/renderer-spreadsheet 2.4.0 → 3.0.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.
@@ -1,5 +1,6 @@
1
1
  import { utils } from 'styled-exceljs';
2
2
  import { getTintColor, indexedColors } from './color.js';
3
+ import { parseCellRichText, richTextToPlainText } from './richText.js';
3
4
  const EXCEL_DEFAULT_COLUMN_WIDTH = 8.43;
4
5
  const EXCEL_DEFAULT_ROW_HEIGHT_PT = 15;
5
6
  const EXCEL_DEFAULT_TEXT_COLOR = '#202124';
@@ -64,6 +65,10 @@ const formatCellValue = (cell) => {
64
65
  if (!cell) {
65
66
  return '';
66
67
  }
68
+ const richText = parseCellRichText(cell);
69
+ if (richText === null || richText === void 0 ? void 0 : richText.length) {
70
+ return richTextToPlainText(richText);
71
+ }
67
72
  if (cell.w !== undefined && cell.w !== null) {
68
73
  return `${cell.w}`;
69
74
  }
@@ -285,11 +290,17 @@ const mergeStyle = (...styles) => {
285
290
  });
286
291
  return Object.keys(result).length ? result : undefined;
287
292
  };
293
+ const resolveTableCellStyle = (worksheet, rowIndex, colIndex, baseStyle) => {
294
+ const resolver = utils.resolve_table_cell_style;
295
+ return typeof resolver === 'function'
296
+ ? resolver(worksheet, rowIndex, colIndex, baseStyle)
297
+ : baseStyle;
298
+ };
288
299
  const getCellStyle = (cellStyle) => {
289
300
  const style = {};
290
301
  const fill = (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.fill) || {};
291
- const fillColor = normalizeColor((cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.fgColor) || fill.fgColor || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.bgColor) || fill.bgColor);
292
- const patternType = (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.patternType) || fill.patternType;
302
+ const fillColor = normalizeColor(fill.fgColor || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.fgColor) || fill.bgColor || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.bgColor));
303
+ const patternType = fill.patternType || (cellStyle === null || cellStyle === void 0 ? void 0 : cellStyle.patternType);
293
304
  if (fillColor && patternType !== 'none') {
294
305
  style.backgroundColor = fillColor;
295
306
  }
@@ -511,6 +522,7 @@ class SheetJsModel {
511
522
  valueAxisTitle: chart.valueAxisTitle,
512
523
  barDirection: chart.barDirection,
513
524
  grouping: chart.grouping,
525
+ scatterStyle: chart.scatterStyle,
514
526
  legendPosition: chart.legendPosition,
515
527
  series: chart.series,
516
528
  left: Math.max(0, left),
@@ -558,15 +570,18 @@ class SheetJsModel {
558
570
  for (let rowIndex = this.startRow; rowIndex < this.endRow; rowIndex += 1) {
559
571
  for (let colIndex = 0; colIndex < this.totalCols; colIndex += 1) {
560
572
  const cell = this.getCellAt(rowIndex, colIndex);
561
- const rawStyle = mergeStyle((_a = cols[colIndex]) === null || _a === void 0 ? void 0 : _a.s, (_b = rows[rowIndex]) === null || _b === void 0 ? void 0 : _b.s, cell === null || cell === void 0 ? void 0 : cell.s);
573
+ const inheritedStyle = mergeStyle((_a = cols[colIndex]) === null || _a === void 0 ? void 0 : _a.s, (_b = rows[rowIndex]) === null || _b === void 0 ? void 0 : _b.s, cell === null || cell === void 0 ? void 0 : cell.s);
574
+ const rawStyle = resolveTableCellStyle(this.ws, rowIndex, colIndex, inheritedStyle);
562
575
  const className = alignToClassName(rawStyle === null || rawStyle === void 0 ? void 0 : rawStyle.alignment);
563
576
  const style = getCellStyle(rawStyle);
564
- if (!className && !style) {
577
+ const richText = parseCellRichText(cell);
578
+ if (!className && !style && !(richText === null || richText === void 0 ? void 0 : richText.length)) {
565
579
  continue;
566
580
  }
567
581
  result[cellKey(rowIndex - this.startRow, colIndex)] = {
568
582
  ...(className ? { className } : {}),
569
- style: style || {}
583
+ style: style || {},
584
+ ...((richText === null || richText === void 0 ? void 0 : richText.length) ? { richText } : {})
570
585
  };
571
586
  }
572
587
  }
@@ -1,8 +1,10 @@
1
1
  import { DOMParser } from '@xmldom/xmldom';
2
2
  import JSZip from 'jszip';
3
+ import { extremaPointIndexes, MAX_TRANSFERRED_LINE_CHART_POINTS } from '../../chartSampling.js';
3
4
  const CHART_RELATIONSHIP_SUFFIX = '/chart';
4
5
  const DRAWING_RELATIONSHIP_SUFFIX = '/drawing';
5
6
  const WORKSHEET_RELATIONSHIP_SUFFIX = '/worksheet';
7
+ const EMUS_PER_CSS_PIXEL = 9525;
6
8
  const CHART_TYPE_MAP = {
7
9
  areaChart: 'area',
8
10
  area3DChart: 'area',
@@ -276,25 +278,70 @@ const parseSeriesColor = (series) => {
276
278
  const scheme = ((_b = firstByLocal(solidFill, 'schemeClr')) === null || _b === void 0 ? void 0 : _b.getAttribute('val')) || '';
277
279
  return SCHEME_COLORS[scheme];
278
280
  };
281
+ const parseSeriesLine = (series) => {
282
+ var _a;
283
+ const shape = firstChildByLocal(series, 'spPr');
284
+ const line = firstChildByLocal(shape, 'ln');
285
+ const widthEmus = Number(line === null || line === void 0 ? void 0 : line.getAttribute('w'));
286
+ return {
287
+ lineWidth: Number.isFinite(widthEmus) && widthEmus > 0 ? widthEmus / EMUS_PER_CSS_PIXEL : undefined,
288
+ lineDash: ((_a = firstChildByLocal(line, 'prstDash')) === null || _a === void 0 ? void 0 : _a.getAttribute('val')) || undefined,
289
+ lineVisible: line ? !firstChildByLocal(line, 'noFill') : undefined
290
+ };
291
+ };
292
+ const parseSeriesMarker = (series) => {
293
+ var _a, _b;
294
+ const marker = firstChildByLocal(series, 'marker');
295
+ if (!marker) {
296
+ return undefined;
297
+ }
298
+ const symbol = ((_a = firstChildByLocal(marker, 'symbol')) === null || _a === void 0 ? void 0 : _a.getAttribute('val')) || 'auto';
299
+ const sizeValue = Number((_b = firstChildByLocal(marker, 'size')) === null || _b === void 0 ? void 0 : _b.getAttribute('val'));
300
+ return {
301
+ symbol,
302
+ size: Number.isFinite(sizeValue) && sizeValue > 0 ? sizeValue : undefined
303
+ };
304
+ };
279
305
  const parseSeries = (chartNode, workbook) => {
306
+ const chartType = CHART_TYPE_MAP[localName(chartNode)];
307
+ const compactLineSeries = chartType === 'line'
308
+ || chartType === 'area'
309
+ || chartType === 'scatter'
310
+ || chartType === 'radar';
280
311
  return childrenByLocal(chartNode, 'ser').map((series, index) => {
281
312
  const tx = firstChildByLocal(series, 'tx');
282
313
  const category = firstChildByLocal(series, 'cat') || firstChildByLocal(series, 'xVal');
283
314
  const value = firstChildByLocal(series, 'val') || firstChildByLocal(series, 'yVal');
284
315
  const categories = parsePointValues(category, workbook);
285
316
  const values = parsePointValues(value, workbook, false).map(Number).filter(Number.isFinite);
286
- return {
317
+ const result = {
287
318
  name: chartText(tx, workbook) || `Series ${index + 1}`,
288
319
  categories: categories.length
289
320
  ? categories
290
321
  : values.map((_, valueIndex) => `${valueIndex + 1}`),
291
322
  values,
292
- color: parseSeriesColor(series)
323
+ color: parseSeriesColor(series),
324
+ ...parseSeriesLine(series),
325
+ marker: parseSeriesMarker(series)
326
+ };
327
+ if (!compactLineSeries || values.length <= MAX_TRANSFERRED_LINE_CHART_POINTS) {
328
+ return result;
329
+ }
330
+ const sourcePointIndexes = extremaPointIndexes(values, MAX_TRANSFERRED_LINE_CHART_POINTS);
331
+ return {
332
+ ...result,
333
+ categories: sourcePointIndexes.map((sourceIndex) => {
334
+ var _a;
335
+ return ((_a = result.categories[sourceIndex]) !== null && _a !== void 0 ? _a : `${sourceIndex + 1}`);
336
+ }),
337
+ values: sourcePointIndexes.map((sourceIndex) => values[sourceIndex]),
338
+ sourcePointCount: values.length,
339
+ sourcePointIndexes
293
340
  };
294
341
  });
295
342
  };
296
343
  const parseChart = (document, workbook) => {
297
- var _a, _b, _c;
344
+ var _a, _b, _c, _d;
298
345
  const root = document.documentElement;
299
346
  const chart = firstByLocal(root, 'chart');
300
347
  const plotArea = firstChildByLocal(chart, 'plotArea') || firstByLocal(chart, 'plotArea');
@@ -318,6 +365,7 @@ const parseChart = (document, workbook) => {
318
365
  valueAxisTitle: chartText(firstChildByLocal(valueAxis, 'title'), workbook) || undefined,
319
366
  barDirection,
320
367
  grouping: ((_c = firstChildByLocal(chartEntry.element, 'grouping')) === null || _c === void 0 ? void 0 : _c.getAttribute('val')) || undefined,
368
+ scatterStyle: ((_d = firstChildByLocal(chartEntry.element, 'scatterStyle')) === null || _d === void 0 ? void 0 : _d.getAttribute('val')) || undefined,
321
369
  legendPosition: legend ? LEGEND_POSITION_MAP[legendPositionValue] || 'bottom' : undefined,
322
370
  series: parseSeries(chartEntry.element, workbook)
323
371
  };
@@ -10,7 +10,87 @@ const readOptions = {
10
10
  cellStyles: true,
11
11
  browserPixels: true,
12
12
  drawings: true,
13
- validateMerges: true,
13
+ };
14
+ const isMergeValidationError = (error) => (error instanceof Error
15
+ && typeof error.code === 'string'
16
+ && /^E_MERGE_/.test(error.code));
17
+ const sanitizeToleratedMerges = (workbook) => {
18
+ for (const name of workbook.SheetNames || []) {
19
+ const worksheet = workbook.Sheets[name];
20
+ const merges = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!merges'];
21
+ const errors = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!mergeErrors'];
22
+ if (!worksheet || !(merges === null || merges === void 0 ? void 0 : merges.length) || !(errors === null || errors === void 0 ? void 0 : errors.length))
23
+ continue;
24
+ let worksheetRange;
25
+ try {
26
+ worksheetRange = worksheet['!ref'] ? utils.decode_range(worksheet['!ref']) : undefined;
27
+ }
28
+ catch {
29
+ worksheetRange = undefined;
30
+ }
31
+ const errorsByIndex = new Map();
32
+ for (const error of errors) {
33
+ const index = error.index;
34
+ if (!Number.isInteger(index) || typeof index !== 'number' || typeof error.code !== 'string')
35
+ continue;
36
+ const codes = errorsByIndex.get(index) || new Set();
37
+ codes.add(error.code);
38
+ errorsByIndex.set(index, codes);
39
+ }
40
+ worksheet['!merges'] = merges.flatMap((merge, index) => {
41
+ var _a, _b, _c, _d;
42
+ const codes = errorsByIndex.get(index);
43
+ const startRow = Number((_a = merge.s) === null || _a === void 0 ? void 0 : _a.r);
44
+ const startCol = Number((_b = merge.s) === null || _b === void 0 ? void 0 : _b.c);
45
+ let endRow = Number((_c = merge.e) === null || _c === void 0 ? void 0 : _c.r);
46
+ let endCol = Number((_d = merge.e) === null || _d === void 0 ? void 0 : _d.c);
47
+ if (!Number.isInteger(startRow)
48
+ || !Number.isInteger(startCol)
49
+ || !Number.isInteger(endRow)
50
+ || !Number.isInteger(endCol)
51
+ || startRow < 0
52
+ || startCol < 0
53
+ || endRow < startRow
54
+ || endCol < startCol
55
+ || (codes === null || codes === void 0 ? void 0 : codes.has('E_MERGE_RANGE'))
56
+ || (codes === null || codes === void 0 ? void 0 : codes.has('E_MERGE_DUP'))
57
+ || (codes === null || codes === void 0 ? void 0 : codes.has('E_MERGE_OVERLAP'))) {
58
+ return [];
59
+ }
60
+ if (codes === null || codes === void 0 ? void 0 : codes.has('E_MERGE_BOUNDS')) {
61
+ if (!worksheetRange
62
+ || startRow < worksheetRange.s.r
63
+ || startCol < worksheetRange.s.c
64
+ || startRow > worksheetRange.e.r
65
+ || startCol > worksheetRange.e.c) {
66
+ return [];
67
+ }
68
+ endRow = Math.min(endRow, worksheetRange.e.r);
69
+ endCol = Math.min(endCol, worksheetRange.e.c);
70
+ }
71
+ return [{
72
+ ...merge,
73
+ s: { ...merge.s, r: startRow, c: startCol },
74
+ e: { ...merge.e, r: endRow, c: endCol },
75
+ }];
76
+ });
77
+ }
78
+ };
79
+ const readPreparedWorkbook = (input, validateMerges) => (input.kind === 'text'
80
+ ? read(input.data, { ...readOptions, type: 'string', validateMerges })
81
+ : read(input.data, { ...readOptions, validateMerges }));
82
+ const readWorkbookWithMergeRecovery = (input) => {
83
+ try {
84
+ return readPreparedWorkbook(input, true);
85
+ }
86
+ catch (error) {
87
+ if (!isMergeValidationError(error))
88
+ throw error;
89
+ const workbook = readPreparedWorkbook(input, false);
90
+ sanitizeToleratedMerges(workbook);
91
+ console.warn(`[file-viewer] Recovered a workbook with invalid merge metadata: ${error.message}`);
92
+ return workbook;
93
+ }
14
94
  };
15
95
  export const createSpreadsheetParserContext = () => ({
16
96
  workbook: null,
@@ -188,9 +268,7 @@ const parseSheets = (context) => {
188
268
  export const parseSpreadsheetWorkbook = async (context, data, source = {}) => {
189
269
  try {
190
270
  const input = prepareSpreadsheetReadInput(data, source);
191
- context.workbook = input.kind === 'text'
192
- ? read(input.data, { ...readOptions, type: 'string' })
193
- : read(input.data, readOptions);
271
+ context.workbook = readWorkbookWithMergeRecovery(input);
194
272
  const signature = data.byteLength >= 2 ? new DataView(data).getUint16(0, false) : 0;
195
273
  if (signature === 0x504b) {
196
274
  const [charts, cellImages] = await Promise.all([
@@ -0,0 +1,4 @@
1
+ import type { CellObject } from 'styled-exceljs';
2
+ import type { SheetRichTextRun } from '../type.js';
3
+ export declare const parseCellRichText: (cell?: CellObject) => SheetRichTextRun[] | undefined;
4
+ export declare const richTextToPlainText: (runs: SheetRichTextRun[] | undefined) => string;
@@ -0,0 +1,135 @@
1
+ import { DOMParser } from '@xmldom/xmldom';
2
+ import { indexedColors } from './color.js';
3
+ const SPREADSHEETML_NAMESPACE = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
4
+ const MAX_RICH_TEXT_XML_LENGTH = 1000000;
5
+ const MAX_RICH_TEXT_RUNS = 10000;
6
+ const SYMBOL_FONT_FAMILY = '"Segoe UI Symbol", "Apple Symbols", "Noto Sans Symbols 2", sans-serif';
7
+ const richTextCache = new WeakMap();
8
+ const localName = (node) => {
9
+ const name = node.localName || node.nodeName;
10
+ return name.split(':').pop() || name;
11
+ };
12
+ const childElements = (node) => {
13
+ if (!node) {
14
+ return [];
15
+ }
16
+ return Array.from(node.childNodes).filter((child) => child.nodeType === 1);
17
+ };
18
+ const firstChild = (node, name) => {
19
+ return childElements(node).find(child => localName(child) === name);
20
+ };
21
+ const hasEnabledProperty = (element) => {
22
+ if (!element) {
23
+ return false;
24
+ }
25
+ const value = element.getAttribute('val');
26
+ return value === null || !['0', 'false', 'off', 'none'].includes(value.toLowerCase());
27
+ };
28
+ const normalizeHexColor = (value) => {
29
+ if (!value) {
30
+ return undefined;
31
+ }
32
+ const clean = value.replace(/^#/, '');
33
+ if (!/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(clean)) {
34
+ return undefined;
35
+ }
36
+ return `#${clean.length === 8 ? clean.slice(2) : clean}`;
37
+ };
38
+ const parseColor = (element) => {
39
+ const rgb = normalizeHexColor((element === null || element === void 0 ? void 0 : element.getAttribute('rgb')) || null);
40
+ if (rgb) {
41
+ return rgb;
42
+ }
43
+ const indexedAttribute = element === null || element === void 0 ? void 0 : element.getAttribute('indexed');
44
+ const indexed = indexedAttribute === null || indexedAttribute === undefined || indexedAttribute === ''
45
+ ? undefined
46
+ : Number(indexedAttribute);
47
+ const indexedValue = Number.isInteger(indexed) ? indexedColors[indexed] : undefined;
48
+ return indexedValue ? `#${indexedValue.slice(-6)}` : undefined;
49
+ };
50
+ const parseFontSize = (element) => {
51
+ const value = Number(element === null || element === void 0 ? void 0 : element.getAttribute('val'));
52
+ return Number.isFinite(value) && value > 0 ? value : undefined;
53
+ };
54
+ const normalizeSymbolText = (text, fontFamily) => {
55
+ if ((fontFamily === null || fontFamily === void 0 ? void 0 : fontFamily.trim().toLowerCase()) !== 'wingdings 2') {
56
+ return { text, fontFamily };
57
+ }
58
+ let converted = false;
59
+ const normalized = Array.from(text, character => {
60
+ if (character === '\u00a3') {
61
+ converted = true;
62
+ return '\u2610';
63
+ }
64
+ return character;
65
+ }).join('');
66
+ return {
67
+ text: normalized,
68
+ fontFamily: converted ? SYMBOL_FONT_FAMILY : fontFamily
69
+ };
70
+ };
71
+ const parseRun = (element) => {
72
+ var _a, _b, _c;
73
+ const properties = firstChild(element, 'rPr');
74
+ const rawText = ((_a = firstChild(element, 't')) === null || _a === void 0 ? void 0 : _a.textContent) || '';
75
+ if (!rawText) {
76
+ return undefined;
77
+ }
78
+ const rawFontFamily = ((_b = firstChild(properties, 'rFont')) === null || _b === void 0 ? void 0 : _b.getAttribute('val')) || undefined;
79
+ const normalized = normalizeSymbolText(rawText, rawFontFamily);
80
+ const fontSize = parseFontSize(firstChild(properties, 'sz'));
81
+ const color = parseColor(firstChild(properties, 'color'));
82
+ const verticalAlign = (_c = firstChild(properties, 'vertAlign')) === null || _c === void 0 ? void 0 : _c.getAttribute('val');
83
+ return {
84
+ text: normalized.text,
85
+ ...(normalized.fontFamily ? { fontFamily: normalized.fontFamily } : {}),
86
+ ...(fontSize ? { fontSize } : {}),
87
+ ...(color ? { color } : {}),
88
+ ...(hasEnabledProperty(firstChild(properties, 'b')) ? { bold: true } : {}),
89
+ ...(hasEnabledProperty(firstChild(properties, 'i')) ? { italic: true } : {}),
90
+ ...(hasEnabledProperty(firstChild(properties, 'u')) ? { underline: true } : {}),
91
+ ...(hasEnabledProperty(firstChild(properties, 'strike')) ? { strike: true } : {}),
92
+ ...(verticalAlign === 'superscript' ? { verticalAlign: 'super' } : {}),
93
+ ...(verticalAlign === 'subscript' ? { verticalAlign: 'sub' } : {})
94
+ };
95
+ };
96
+ export const parseCellRichText = (cell) => {
97
+ if (!cell) {
98
+ return undefined;
99
+ }
100
+ const cached = richTextCache.get(cell);
101
+ if (cached !== undefined) {
102
+ return cached || undefined;
103
+ }
104
+ const raw = cell.r;
105
+ if (typeof raw !== 'string' || !raw.includes('<r') || raw.length > MAX_RICH_TEXT_XML_LENGTH) {
106
+ richTextCache.set(cell, null);
107
+ return undefined;
108
+ }
109
+ try {
110
+ const document = new DOMParser().parseFromString(`<si xmlns="${SPREADSHEETML_NAMESPACE}">${raw}</si>`, 'application/xml');
111
+ const root = document.documentElement;
112
+ if (!root || localName(root) === 'parsererror') {
113
+ richTextCache.set(cell, null);
114
+ return undefined;
115
+ }
116
+ const runElements = childElements(root).filter(child => localName(child) === 'r');
117
+ if (runElements.length > MAX_RICH_TEXT_RUNS) {
118
+ richTextCache.set(cell, null);
119
+ return undefined;
120
+ }
121
+ const runs = runElements
122
+ .map(parseRun)
123
+ .filter((run) => !!run);
124
+ const result = runs.length ? runs : undefined;
125
+ richTextCache.set(cell, result || null);
126
+ return result;
127
+ }
128
+ catch {
129
+ richTextCache.set(cell, null);
130
+ return undefined;
131
+ }
132
+ };
133
+ export const richTextToPlainText = (runs) => {
134
+ return (runs === null || runs === void 0 ? void 0 : runs.map(run => run.text).join('')) || '';
135
+ };
@@ -1,3 +1,19 @@
1
+ export interface SheetRichTextRun {
2
+ text: string;
3
+ fontFamily?: string;
4
+ fontSize?: number;
5
+ color?: string;
6
+ bold?: boolean;
7
+ italic?: boolean;
8
+ underline?: boolean;
9
+ strike?: boolean;
10
+ verticalAlign?: 'sub' | 'super';
11
+ }
12
+ export interface SheetCellMetadata {
13
+ className?: string;
14
+ style: Record<string, string>;
15
+ richText?: SheetRichTextRun[];
16
+ }
1
17
  export interface CellMerge {
2
18
  row: number;
3
19
  col: number;
@@ -33,7 +49,16 @@ export interface SheetChartSeries {
33
49
  name: string;
34
50
  categories: string[];
35
51
  values: number[];
52
+ sourcePointCount?: number;
53
+ sourcePointIndexes?: number[];
36
54
  color?: string;
55
+ lineWidth?: number;
56
+ lineDash?: string;
57
+ lineVisible?: boolean;
58
+ marker?: {
59
+ symbol: string;
60
+ size?: number;
61
+ };
37
62
  }
38
63
  export interface SheetChartDefinition {
39
64
  id: string;
@@ -43,6 +68,7 @@ export interface SheetChartDefinition {
43
68
  valueAxisTitle?: string;
44
69
  barDirection?: 'column' | 'bar';
45
70
  grouping?: string;
71
+ scatterStyle?: string;
46
72
  legendPosition?: 'top' | 'right' | 'bottom' | 'left';
47
73
  series: SheetChartSeries[];
48
74
  from: SheetDrawingMarker;
@@ -93,7 +119,7 @@ export interface SheetWindow {
93
119
  export interface SheetModel {
94
120
  get defaults(): any;
95
121
  get data(): string[][];
96
- get cell(): Record<string, unknown>;
122
+ get cell(): Record<string, SheetCellMetadata>;
97
123
  get merge(): CellMerge[];
98
124
  get rowHeights(): number | number[];
99
125
  get colWidths(): number | number[];