@file-viewer/renderer-spreadsheet 2.1.25 → 2.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/spreadsheet/chartRenderer.d.ts +2 -0
- package/dist/spreadsheet/chartRenderer.js +344 -0
- package/dist/spreadsheet/view.d.ts +1 -1
- package/dist/spreadsheet/worker/sheetjs/SheetJsModel.d.ts +4 -1
- package/dist/spreadsheet/worker/sheetjs/SheetJsModel.js +34 -1
- package/dist/spreadsheet/worker/sheetjs/chartParser.d.ts +2 -0
- package/dist/spreadsheet/worker/sheetjs/chartParser.js +315 -0
- package/dist/spreadsheet/worker/sheetjs/parser.d.ts +4 -3
- package/dist/spreadsheet/worker/sheetjs/parser.js +41 -4
- package/dist/spreadsheet/worker/sheetjs/sheet.worker.js +2 -1
- package/dist/spreadsheet/worker/type.d.ts +39 -0
- package/dist/spreadsheet.js +38 -4
- package/package.json +4 -2
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
|
|
2
|
+
const DEFAULT_COLORS = ['#4472c4', '#ed7d31', '#70ad47', '#ffc000', '#5b9bd5', '#a5a5a5'];
|
|
3
|
+
const svgElement = (documentRef, name, attributes = {}) => {
|
|
4
|
+
const element = documentRef.createElementNS(SVG_NAMESPACE, name);
|
|
5
|
+
Object.entries(attributes).forEach(([key, value]) => element.setAttribute(key, `${value}`));
|
|
6
|
+
return element;
|
|
7
|
+
};
|
|
8
|
+
const svgText = (documentRef, value, x, y, options = {}) => {
|
|
9
|
+
const text = svgElement(documentRef, 'text', {
|
|
10
|
+
x,
|
|
11
|
+
y,
|
|
12
|
+
'text-anchor': options.anchor || 'start',
|
|
13
|
+
'font-family': "Aptos, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif",
|
|
14
|
+
'font-size': options.size || 11,
|
|
15
|
+
'font-weight': options.weight || '400',
|
|
16
|
+
fill: options.fill || '#5f6368'
|
|
17
|
+
});
|
|
18
|
+
if (options.rotate) {
|
|
19
|
+
text.setAttribute('transform', `rotate(${options.rotate} ${x} ${y})`);
|
|
20
|
+
}
|
|
21
|
+
text.textContent = value;
|
|
22
|
+
return text;
|
|
23
|
+
};
|
|
24
|
+
const seriesColor = (series, index) => {
|
|
25
|
+
return series.color || DEFAULT_COLORS[index % DEFAULT_COLORS.length];
|
|
26
|
+
};
|
|
27
|
+
const categoryLabels = (chart) => {
|
|
28
|
+
var _a;
|
|
29
|
+
const labels = ((_a = chart.series.find((series) => series.categories.length)) === null || _a === void 0 ? void 0 : _a.categories) || [];
|
|
30
|
+
const valueCount = Math.max(0, ...chart.series.map((series) => series.values.length));
|
|
31
|
+
return labels.length ? labels : Array.from({ length: valueCount }, (_, index) => `${index + 1}`);
|
|
32
|
+
};
|
|
33
|
+
const valueDomain = (chart) => {
|
|
34
|
+
const values = chart.series.flatMap((series) => series.values).filter(Number.isFinite);
|
|
35
|
+
const min = Math.min(0, ...values);
|
|
36
|
+
const max = Math.max(0, ...values);
|
|
37
|
+
if (min === max) {
|
|
38
|
+
return { min: 0, max: Math.max(1, max), span: Math.max(1, max) };
|
|
39
|
+
}
|
|
40
|
+
return { min, max, span: max - min };
|
|
41
|
+
};
|
|
42
|
+
const createPlot = (chart) => {
|
|
43
|
+
const hasTitle = !!chart.title;
|
|
44
|
+
const hasLegend = !!chart.legendPosition;
|
|
45
|
+
const rightLegend = chart.legendPosition === 'right';
|
|
46
|
+
const top = hasTitle ? 48 : 24;
|
|
47
|
+
const bottom = hasLegend && !rightLegend ? 302 : 326;
|
|
48
|
+
const left = chart.valueAxisTitle ? 76 : 58;
|
|
49
|
+
const right = rightLegend ? 492 : 612;
|
|
50
|
+
return {
|
|
51
|
+
left,
|
|
52
|
+
top,
|
|
53
|
+
width: right - left,
|
|
54
|
+
height: bottom - top,
|
|
55
|
+
bottom
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
const drawValueGrid = (documentRef, svg, plot, domain) => {
|
|
59
|
+
const tickCount = 5;
|
|
60
|
+
for (let index = 0; index <= tickCount; index += 1) {
|
|
61
|
+
const ratio = index / tickCount;
|
|
62
|
+
const y = plot.bottom - ratio * plot.height;
|
|
63
|
+
const value = domain.min + ratio * domain.span;
|
|
64
|
+
svg.appendChild(svgElement(documentRef, 'line', {
|
|
65
|
+
x1: plot.left,
|
|
66
|
+
y1: y,
|
|
67
|
+
x2: plot.left + plot.width,
|
|
68
|
+
y2: y,
|
|
69
|
+
stroke: index === 0 ? '#9ca3af' : '#e5e7eb',
|
|
70
|
+
'stroke-width': 1
|
|
71
|
+
}));
|
|
72
|
+
svg.appendChild(svgText(documentRef, Number.isInteger(value) ? `${value}` : value.toFixed(1), plot.left - 8, y + 4, {
|
|
73
|
+
anchor: 'end',
|
|
74
|
+
size: 10
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const drawCategoryLabels = (documentRef, svg, chart, plot) => {
|
|
79
|
+
const categories = categoryLabels(chart);
|
|
80
|
+
if (!categories.length) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const step = plot.width / categories.length;
|
|
84
|
+
categories.forEach((category, index) => {
|
|
85
|
+
const maxLength = categories.length > 8 ? 8 : 14;
|
|
86
|
+
const label = category.length > maxLength ? `${category.slice(0, maxLength - 1)}…` : category;
|
|
87
|
+
svg.appendChild(svgText(documentRef, label, plot.left + (index + 0.5) * step, plot.bottom + 17, {
|
|
88
|
+
anchor: 'middle',
|
|
89
|
+
size: 10
|
|
90
|
+
}));
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
const drawColumnChart = (documentRef, svg, chart, plot) => {
|
|
94
|
+
const domain = valueDomain(chart);
|
|
95
|
+
const categories = categoryLabels(chart);
|
|
96
|
+
const categoryCount = Math.max(categories.length, ...chart.series.map((series) => series.values.length), 1);
|
|
97
|
+
const groupWidth = plot.width / categoryCount;
|
|
98
|
+
const seriesCount = Math.max(chart.series.length, 1);
|
|
99
|
+
const slotWidth = (groupWidth * 0.76) / seriesCount;
|
|
100
|
+
const zeroY = plot.bottom - ((0 - domain.min) / domain.span) * plot.height;
|
|
101
|
+
drawValueGrid(documentRef, svg, plot, domain);
|
|
102
|
+
chart.series.forEach((series, seriesIndex) => {
|
|
103
|
+
series.values.forEach((value, valueIndex) => {
|
|
104
|
+
const valueY = plot.bottom - ((value - domain.min) / domain.span) * plot.height;
|
|
105
|
+
const x = plot.left + valueIndex * groupWidth + groupWidth * 0.12 + seriesIndex * slotWidth;
|
|
106
|
+
const y = Math.min(zeroY, valueY);
|
|
107
|
+
const rect = svgElement(documentRef, 'rect', {
|
|
108
|
+
x,
|
|
109
|
+
y,
|
|
110
|
+
width: Math.max(1, slotWidth - 2),
|
|
111
|
+
height: Math.max(1, Math.abs(zeroY - valueY)),
|
|
112
|
+
fill: seriesColor(series, seriesIndex),
|
|
113
|
+
rx: 1
|
|
114
|
+
});
|
|
115
|
+
const title = svgElement(documentRef, 'title');
|
|
116
|
+
title.textContent = `${series.name}: ${value}`;
|
|
117
|
+
rect.appendChild(title);
|
|
118
|
+
svg.appendChild(rect);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
drawCategoryLabels(documentRef, svg, chart, plot);
|
|
122
|
+
};
|
|
123
|
+
const drawHorizontalBarChart = (documentRef, svg, chart, plot) => {
|
|
124
|
+
const domain = valueDomain(chart);
|
|
125
|
+
const categories = categoryLabels(chart);
|
|
126
|
+
const categoryCount = Math.max(categories.length, ...chart.series.map((series) => series.values.length), 1);
|
|
127
|
+
const groupHeight = plot.height / categoryCount;
|
|
128
|
+
const seriesCount = Math.max(chart.series.length, 1);
|
|
129
|
+
const slotHeight = (groupHeight * 0.76) / seriesCount;
|
|
130
|
+
const zeroX = plot.left + ((0 - domain.min) / domain.span) * plot.width;
|
|
131
|
+
for (let index = 0; index <= 5; index += 1) {
|
|
132
|
+
const ratio = index / 5;
|
|
133
|
+
const x = plot.left + ratio * plot.width;
|
|
134
|
+
svg.appendChild(svgElement(documentRef, 'line', {
|
|
135
|
+
x1: x,
|
|
136
|
+
y1: plot.top,
|
|
137
|
+
x2: x,
|
|
138
|
+
y2: plot.bottom,
|
|
139
|
+
stroke: '#e5e7eb',
|
|
140
|
+
'stroke-width': 1
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
chart.series.forEach((series, seriesIndex) => {
|
|
144
|
+
series.values.forEach((value, valueIndex) => {
|
|
145
|
+
const valueX = plot.left + ((value - domain.min) / domain.span) * plot.width;
|
|
146
|
+
const y = plot.top + valueIndex * groupHeight + groupHeight * 0.12 + seriesIndex * slotHeight;
|
|
147
|
+
svg.appendChild(svgElement(documentRef, 'rect', {
|
|
148
|
+
x: Math.min(zeroX, valueX),
|
|
149
|
+
y,
|
|
150
|
+
width: Math.max(1, Math.abs(valueX - zeroX)),
|
|
151
|
+
height: Math.max(1, slotHeight - 2),
|
|
152
|
+
fill: seriesColor(series, seriesIndex),
|
|
153
|
+
rx: 1
|
|
154
|
+
}));
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
categories.forEach((category, index) => {
|
|
158
|
+
svg.appendChild(svgText(documentRef, category, plot.left - 8, plot.top + (index + 0.5) * groupHeight + 4, {
|
|
159
|
+
anchor: 'end',
|
|
160
|
+
size: 10
|
|
161
|
+
}));
|
|
162
|
+
});
|
|
163
|
+
};
|
|
164
|
+
const drawLineChart = (documentRef, svg, chart, plot, fillArea) => {
|
|
165
|
+
const domain = valueDomain(chart);
|
|
166
|
+
const count = Math.max(...chart.series.map((series) => series.values.length), 1);
|
|
167
|
+
const step = count > 1 ? plot.width / (count - 1) : plot.width;
|
|
168
|
+
drawValueGrid(documentRef, svg, plot, domain);
|
|
169
|
+
chart.series.forEach((series, seriesIndex) => {
|
|
170
|
+
const points = series.values.map((value, index) => ({
|
|
171
|
+
x: plot.left + (count > 1 ? index * step : plot.width / 2),
|
|
172
|
+
y: plot.bottom - ((value - domain.min) / domain.span) * plot.height
|
|
173
|
+
}));
|
|
174
|
+
if (!points.length) {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const pathData = points
|
|
178
|
+
.map((point, index) => `${index ? 'L' : 'M'}${point.x},${point.y}`)
|
|
179
|
+
.join(' ');
|
|
180
|
+
if (fillArea && points.length > 1) {
|
|
181
|
+
svg.appendChild(svgElement(documentRef, 'path', {
|
|
182
|
+
d: `${pathData} L${points[points.length - 1].x},${plot.bottom} L${points[0].x},${plot.bottom} Z`,
|
|
183
|
+
fill: seriesColor(series, seriesIndex),
|
|
184
|
+
opacity: 0.2
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
svg.appendChild(svgElement(documentRef, 'path', {
|
|
188
|
+
d: pathData,
|
|
189
|
+
fill: 'none',
|
|
190
|
+
stroke: seriesColor(series, seriesIndex),
|
|
191
|
+
'stroke-width': 2.5,
|
|
192
|
+
'stroke-linejoin': 'round',
|
|
193
|
+
'stroke-linecap': 'round'
|
|
194
|
+
}));
|
|
195
|
+
points.forEach((point) => {
|
|
196
|
+
svg.appendChild(svgElement(documentRef, 'circle', {
|
|
197
|
+
cx: point.x,
|
|
198
|
+
cy: point.y,
|
|
199
|
+
r: 3.5,
|
|
200
|
+
fill: seriesColor(series, seriesIndex),
|
|
201
|
+
stroke: '#ffffff',
|
|
202
|
+
'stroke-width': 1
|
|
203
|
+
}));
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
drawCategoryLabels(documentRef, svg, chart, plot);
|
|
207
|
+
};
|
|
208
|
+
const polarPoint = (cx, cy, radius, angle) => {
|
|
209
|
+
const radians = ((angle - 90) * Math.PI) / 180;
|
|
210
|
+
return {
|
|
211
|
+
x: cx + radius * Math.cos(radians),
|
|
212
|
+
y: cy + radius * Math.sin(radians)
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
const pieSlicePath = (cx, cy, outerRadius, innerRadius, startAngle, endAngle) => {
|
|
216
|
+
const outerStart = polarPoint(cx, cy, outerRadius, endAngle);
|
|
217
|
+
const outerEnd = polarPoint(cx, cy, outerRadius, startAngle);
|
|
218
|
+
const largeArc = endAngle - startAngle > 180 ? 1 : 0;
|
|
219
|
+
if (!innerRadius) {
|
|
220
|
+
return `M${cx},${cy} L${outerStart.x},${outerStart.y} A${outerRadius},${outerRadius} 0 ${largeArc},0 ${outerEnd.x},${outerEnd.y} Z`;
|
|
221
|
+
}
|
|
222
|
+
const innerStart = polarPoint(cx, cy, innerRadius, startAngle);
|
|
223
|
+
const innerEnd = polarPoint(cx, cy, innerRadius, endAngle);
|
|
224
|
+
return `M${outerStart.x},${outerStart.y} A${outerRadius},${outerRadius} 0 ${largeArc},0 ${outerEnd.x},${outerEnd.y} L${innerStart.x},${innerStart.y} A${innerRadius},${innerRadius} 0 ${largeArc},1 ${innerEnd.x},${innerEnd.y} Z`;
|
|
225
|
+
};
|
|
226
|
+
const drawPieChart = (documentRef, svg, chart, doughnut) => {
|
|
227
|
+
const series = chart.series[0];
|
|
228
|
+
const values = (series === null || series === void 0 ? void 0 : series.values) || [];
|
|
229
|
+
const categories = (series === null || series === void 0 ? void 0 : series.categories) || [];
|
|
230
|
+
const total = values.reduce((sum, value) => sum + Math.max(0, value), 0) || 1;
|
|
231
|
+
const cx = chart.legendPosition === 'right' ? 260 : 320;
|
|
232
|
+
const cy = chart.title ? 180 : 170;
|
|
233
|
+
const radius = 120;
|
|
234
|
+
let angle = 0;
|
|
235
|
+
values.forEach((value, index) => {
|
|
236
|
+
const nextAngle = angle + (Math.max(0, value) / total) * 360;
|
|
237
|
+
const color = DEFAULT_COLORS[index % DEFAULT_COLORS.length];
|
|
238
|
+
const path = svgElement(documentRef, 'path', {
|
|
239
|
+
d: pieSlicePath(cx, cy, radius, doughnut ? 62 : 0, angle, nextAngle),
|
|
240
|
+
fill: color,
|
|
241
|
+
stroke: '#ffffff',
|
|
242
|
+
'stroke-width': 1.5
|
|
243
|
+
});
|
|
244
|
+
const title = svgElement(documentRef, 'title');
|
|
245
|
+
title.textContent = `${categories[index] || index + 1}: ${value}`;
|
|
246
|
+
path.appendChild(title);
|
|
247
|
+
svg.appendChild(path);
|
|
248
|
+
angle = nextAngle;
|
|
249
|
+
});
|
|
250
|
+
};
|
|
251
|
+
const drawLegend = (documentRef, svg, chart) => {
|
|
252
|
+
if (!chart.legendPosition) {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const right = chart.legendPosition === 'right';
|
|
256
|
+
chart.series.slice(0, 8).forEach((series, index) => {
|
|
257
|
+
const x = right ? 510 : 76 + (index % 4) * 136;
|
|
258
|
+
const y = right ? 72 + index * 28 : 342 - Math.floor(index / 4) * 20;
|
|
259
|
+
svg.appendChild(svgElement(documentRef, 'rect', {
|
|
260
|
+
x,
|
|
261
|
+
y: y - 10,
|
|
262
|
+
width: 10,
|
|
263
|
+
height: 10,
|
|
264
|
+
fill: seriesColor(series, index)
|
|
265
|
+
}));
|
|
266
|
+
const label = series.name.length > 16 ? `${series.name.slice(0, 15)}…` : series.name;
|
|
267
|
+
svg.appendChild(svgText(documentRef, label, x + 15, y, { size: 10 }));
|
|
268
|
+
});
|
|
269
|
+
};
|
|
270
|
+
export const renderSpreadsheetChart = (documentRef, chart) => {
|
|
271
|
+
const container = documentRef.createElement('div');
|
|
272
|
+
container.className = 'excel-chart';
|
|
273
|
+
container.dataset.chartId = chart.id;
|
|
274
|
+
container.dataset.chartType = chart.type;
|
|
275
|
+
container.dataset.seriesNames = JSON.stringify(chart.series.map((series) => series.name));
|
|
276
|
+
container.setAttribute('role', 'img');
|
|
277
|
+
container.setAttribute('aria-label', chart.title || chart.id || 'Spreadsheet chart');
|
|
278
|
+
const svg = svgElement(documentRef, 'svg', {
|
|
279
|
+
viewBox: '0 0 640 360',
|
|
280
|
+
preserveAspectRatio: 'xMidYMid meet',
|
|
281
|
+
focusable: 'false',
|
|
282
|
+
'aria-hidden': 'true'
|
|
283
|
+
});
|
|
284
|
+
svg.appendChild(svgElement(documentRef, 'rect', {
|
|
285
|
+
x: 0.5,
|
|
286
|
+
y: 0.5,
|
|
287
|
+
width: 639,
|
|
288
|
+
height: 359,
|
|
289
|
+
fill: '#ffffff',
|
|
290
|
+
stroke: '#d1d5db'
|
|
291
|
+
}));
|
|
292
|
+
if (chart.title) {
|
|
293
|
+
svg.appendChild(svgText(documentRef, chart.title, 320, 28, {
|
|
294
|
+
anchor: 'middle',
|
|
295
|
+
size: 16,
|
|
296
|
+
weight: '600',
|
|
297
|
+
fill: '#1f2937'
|
|
298
|
+
}));
|
|
299
|
+
}
|
|
300
|
+
const plot = createPlot(chart);
|
|
301
|
+
switch (chart.type) {
|
|
302
|
+
case 'pie':
|
|
303
|
+
drawPieChart(documentRef, svg, chart, false);
|
|
304
|
+
break;
|
|
305
|
+
case 'doughnut':
|
|
306
|
+
drawPieChart(documentRef, svg, chart, true);
|
|
307
|
+
break;
|
|
308
|
+
case 'line':
|
|
309
|
+
case 'scatter':
|
|
310
|
+
case 'radar':
|
|
311
|
+
drawLineChart(documentRef, svg, chart, plot, false);
|
|
312
|
+
break;
|
|
313
|
+
case 'area':
|
|
314
|
+
drawLineChart(documentRef, svg, chart, plot, true);
|
|
315
|
+
break;
|
|
316
|
+
case 'bar':
|
|
317
|
+
default:
|
|
318
|
+
if (chart.barDirection === 'bar') {
|
|
319
|
+
drawHorizontalBarChart(documentRef, svg, chart, plot);
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
drawColumnChart(documentRef, svg, chart, plot);
|
|
323
|
+
}
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
if (chart.categoryAxisTitle && chart.type !== 'pie' && chart.type !== 'doughnut') {
|
|
327
|
+
svg.appendChild(svgText(documentRef, chart.categoryAxisTitle, plot.left + plot.width / 2, 324, {
|
|
328
|
+
anchor: 'middle',
|
|
329
|
+
size: 11,
|
|
330
|
+
fill: '#374151'
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
if (chart.valueAxisTitle && chart.type !== 'pie' && chart.type !== 'doughnut') {
|
|
334
|
+
svg.appendChild(svgText(documentRef, chart.valueAxisTitle, 18, plot.top + plot.height / 2, {
|
|
335
|
+
anchor: 'middle',
|
|
336
|
+
size: 11,
|
|
337
|
+
fill: '#374151',
|
|
338
|
+
rotate: -90
|
|
339
|
+
}));
|
|
340
|
+
}
|
|
341
|
+
drawLegend(documentRef, svg, chart);
|
|
342
|
+
container.appendChild(svg);
|
|
343
|
+
return container;
|
|
344
|
+
};
|
|
@@ -22,7 +22,7 @@ interface SpreadsheetCopyParams {
|
|
|
22
22
|
}
|
|
23
23
|
export declare const getRowHeight: (heights: number | number[] | undefined, index: number, fallback: number) => number;
|
|
24
24
|
export declare const normalizeRowHeight: (height: number | undefined, fallback: number) => number;
|
|
25
|
-
export declare const detectIndexOffset: (ws: SheetModel) =>
|
|
25
|
+
export declare const detectIndexOffset: (ws: SheetModel) => 1 | 0;
|
|
26
26
|
export declare const buildColumns: (ws: SheetModel) => {
|
|
27
27
|
columns: Column[];
|
|
28
28
|
dataKeys: string[];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { WorkSheet } from 'styled-exceljs';
|
|
2
|
-
import type { CellMerge, SheetColumn, SheetModel, SheetStructure, SheetWindow } from '../type.js';
|
|
2
|
+
import type { CellMerge, SheetChartDefinition, SheetColumn, SheetModel, SheetStructure, SheetWindow } from '../type.js';
|
|
3
3
|
export declare const defaults: {
|
|
4
4
|
rowHeight: number;
|
|
5
5
|
colWidth: number;
|
|
@@ -9,6 +9,7 @@ interface SheetSliceOptions {
|
|
|
9
9
|
pageSize?: number;
|
|
10
10
|
totalRows?: number;
|
|
11
11
|
totalCols?: number;
|
|
12
|
+
charts?: SheetChartDefinition[];
|
|
12
13
|
}
|
|
13
14
|
type SheetCellMeta = {
|
|
14
15
|
className?: string;
|
|
@@ -20,6 +21,7 @@ export default class SheetJsModel implements SheetModel {
|
|
|
20
21
|
private readonly _pageSize;
|
|
21
22
|
private readonly _totalRows?;
|
|
22
23
|
private readonly _totalCols?;
|
|
24
|
+
private readonly _charts;
|
|
23
25
|
private static readonly defaults;
|
|
24
26
|
private _data;
|
|
25
27
|
private _cell;
|
|
@@ -56,6 +58,7 @@ export default class SheetJsModel implements SheetModel {
|
|
|
56
58
|
private getMarkerLeft;
|
|
57
59
|
private getMarkerTop;
|
|
58
60
|
private getImages;
|
|
61
|
+
private getCharts;
|
|
59
62
|
private getAllMerge;
|
|
60
63
|
private getData;
|
|
61
64
|
private getCell;
|
|
@@ -318,6 +318,7 @@ class SheetJsModel {
|
|
|
318
318
|
this._pageSize = Math.max(options.pageSize || 500, 1);
|
|
319
319
|
this._totalRows = options.totalRows;
|
|
320
320
|
this._totalCols = options.totalCols;
|
|
321
|
+
this._charts = options.charts || [];
|
|
321
322
|
const { '!ref': refs } = ws;
|
|
322
323
|
this.range = utils.decode_range(refs || 'A1');
|
|
323
324
|
}
|
|
@@ -444,6 +445,37 @@ class SheetJsModel {
|
|
|
444
445
|
});
|
|
445
446
|
return result.length ? result : undefined;
|
|
446
447
|
}
|
|
448
|
+
getCharts() {
|
|
449
|
+
const result = this._charts.map((chart) => {
|
|
450
|
+
var _a, _b;
|
|
451
|
+
const left = this.getMarkerLeft(chart.from);
|
|
452
|
+
const top = this.getMarkerTop(chart.from);
|
|
453
|
+
const right = chart.to
|
|
454
|
+
? this.getMarkerLeft(chart.to)
|
|
455
|
+
: left + emuToPixels((_a = chart.ext) === null || _a === void 0 ? void 0 : _a.width);
|
|
456
|
+
const bottom = chart.to
|
|
457
|
+
? this.getMarkerTop(chart.to)
|
|
458
|
+
: top + emuToPixels((_b = chart.ext) === null || _b === void 0 ? void 0 : _b.height);
|
|
459
|
+
return {
|
|
460
|
+
id: chart.id,
|
|
461
|
+
type: chart.type,
|
|
462
|
+
title: chart.title,
|
|
463
|
+
categoryAxisTitle: chart.categoryAxisTitle,
|
|
464
|
+
valueAxisTitle: chart.valueAxisTitle,
|
|
465
|
+
barDirection: chart.barDirection,
|
|
466
|
+
grouping: chart.grouping,
|
|
467
|
+
legendPosition: chart.legendPosition,
|
|
468
|
+
series: chart.series,
|
|
469
|
+
left: Math.max(0, left),
|
|
470
|
+
top: Math.max(0, top),
|
|
471
|
+
width: Math.max(1, right > left ? right - left : DEFAULT_IMAGE_WIDTH),
|
|
472
|
+
height: Math.max(1, bottom > top ? bottom - top : DEFAULT_IMAGE_HEIGHT),
|
|
473
|
+
row: chart.from.row,
|
|
474
|
+
col: chart.from.col
|
|
475
|
+
};
|
|
476
|
+
});
|
|
477
|
+
return result.length ? result : undefined;
|
|
478
|
+
}
|
|
447
479
|
getAllMerge() {
|
|
448
480
|
const sheet = this.ws;
|
|
449
481
|
const { '!merges': merges = [] } = sheet;
|
|
@@ -602,7 +634,8 @@ class SheetJsModel {
|
|
|
602
634
|
colWidths: this.getColWidths(),
|
|
603
635
|
rowHeights: this.getAllRowHeights(),
|
|
604
636
|
columns: this.getColumns(),
|
|
605
|
-
images: this.getImages()
|
|
637
|
+
images: this.getImages(),
|
|
638
|
+
charts: this.getCharts()
|
|
606
639
|
};
|
|
607
640
|
}
|
|
608
641
|
toObject() {
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { DOMParser } from '@xmldom/xmldom';
|
|
2
|
+
import JSZip from 'jszip';
|
|
3
|
+
const CHART_RELATIONSHIP_SUFFIX = '/chart';
|
|
4
|
+
const DRAWING_RELATIONSHIP_SUFFIX = '/drawing';
|
|
5
|
+
const WORKSHEET_RELATIONSHIP_SUFFIX = '/worksheet';
|
|
6
|
+
const CHART_TYPE_MAP = {
|
|
7
|
+
areaChart: 'area',
|
|
8
|
+
area3DChart: 'area',
|
|
9
|
+
barChart: 'bar',
|
|
10
|
+
bar3DChart: 'bar',
|
|
11
|
+
doughnutChart: 'doughnut',
|
|
12
|
+
lineChart: 'line',
|
|
13
|
+
line3DChart: 'line',
|
|
14
|
+
pieChart: 'pie',
|
|
15
|
+
pie3DChart: 'pie',
|
|
16
|
+
radarChart: 'radar',
|
|
17
|
+
scatterChart: 'scatter'
|
|
18
|
+
};
|
|
19
|
+
const LEGEND_POSITION_MAP = {
|
|
20
|
+
b: 'bottom',
|
|
21
|
+
l: 'left',
|
|
22
|
+
r: 'right',
|
|
23
|
+
t: 'top',
|
|
24
|
+
tr: 'top'
|
|
25
|
+
};
|
|
26
|
+
const SCHEME_COLORS = {
|
|
27
|
+
accent1: '#4472c4',
|
|
28
|
+
accent2: '#ed7d31',
|
|
29
|
+
accent3: '#a5a5a5',
|
|
30
|
+
accent4: '#ffc000',
|
|
31
|
+
accent5: '#5b9bd5',
|
|
32
|
+
accent6: '#70ad47',
|
|
33
|
+
dk1: '#000000',
|
|
34
|
+
dk2: '#44546a',
|
|
35
|
+
lt1: '#ffffff',
|
|
36
|
+
lt2: '#e7e6e6',
|
|
37
|
+
tx1: '#000000',
|
|
38
|
+
tx2: '#44546a'
|
|
39
|
+
};
|
|
40
|
+
const localName = (node) => {
|
|
41
|
+
const name = node.localName || node.nodeName;
|
|
42
|
+
return name.split(':').pop() || name;
|
|
43
|
+
};
|
|
44
|
+
const childElements = (node) => {
|
|
45
|
+
if (!node) {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
return Array.from(node.childNodes).filter((child) => child.nodeType === 1);
|
|
49
|
+
};
|
|
50
|
+
const childrenByLocal = (node, name) => {
|
|
51
|
+
return childElements(node).filter((child) => localName(child) === name);
|
|
52
|
+
};
|
|
53
|
+
const firstChildByLocal = (node, name) => {
|
|
54
|
+
return childrenByLocal(node, name)[0];
|
|
55
|
+
};
|
|
56
|
+
const elementsByLocal = (node, name) => {
|
|
57
|
+
const result = [];
|
|
58
|
+
const visit = (current) => {
|
|
59
|
+
childElements(current).forEach((child) => {
|
|
60
|
+
if (localName(child) === name) {
|
|
61
|
+
result.push(child);
|
|
62
|
+
}
|
|
63
|
+
visit(child);
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
if (node) {
|
|
67
|
+
visit(node);
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
};
|
|
71
|
+
const firstByLocal = (node, name) => {
|
|
72
|
+
return elementsByLocal(node, name)[0];
|
|
73
|
+
};
|
|
74
|
+
const numericAttribute = (element, name = 'val') => {
|
|
75
|
+
const value = Number(element === null || element === void 0 ? void 0 : element.getAttribute(name));
|
|
76
|
+
return Number.isFinite(value) ? value : 0;
|
|
77
|
+
};
|
|
78
|
+
const textContent = (element) => {
|
|
79
|
+
var _a;
|
|
80
|
+
return ((_a = element === null || element === void 0 ? void 0 : element.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
|
|
81
|
+
};
|
|
82
|
+
const relationshipId = (element) => {
|
|
83
|
+
if (!element) {
|
|
84
|
+
return '';
|
|
85
|
+
}
|
|
86
|
+
return (element.getAttribute('r:id') ||
|
|
87
|
+
element.getAttributeNS('http://schemas.openxmlformats.org/officeDocument/2006/relationships', 'id') ||
|
|
88
|
+
'');
|
|
89
|
+
};
|
|
90
|
+
const resolvePartPath = (sourcePart, target) => {
|
|
91
|
+
const sourceDirectory = sourcePart.includes('/')
|
|
92
|
+
? sourcePart.slice(0, sourcePart.lastIndexOf('/'))
|
|
93
|
+
: '';
|
|
94
|
+
const parts = (target.startsWith('/') ? target.slice(1) : `${sourceDirectory}/${target}`).split('/');
|
|
95
|
+
const normalized = [];
|
|
96
|
+
for (const part of parts) {
|
|
97
|
+
if (!part || part === '.') {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (part === '..') {
|
|
101
|
+
normalized.pop();
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
normalized.push(part);
|
|
105
|
+
}
|
|
106
|
+
return normalized.join('/');
|
|
107
|
+
};
|
|
108
|
+
const relationshipPartPath = (sourcePart) => {
|
|
109
|
+
const slash = sourcePart.lastIndexOf('/');
|
|
110
|
+
const directory = slash >= 0 ? sourcePart.slice(0, slash) : '';
|
|
111
|
+
const filename = slash >= 0 ? sourcePart.slice(slash + 1) : sourcePart;
|
|
112
|
+
return `${directory ? `${directory}/` : ''}_rels/${filename}.rels`;
|
|
113
|
+
};
|
|
114
|
+
const parseXml = (xml) => {
|
|
115
|
+
return new DOMParser().parseFromString(xml, 'application/xml');
|
|
116
|
+
};
|
|
117
|
+
const loadXml = async (zip, path) => {
|
|
118
|
+
const file = zip.file(path);
|
|
119
|
+
if (!file) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
return parseXml(await file.async('text'));
|
|
123
|
+
};
|
|
124
|
+
const loadRelationships = async (zip, sourcePart) => {
|
|
125
|
+
const document = await loadXml(zip, relationshipPartPath(sourcePart));
|
|
126
|
+
if (!document) {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
return elementsByLocal(document.documentElement, 'Relationship').flatMap((element) => {
|
|
130
|
+
const id = element.getAttribute('Id') || '';
|
|
131
|
+
const target = element.getAttribute('Target') || '';
|
|
132
|
+
const type = element.getAttribute('Type') || '';
|
|
133
|
+
if (!id || !target || element.getAttribute('TargetMode') === 'External') {
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
return [{ id, target: resolvePartPath(sourcePart, target), type }];
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
const relationById = (relationships, id) => {
|
|
140
|
+
return relationships.find((relationship) => relationship.id === id);
|
|
141
|
+
};
|
|
142
|
+
const parseMarker = (element) => {
|
|
143
|
+
if (!element) {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
row: Number(textContent(firstChildByLocal(element, 'row'))) || 0,
|
|
148
|
+
col: Number(textContent(firstChildByLocal(element, 'col'))) || 0,
|
|
149
|
+
rowOff: Number(textContent(firstChildByLocal(element, 'rowOff'))) || 0,
|
|
150
|
+
colOff: Number(textContent(firstChildByLocal(element, 'colOff'))) || 0
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
const parsePointValues = (element) => {
|
|
154
|
+
if (!element) {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
return elementsByLocal(element, 'pt')
|
|
158
|
+
.map((point) => ({
|
|
159
|
+
index: Number(point.getAttribute('idx')) || 0,
|
|
160
|
+
value: textContent(firstChildByLocal(point, 'v')) || textContent(firstByLocal(point, 'v'))
|
|
161
|
+
}))
|
|
162
|
+
.sort((left, right) => left.index - right.index)
|
|
163
|
+
.map((point) => point.value);
|
|
164
|
+
};
|
|
165
|
+
const chartText = (element) => {
|
|
166
|
+
if (!element) {
|
|
167
|
+
return '';
|
|
168
|
+
}
|
|
169
|
+
const points = parsePointValues(element);
|
|
170
|
+
if (points.length) {
|
|
171
|
+
return points.join(' ').trim();
|
|
172
|
+
}
|
|
173
|
+
const richText = elementsByLocal(element, 't').map(textContent).filter(Boolean).join(' ').trim();
|
|
174
|
+
if (richText) {
|
|
175
|
+
return richText;
|
|
176
|
+
}
|
|
177
|
+
return textContent(firstByLocal(element, 'v'));
|
|
178
|
+
};
|
|
179
|
+
const parseSeriesColor = (series) => {
|
|
180
|
+
var _a, _b;
|
|
181
|
+
const shape = firstChildByLocal(series, 'spPr');
|
|
182
|
+
const solidFill = firstByLocal(shape, 'solidFill');
|
|
183
|
+
const rgb = (_a = firstByLocal(solidFill, 'srgbClr')) === null || _a === void 0 ? void 0 : _a.getAttribute('val');
|
|
184
|
+
if (rgb && /^[0-9a-f]{6}$/i.test(rgb)) {
|
|
185
|
+
return `#${rgb}`;
|
|
186
|
+
}
|
|
187
|
+
const scheme = ((_b = firstByLocal(solidFill, 'schemeClr')) === null || _b === void 0 ? void 0 : _b.getAttribute('val')) || '';
|
|
188
|
+
return SCHEME_COLORS[scheme];
|
|
189
|
+
};
|
|
190
|
+
const parseSeries = (chartNode) => {
|
|
191
|
+
return childrenByLocal(chartNode, 'ser').map((series, index) => {
|
|
192
|
+
const tx = firstChildByLocal(series, 'tx');
|
|
193
|
+
const category = firstChildByLocal(series, 'cat') || firstChildByLocal(series, 'xVal');
|
|
194
|
+
const value = firstChildByLocal(series, 'val') || firstChildByLocal(series, 'yVal');
|
|
195
|
+
const categories = parsePointValues(category);
|
|
196
|
+
const values = parsePointValues(value).map(Number).filter(Number.isFinite);
|
|
197
|
+
return {
|
|
198
|
+
name: chartText(tx) || `Series ${index + 1}`,
|
|
199
|
+
categories: categories.length
|
|
200
|
+
? categories
|
|
201
|
+
: values.map((_, valueIndex) => `${valueIndex + 1}`),
|
|
202
|
+
values,
|
|
203
|
+
color: parseSeriesColor(series)
|
|
204
|
+
};
|
|
205
|
+
});
|
|
206
|
+
};
|
|
207
|
+
const parseChart = (document) => {
|
|
208
|
+
var _a, _b, _c;
|
|
209
|
+
const root = document.documentElement;
|
|
210
|
+
const chart = firstByLocal(root, 'chart');
|
|
211
|
+
const plotArea = firstChildByLocal(chart, 'plotArea') || firstByLocal(chart, 'plotArea');
|
|
212
|
+
const chartEntry = childElements(plotArea)
|
|
213
|
+
.map((element) => ({ element, type: CHART_TYPE_MAP[localName(element)] }))
|
|
214
|
+
.find((entry) => entry.type);
|
|
215
|
+
if (!chartEntry) {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
const legend = firstChildByLocal(chart, 'legend');
|
|
219
|
+
const legendPositionValue = ((_a = firstChildByLocal(legend, 'legendPos')) === null || _a === void 0 ? void 0 : _a.getAttribute('val')) || '';
|
|
220
|
+
const categoryAxis = firstChildByLocal(plotArea, 'catAx');
|
|
221
|
+
const valueAxis = firstChildByLocal(plotArea, 'valAx');
|
|
222
|
+
const barDirection = ((_b = firstChildByLocal(chartEntry.element, 'barDir')) === null || _b === void 0 ? void 0 : _b.getAttribute('val')) === 'bar'
|
|
223
|
+
? 'bar'
|
|
224
|
+
: 'column';
|
|
225
|
+
return {
|
|
226
|
+
type: chartEntry.type,
|
|
227
|
+
title: chartText(firstChildByLocal(chart, 'title')) || undefined,
|
|
228
|
+
categoryAxisTitle: chartText(firstChildByLocal(categoryAxis, 'title')) || undefined,
|
|
229
|
+
valueAxisTitle: chartText(firstChildByLocal(valueAxis, 'title')) || undefined,
|
|
230
|
+
barDirection,
|
|
231
|
+
grouping: ((_c = firstChildByLocal(chartEntry.element, 'grouping')) === null || _c === void 0 ? void 0 : _c.getAttribute('val')) || undefined,
|
|
232
|
+
legendPosition: legend ? LEGEND_POSITION_MAP[legendPositionValue] || 'bottom' : undefined,
|
|
233
|
+
series: parseSeries(chartEntry.element)
|
|
234
|
+
};
|
|
235
|
+
};
|
|
236
|
+
const parseDrawingCharts = async (zip, drawingPart) => {
|
|
237
|
+
const [document, relationships] = await Promise.all([
|
|
238
|
+
loadXml(zip, drawingPart),
|
|
239
|
+
loadRelationships(zip, drawingPart)
|
|
240
|
+
]);
|
|
241
|
+
if (!document) {
|
|
242
|
+
return [];
|
|
243
|
+
}
|
|
244
|
+
const anchors = childElements(document.documentElement).filter((element) => localName(element).endsWith('Anchor'));
|
|
245
|
+
const charts = await Promise.all(anchors.map(async (anchor, index) => {
|
|
246
|
+
var _a;
|
|
247
|
+
const chartReference = firstByLocal(anchor, 'chart');
|
|
248
|
+
const chartRelationship = relationById(relationships, relationshipId(chartReference));
|
|
249
|
+
if (!(chartRelationship === null || chartRelationship === void 0 ? void 0 : chartRelationship.type.endsWith(CHART_RELATIONSHIP_SUFFIX))) {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
const chartDocument = await loadXml(zip, chartRelationship.target);
|
|
253
|
+
const chart = chartDocument ? parseChart(chartDocument) : null;
|
|
254
|
+
if (!chart || !chart.series.length || chart.series.every((series) => !series.values.length)) {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
const from = parseMarker(firstChildByLocal(anchor, 'from')) || {
|
|
258
|
+
row: 0,
|
|
259
|
+
col: 0,
|
|
260
|
+
rowOff: numericAttribute(firstChildByLocal(anchor, 'pos'), 'y'),
|
|
261
|
+
colOff: numericAttribute(firstChildByLocal(anchor, 'pos'), 'x')
|
|
262
|
+
};
|
|
263
|
+
const to = parseMarker(firstChildByLocal(anchor, 'to'));
|
|
264
|
+
const extElement = firstChildByLocal(anchor, 'ext');
|
|
265
|
+
const name = (_a = firstByLocal(anchor, 'cNvPr')) === null || _a === void 0 ? void 0 : _a.getAttribute('name');
|
|
266
|
+
return {
|
|
267
|
+
...chart,
|
|
268
|
+
id: name || chartRelationship.target || `chart-${index + 1}`,
|
|
269
|
+
from,
|
|
270
|
+
to,
|
|
271
|
+
ext: extElement
|
|
272
|
+
? {
|
|
273
|
+
width: numericAttribute(extElement, 'cx'),
|
|
274
|
+
height: numericAttribute(extElement, 'cy')
|
|
275
|
+
}
|
|
276
|
+
: undefined
|
|
277
|
+
};
|
|
278
|
+
}));
|
|
279
|
+
return charts.filter((chart) => chart !== null);
|
|
280
|
+
};
|
|
281
|
+
export const parseSpreadsheetCharts = async (data) => {
|
|
282
|
+
const zip = await JSZip.loadAsync(data);
|
|
283
|
+
const workbookPart = 'xl/workbook.xml';
|
|
284
|
+
const [workbookDocument, workbookRelationships] = await Promise.all([
|
|
285
|
+
loadXml(zip, workbookPart),
|
|
286
|
+
loadRelationships(zip, workbookPart)
|
|
287
|
+
]);
|
|
288
|
+
const result = {};
|
|
289
|
+
if (!workbookDocument) {
|
|
290
|
+
return result;
|
|
291
|
+
}
|
|
292
|
+
for (const sheet of elementsByLocal(workbookDocument.documentElement, 'sheet')) {
|
|
293
|
+
const name = sheet.getAttribute('name') || '';
|
|
294
|
+
const worksheetRelationship = relationById(workbookRelationships, relationshipId(sheet));
|
|
295
|
+
if (!name || !(worksheetRelationship === null || worksheetRelationship === void 0 ? void 0 : worksheetRelationship.type.endsWith(WORKSHEET_RELATIONSHIP_SUFFIX))) {
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const [worksheetDocument, worksheetRelationships] = await Promise.all([
|
|
299
|
+
loadXml(zip, worksheetRelationship.target),
|
|
300
|
+
loadRelationships(zip, worksheetRelationship.target)
|
|
301
|
+
]);
|
|
302
|
+
if (!worksheetDocument) {
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
const drawingParts = elementsByLocal(worksheetDocument.documentElement, 'drawing')
|
|
306
|
+
.map((drawing) => relationById(worksheetRelationships, relationshipId(drawing)))
|
|
307
|
+
.filter((relationship) => relationship === null || relationship === void 0 ? void 0 : relationship.type.endsWith(DRAWING_RELATIONSHIP_SUFFIX))
|
|
308
|
+
.map((relationship) => relationship.target);
|
|
309
|
+
const charts = (await Promise.all(drawingParts.map((part) => parseDrawingCharts(zip, part)))).flat();
|
|
310
|
+
if (charts.length) {
|
|
311
|
+
result[name] = charts;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return result;
|
|
315
|
+
};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { WorkBook } from 'styled-exceljs';
|
|
2
|
-
import type { SheetDefinition } from '../type.js';
|
|
2
|
+
import type { SheetChartDefinition, SheetDefinition } from '../type.js';
|
|
3
3
|
export interface SpreadsheetParserContext {
|
|
4
4
|
workbook: WorkBook | null;
|
|
5
5
|
sheets: SheetDefinition[];
|
|
6
|
+
charts: Record<string, SheetChartDefinition[]>;
|
|
6
7
|
}
|
|
7
8
|
export interface SpreadsheetWorkerRequest {
|
|
8
9
|
type: string;
|
|
@@ -13,6 +14,6 @@ export interface SpreadsheetWorkerResponse {
|
|
|
13
14
|
payload?: Record<string, any>;
|
|
14
15
|
}
|
|
15
16
|
export declare const createSpreadsheetParserContext: () => SpreadsheetParserContext;
|
|
16
|
-
export declare const parseSpreadsheetWorkbook: (context: SpreadsheetParserContext, data: ArrayBuffer) => SpreadsheetWorkerResponse[]
|
|
17
|
+
export declare const parseSpreadsheetWorkbook: (context: SpreadsheetParserContext, data: ArrayBuffer) => Promise<SpreadsheetWorkerResponse[]>;
|
|
17
18
|
export declare const parseSpreadsheetSheet: (context: SpreadsheetParserContext, payload?: Record<string, any>) => SpreadsheetWorkerResponse[];
|
|
18
|
-
export declare const handleSpreadsheetWorkerRequest: (context: SpreadsheetParserContext, request: SpreadsheetWorkerRequest) => SpreadsheetWorkerResponse[]
|
|
19
|
+
export declare const handleSpreadsheetWorkerRequest: (context: SpreadsheetParserContext, request: SpreadsheetWorkerRequest) => SpreadsheetWorkerResponse[] | Promise<SpreadsheetWorkerResponse[]>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { read, utils } from 'styled-exceljs';
|
|
2
2
|
import SheetJsModel from './SheetJsModel.js';
|
|
3
|
+
import { parseSpreadsheetCharts } from './chartParser.js';
|
|
3
4
|
const readOptions = {
|
|
4
5
|
type: 'array',
|
|
5
6
|
dense: true,
|
|
@@ -12,6 +13,7 @@ const readOptions = {
|
|
|
12
13
|
export const createSpreadsheetParserContext = () => ({
|
|
13
14
|
workbook: null,
|
|
14
15
|
sheets: [],
|
|
16
|
+
charts: {},
|
|
15
17
|
});
|
|
16
18
|
const toErrorResponse = (error, payload = {}) => ({
|
|
17
19
|
type: 'parseError',
|
|
@@ -37,6 +39,26 @@ const getDrawingBounds = (worksheet) => {
|
|
|
37
39
|
colCount: 0,
|
|
38
40
|
});
|
|
39
41
|
};
|
|
42
|
+
const getChartBounds = (charts) => {
|
|
43
|
+
return (charts || []).reduce((bounds, chart) => {
|
|
44
|
+
var _a, _b, _c, _d, _e, _f;
|
|
45
|
+
const estimatedRows = ((_a = chart.ext) === null || _a === void 0 ? void 0 : _a.height)
|
|
46
|
+
? Math.ceil(chart.ext.height / 9525 / 20)
|
|
47
|
+
: 0;
|
|
48
|
+
const estimatedCols = ((_b = chart.ext) === null || _b === void 0 ? void 0 : _b.width)
|
|
49
|
+
? Math.ceil(chart.ext.width / 9525 / 64)
|
|
50
|
+
: 0;
|
|
51
|
+
const row = (_d = (_c = chart.to) === null || _c === void 0 ? void 0 : _c.row) !== null && _d !== void 0 ? _d : chart.from.row + estimatedRows;
|
|
52
|
+
const col = (_f = (_e = chart.to) === null || _e === void 0 ? void 0 : _e.col) !== null && _f !== void 0 ? _f : chart.from.col + estimatedCols;
|
|
53
|
+
return {
|
|
54
|
+
rowCount: Math.max(bounds.rowCount, row + 1),
|
|
55
|
+
colCount: Math.max(bounds.colCount, col + 1),
|
|
56
|
+
};
|
|
57
|
+
}, {
|
|
58
|
+
rowCount: 0,
|
|
59
|
+
colCount: 0,
|
|
60
|
+
});
|
|
61
|
+
};
|
|
40
62
|
const parseSheets = (context) => {
|
|
41
63
|
var _a;
|
|
42
64
|
const workbook = context.workbook;
|
|
@@ -49,7 +71,8 @@ const parseSheets = (context) => {
|
|
|
49
71
|
const worksheet = workbook.Sheets[name];
|
|
50
72
|
const ref = worksheet === null || worksheet === void 0 ? void 0 : worksheet['!ref'];
|
|
51
73
|
const drawingBounds = getDrawingBounds(worksheet);
|
|
52
|
-
|
|
74
|
+
const chartBounds = getChartBounds(context.charts[name]);
|
|
75
|
+
if (!ref && !drawingBounds.rowCount && !drawingBounds.colCount && !chartBounds.rowCount && !chartBounds.colCount) {
|
|
53
76
|
return result;
|
|
54
77
|
}
|
|
55
78
|
const range = ref ? utils.decode_range(ref) : utils.decode_range('A1');
|
|
@@ -57,16 +80,29 @@ const parseSheets = (context) => {
|
|
|
57
80
|
id: result.length,
|
|
58
81
|
name,
|
|
59
82
|
hidden: !!((_a = workbookSheets[sourceIndex]) === null || _a === void 0 ? void 0 : _a.Hidden),
|
|
60
|
-
rowCount: Math.max(range.e.r + 1, drawingBounds.rowCount),
|
|
61
|
-
colCount: Math.max(range.e.c + 1, drawingBounds.colCount),
|
|
83
|
+
rowCount: Math.max(range.e.r + 1, drawingBounds.rowCount, chartBounds.rowCount),
|
|
84
|
+
colCount: Math.max(range.e.c + 1, drawingBounds.colCount, chartBounds.colCount),
|
|
62
85
|
});
|
|
63
86
|
return result;
|
|
64
87
|
}, []);
|
|
65
88
|
return [{ type: 'sheets', payload: { sheets: context.sheets } }];
|
|
66
89
|
};
|
|
67
|
-
export const parseSpreadsheetWorkbook = (context, data) => {
|
|
90
|
+
export const parseSpreadsheetWorkbook = async (context, data) => {
|
|
68
91
|
try {
|
|
69
92
|
context.workbook = read(data, readOptions);
|
|
93
|
+
const signature = data.byteLength >= 2 ? new DataView(data).getUint16(0, false) : 0;
|
|
94
|
+
if (signature === 0x504b) {
|
|
95
|
+
try {
|
|
96
|
+
context.charts = await parseSpreadsheetCharts(data);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
context.charts = {};
|
|
100
|
+
console.warn('[file-viewer] Spreadsheet chart parsing failed; continuing with cell content.', error);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
context.charts = {};
|
|
105
|
+
}
|
|
70
106
|
return parseSheets(context);
|
|
71
107
|
}
|
|
72
108
|
catch (error) {
|
|
@@ -92,6 +128,7 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
|
|
|
92
128
|
pageSize,
|
|
93
129
|
totalRows: sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.rowCount,
|
|
94
130
|
totalCols: sheetMeta === null || sheetMeta === void 0 ? void 0 : sheetMeta.colCount,
|
|
131
|
+
charts: context.charts[sheetName],
|
|
95
132
|
});
|
|
96
133
|
const windowData = sheetModel.toObject();
|
|
97
134
|
const structure = startRow === 0 ? sheetModel.structure : undefined;
|
|
@@ -5,7 +5,8 @@ const ctx = typeof self === 'undefined'
|
|
|
5
5
|
if (ctx) {
|
|
6
6
|
const context = createSpreadsheetParserContext();
|
|
7
7
|
ctx.onmessage = async (message) => {
|
|
8
|
-
handleSpreadsheetWorkerRequest(context, message.data)
|
|
8
|
+
const responses = await handleSpreadsheetWorkerRequest(context, message.data);
|
|
9
|
+
responses.forEach(response => {
|
|
9
10
|
ctx.postMessage(response);
|
|
10
11
|
});
|
|
11
12
|
};
|
|
@@ -15,12 +15,51 @@ export interface SheetImage {
|
|
|
15
15
|
row: number;
|
|
16
16
|
col: number;
|
|
17
17
|
}
|
|
18
|
+
export type SheetChartType = 'bar' | 'line' | 'area' | 'pie' | 'doughnut' | 'scatter' | 'radar';
|
|
19
|
+
export interface SheetDrawingMarker {
|
|
20
|
+
row: number;
|
|
21
|
+
col: number;
|
|
22
|
+
rowOff: number;
|
|
23
|
+
colOff: number;
|
|
24
|
+
}
|
|
25
|
+
export interface SheetChartSeries {
|
|
26
|
+
name: string;
|
|
27
|
+
categories: string[];
|
|
28
|
+
values: number[];
|
|
29
|
+
color?: string;
|
|
30
|
+
}
|
|
31
|
+
export interface SheetChartDefinition {
|
|
32
|
+
id: string;
|
|
33
|
+
type: SheetChartType;
|
|
34
|
+
title?: string;
|
|
35
|
+
categoryAxisTitle?: string;
|
|
36
|
+
valueAxisTitle?: string;
|
|
37
|
+
barDirection?: 'column' | 'bar';
|
|
38
|
+
grouping?: string;
|
|
39
|
+
legendPosition?: 'top' | 'right' | 'bottom' | 'left';
|
|
40
|
+
series: SheetChartSeries[];
|
|
41
|
+
from: SheetDrawingMarker;
|
|
42
|
+
to?: SheetDrawingMarker;
|
|
43
|
+
ext?: {
|
|
44
|
+
width: number;
|
|
45
|
+
height: number;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export interface SheetChart extends Omit<SheetChartDefinition, 'from' | 'to' | 'ext'> {
|
|
49
|
+
left: number;
|
|
50
|
+
top: number;
|
|
51
|
+
width: number;
|
|
52
|
+
height: number;
|
|
53
|
+
row: number;
|
|
54
|
+
col: number;
|
|
55
|
+
}
|
|
18
56
|
export interface SheetStructure {
|
|
19
57
|
merge?: CellMerge[];
|
|
20
58
|
colWidths?: number | number[];
|
|
21
59
|
rowHeights?: number | number[];
|
|
22
60
|
columns?: SheetColumn[];
|
|
23
61
|
images?: SheetImage[];
|
|
62
|
+
charts?: SheetChart[];
|
|
24
63
|
}
|
|
25
64
|
export interface SheetColumn {
|
|
26
65
|
key: number;
|
package/dist/spreadsheet.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createFileViewerWorkerController, createFileViewerTranslator, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, registerFileViewerZoomProvider, resolveFileViewerSpreadsheetWorkerUrl, unregisterFileViewerZoomProvider, } from '@file-viewer/core';
|
|
2
|
+
import { renderSpreadsheetChart } from './spreadsheet/chartRenderer.js';
|
|
2
3
|
import { buildRows, clampWindowStart, collectWindowStarts, createEmptyVirtualState, DEFAULT_SHEET_DEFAULTS, displayCellKey, getDataKey, INDEX_COLUMN_KEY, markWindowState, ROW_STATE_FIELD, RowState, WINDOW_SIZE, } from './spreadsheet/state.js';
|
|
3
4
|
import { buildColumns, createTableConfig, detectIndexOffset, getDisplayColumns, getRowHeight, HEADER_HEIGHT, INDEX_COLUMN_WIDTH, normalizeCellStyle, normalizeRowHeight, RESIZABLE_COLUMN_MIN_WIDTH, RESIZABLE_ROW_MIN_HEIGHT, } from './spreadsheet/view.js';
|
|
4
5
|
const EXCEL_IMAGE_SCROLLBAR_GUARD = 18;
|
|
@@ -18,6 +19,8 @@ const spreadsheetStyle = `
|
|
|
18
19
|
.excel-wrapper .excel-image-viewport{position:absolute;z-index:35;overflow:hidden;pointer-events:none}
|
|
19
20
|
.excel-wrapper .excel-image-layer{position:absolute;inset:0 auto auto 0;width:0;height:0;transform-origin:0 0;will-change:transform}
|
|
20
21
|
.excel-wrapper .excel-image{position:absolute;display:block;max-width:none;height:auto;object-fit:contain;user-select:none}
|
|
22
|
+
.excel-wrapper .excel-chart{position:absolute;display:block;max-width:none;overflow:hidden;background:#fff;box-shadow:0 1px 3px rgba(15,23,42,.08);user-select:none}
|
|
23
|
+
.excel-wrapper .excel-chart svg{display:block;width:100%;height:100%;overflow:visible}
|
|
21
24
|
.excel-wrapper .loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.96);z-index:999;backdrop-filter:blur(6px)}
|
|
22
25
|
.excel-wrapper .loading-card{width:min(100%,460px);display:flex;align-items:center;gap:18px;padding:22px;border-radius:24px;background:rgba(255,255,255,.92);border:1px solid rgba(33,163,102,.1);box-shadow:0 22px 48px rgba(18,36,27,.12)}
|
|
23
26
|
.excel-wrapper .loading-brand{flex-shrink:0;width:78px;height:78px;display:flex;align-items:center;justify-content:center;border-radius:22px;background:linear-gradient(135deg,rgba(33,163,102,.14),rgba(33,163,102,.04));color:#1a7f50;font-size:18px;font-weight:900;letter-spacing:0}
|
|
@@ -174,7 +177,8 @@ class MainThreadSpreadsheetWorker {
|
|
|
174
177
|
}
|
|
175
178
|
try {
|
|
176
179
|
const parser = await this.loadParser();
|
|
177
|
-
parser.handleSpreadsheetWorkerRequest(this.context || parser.createSpreadsheetParserContext(), message)
|
|
180
|
+
const responses = await parser.handleSpreadsheetWorkerRequest(this.context || parser.createSpreadsheetParserContext(), message);
|
|
181
|
+
responses.forEach(response => {
|
|
178
182
|
if (!this.destroyed) {
|
|
179
183
|
this.dispatchMessage(response);
|
|
180
184
|
}
|
|
@@ -503,6 +507,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
503
507
|
let loadedWindowCount = 0;
|
|
504
508
|
let loadingWindowCount = 0;
|
|
505
509
|
let sheetImages = [];
|
|
510
|
+
let sheetCharts = [];
|
|
506
511
|
let zoom = 1;
|
|
507
512
|
let imageViewportState = {
|
|
508
513
|
scrollX: 0,
|
|
@@ -514,6 +519,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
514
519
|
let virtualState = createEmptyVirtualState();
|
|
515
520
|
const sheetStateCache = new Map();
|
|
516
521
|
const sheetImageCache = new Map();
|
|
522
|
+
const sheetChartCache = new Map();
|
|
517
523
|
let table = null;
|
|
518
524
|
let resizeObserver = null;
|
|
519
525
|
let resizeFrame = 0;
|
|
@@ -615,7 +621,15 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
615
621
|
y + scalePx(image.height) >= -margin &&
|
|
616
622
|
y <= height + margin;
|
|
617
623
|
});
|
|
618
|
-
|
|
624
|
+
const visibleCharts = sheetCharts.filter((chart) => {
|
|
625
|
+
const x = scalePx(chart.left) - imageViewportState.scrollX;
|
|
626
|
+
const y = scalePx(chart.top) - imageViewportState.scrollY;
|
|
627
|
+
return x + scalePx(chart.width) >= -margin &&
|
|
628
|
+
x <= width + margin &&
|
|
629
|
+
y + scalePx(chart.height) >= -margin &&
|
|
630
|
+
y <= height + margin;
|
|
631
|
+
});
|
|
632
|
+
setHidden(imageViewport, visibleImages.length === 0 && visibleCharts.length === 0);
|
|
619
633
|
Object.assign(imageViewport.style, {
|
|
620
634
|
left: `${scalePx(INDEX_COLUMN_WIDTH)}px`,
|
|
621
635
|
top: `${scalePx(HEADER_HEIGHT)}px`,
|
|
@@ -626,7 +640,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
626
640
|
});
|
|
627
641
|
imageLayer.style.transform =
|
|
628
642
|
`translate(${-imageViewportState.scrollX}px, ${-imageViewportState.scrollY}px)`;
|
|
629
|
-
|
|
643
|
+
const imageElements = visibleImages.map((image, index) => {
|
|
630
644
|
const element = documentRef.createElement('img');
|
|
631
645
|
element.className = 'excel-image';
|
|
632
646
|
element.src = image.src;
|
|
@@ -640,7 +654,18 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
640
654
|
});
|
|
641
655
|
element.dataset.imageIndex = `${index}`;
|
|
642
656
|
return element;
|
|
643
|
-
})
|
|
657
|
+
});
|
|
658
|
+
const chartElements = visibleCharts.map((chart) => {
|
|
659
|
+
const element = renderSpreadsheetChart(documentRef, chart);
|
|
660
|
+
Object.assign(element.style, {
|
|
661
|
+
left: `${scalePx(chart.left)}px`,
|
|
662
|
+
top: `${scalePx(chart.top)}px`,
|
|
663
|
+
width: `${scalePx(chart.width)}px`,
|
|
664
|
+
height: `${scalePx(chart.height)}px`,
|
|
665
|
+
});
|
|
666
|
+
return element;
|
|
667
|
+
});
|
|
668
|
+
imageLayer.replaceChildren(...imageElements, ...chartElements);
|
|
644
669
|
};
|
|
645
670
|
const scrollActiveSheetIntoView = () => {
|
|
646
671
|
requestAnimationFrame(() => {
|
|
@@ -1150,6 +1175,13 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
1150
1175
|
sheetImageCache.set(sheetId, structure.images);
|
|
1151
1176
|
}
|
|
1152
1177
|
}
|
|
1178
|
+
if (structure === null || structure === void 0 ? void 0 : structure.charts) {
|
|
1179
|
+
sheetCharts = structure.charts;
|
|
1180
|
+
const sheetId = getActiveSheetId();
|
|
1181
|
+
if (sheetId !== undefined) {
|
|
1182
|
+
sheetChartCache.set(sheetId, structure.charts);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1153
1185
|
};
|
|
1154
1186
|
const applyVirtualWindow = (ws) => {
|
|
1155
1187
|
var _a;
|
|
@@ -1198,6 +1230,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
1198
1230
|
totalCols = 0;
|
|
1199
1231
|
sheetDefaults = { ...DEFAULT_SHEET_DEFAULTS };
|
|
1200
1232
|
sheetImages = [];
|
|
1233
|
+
sheetCharts = [];
|
|
1201
1234
|
virtualState = createEmptyVirtualState();
|
|
1202
1235
|
hasInitialWindow = false;
|
|
1203
1236
|
resetViewportTracking();
|
|
@@ -1230,6 +1263,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, _type, context) => {
|
|
|
1230
1263
|
totalCols = cached.totalCols;
|
|
1231
1264
|
sheetDefaults = cached.defaults;
|
|
1232
1265
|
sheetImages = sheetImageCache.get(sheetId) || [];
|
|
1266
|
+
sheetCharts = sheetChartCache.get(sheetId) || [];
|
|
1233
1267
|
hasInitialWindow = cached.loadedWindows.size > 0;
|
|
1234
1268
|
sheetInitializing = !hasInitialWindow;
|
|
1235
1269
|
syncWindowStats();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@file-viewer/renderer-spreadsheet",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.26",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Standalone spreadsheet renderer plugin for Flyfish File Viewer powered by styled-exceljs and e-virt-table.",
|
|
@@ -68,8 +68,10 @@
|
|
|
68
68
|
"LICENSE"
|
|
69
69
|
],
|
|
70
70
|
"dependencies": {
|
|
71
|
-
"@file-viewer/core": "2.1.
|
|
71
|
+
"@file-viewer/core": "2.1.26",
|
|
72
|
+
"@xmldom/xmldom": "^0.9.10",
|
|
72
73
|
"e-virt-table": "^1.3.26",
|
|
74
|
+
"jszip": "^3.10.1",
|
|
73
75
|
"styled-exceljs": "0.21.1",
|
|
74
76
|
"tinycolor2": "^1.6.0"
|
|
75
77
|
},
|