@file-viewer/renderer-spreadsheet 2.2.9 → 2.3.0
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/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +8 -6
- package/dist/spreadsheet/worker/sheetjs/SheetJsModel.d.ts +5 -1
- package/dist/spreadsheet/worker/sheetjs/SheetJsModel.js +34 -4
- package/dist/spreadsheet/worker/sheetjs/chartParser.d.ts +16 -1
- package/dist/spreadsheet/worker/sheetjs/chartParser.js +114 -25
- package/dist/spreadsheet/worker/sheetjs/parser.d.ts +2 -1
- package/dist/spreadsheet/worker/sheetjs/parser.js +16 -7
- package/dist/spreadsheet/worker/sheetjs/richDataParser.d.ts +2 -0
- package/dist/spreadsheet/worker/sheetjs/richDataParser.js +320 -0
- package/dist/spreadsheet/worker/sheetjs/textEncoding.d.ts +2 -1
- package/dist/spreadsheet/worker/sheetjs/textEncoding.js +3 -116
- package/dist/spreadsheet/worker/type.d.ts +7 -0
- package/dist/spreadsheet.js +97 -2
- package/dist/worker/sheet.worker.js +67 -51
- package/package.json +5 -4
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import JSZip from 'jszip';
|
|
2
|
+
import { utils } from 'styled-exceljs';
|
|
3
|
+
import { childElements, elementsByLocal, loadRelationships, loadXml, localName, relationById, relationshipId } from './chartParser.js';
|
|
4
|
+
const WORKBOOK_PART = 'xl/workbook.xml';
|
|
5
|
+
const CONTENT_TYPES_PART = '[Content_Types].xml';
|
|
6
|
+
const WORKSHEET_RELATIONSHIP_SUFFIX = '/worksheet';
|
|
7
|
+
const METADATA_RELATIONSHIP_SUFFIX = '/sheetmetadata';
|
|
8
|
+
const RICH_VALUE_RELATIONSHIP_SUFFIX = '/rdrichvalue';
|
|
9
|
+
const RICH_VALUE_STRUCTURE_RELATIONSHIP_SUFFIX = '/rdrichvaluestructure';
|
|
10
|
+
const RICH_VALUE_RELATION_LIST_SUFFIX = '/richvaluerel';
|
|
11
|
+
const WPS_CELL_IMAGE_RELATIONSHIP = 'http://www.wps.cn/officeDocument/2017/relationships/cellimage';
|
|
12
|
+
const RICH_VALUE_METADATA_NAME = 'XLRICHVALUE';
|
|
13
|
+
const LOCAL_IMAGE_STRUCTURE_TYPE = '_localImage';
|
|
14
|
+
const LOCAL_IMAGE_KEY_SUFFIX = 'LocalImageIdentifier';
|
|
15
|
+
const textContent = (element) => { var _a; return ((_a = element === null || element === void 0 ? void 0 : element.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || ''; };
|
|
16
|
+
const directChildrenByLocal = (node, name) => (childElements(node).filter((child) => localName(child) === name));
|
|
17
|
+
const firstDescendantByLocal = (node, name) => (elementsByLocal(node, name)[0]);
|
|
18
|
+
const relationshipBySuffix = (relationships, suffix) => (relationships.find((relationship) => relationship.type.toLowerCase().endsWith(suffix)));
|
|
19
|
+
const parseContentTypes = (document) => {
|
|
20
|
+
const defaults = new Map();
|
|
21
|
+
const overrides = new Map();
|
|
22
|
+
if (!document) {
|
|
23
|
+
return { defaults, overrides };
|
|
24
|
+
}
|
|
25
|
+
elementsByLocal(document.documentElement, 'Default').forEach((element) => {
|
|
26
|
+
const extension = (element.getAttribute('Extension') || '').toLowerCase();
|
|
27
|
+
const contentType = element.getAttribute('ContentType') || '';
|
|
28
|
+
if (extension && contentType) {
|
|
29
|
+
defaults.set(extension, contentType);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
elementsByLocal(document.documentElement, 'Override').forEach((element) => {
|
|
33
|
+
const partName = (element.getAttribute('PartName') || '').replace(/^\//, '');
|
|
34
|
+
const contentType = element.getAttribute('ContentType') || '';
|
|
35
|
+
if (partName && contentType) {
|
|
36
|
+
overrides.set(partName, contentType);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
return { defaults, overrides };
|
|
40
|
+
};
|
|
41
|
+
const fallbackImageContentType = (path) => {
|
|
42
|
+
var _a;
|
|
43
|
+
const extension = ((_a = path.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
|
|
44
|
+
switch (extension) {
|
|
45
|
+
case 'bmp':
|
|
46
|
+
return 'image/bmp';
|
|
47
|
+
case 'gif':
|
|
48
|
+
return 'image/gif';
|
|
49
|
+
case 'jpeg':
|
|
50
|
+
case 'jpg':
|
|
51
|
+
return 'image/jpeg';
|
|
52
|
+
case 'png':
|
|
53
|
+
return 'image/png';
|
|
54
|
+
case 'svg':
|
|
55
|
+
return 'image/svg+xml';
|
|
56
|
+
case 'webp':
|
|
57
|
+
return 'image/webp';
|
|
58
|
+
default:
|
|
59
|
+
return '';
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const getContentType = (path, contentTypes) => {
|
|
63
|
+
var _a;
|
|
64
|
+
const override = contentTypes.overrides.get(path);
|
|
65
|
+
if (override) {
|
|
66
|
+
return override;
|
|
67
|
+
}
|
|
68
|
+
const extension = ((_a = path.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
|
|
69
|
+
return contentTypes.defaults.get(extension) || fallbackImageContentType(path);
|
|
70
|
+
};
|
|
71
|
+
const parseRichValueStructures = (document) => {
|
|
72
|
+
if (!document) {
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
return directChildrenByLocal(document.documentElement, 's').map((structure) => ({
|
|
76
|
+
type: structure.getAttribute('t') || '',
|
|
77
|
+
keys: directChildrenByLocal(structure, 'k').map((key) => key.getAttribute('n') || '')
|
|
78
|
+
}));
|
|
79
|
+
};
|
|
80
|
+
const parseRichValues = (document) => {
|
|
81
|
+
if (!document) {
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
return directChildrenByLocal(document.documentElement, 'rv').map((richValue) => ({
|
|
85
|
+
structureIndex: Number(richValue.getAttribute('s')),
|
|
86
|
+
values: directChildrenByLocal(richValue, 'v').map((value) => Number(textContent(value)))
|
|
87
|
+
}));
|
|
88
|
+
};
|
|
89
|
+
const parseRichValueRelationshipIds = (document) => {
|
|
90
|
+
if (!document) {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
return directChildrenByLocal(document.documentElement, 'rel').map(relationshipId);
|
|
94
|
+
};
|
|
95
|
+
const parseMetadataRichValueIndexes = (document) => {
|
|
96
|
+
if (!document) {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
const metadataTypes = firstDescendantByLocal(document.documentElement, 'metadataTypes');
|
|
100
|
+
const richValueMetadataType = directChildrenByLocal(metadataTypes, 'metadataType')
|
|
101
|
+
.findIndex((metadataType) => metadataType.getAttribute('name') === RICH_VALUE_METADATA_NAME) + 1;
|
|
102
|
+
if (richValueMetadataType <= 0) {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
const futureMetadata = elementsByLocal(document.documentElement, 'futureMetadata')
|
|
106
|
+
.find((element) => element.getAttribute('name') === RICH_VALUE_METADATA_NAME);
|
|
107
|
+
const futureRichValueIndexes = directChildrenByLocal(futureMetadata, 'bk').map((block) => {
|
|
108
|
+
const richValueBlock = firstDescendantByLocal(block, 'rvb');
|
|
109
|
+
const value = Number(richValueBlock === null || richValueBlock === void 0 ? void 0 : richValueBlock.getAttribute('i'));
|
|
110
|
+
return Number.isInteger(value) && value >= 0 ? value : undefined;
|
|
111
|
+
});
|
|
112
|
+
const valueMetadata = firstDescendantByLocal(document.documentElement, 'valueMetadata');
|
|
113
|
+
return directChildrenByLocal(valueMetadata, 'bk').map((block) => {
|
|
114
|
+
const reference = directChildrenByLocal(block, 'rc').find((element) => Number(element.getAttribute('t')) === richValueMetadataType);
|
|
115
|
+
const futureIndex = Number(reference === null || reference === void 0 ? void 0 : reference.getAttribute('v'));
|
|
116
|
+
return Number.isInteger(futureIndex) && futureIndex >= 0
|
|
117
|
+
? futureRichValueIndexes[futureIndex]
|
|
118
|
+
: undefined;
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
const attributeValue = (tag, name) => {
|
|
122
|
+
var _a, _b;
|
|
123
|
+
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
124
|
+
const match = tag.match(new RegExp(`(?:^|\\s)${escapedName}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i'));
|
|
125
|
+
return (_b = (_a = match === null || match === void 0 ? void 0 : match[1]) !== null && _a !== void 0 ? _a : match === null || match === void 0 ? void 0 : match[2]) !== null && _b !== void 0 ? _b : '';
|
|
126
|
+
};
|
|
127
|
+
const parseWorksheetCellMetadata = (xml) => {
|
|
128
|
+
const result = [];
|
|
129
|
+
const cellTagPattern = /<(?:[A-Za-z_][\w.-]*:)?c\b[^>]*>/gi;
|
|
130
|
+
for (const match of xml.matchAll(cellTagPattern)) {
|
|
131
|
+
const tag = match[0];
|
|
132
|
+
const ref = attributeValue(tag, 'r');
|
|
133
|
+
const metadataText = attributeValue(tag, 'vm');
|
|
134
|
+
const metadataValue = Number(metadataText);
|
|
135
|
+
if (!ref || !metadataText || !Number.isInteger(metadataValue) || metadataValue < 0) {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
// Cell metadata indexes are one-based in OOXML. Accept zero as a
|
|
139
|
+
// producer-tolerance fallback without shifting it below zero.
|
|
140
|
+
result.push({ ref, metadataIndex: metadataValue > 0 ? metadataValue - 1 : 0 });
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
};
|
|
144
|
+
const decodeFormulaText = (value) => value
|
|
145
|
+
.replace(/"/gi, '"')
|
|
146
|
+
.replace(/'/gi, "'")
|
|
147
|
+
.replace(/</gi, '<')
|
|
148
|
+
.replace(/>/gi, '>')
|
|
149
|
+
.replace(/&/gi, '&');
|
|
150
|
+
const parseWorksheetDispImages = (xml) => {
|
|
151
|
+
var _a, _b;
|
|
152
|
+
const result = [];
|
|
153
|
+
const cellPattern = /<(?:[A-Za-z_][\w.-]*:)?c\b[^>]*>[\s\S]*?<\/(?:[A-Za-z_][\w.-]*:)?c\s*>/gi;
|
|
154
|
+
for (const match of xml.matchAll(cellPattern)) {
|
|
155
|
+
const cellXml = match[0];
|
|
156
|
+
const startTag = cellXml.slice(0, cellXml.indexOf('>') + 1);
|
|
157
|
+
const ref = attributeValue(startTag, 'r');
|
|
158
|
+
const formulaMatch = cellXml.match(/<(?:[A-Za-z_][\w.-]*:)?f\b[^>]*>([\s\S]*?)<\/(?:[A-Za-z_][\w.-]*:)?f\s*>/i);
|
|
159
|
+
const formula = decodeFormulaText(((_a = formulaMatch === null || formulaMatch === void 0 ? void 0 : formulaMatch[1]) === null || _a === void 0 ? void 0 : _a.trim()) || '');
|
|
160
|
+
const imageId = (_b = formula.match(/(?:_xlfn\.)?(?:_xlws\.)?DISPIMG\s*\(\s*["']([^"']+)["']/i)) === null || _b === void 0 ? void 0 : _b[1];
|
|
161
|
+
if (ref && imageId) {
|
|
162
|
+
result.push({ ref, imageId });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return result;
|
|
166
|
+
};
|
|
167
|
+
const embeddedRelationshipId = (element) => {
|
|
168
|
+
if (!element) {
|
|
169
|
+
return '';
|
|
170
|
+
}
|
|
171
|
+
return (element.getAttribute('r:embed') ||
|
|
172
|
+
element.getAttributeNS('http://schemas.openxmlformats.org/officeDocument/2006/relationships', 'embed') ||
|
|
173
|
+
element.getAttribute('embed') ||
|
|
174
|
+
'');
|
|
175
|
+
};
|
|
176
|
+
const loadWpsCellImages = async (zip, relationship, contentTypes) => {
|
|
177
|
+
const result = new Map();
|
|
178
|
+
if (!relationship) {
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
const [document, relationships] = await Promise.all([
|
|
182
|
+
loadXml(zip, relationship.target),
|
|
183
|
+
loadRelationships(zip, relationship.target)
|
|
184
|
+
]);
|
|
185
|
+
if (!document) {
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
await Promise.all(elementsByLocal(document.documentElement, 'cellImage').map(async (cellImage) => {
|
|
189
|
+
const nonVisualProperties = firstDescendantByLocal(cellImage, 'cNvPr');
|
|
190
|
+
const imageId = (nonVisualProperties === null || nonVisualProperties === void 0 ? void 0 : nonVisualProperties.getAttribute('name')) || '';
|
|
191
|
+
const blip = firstDescendantByLocal(cellImage, 'blip');
|
|
192
|
+
const imageRelationship = relationById(relationships, embeddedRelationshipId(blip));
|
|
193
|
+
if (!imageId || !imageRelationship) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const contentType = getContentType(imageRelationship.target, contentTypes);
|
|
197
|
+
const imageFile = zip.file(imageRelationship.target);
|
|
198
|
+
if (!imageFile || !contentType.startsWith('image/')) {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
result.set(imageId, {
|
|
202
|
+
id: imageId,
|
|
203
|
+
src: `data:${contentType};base64,${await imageFile.async('base64')}`,
|
|
204
|
+
contentType
|
|
205
|
+
});
|
|
206
|
+
}));
|
|
207
|
+
return result;
|
|
208
|
+
};
|
|
209
|
+
const loadRichValueImages = async (zip, structures, richValues, relationshipIds, relationships, contentTypes) => {
|
|
210
|
+
const result = new Map();
|
|
211
|
+
await Promise.all(richValues.map(async (richValue, richValueIndex) => {
|
|
212
|
+
const structure = structures[richValue.structureIndex];
|
|
213
|
+
if (!structure || structure.type !== LOCAL_IMAGE_STRUCTURE_TYPE) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const imageKeyIndex = structure.keys.findIndex((key) => key.endsWith(LOCAL_IMAGE_KEY_SUFFIX));
|
|
217
|
+
const imageRelationshipIndex = richValue.values[imageKeyIndex];
|
|
218
|
+
if (imageKeyIndex < 0 || !Number.isInteger(imageRelationshipIndex) || imageRelationshipIndex < 0) {
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const imageRelationshipId = relationshipIds[imageRelationshipIndex];
|
|
222
|
+
const imageRelationship = relationById(relationships, imageRelationshipId);
|
|
223
|
+
if (!imageRelationship) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const contentType = getContentType(imageRelationship.target, contentTypes);
|
|
227
|
+
const imageFile = zip.file(imageRelationship.target);
|
|
228
|
+
if (!imageFile || !contentType.startsWith('image/')) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const base64 = await imageFile.async('base64');
|
|
232
|
+
result.set(richValueIndex, {
|
|
233
|
+
id: imageRelationship.id,
|
|
234
|
+
src: `data:${contentType};base64,${base64}`,
|
|
235
|
+
contentType
|
|
236
|
+
});
|
|
237
|
+
}));
|
|
238
|
+
return result;
|
|
239
|
+
};
|
|
240
|
+
export const parseSpreadsheetCellImages = async (data) => {
|
|
241
|
+
const zip = await JSZip.loadAsync(data);
|
|
242
|
+
const [workbookDocument, workbookRelationships, contentTypesDocument] = await Promise.all([
|
|
243
|
+
loadXml(zip, WORKBOOK_PART),
|
|
244
|
+
loadRelationships(zip, WORKBOOK_PART),
|
|
245
|
+
loadXml(zip, CONTENT_TYPES_PART)
|
|
246
|
+
]);
|
|
247
|
+
const result = {};
|
|
248
|
+
if (!workbookDocument) {
|
|
249
|
+
return result;
|
|
250
|
+
}
|
|
251
|
+
const metadataRelationship = relationshipBySuffix(workbookRelationships, METADATA_RELATIONSHIP_SUFFIX);
|
|
252
|
+
const richValueRelationship = relationshipBySuffix(workbookRelationships, RICH_VALUE_RELATIONSHIP_SUFFIX);
|
|
253
|
+
const richValueStructureRelationship = relationshipBySuffix(workbookRelationships, RICH_VALUE_STRUCTURE_RELATIONSHIP_SUFFIX);
|
|
254
|
+
const richValueRelationListRelationship = relationshipBySuffix(workbookRelationships, RICH_VALUE_RELATION_LIST_SUFFIX);
|
|
255
|
+
const contentTypes = parseContentTypes(contentTypesDocument);
|
|
256
|
+
let metadataRichValueIndexes = [];
|
|
257
|
+
let richValueImages = new Map();
|
|
258
|
+
if (metadataRelationship &&
|
|
259
|
+
richValueRelationship &&
|
|
260
|
+
richValueStructureRelationship &&
|
|
261
|
+
richValueRelationListRelationship) {
|
|
262
|
+
const [metadataDocument, richValueDocument, richValueStructureDocument, richValueRelationListDocument, richValueRelationships] = await Promise.all([
|
|
263
|
+
loadXml(zip, metadataRelationship.target),
|
|
264
|
+
loadXml(zip, richValueRelationship.target),
|
|
265
|
+
loadXml(zip, richValueStructureRelationship.target),
|
|
266
|
+
loadXml(zip, richValueRelationListRelationship.target),
|
|
267
|
+
loadRelationships(zip, richValueRelationListRelationship.target)
|
|
268
|
+
]);
|
|
269
|
+
metadataRichValueIndexes = parseMetadataRichValueIndexes(metadataDocument);
|
|
270
|
+
richValueImages = await loadRichValueImages(zip, parseRichValueStructures(richValueStructureDocument), parseRichValues(richValueDocument), parseRichValueRelationshipIds(richValueRelationListDocument), richValueRelationships, contentTypes);
|
|
271
|
+
}
|
|
272
|
+
const wpsCellImageRelationship = workbookRelationships.find((relationship) => (relationship.type.toLowerCase() === WPS_CELL_IMAGE_RELATIONSHIP.toLowerCase()));
|
|
273
|
+
const wpsCellImages = await loadWpsCellImages(zip, wpsCellImageRelationship, contentTypes);
|
|
274
|
+
if (!richValueImages.size && !wpsCellImages.size) {
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
277
|
+
for (const sheet of elementsByLocal(workbookDocument.documentElement, 'sheet')) {
|
|
278
|
+
const name = sheet.getAttribute('name') || '';
|
|
279
|
+
const worksheetRelationship = relationById(workbookRelationships, relationshipId(sheet));
|
|
280
|
+
const worksheetFile = (worksheetRelationship === null || worksheetRelationship === void 0 ? void 0 : worksheetRelationship.type.toLowerCase().endsWith(WORKSHEET_RELATIONSHIP_SUFFIX))
|
|
281
|
+
? zip.file(worksheetRelationship.target)
|
|
282
|
+
: null;
|
|
283
|
+
if (!name || !worksheetFile) {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const worksheetXml = await worksheetFile.async('text');
|
|
287
|
+
const imagesByRef = new Map();
|
|
288
|
+
parseWorksheetCellMetadata(worksheetXml).forEach(({ ref, metadataIndex }) => {
|
|
289
|
+
const richValueIndex = metadataRichValueIndexes[metadataIndex];
|
|
290
|
+
const image = richValueIndex === undefined ? undefined : richValueImages.get(richValueIndex);
|
|
291
|
+
if (image) {
|
|
292
|
+
imagesByRef.set(ref, image);
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
parseWorksheetDispImages(worksheetXml).forEach(({ ref, imageId }) => {
|
|
296
|
+
const image = wpsCellImages.get(imageId);
|
|
297
|
+
if (image && !imagesByRef.has(ref)) {
|
|
298
|
+
imagesByRef.set(ref, image);
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
const images = Array.from(imagesByRef).flatMap(([ref, image]) => {
|
|
302
|
+
try {
|
|
303
|
+
const cell = utils.decode_cell(ref);
|
|
304
|
+
return [{
|
|
305
|
+
...image,
|
|
306
|
+
id: `cell-image-${ref}-${image.id}`,
|
|
307
|
+
row: cell.r,
|
|
308
|
+
col: cell.c
|
|
309
|
+
}];
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return [];
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
if (images.length) {
|
|
316
|
+
result[name] = images;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return result;
|
|
320
|
+
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ResolvedFileViewerTextEncoding } from '@file-viewer/core';
|
|
1
2
|
export type SpreadsheetTextEncoding = 'auto' | 'utf-8' | 'gbk' | 'gb18030';
|
|
2
3
|
export interface SpreadsheetTextSource {
|
|
3
4
|
fileType?: string;
|
|
@@ -6,7 +7,7 @@ export interface SpreadsheetTextSource {
|
|
|
6
7
|
}
|
|
7
8
|
export interface DecodedSpreadsheetText {
|
|
8
9
|
text: string;
|
|
9
|
-
encoding:
|
|
10
|
+
encoding: ResolvedFileViewerTextEncoding;
|
|
10
11
|
}
|
|
11
12
|
export type PreparedSpreadsheetReadInput = {
|
|
12
13
|
kind: 'binary';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { decodeFileViewerTextBuffer, isValidFileViewerUtf8, } from '@file-viewer/core';
|
|
1
2
|
const TEXT_SPREADSHEET_EXTENSIONS = new Set(['csv', 'tsv']);
|
|
2
3
|
const TEXT_SPREADSHEET_MIME_TYPES = new Set([
|
|
3
4
|
'text/csv',
|
|
@@ -24,122 +25,8 @@ export const isTextSpreadsheetSource = ({ fileType, filename, }) => {
|
|
|
24
25
|
}
|
|
25
26
|
return TEXT_SPREADSHEET_EXTENSIONS.has(getFilenameExtension(filename));
|
|
26
27
|
};
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
throw new Error('Spreadsheet text decoding requires the browser TextDecoder API.');
|
|
30
|
-
}
|
|
31
|
-
try {
|
|
32
|
-
return new TextDecoder(encoding).decode(bytes);
|
|
33
|
-
}
|
|
34
|
-
catch (error) {
|
|
35
|
-
if (encoding === 'gb18030' && error instanceof RangeError) {
|
|
36
|
-
throw new Error('This browser does not provide GB18030 text decoding. Use a current browser or set spreadsheet.textEncoding to "utf-8".');
|
|
37
|
-
}
|
|
38
|
-
throw error;
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
const hasUtf8Bom = (bytes) => {
|
|
42
|
-
return bytes.length >= 3 &&
|
|
43
|
-
bytes[0] === 0xef &&
|
|
44
|
-
bytes[1] === 0xbb &&
|
|
45
|
-
bytes[2] === 0xbf;
|
|
46
|
-
};
|
|
47
|
-
const isContinuationByte = (value) => {
|
|
48
|
-
return value !== undefined && value >= 0x80 && value <= 0xbf;
|
|
49
|
-
};
|
|
50
|
-
// Validate bytes directly instead of relying on TextDecoder({ fatal: true }).
|
|
51
|
-
// Some older WebViews accept TextDecoder but ignore the fatal option, which
|
|
52
|
-
// would turn GBK into replacement characters before the GB18030 fallback runs.
|
|
53
|
-
export const isValidUtf8 = (bytes) => {
|
|
54
|
-
for (let index = 0; index < bytes.length;) {
|
|
55
|
-
const first = bytes[index];
|
|
56
|
-
if (first === undefined) {
|
|
57
|
-
return false;
|
|
58
|
-
}
|
|
59
|
-
if (first <= 0x7f) {
|
|
60
|
-
index += 1;
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
const second = bytes[index + 1];
|
|
64
|
-
const third = bytes[index + 2];
|
|
65
|
-
const fourth = bytes[index + 3];
|
|
66
|
-
if (first >= 0xc2 && first <= 0xdf && isContinuationByte(second)) {
|
|
67
|
-
index += 2;
|
|
68
|
-
continue;
|
|
69
|
-
}
|
|
70
|
-
if (first === 0xe0 &&
|
|
71
|
-
second !== undefined && second >= 0xa0 && second <= 0xbf &&
|
|
72
|
-
isContinuationByte(third)) {
|
|
73
|
-
index += 3;
|
|
74
|
-
continue;
|
|
75
|
-
}
|
|
76
|
-
if (((first >= 0xe1 && first <= 0xec) || (first >= 0xee && first <= 0xef)) &&
|
|
77
|
-
isContinuationByte(second) &&
|
|
78
|
-
isContinuationByte(third)) {
|
|
79
|
-
index += 3;
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
if (first === 0xed &&
|
|
83
|
-
second !== undefined && second >= 0x80 && second <= 0x9f &&
|
|
84
|
-
isContinuationByte(third)) {
|
|
85
|
-
index += 3;
|
|
86
|
-
continue;
|
|
87
|
-
}
|
|
88
|
-
if (first === 0xf0 &&
|
|
89
|
-
second !== undefined && second >= 0x90 && second <= 0xbf &&
|
|
90
|
-
isContinuationByte(third) &&
|
|
91
|
-
isContinuationByte(fourth)) {
|
|
92
|
-
index += 4;
|
|
93
|
-
continue;
|
|
94
|
-
}
|
|
95
|
-
if (first >= 0xf1 && first <= 0xf3 &&
|
|
96
|
-
isContinuationByte(second) &&
|
|
97
|
-
isContinuationByte(third) &&
|
|
98
|
-
isContinuationByte(fourth)) {
|
|
99
|
-
index += 4;
|
|
100
|
-
continue;
|
|
101
|
-
}
|
|
102
|
-
if (first === 0xf4 &&
|
|
103
|
-
second !== undefined && second >= 0x80 && second <= 0x8f &&
|
|
104
|
-
isContinuationByte(third) &&
|
|
105
|
-
isContinuationByte(fourth)) {
|
|
106
|
-
index += 4;
|
|
107
|
-
continue;
|
|
108
|
-
}
|
|
109
|
-
return false;
|
|
110
|
-
}
|
|
111
|
-
return true;
|
|
112
|
-
};
|
|
113
|
-
const normalizeTextEncoding = (encoding) => {
|
|
114
|
-
const normalized = String(encoding || 'auto').trim().toLowerCase().replace('_', '-');
|
|
115
|
-
if (normalized === 'utf8' || normalized === 'utf-8') {
|
|
116
|
-
return 'utf-8';
|
|
117
|
-
}
|
|
118
|
-
if (normalized === 'gbk' || normalized === 'cp936' || normalized === 'gb2312') {
|
|
119
|
-
return 'gbk';
|
|
120
|
-
}
|
|
121
|
-
if (normalized === 'gb18030') {
|
|
122
|
-
return 'gb18030';
|
|
123
|
-
}
|
|
124
|
-
return 'auto';
|
|
125
|
-
};
|
|
126
|
-
export const decodeSpreadsheetText = (data, encoding = 'auto') => {
|
|
127
|
-
const bytes = new Uint8Array(data);
|
|
128
|
-
const normalizedEncoding = normalizeTextEncoding(encoding);
|
|
129
|
-
if (normalizedEncoding === 'utf-8') {
|
|
130
|
-
const content = hasUtf8Bom(bytes) ? bytes.subarray(3) : bytes;
|
|
131
|
-
return { text: decodeBytes(content, 'utf-8'), encoding: 'utf-8' };
|
|
132
|
-
}
|
|
133
|
-
if (normalizedEncoding === 'gbk' || normalizedEncoding === 'gb18030') {
|
|
134
|
-
return { text: decodeBytes(bytes, 'gb18030'), encoding: 'gb18030' };
|
|
135
|
-
}
|
|
136
|
-
if (hasUtf8Bom(bytes)) {
|
|
137
|
-
return { text: decodeBytes(bytes.subarray(3), 'utf-8'), encoding: 'utf-8' };
|
|
138
|
-
}
|
|
139
|
-
return isValidUtf8(bytes)
|
|
140
|
-
? { text: decodeBytes(bytes, 'utf-8'), encoding: 'utf-8' }
|
|
141
|
-
: { text: decodeBytes(bytes, 'gb18030'), encoding: 'gb18030' };
|
|
142
|
-
};
|
|
28
|
+
export const isValidUtf8 = isValidFileViewerUtf8;
|
|
29
|
+
export const decodeSpreadsheetText = (data, encoding = 'auto') => decodeFileViewerTextBuffer(data, encoding);
|
|
143
30
|
export const prepareSpreadsheetReadInput = (data, source = {}) => {
|
|
144
31
|
if (!isTextSpreadsheetSource(source)) {
|
|
145
32
|
return { kind: 'binary', data };
|
|
@@ -15,6 +15,13 @@ export interface SheetImage {
|
|
|
15
15
|
row: number;
|
|
16
16
|
col: number;
|
|
17
17
|
}
|
|
18
|
+
export interface SheetCellImage {
|
|
19
|
+
id: string;
|
|
20
|
+
src: string;
|
|
21
|
+
contentType?: string;
|
|
22
|
+
row: number;
|
|
23
|
+
col: number;
|
|
24
|
+
}
|
|
18
25
|
export type SheetChartType = 'bar' | 'line' | 'area' | 'pie' | 'doughnut' | 'scatter' | 'radar';
|
|
19
26
|
export interface SheetDrawingMarker {
|
|
20
27
|
row: number;
|
package/dist/spreadsheet.js
CHANGED
|
@@ -29,6 +29,13 @@ const spreadsheetStyle = `
|
|
|
29
29
|
.excel-wrapper .excel-image{position:absolute;display:block;max-width:none;height:auto;object-fit:contain;user-select:none}
|
|
30
30
|
.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}
|
|
31
31
|
.excel-wrapper .excel-chart svg{display:block;width:100%;height:100%;overflow:visible}
|
|
32
|
+
.excel-wrapper .excel-image-lightbox{position:absolute;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;padding:clamp(16px,4vw,48px);background:rgba(15,23,42,.9);box-sizing:border-box;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .18s ease,visibility 0s linear .18s}
|
|
33
|
+
.excel-wrapper .excel-image-lightbox[data-open='true']{opacity:1;visibility:visible;pointer-events:auto;transition-delay:0s}
|
|
34
|
+
.excel-wrapper .excel-image-lightbox img{display:block;max-width:100%;max-height:100%;object-fit:contain;background:#fff;box-shadow:0 30px 80px rgba(0,0,0,.4);transform:scale(.985);transition:transform .18s ease;user-select:none}
|
|
35
|
+
.excel-wrapper .excel-image-lightbox[data-open='true'] img{transform:scale(1)}
|
|
36
|
+
.excel-wrapper .excel-image-lightbox button{position:absolute;top:16px;right:16px;display:grid;width:40px;height:40px;place-items:center;padding:0;border:1px solid rgba(255,255,255,.7);border-radius:999px;background:rgba(255,255,255,.96);color:#172033;font:400 27px/1 Arial,sans-serif;cursor:pointer;box-shadow:0 12px 28px rgba(0,0,0,.24);transition:background-color .14s ease,transform .14s ease}
|
|
37
|
+
.excel-wrapper .excel-image-lightbox button:hover{background:#fff;transform:scale(1.04)}
|
|
38
|
+
.excel-wrapper .excel-image-lightbox button:focus-visible{outline:3px solid #60a5fa;outline-offset:2px}
|
|
32
39
|
.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)}
|
|
33
40
|
.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)}
|
|
34
41
|
.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}
|
|
@@ -59,7 +66,8 @@ const spreadsheetStyle = `
|
|
|
59
66
|
.excel-wrapper[data-spreadsheet-theme='dark'] .error{border-color:rgba(251,146,60,.28);background:#2a1710;color:#fdba74;box-shadow:0 20px 48px rgba(0,0,0,.36)}
|
|
60
67
|
@keyframes file-viewer-spreadsheet-loading-spin{to{transform:rotate(360deg)}}
|
|
61
68
|
@keyframes file-viewer-spreadsheet-loading-pulse{0%,100%{opacity:.55;transform:scale(.9)}50%{opacity:1;transform:scale(1)}}
|
|
62
|
-
@media (max-width:720px){.excel-wrapper .toolbar{align-items:stretch;flex-direction:column}.excel-wrapper .btn-group{flex:0 0 auto}.excel-wrapper .summary{max-width:none;white-space:normal}.excel-wrapper .sheet-loading{left:12px;right:12px;bottom:58px;justify-content:center}.excel-wrapper .loading-card{margin:18px;flex-direction:column;text-align:center}}
|
|
69
|
+
@media (max-width:720px){.excel-wrapper .toolbar{align-items:stretch;flex-direction:column}.excel-wrapper .btn-group{flex:0 0 auto}.excel-wrapper .summary{max-width:none;white-space:normal}.excel-wrapper .sheet-loading{left:12px;right:12px;bottom:58px;justify-content:center}.excel-wrapper .loading-card{margin:18px;flex-direction:column;text-align:center}.excel-wrapper .excel-image-lightbox button{top:12px;right:12px}}
|
|
70
|
+
@media (prefers-reduced-motion:reduce){.excel-wrapper .excel-image-lightbox,.excel-wrapper .excel-image-lightbox img,.excel-wrapper .excel-image-lightbox button{transition:none}}
|
|
63
71
|
`;
|
|
64
72
|
const scopedSpreadsheetStyle = spreadsheetStyle.replace(/\.excel-wrapper/g, SPREADSHEET_STYLE_SCOPE);
|
|
65
73
|
const isEVirtTableConstructor = (value) => {
|
|
@@ -584,6 +592,20 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
|
|
|
584
592
|
imageViewport.appendChild(imageLayer);
|
|
585
593
|
tableHostShell.append(tableHost, imageViewport);
|
|
586
594
|
tableWrapper.append(sheetLoading, tableHostShell);
|
|
595
|
+
const imageLightbox = documentRef.createElement('div');
|
|
596
|
+
imageLightbox.className = 'excel-image-lightbox';
|
|
597
|
+
imageLightbox.dataset.open = 'false';
|
|
598
|
+
imageLightbox.setAttribute('role', 'dialog');
|
|
599
|
+
imageLightbox.setAttribute('aria-modal', 'true');
|
|
600
|
+
imageLightbox.setAttribute('aria-hidden', 'true');
|
|
601
|
+
const lightboxImage = documentRef.createElement('img');
|
|
602
|
+
lightboxImage.alt = t('image.lightbox.alt');
|
|
603
|
+
lightboxImage.draggable = false;
|
|
604
|
+
const lightboxCloseButton = documentRef.createElement('button');
|
|
605
|
+
lightboxCloseButton.type = 'button';
|
|
606
|
+
lightboxCloseButton.setAttribute('aria-label', t('image.lightbox.close'));
|
|
607
|
+
lightboxCloseButton.textContent = '×';
|
|
608
|
+
imageLightbox.append(lightboxImage, lightboxCloseButton);
|
|
587
609
|
const toolbar = documentRef.createElement('div');
|
|
588
610
|
toolbar.className = 'toolbar';
|
|
589
611
|
const sheetTabsBar = documentRef.createElement('div');
|
|
@@ -592,7 +614,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
|
|
|
592
614
|
const summary = documentRef.createElement('div');
|
|
593
615
|
summary.className = 'summary';
|
|
594
616
|
toolbar.append(sheetTabsBar, summary);
|
|
595
|
-
root.append(loading, error, tableWrapper, toolbar);
|
|
617
|
+
root.append(loading, error, tableWrapper, toolbar, imageLightbox);
|
|
596
618
|
target.replaceChildren(createEVirtTableStyle(documentRef, target, loadedEVirtTable.styleText), createStyle(documentRef), root);
|
|
597
619
|
let sheets = [];
|
|
598
620
|
let sheetIndex = 0;
|
|
@@ -629,6 +651,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
|
|
|
629
651
|
let lastScrollY = 0;
|
|
630
652
|
let sheetSessionId = 0;
|
|
631
653
|
let disposed = false;
|
|
654
|
+
let imageLightboxPreviousFocus = null;
|
|
632
655
|
let hasNotifiedFirstPaint = false;
|
|
633
656
|
let hasAppliedDefaultInitialFit = false;
|
|
634
657
|
const resizableColumns = ((_f = (_e = context === null || context === void 0 ? void 0 : context.options) === null || _e === void 0 ? void 0 : _e.spreadsheet) === null || _f === void 0 ? void 0 : _f.resizableColumns) === true;
|
|
@@ -648,6 +671,73 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
|
|
|
648
671
|
loadingWindowCount > 0;
|
|
649
672
|
const scalePx = (value) => Math.max(1, Math.round(value * zoom));
|
|
650
673
|
const scaleRowHeight = (value) => Math.max(0.1, Math.round(value * zoom));
|
|
674
|
+
const closeImageLightbox = () => {
|
|
675
|
+
if (imageLightbox.dataset.open !== 'true') {
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
imageLightbox.dataset.open = 'false';
|
|
679
|
+
imageLightbox.setAttribute('aria-hidden', 'true');
|
|
680
|
+
delete imageLightbox.dataset.imageId;
|
|
681
|
+
if (imageLightboxPreviousFocus === null || imageLightboxPreviousFocus === void 0 ? void 0 : imageLightboxPreviousFocus.isConnected) {
|
|
682
|
+
imageLightboxPreviousFocus.focus({ preventScroll: true });
|
|
683
|
+
}
|
|
684
|
+
imageLightboxPreviousFocus = null;
|
|
685
|
+
};
|
|
686
|
+
const openImageLightbox = (image) => {
|
|
687
|
+
imageLightboxPreviousFocus = documentRef.activeElement instanceof HTMLElement
|
|
688
|
+
? documentRef.activeElement
|
|
689
|
+
: null;
|
|
690
|
+
lightboxImage.src = image.src;
|
|
691
|
+
imageLightbox.dataset.imageId = image.id;
|
|
692
|
+
imageLightbox.dataset.open = 'true';
|
|
693
|
+
imageLightbox.setAttribute('aria-hidden', 'false');
|
|
694
|
+
lightboxCloseButton.focus({ preventScroll: true });
|
|
695
|
+
};
|
|
696
|
+
const containsViewportPoint = (item, x, y) => {
|
|
697
|
+
const left = scalePx(item.left) - imageViewportState.scrollX;
|
|
698
|
+
const top = scalePx(item.top) - imageViewportState.scrollY;
|
|
699
|
+
const right = left + scalePx(item.width);
|
|
700
|
+
const bottom = top + scalePx(item.height);
|
|
701
|
+
return x >= left && x <= right && y >= top && y <= bottom;
|
|
702
|
+
};
|
|
703
|
+
const findImageAtViewportPoint = (clientX, clientY) => {
|
|
704
|
+
const viewportRect = imageViewport.getBoundingClientRect();
|
|
705
|
+
const x = clientX - viewportRect.left;
|
|
706
|
+
const y = clientY - viewportRect.top;
|
|
707
|
+
if (x < 0 || y < 0 || x > viewportRect.width || y > viewportRect.height) {
|
|
708
|
+
return undefined;
|
|
709
|
+
}
|
|
710
|
+
// Charts are appended after images and therefore paint above them. Do not
|
|
711
|
+
// open an image hidden under a chart when their saved bounds overlap.
|
|
712
|
+
if ([...sheetCharts].reverse().some(chart => containsViewportPoint(chart, x, y))) {
|
|
713
|
+
return undefined;
|
|
714
|
+
}
|
|
715
|
+
return [...sheetImages].reverse().find(image => containsViewportPoint(image, x, y));
|
|
716
|
+
};
|
|
717
|
+
const handleImageDoubleClick = (event) => {
|
|
718
|
+
const image = findImageAtViewportPoint(event.clientX, event.clientY);
|
|
719
|
+
if (!image) {
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
event.preventDefault();
|
|
723
|
+
event.stopPropagation();
|
|
724
|
+
openImageLightbox(image);
|
|
725
|
+
};
|
|
726
|
+
const handleImageLightboxClick = (event) => {
|
|
727
|
+
if (event.target === imageLightbox) {
|
|
728
|
+
closeImageLightbox();
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
const handleImageLightboxKeyDown = (event) => {
|
|
732
|
+
if (event.key === 'Escape' && imageLightbox.dataset.open === 'true') {
|
|
733
|
+
event.preventDefault();
|
|
734
|
+
closeImageLightbox();
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
tableHostShell.addEventListener('dblclick', handleImageDoubleClick, true);
|
|
738
|
+
imageLightbox.addEventListener('click', handleImageLightboxClick);
|
|
739
|
+
lightboxCloseButton.addEventListener('click', closeImageLightbox);
|
|
740
|
+
documentRef.addEventListener('keydown', handleImageLightboxKeyDown);
|
|
651
741
|
const getSheetLoadingText = () => {
|
|
652
742
|
var _a;
|
|
653
743
|
if (!sheets.length) {
|
|
@@ -1615,6 +1705,11 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
|
|
|
1615
1705
|
unmount() {
|
|
1616
1706
|
var _a, _b;
|
|
1617
1707
|
disposed = true;
|
|
1708
|
+
closeImageLightbox();
|
|
1709
|
+
tableHostShell.removeEventListener('dblclick', handleImageDoubleClick, true);
|
|
1710
|
+
imageLightbox.removeEventListener('click', handleImageLightboxClick);
|
|
1711
|
+
lightboxCloseButton.removeEventListener('click', closeImageLightbox);
|
|
1712
|
+
documentRef.removeEventListener('keydown', handleImageLightboxKeyDown);
|
|
1618
1713
|
if (resizeFrame) {
|
|
1619
1714
|
cancelAnimationFrame(resizeFrame);
|
|
1620
1715
|
}
|