@file-viewer/renderer-spreadsheet 2.2.9 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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(/&quot;/gi, '"')
146
+ .replace(/&apos;/gi, "'")
147
+ .replace(/&lt;/gi, '<')
148
+ .replace(/&gt;/gi, '>')
149
+ .replace(/&amp;/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: 'utf-8' | 'gb18030';
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 decodeBytes = (bytes, encoding) => {
28
- if (typeof TextDecoder === 'undefined') {
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;
@@ -7,6 +7,8 @@ type EVirtTableInstance = {
7
7
  };
8
8
  scrollX?: number;
9
9
  scrollY?: number;
10
+ containerElement: HTMLElement;
11
+ isTarget(event: Event): boolean;
10
12
  selector?: {
11
13
  xArr: number[];
12
14
  yArr: number[];
@@ -30,6 +32,7 @@ type EVirtTableConstructor = new (container: HTMLElement, options: {
30
32
  columns: unknown[];
31
33
  config: unknown;
32
34
  }) => EVirtTableInstance;
35
+ export declare const enableEVirtTableShadowEventTargeting: (context: Pick<EVirtTableInstance["ctx"], "containerElement" | "isTarget">) => void;
33
36
  export declare const resolveEVirtTableConstructor: (module: unknown) => EVirtTableConstructor;
34
37
  export declare const resolveEVirtTableStyleText: (documentRef: Document) => string;
35
38
  export declare const scopeEVirtTableStyleText: (cssText: string, shadow: boolean) => string;
@@ -12,6 +12,16 @@ const E_VIRT_TABLE_STYLE_MARKERS = [
12
12
  ];
13
13
  const SPREADSHEET_STYLE_SCOPE = '.excel-wrapper[data-file-viewer-spreadsheet-root]';
14
14
  const E_VIRT_TABLE_ROTATE_KEYFRAME = 'file-viewer-e-virt-table-rotate';
15
+ export const enableEVirtTableShadowEventTargeting = (context) => {
16
+ const isNativeTarget = context.isTarget.bind(context);
17
+ context.isTarget = (event) => {
18
+ if (isNativeTarget(event)) {
19
+ return true;
20
+ }
21
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
22
+ return path.includes(context.containerElement);
23
+ };
24
+ };
15
25
  const spreadsheetStyle = `
16
26
  .excel-wrapper{position:relative;width:100%;height:100%;display:flex;flex-direction:column;background:var(--file-viewer-render-surface-background,#fff);color:#172033;font-family:Aptos,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif}
17
27
  .excel-wrapper *{box-sizing:border-box}
@@ -29,6 +39,13 @@ const spreadsheetStyle = `
29
39
  .excel-wrapper .excel-image{position:absolute;display:block;max-width:none;height:auto;object-fit:contain;user-select:none}
30
40
  .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
41
  .excel-wrapper .excel-chart svg{display:block;width:100%;height:100%;overflow:visible}
42
+ .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}
43
+ .excel-wrapper .excel-image-lightbox[data-open='true']{opacity:1;visibility:visible;pointer-events:auto;transition-delay:0s}
44
+ .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}
45
+ .excel-wrapper .excel-image-lightbox[data-open='true'] img{transform:scale(1)}
46
+ .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}
47
+ .excel-wrapper .excel-image-lightbox button:hover{background:#fff;transform:scale(1.04)}
48
+ .excel-wrapper .excel-image-lightbox button:focus-visible{outline:3px solid #60a5fa;outline-offset:2px}
32
49
  .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
50
  .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
51
  .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 +76,8 @@ const spreadsheetStyle = `
59
76
  .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
77
  @keyframes file-viewer-spreadsheet-loading-spin{to{transform:rotate(360deg)}}
61
78
  @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}}
79
+ @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}}
80
+ @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
81
  `;
64
82
  const scopedSpreadsheetStyle = spreadsheetStyle.replace(/\.excel-wrapper/g, SPREADSHEET_STYLE_SCOPE);
65
83
  const isEVirtTableConstructor = (value) => {
@@ -584,6 +602,20 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
584
602
  imageViewport.appendChild(imageLayer);
585
603
  tableHostShell.append(tableHost, imageViewport);
586
604
  tableWrapper.append(sheetLoading, tableHostShell);
605
+ const imageLightbox = documentRef.createElement('div');
606
+ imageLightbox.className = 'excel-image-lightbox';
607
+ imageLightbox.dataset.open = 'false';
608
+ imageLightbox.setAttribute('role', 'dialog');
609
+ imageLightbox.setAttribute('aria-modal', 'true');
610
+ imageLightbox.setAttribute('aria-hidden', 'true');
611
+ const lightboxImage = documentRef.createElement('img');
612
+ lightboxImage.alt = t('image.lightbox.alt');
613
+ lightboxImage.draggable = false;
614
+ const lightboxCloseButton = documentRef.createElement('button');
615
+ lightboxCloseButton.type = 'button';
616
+ lightboxCloseButton.setAttribute('aria-label', t('image.lightbox.close'));
617
+ lightboxCloseButton.textContent = '×';
618
+ imageLightbox.append(lightboxImage, lightboxCloseButton);
587
619
  const toolbar = documentRef.createElement('div');
588
620
  toolbar.className = 'toolbar';
589
621
  const sheetTabsBar = documentRef.createElement('div');
@@ -592,7 +624,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
592
624
  const summary = documentRef.createElement('div');
593
625
  summary.className = 'summary';
594
626
  toolbar.append(sheetTabsBar, summary);
595
- root.append(loading, error, tableWrapper, toolbar);
627
+ root.append(loading, error, tableWrapper, toolbar, imageLightbox);
596
628
  target.replaceChildren(createEVirtTableStyle(documentRef, target, loadedEVirtTable.styleText), createStyle(documentRef), root);
597
629
  let sheets = [];
598
630
  let sheetIndex = 0;
@@ -629,6 +661,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
629
661
  let lastScrollY = 0;
630
662
  let sheetSessionId = 0;
631
663
  let disposed = false;
664
+ let imageLightboxPreviousFocus = null;
632
665
  let hasNotifiedFirstPaint = false;
633
666
  let hasAppliedDefaultInitialFit = false;
634
667
  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 +681,73 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
648
681
  loadingWindowCount > 0;
649
682
  const scalePx = (value) => Math.max(1, Math.round(value * zoom));
650
683
  const scaleRowHeight = (value) => Math.max(0.1, Math.round(value * zoom));
684
+ const closeImageLightbox = () => {
685
+ if (imageLightbox.dataset.open !== 'true') {
686
+ return;
687
+ }
688
+ imageLightbox.dataset.open = 'false';
689
+ imageLightbox.setAttribute('aria-hidden', 'true');
690
+ delete imageLightbox.dataset.imageId;
691
+ if (imageLightboxPreviousFocus === null || imageLightboxPreviousFocus === void 0 ? void 0 : imageLightboxPreviousFocus.isConnected) {
692
+ imageLightboxPreviousFocus.focus({ preventScroll: true });
693
+ }
694
+ imageLightboxPreviousFocus = null;
695
+ };
696
+ const openImageLightbox = (image) => {
697
+ imageLightboxPreviousFocus = documentRef.activeElement instanceof HTMLElement
698
+ ? documentRef.activeElement
699
+ : null;
700
+ lightboxImage.src = image.src;
701
+ imageLightbox.dataset.imageId = image.id;
702
+ imageLightbox.dataset.open = 'true';
703
+ imageLightbox.setAttribute('aria-hidden', 'false');
704
+ lightboxCloseButton.focus({ preventScroll: true });
705
+ };
706
+ const containsViewportPoint = (item, x, y) => {
707
+ const left = scalePx(item.left) - imageViewportState.scrollX;
708
+ const top = scalePx(item.top) - imageViewportState.scrollY;
709
+ const right = left + scalePx(item.width);
710
+ const bottom = top + scalePx(item.height);
711
+ return x >= left && x <= right && y >= top && y <= bottom;
712
+ };
713
+ const findImageAtViewportPoint = (clientX, clientY) => {
714
+ const viewportRect = imageViewport.getBoundingClientRect();
715
+ const x = clientX - viewportRect.left;
716
+ const y = clientY - viewportRect.top;
717
+ if (x < 0 || y < 0 || x > viewportRect.width || y > viewportRect.height) {
718
+ return undefined;
719
+ }
720
+ // Charts are appended after images and therefore paint above them. Do not
721
+ // open an image hidden under a chart when their saved bounds overlap.
722
+ if ([...sheetCharts].reverse().some(chart => containsViewportPoint(chart, x, y))) {
723
+ return undefined;
724
+ }
725
+ return [...sheetImages].reverse().find(image => containsViewportPoint(image, x, y));
726
+ };
727
+ const handleImageDoubleClick = (event) => {
728
+ const image = findImageAtViewportPoint(event.clientX, event.clientY);
729
+ if (!image) {
730
+ return;
731
+ }
732
+ event.preventDefault();
733
+ event.stopPropagation();
734
+ openImageLightbox(image);
735
+ };
736
+ const handleImageLightboxClick = (event) => {
737
+ if (event.target === imageLightbox) {
738
+ closeImageLightbox();
739
+ }
740
+ };
741
+ const handleImageLightboxKeyDown = (event) => {
742
+ if (event.key === 'Escape' && imageLightbox.dataset.open === 'true') {
743
+ event.preventDefault();
744
+ closeImageLightbox();
745
+ }
746
+ };
747
+ tableHostShell.addEventListener('dblclick', handleImageDoubleClick, true);
748
+ imageLightbox.addEventListener('click', handleImageLightboxClick);
749
+ lightboxCloseButton.addEventListener('click', closeImageLightbox);
750
+ documentRef.addEventListener('keydown', handleImageLightboxKeyDown);
651
751
  const getSheetLoadingText = () => {
652
752
  var _a;
653
753
  if (!sheets.length) {
@@ -1051,6 +1151,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1051
1151
  zoomScale: zoom,
1052
1152
  }),
1053
1153
  });
1154
+ enableEVirtTableShadowEventTargeting(table.ctx);
1054
1155
  table.on('onScrollX', scheduleViewportLoad);
1055
1156
  table.on('onScrollY', scheduleViewportLoad);
1056
1157
  table.on('resize', scheduleViewportLoad);
@@ -1615,6 +1716,11 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1615
1716
  unmount() {
1616
1717
  var _a, _b;
1617
1718
  disposed = true;
1719
+ closeImageLightbox();
1720
+ tableHostShell.removeEventListener('dblclick', handleImageDoubleClick, true);
1721
+ imageLightbox.removeEventListener('click', handleImageLightboxClick);
1722
+ lightboxCloseButton.removeEventListener('click', closeImageLightbox);
1723
+ documentRef.removeEventListener('keydown', handleImageLightboxKeyDown);
1618
1724
  if (resizeFrame) {
1619
1725
  cancelAnimationFrame(resizeFrame);
1620
1726
  }