@file-viewer/renderer-spreadsheet 3.0.0 → 3.0.2

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';
@@ -60,10 +61,14 @@ export const defaults = {
60
61
  const cellKey = (row, col) => {
61
62
  return `${row}-${col}`;
62
63
  };
63
- const formatCellValue = (cell) => {
64
+ export 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
  }
@@ -517,6 +522,7 @@ class SheetJsModel {
517
522
  valueAxisTitle: chart.valueAxisTitle,
518
523
  barDirection: chart.barDirection,
519
524
  grouping: chart.grouping,
525
+ scatterStyle: chart.scatterStyle,
520
526
  legendPosition: chart.legendPosition,
521
527
  series: chart.series,
522
528
  left: Math.max(0, left),
@@ -568,12 +574,14 @@ class SheetJsModel {
568
574
  const rawStyle = resolveTableCellStyle(this.ws, rowIndex, colIndex, inheritedStyle);
569
575
  const className = alignToClassName(rawStyle === null || rawStyle === void 0 ? void 0 : rawStyle.alignment);
570
576
  const style = getCellStyle(rawStyle);
571
- if (!className && !style) {
577
+ const richText = parseCellRichText(cell);
578
+ if (!className && !style && !(richText === null || richText === void 0 ? void 0 : richText.length)) {
572
579
  continue;
573
580
  }
574
581
  result[cellKey(rowIndex - this.startRow, colIndex)] = {
575
582
  ...(className ? { className } : {}),
576
- style: style || {}
583
+ style: style || {},
584
+ ...((richText === null || richText === void 0 ? void 0 : richText.length) ? { richText } : {})
577
585
  };
578
586
  }
579
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
  };
@@ -30,6 +30,19 @@ export interface SpreadsheetWorkerResponse {
30
30
  type: string;
31
31
  payload?: Record<string, any>;
32
32
  }
33
+ export interface SpreadsheetSearchOptions {
34
+ caseSensitive?: boolean;
35
+ wholeWord?: boolean;
36
+ maxMatches?: number;
37
+ }
38
+ export interface SpreadsheetSearchMatch {
39
+ sheet: number;
40
+ sheetName: string;
41
+ row: number;
42
+ col: number;
43
+ text: string;
44
+ matchText: string;
45
+ }
33
46
  export declare const createSpreadsheetParserContext: () => SpreadsheetParserContext;
34
47
  interface WorksheetRangeLike extends WorksheetWithDrawings {
35
48
  '!ref'?: string;
@@ -51,5 +64,6 @@ export interface WorksheetDisplayBounds {
51
64
  export declare const getWorksheetDisplayBounds: (worksheet: WorksheetRangeLike | undefined, charts: SheetChartDefinition[] | undefined) => WorksheetDisplayBounds;
52
65
  export declare const parseSpreadsheetWorkbook: (context: SpreadsheetParserContext, data: ArrayBuffer, source?: SpreadsheetTextSource) => Promise<SpreadsheetWorkerResponse[]>;
53
66
  export declare const parseSpreadsheetSheet: (context: SpreadsheetParserContext, payload?: Record<string, any>) => SpreadsheetWorkerResponse[];
67
+ export declare const searchSpreadsheetWorkbook: (context: SpreadsheetParserContext, query: string, options?: SpreadsheetSearchOptions) => SpreadsheetSearchMatch[];
54
68
  export declare const handleSpreadsheetWorkerRequest: (context: SpreadsheetParserContext, request: SpreadsheetWorkerRequest) => SpreadsheetWorkerResponse[] | Promise<SpreadsheetWorkerResponse[]>;
55
69
  export {};
@@ -1,5 +1,5 @@
1
1
  import { read, utils } from 'styled-exceljs';
2
- import SheetJsModel from './SheetJsModel.js';
2
+ import SheetJsModel, { formatCellValue } from './SheetJsModel.js';
3
3
  import { parseSpreadsheetCharts } from './chartParser.js';
4
4
  import { prepareSpreadsheetReadInput, } from './textEncoding.js';
5
5
  import { parseSpreadsheetCellImages } from './richDataParser.js';
@@ -336,8 +336,104 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
336
336
  return [toErrorResponse(error, { sessionId, startRow })];
337
337
  }
338
338
  };
339
+ const escapeSearchRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
340
+ const createSpreadsheetSearchRegExp = (query, options) => {
341
+ const source = options.wholeWord
342
+ ? `\\b${escapeSearchRegExp(query)}\\b`
343
+ : escapeSearchRegExp(query);
344
+ return new RegExp(source, options.caseSensitive ? 'g' : 'gi');
345
+ };
346
+ const visitWorksheetCells = (worksheet, visit) => {
347
+ const candidate = worksheet;
348
+ const rows = Array.isArray(worksheet)
349
+ ? worksheet
350
+ : candidate['!data'];
351
+ if (rows) {
352
+ for (const rowKey of Object.keys(rows)) {
353
+ const row = rows[Number(rowKey)];
354
+ const rowIndex = Number(rowKey);
355
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || !Array.isArray(row)) {
356
+ continue;
357
+ }
358
+ for (const colKey of Object.keys(row)) {
359
+ const colIndex = Number(colKey);
360
+ const cell = row[colIndex];
361
+ if (!Number.isInteger(colIndex) || colIndex < 0 || !cell) {
362
+ continue;
363
+ }
364
+ if (!visit(cell, rowIndex, colIndex)) {
365
+ return false;
366
+ }
367
+ }
368
+ }
369
+ return true;
370
+ }
371
+ for (const key of Object.keys(worksheet)) {
372
+ if (key.startsWith('!') || !/^[A-Z]+[1-9][0-9]*$/i.test(key)) {
373
+ continue;
374
+ }
375
+ const cell = worksheet[key];
376
+ if (!cell) {
377
+ continue;
378
+ }
379
+ let position;
380
+ try {
381
+ position = utils.decode_cell(key);
382
+ }
383
+ catch {
384
+ continue;
385
+ }
386
+ if (!visit(cell, position.r, position.c)) {
387
+ return false;
388
+ }
389
+ }
390
+ return true;
391
+ };
392
+ export const searchSpreadsheetWorkbook = (context, query, options = {}) => {
393
+ var _a;
394
+ const normalizedQuery = query.replace(/\s+/g, ' ').trim();
395
+ if (!normalizedQuery || !((_a = context.workbook) === null || _a === void 0 ? void 0 : _a.Sheets)) {
396
+ return [];
397
+ }
398
+ const maxMatches = Math.max(1, Math.floor(options.maxMatches || 1000));
399
+ const expression = createSpreadsheetSearchRegExp(normalizedQuery, options);
400
+ const matches = [];
401
+ for (const sheet of context.sheets) {
402
+ const worksheet = context.workbook.Sheets[sheet.name];
403
+ if (!worksheet) {
404
+ continue;
405
+ }
406
+ const completed = visitWorksheetCells(worksheet, (cell, row, col) => {
407
+ const text = formatCellValue(cell);
408
+ if (!text) {
409
+ return true;
410
+ }
411
+ expression.lastIndex = 0;
412
+ let match;
413
+ while ((match = expression.exec(text)) && matches.length < maxMatches) {
414
+ if (!match[0]) {
415
+ expression.lastIndex += 1;
416
+ continue;
417
+ }
418
+ matches.push({
419
+ sheet: sheet.id,
420
+ sheetName: sheet.name,
421
+ row,
422
+ col,
423
+ text,
424
+ matchText: match[0],
425
+ });
426
+ }
427
+ return matches.length < maxMatches;
428
+ });
429
+ if (!completed || matches.length >= maxMatches) {
430
+ break;
431
+ }
432
+ }
433
+ return matches;
434
+ };
339
435
  export const handleSpreadsheetWorkerRequest = (context, request) => {
340
- var _a, _b, _c, _d;
436
+ var _a, _b, _c, _d, _e, _f, _g;
341
437
  switch (request.type) {
342
438
  case 'parseWorkbook':
343
439
  return parseSpreadsheetWorkbook(context, (_a = request.payload) === null || _a === void 0 ? void 0 : _a.workbook, {
@@ -347,6 +443,15 @@ export const handleSpreadsheetWorkerRequest = (context, request) => {
347
443
  });
348
444
  case 'parseSheet':
349
445
  return parseSpreadsheetSheet(context, request.payload);
446
+ case 'searchWorkbook':
447
+ return [{
448
+ type: 'searchWorkbook',
449
+ payload: {
450
+ requestId: (_e = request.payload) === null || _e === void 0 ? void 0 : _e.requestId,
451
+ query: ((_f = request.payload) === null || _f === void 0 ? void 0 : _f.query) || '',
452
+ matches: searchSpreadsheetWorkbook(context, ((_g = request.payload) === null || _g === void 0 ? void 0 : _g.query) || '', request.payload),
453
+ },
454
+ }];
350
455
  default:
351
456
  return [];
352
457
  }
@@ -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[];