@file-viewer/core 2.0.11 → 2.1.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.
Files changed (116) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/dist/config/options.d.ts +1 -1
  4. package/dist/config/options.js +1 -1
  5. package/dist/contracts/types.d.ts +76 -1
  6. package/dist/headless.d.ts +3 -3
  7. package/dist/headless.js +2 -2
  8. package/dist/index.d.ts +10 -7
  9. package/dist/index.js +106 -49
  10. package/dist/lifecycle/operations.d.ts +1 -0
  11. package/dist/lifecycle/operations.js +65 -6
  12. package/dist/platform/assets.d.ts +3 -1
  13. package/dist/platform/assets.js +43 -6
  14. package/dist/registry/capabilities.d.ts +2 -2
  15. package/dist/registry/capabilities.js +2 -1
  16. package/dist/registry/formats.d.ts +20 -7
  17. package/dist/registry/formats.js +14 -5
  18. package/dist/registry/registry.d.ts +8 -1
  19. package/dist/registry/registry.js +29 -0
  20. package/dist/renderers/image.js +1 -10
  21. package/dist/renderers/index.d.ts +320 -2
  22. package/dist/renderers/index.js +27 -157
  23. package/dist/viewer/createViewer.js +86 -3
  24. package/package.json +17 -44
  25. package/dist/renderers/archive.d.ts +0 -2
  26. package/dist/renderers/archive.js +0 -547
  27. package/dist/renderers/archiveCache.d.ts +0 -10
  28. package/dist/renderers/archiveCache.js +0 -96
  29. package/dist/renderers/archiveFallback.d.ts +0 -7
  30. package/dist/renderers/archiveFallback.js +0 -166
  31. package/dist/renderers/archiveShared.d.ts +0 -23
  32. package/dist/renderers/archiveShared.js +0 -71
  33. package/dist/renderers/audio.d.ts +0 -8
  34. package/dist/renderers/audio.js +0 -219
  35. package/dist/renderers/cad.d.ts +0 -2
  36. package/dist/renderers/cad.js +0 -446
  37. package/dist/renderers/code.d.ts +0 -11
  38. package/dist/renderers/code.js +0 -233
  39. package/dist/renderers/data.d.ts +0 -7
  40. package/dist/renderers/data.js +0 -370
  41. package/dist/renderers/drawing.d.ts +0 -10
  42. package/dist/renderers/drawing.js +0 -882
  43. package/dist/renderers/eda.d.ts +0 -2
  44. package/dist/renderers/eda.js +0 -434
  45. package/dist/renderers/edaParser.d.ts +0 -77
  46. package/dist/renderers/edaParser.js +0 -569
  47. package/dist/renderers/email.d.ts +0 -2
  48. package/dist/renderers/email.js +0 -463
  49. package/dist/renderers/epub.d.ts +0 -2
  50. package/dist/renderers/epub.js +0 -331
  51. package/dist/renderers/geo.d.ts +0 -2
  52. package/dist/renderers/geo.js +0 -284
  53. package/dist/renderers/markdown.d.ts +0 -2
  54. package/dist/renderers/markdown.js +0 -83
  55. package/dist/renderers/model.d.ts +0 -2
  56. package/dist/renderers/model.js +0 -567
  57. package/dist/renderers/ofd.d.ts +0 -2
  58. package/dist/renderers/ofd.js +0 -256
  59. package/dist/renderers/openDocument.d.ts +0 -2
  60. package/dist/renderers/openDocument.js +0 -122
  61. package/dist/renderers/pdf.d.ts +0 -3
  62. package/dist/renderers/pdf.js +0 -1001
  63. package/dist/renderers/pdfStyles.d.ts +0 -1
  64. package/dist/renderers/pdfStyles.js +0 -1
  65. package/dist/renderers/pptx.d.ts +0 -2
  66. package/dist/renderers/pptx.js +0 -217
  67. package/dist/renderers/spreadsheet/state.d.ts +0 -80
  68. package/dist/renderers/spreadsheet/state.js +0 -96
  69. package/dist/renderers/spreadsheet/view.d.ts +0 -25
  70. package/dist/renderers/spreadsheet/view.js +0 -833
  71. package/dist/renderers/spreadsheet/worker/index.d.ts +0 -2
  72. package/dist/renderers/spreadsheet/worker/index.js +0 -1
  73. package/dist/renderers/spreadsheet/worker/sheetjs/SheetJsModel.d.ts +0 -73
  74. package/dist/renderers/spreadsheet/worker/sheetjs/SheetJsModel.js +0 -623
  75. package/dist/renderers/spreadsheet/worker/sheetjs/color.d.ts +0 -2
  76. package/dist/renderers/spreadsheet/worker/sheetjs/color.js +0 -73
  77. package/dist/renderers/spreadsheet/worker/sheetjs/index.d.ts +0 -1
  78. package/dist/renderers/spreadsheet/worker/sheetjs/index.js +0 -1
  79. package/dist/renderers/spreadsheet/worker/sheetjs/parser.d.ts +0 -18
  80. package/dist/renderers/spreadsheet/worker/sheetjs/parser.js +0 -106
  81. package/dist/renderers/spreadsheet/worker/sheetjs/sheet.worker.d.ts +0 -1
  82. package/dist/renderers/spreadsheet/worker/sheetjs/sheet.worker.js +0 -11
  83. package/dist/renderers/spreadsheet/worker/type.d.ts +0 -57
  84. package/dist/renderers/spreadsheet/worker/type.js +0 -1
  85. package/dist/renderers/spreadsheet.d.ts +0 -3
  86. package/dist/renderers/spreadsheet.js +0 -929
  87. package/dist/renderers/typst.d.ts +0 -8
  88. package/dist/renderers/typst.js +0 -547
  89. package/dist/renderers/umd/parser.d.ts +0 -30
  90. package/dist/renderers/umd/parser.js +0 -408
  91. package/dist/renderers/umd.d.ts +0 -2
  92. package/dist/renderers/umd.js +0 -297
  93. package/dist/renderers/video.d.ts +0 -8
  94. package/dist/renderers/video.js +0 -108
  95. package/dist/renderers/wordDoc.d.ts +0 -5
  96. package/dist/renderers/wordDoc.js +0 -284
  97. package/dist/renderers/wordDocx.d.ts +0 -5
  98. package/dist/renderers/wordDocx.js +0 -985
  99. package/dist/renderers/wordDocx.worker.d.ts +0 -1
  100. package/dist/renderers/wordDocx.worker.js +0 -96
  101. package/vendor/ofd/dltech/jbig2/arithmetic_decoder.js +0 -183
  102. package/vendor/ofd/dltech/jbig2/ccitt.js +0 -1070
  103. package/vendor/ofd/dltech/jbig2/compatibility.js +0 -12
  104. package/vendor/ofd/dltech/jbig2/core_utils.js +0 -180
  105. package/vendor/ofd/dltech/jbig2/is_node.js +0 -27
  106. package/vendor/ofd/dltech/jbig2/jbig2.js +0 -2589
  107. package/vendor/ofd/dltech/jbig2/jbig2_stream.js +0 -81
  108. package/vendor/ofd/dltech/jbig2/primitives.js +0 -387
  109. package/vendor/ofd/dltech/jbig2/stream.js +0 -1348
  110. package/vendor/ofd/dltech/jbig2/util.js +0 -972
  111. package/vendor/ofd/dltech/ofd/ofd.d.ts +0 -11
  112. package/vendor/ofd/dltech/ofd/ofd.js +0 -100
  113. package/vendor/ofd/dltech/ofd/ofd_parser.js +0 -395
  114. package/vendor/ofd/dltech/ofd/ofd_render.js +0 -473
  115. package/vendor/ofd/dltech/ofd/ofd_util.js +0 -350
  116. package/vendor/ofd/dltech/ofd/pipeline.js +0 -26
@@ -1,985 +0,0 @@
1
- import { resolveFileViewerDocxWorkerJsZipUrl, resolveFileViewerDocxWorkerUrl, } from '../platform/assets.js';
2
- import { applyPrintPageSize, buildPrintPageStyle, formatCssPixels, getElementPrintPageSize } from '../output/printLayout.js';
3
- import { createFileViewerZoomChangeEmitter as createZoomChangeEmitter, } from '../features/document/zoom.js';
4
- import { registerFileViewerZoomProvider, unregisterFileViewerZoomProvider } from '../features/document/dom/index.js';
5
- const DOCX_DEFAULT_PAGE_SIZE = {
6
- width: 794,
7
- height: 1123
8
- };
9
- const DOCX_PROGRESSIVE_BATCH_SIZE = 2;
10
- const DOCX_WORKER_TIMEOUT = 120000;
11
- const DOCX_MIN_SCALE = 0.24;
12
- const DOCX_MAX_SCALE = 3;
13
- const DOCX_ZOOM_STEP = 0.15;
14
- const DOCX_EMU_PER_CSS_PIXEL = 9525;
15
- const ZIP_SIGNATURE_PK = 0x504b;
16
- const loadLibrary = (() => {
17
- const loader = {
18
- module: null,
19
- async load() {
20
- if (!this.module) {
21
- this.module = import('@file-viewer/docx');
22
- }
23
- return this.module;
24
- }
25
- };
26
- return async () => {
27
- return await loader.load();
28
- };
29
- })();
30
- /**
31
- * DOCX / DOCM / DOTX / DOTM are OOXML packages, so a valid file must start
32
- * with a ZIP signature. This catches common enterprise download failures where
33
- * an object-storage XML error page is saved with a `.docx` extension.
34
- */
35
- const assertValidDocxPackage = (buffer) => {
36
- const signature = buffer.byteLength >= 4 ? new DataView(buffer).getUint16(0, false) : 0;
37
- if (signature === ZIP_SIGNATURE_PK) {
38
- return;
39
- }
40
- throw new Error('文件不是有效的 DOCX/OOXML 压缩包,可能下载不完整或被服务端错误内容替换,请重新上传或检查文件源。');
41
- };
42
- const createDocxOptions = (target, context, notifyProgressiveRender) => {
43
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
44
- const docxOptions = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.docx;
45
- const documentBaseUrl = target.ownerDocument.URL || undefined;
46
- const useWorker = (docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.worker) !== false;
47
- const usePagedLayout = (docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.visualPagination) === true;
48
- const progress = (event) => {
49
- if (event.phase === 'render' || event.phase === 'layout' || event.phase === 'done') {
50
- notifyProgressiveRender();
51
- }
52
- };
53
- return {
54
- // Word 会写入 autoSpaceDN/autoSpaceDE 等兼容标签;生产预览保持静默,避免 DOCX 调试告警刷屏。
55
- debug: false,
56
- experimental: false,
57
- useWorker,
58
- workerUrl: useWorker
59
- ? resolveFileViewerDocxWorkerUrl(docxOptions, documentBaseUrl)
60
- : undefined,
61
- workerJsZipUrl: useWorker
62
- ? resolveFileViewerDocxWorkerJsZipUrl(docxOptions, documentBaseUrl)
63
- : undefined,
64
- workerFallback: true,
65
- workerTimeout: (_b = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.workerTimeout) !== null && _b !== void 0 ? _b : DOCX_WORKER_TIMEOUT,
66
- renderPageBatchSize: (_c = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.renderPageBatchSize) !== null && _c !== void 0 ? _c : ((docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.progressive) === false ? Number.MAX_SAFE_INTEGER : DOCX_PROGRESSIVE_BATCH_SIZE),
67
- renderYieldEveryMs: (_d = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.renderYieldEveryMs) !== null && _d !== void 0 ? _d : 16,
68
- strictWordCompatibility: (_e = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.strictWordCompatibility) !== null && _e !== void 0 ? _e : true,
69
- paginationTolerance: (_f = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.paginationTolerance) !== null && _f !== void 0 ? _f : 2,
70
- breakPages: usePagedLayout,
71
- maxDynamicPaginationPasses: usePagedLayout
72
- ? (_g = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.maxDynamicPaginationPasses) !== null && _g !== void 0 ? _g : 1000
73
- : 0,
74
- awaitLayout: (_h = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.awaitLayout) !== null && _h !== void 0 ? _h : usePagedLayout,
75
- preserveComplexFieldResults: (_j = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.preserveComplexFieldResults) !== null && _j !== void 0 ? _j : true,
76
- updatePageReferences: (_k = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.updatePageReferences) !== null && _k !== void 0 ? _k : false,
77
- hideWebHiddenContent: (_l = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.hideWebHiddenContent) !== null && _l !== void 0 ? _l : false,
78
- ignoreLastRenderedPageBreak: (_m = docxOptions === null || docxOptions === void 0 ? void 0 : docxOptions.ignoreLastRenderedPageBreak) !== null && _m !== void 0 ? _m : !usePagedLayout,
79
- progress
80
- };
81
- };
82
- const getTargetWindow = (target) => {
83
- return target.ownerDocument.defaultView;
84
- };
85
- const isTargetHTMLElement = (value, target) => {
86
- var _a;
87
- const HTMLElementCtor = (_a = getTargetWindow(target)) === null || _a === void 0 ? void 0 : _a.HTMLElement;
88
- return HTMLElementCtor ? value instanceof HTMLElementCtor : value instanceof HTMLElement;
89
- };
90
- const shouldPaginateOversizedDocxSections = (context) => {
91
- var _a, _b;
92
- return ((_b = (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.docx) === null || _b === void 0 ? void 0 : _b.visualPagination) === true;
93
- };
94
- const DOCX_RESPONSIVE_CSS = `
95
- .docx-fit-viewer {
96
- box-sizing: border-box;
97
- height: 100%;
98
- overflow: auto;
99
- background: #ececec;
100
- }
101
- .docx-fit-viewer .docx-wrapper {
102
- box-sizing: border-box;
103
- min-width: 0 !important;
104
- width: 100% !important;
105
- padding: 24px 14px 40px !important;
106
- background: #e7e9ec !important;
107
- }
108
- .docx-fit-viewer .docx-page-frame {
109
- position: relative;
110
- width: 100%;
111
- min-width: 0;
112
- margin: 0 auto 24px;
113
- overflow: visible;
114
- }
115
- .docx-fit-viewer .docx-flow-frame {
116
- position: relative;
117
- width: 100%;
118
- min-width: 0;
119
- margin: 0 auto 28px;
120
- overflow: visible;
121
- }
122
- .docx-fit-viewer .docx-page-frame > section.docx,
123
- .docx-fit-viewer .docx-flow-frame > section.docx {
124
- position: absolute;
125
- top: 0;
126
- left: 50%;
127
- margin: 0 !important;
128
- background: #ffffff !important;
129
- box-shadow: 0 2px 14px rgba(25, 35, 48, 0.18);
130
- box-sizing: border-box;
131
- color: #111827;
132
- overflow: hidden;
133
- transform-origin: top center;
134
- }
135
- .docx-fit-viewer .docx-flow-frame > section.docx {
136
- height: auto !important;
137
- min-height: 0 !important;
138
- overflow: visible !important;
139
- }
140
- .docx-fit-viewer .docx-page-frame > section.docx > article,
141
- .docx-fit-viewer .docx-flow-frame > section.docx > article {
142
- position: relative;
143
- z-index: 1;
144
- }
145
- .docx-fit-viewer .docx-vml-watermark {
146
- position: absolute;
147
- inset: 0;
148
- z-index: 0;
149
- width: 100%;
150
- height: 100%;
151
- object-fit: cover;
152
- opacity: 0.28;
153
- filter: saturate(0.72) brightness(1.24);
154
- pointer-events: none;
155
- user-select: none;
156
- }
157
- .docx-fit-viewer .docx-vml-fallback,
158
- .docx-fit-viewer .docx-chart-fallback {
159
- display: block;
160
- max-width: 100%;
161
- margin: 12px auto;
162
- break-inside: avoid;
163
- page-break-inside: avoid;
164
- }
165
- .docx-fit-viewer .docx-vml-fallback {
166
- text-align: center;
167
- }
168
- .docx-fit-viewer .docx-vml-fallback img {
169
- display: block;
170
- max-width: 100%;
171
- height: auto;
172
- margin: 0 auto;
173
- }
174
- .docx-fit-viewer .docx-chart-fallback {
175
- box-sizing: border-box;
176
- overflow: hidden;
177
- border: 1px solid #d7dee8;
178
- border-radius: 8px;
179
- background: #ffffff;
180
- box-shadow: 0 1px 6px rgba(15, 23, 42, 0.08);
181
- }
182
- .docx-fit-viewer .docx-chart-fallback svg {
183
- display: block;
184
- width: 100%;
185
- height: auto;
186
- }
187
- `;
188
- function getXmlLocalName(node) {
189
- return node.localName || node.tagName.split(':').pop() || node.tagName;
190
- }
191
- function getXmlElements(root, localName) {
192
- return Array.from(root.querySelectorAll('*')).filter(element => getXmlLocalName(element) === localName);
193
- }
194
- function getFirstXmlElement(root, localName) {
195
- return getXmlElements(root, localName)[0];
196
- }
197
- function getXmlAttribute(element, name, namespace) {
198
- return (namespace ? element.getAttributeNS(namespace, name) : null)
199
- || element.getAttribute(name)
200
- || element.getAttribute(`r:${name}`);
201
- }
202
- function getXmlText(element) {
203
- if (!element) {
204
- return '';
205
- }
206
- return (element.textContent || '').replace(/\s+/g, ' ').trim();
207
- }
208
- function getXmlAncestor(element, localName) {
209
- let current = (element === null || element === void 0 ? void 0 : element.parentElement) || null;
210
- while (current) {
211
- if (getXmlLocalName(current) === localName) {
212
- return current;
213
- }
214
- current = current.parentElement;
215
- }
216
- return null;
217
- }
218
- function getParagraphIndex(element) {
219
- const paragraph = getXmlLocalName(element) === 'p' ? element : getXmlAncestor(element, 'p');
220
- if (!paragraph) {
221
- return undefined;
222
- }
223
- let index = 0;
224
- let sibling = paragraph.previousElementSibling;
225
- while (sibling) {
226
- if (getXmlLocalName(sibling) === 'p') {
227
- index += 1;
228
- }
229
- sibling = sibling.previousElementSibling;
230
- }
231
- return index;
232
- }
233
- function parseXml(xml, target) {
234
- var _a;
235
- const Parser = ((_a = getTargetWindow(target)) === null || _a === void 0 ? void 0 : _a.DOMParser) || globalThis.DOMParser;
236
- if (!Parser) {
237
- return null;
238
- }
239
- const doc = new Parser().parseFromString(xml, 'application/xml');
240
- if (doc.querySelector('parsererror')) {
241
- return null;
242
- }
243
- return doc;
244
- }
245
- function normalizeZipPath(path) {
246
- const segments = [];
247
- path.split('/').forEach(segment => {
248
- if (!segment || segment === '.') {
249
- return;
250
- }
251
- if (segment === '..') {
252
- segments.pop();
253
- return;
254
- }
255
- segments.push(segment);
256
- });
257
- return segments.join('/');
258
- }
259
- function getDirectoryName(path) {
260
- const index = path.lastIndexOf('/');
261
- return index >= 0 ? path.slice(0, index) : '';
262
- }
263
- function getRelationshipPath(partPath) {
264
- const directory = getDirectoryName(partPath);
265
- const name = partPath.slice(directory ? directory.length + 1 : 0);
266
- return normalizeZipPath(`${directory}/_rels/${name}.rels`);
267
- }
268
- function resolveRelationshipTarget(partPath, target) {
269
- if (target.startsWith('/')) {
270
- return normalizeZipPath(target.slice(1));
271
- }
272
- return normalizeZipPath(`${getDirectoryName(partPath)}/${target}`);
273
- }
274
- function getMimeType(path) {
275
- var _a;
276
- const extension = (_a = path.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase();
277
- switch (extension) {
278
- case 'png':
279
- return 'image/png';
280
- case 'jpg':
281
- case 'jpeg':
282
- return 'image/jpeg';
283
- case 'gif':
284
- return 'image/gif';
285
- case 'bmp':
286
- return 'image/bmp';
287
- case 'webp':
288
- return 'image/webp';
289
- case 'svg':
290
- return 'image/svg+xml';
291
- default:
292
- return 'application/octet-stream';
293
- }
294
- }
295
- function parseCssLengthToPixels(value) {
296
- if (!value) {
297
- return undefined;
298
- }
299
- const match = value.trim().match(/^(-?\d+(?:\.\d+)?)(px|pt|in|cm|mm)?$/i);
300
- if (!match) {
301
- return undefined;
302
- }
303
- const amount = Number(match[1]);
304
- if (!Number.isFinite(amount) || amount <= 0) {
305
- return undefined;
306
- }
307
- const unit = (match[2] || 'px').toLowerCase();
308
- switch (unit) {
309
- case 'pt':
310
- return amount * 96 / 72;
311
- case 'in':
312
- return amount * 96;
313
- case 'cm':
314
- return amount * 96 / 2.54;
315
- case 'mm':
316
- return amount * 96 / 25.4;
317
- default:
318
- return amount;
319
- }
320
- }
321
- function parseStyleDeclaration(style) {
322
- const declarations = new Map();
323
- if (!style) {
324
- return declarations;
325
- }
326
- style.split(';').forEach(declaration => {
327
- const separator = declaration.indexOf(':');
328
- if (separator <= 0) {
329
- return;
330
- }
331
- declarations.set(declaration.slice(0, separator).trim().toLowerCase(), declaration.slice(separator + 1).trim());
332
- });
333
- return declarations;
334
- }
335
- function parseShapeSize(style) {
336
- const declarations = parseStyleDeclaration(style);
337
- return {
338
- width: parseCssLengthToPixels(declarations.get('width')),
339
- height: parseCssLengthToPixels(declarations.get('height'))
340
- };
341
- }
342
- function getExtentSize(element) {
343
- const inline = getXmlAncestor(element, 'inline') || getXmlAncestor(element, 'anchor');
344
- const extent = inline ? getFirstXmlElement(inline, 'extent') : undefined;
345
- const width = Number(extent === null || extent === void 0 ? void 0 : extent.getAttribute('cx'));
346
- const height = Number(extent === null || extent === void 0 ? void 0 : extent.getAttribute('cy'));
347
- return {
348
- width: Number.isFinite(width) && width > 0 ? width / DOCX_EMU_PER_CSS_PIXEL : undefined,
349
- height: Number.isFinite(height) && height > 0 ? height / DOCX_EMU_PER_CSS_PIXEL : undefined
350
- };
351
- }
352
- async function readDocxRelationships(zip, partPath, target) {
353
- const relFile = zip.file(getRelationshipPath(partPath));
354
- const relationships = new Map();
355
- if (!relFile) {
356
- return relationships;
357
- }
358
- const relDoc = parseXml(await relFile.async('text'), target);
359
- if (!relDoc) {
360
- return relationships;
361
- }
362
- getXmlElements(relDoc, 'Relationship').forEach(element => {
363
- const id = element.getAttribute('Id');
364
- const relationshipTarget = element.getAttribute('Target');
365
- if (!id || !relationshipTarget) {
366
- return;
367
- }
368
- relationships.set(id, {
369
- id,
370
- type: element.getAttribute('Type') || '',
371
- target: relationshipTarget,
372
- targetMode: element.getAttribute('TargetMode') || undefined
373
- });
374
- });
375
- return relationships;
376
- }
377
- async function getDataUrlFromZip(zip, sourcePath) {
378
- const file = zip.file(sourcePath);
379
- if (!file) {
380
- return undefined;
381
- }
382
- const base64 = await file.async('base64');
383
- return `data:${getMimeType(sourcePath)};base64,${base64}`;
384
- }
385
- function getDocxPartPaths(zip) {
386
- return Object.keys(zip.files)
387
- .filter(path => path === 'word/document.xml'
388
- || /^word\/header\d+\.xml$/i.test(path)
389
- || /^word\/footer\d+\.xml$/i.test(path))
390
- .sort((left, right) => {
391
- if (left === 'word/document.xml') {
392
- return -1;
393
- }
394
- if (right === 'word/document.xml') {
395
- return 1;
396
- }
397
- return left.localeCompare(right);
398
- });
399
- }
400
- function inferVmlFallbackRole(partPath, shape, style) {
401
- const shapeId = `${(shape === null || shape === void 0 ? void 0 : shape.getAttribute('id')) || ''} ${(shape === null || shape === void 0 ? void 0 : shape.getAttribute('o:spid')) || ''}`.toLowerCase();
402
- const normalizedStyle = (style || '').toLowerCase();
403
- if (partPath.includes('/header')
404
- && (shapeId.includes('watermark') || normalizedStyle.includes('z-index:-') || normalizedStyle.includes('mso-position-horizontal:center'))) {
405
- return 'watermark';
406
- }
407
- if ((shape === null || shape === void 0 ? void 0 : shape.getAttribute('o:ole')) === 't' || (shape === null || shape === void 0 ? void 0 : shape.getAttribute('ole')) === 't') {
408
- return 'ole-preview';
409
- }
410
- return 'vml-image';
411
- }
412
- async function collectDocxVmlFallbacks(zip, target) {
413
- var _a;
414
- const fallbacks = [];
415
- const seen = new Set();
416
- for (const partPath of getDocxPartPaths(zip)) {
417
- const partFile = zip.file(partPath);
418
- if (!partFile) {
419
- continue;
420
- }
421
- const doc = parseXml(await partFile.async('text'), target);
422
- if (!doc) {
423
- continue;
424
- }
425
- const relationships = await readDocxRelationships(zip, partPath, target);
426
- for (const imagedata of getXmlElements(doc, 'imagedata')) {
427
- const relationshipId = getXmlAttribute(imagedata, 'id', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
428
- const relationship = relationshipId ? relationships.get(relationshipId) : undefined;
429
- if (!relationship || relationship.targetMode === 'External' || !relationship.type.includes('/image')) {
430
- continue;
431
- }
432
- const sourcePath = resolveRelationshipTarget(partPath, relationship.target);
433
- const dataUrl = await getDataUrlFromZip(zip, sourcePath);
434
- if (!dataUrl) {
435
- continue;
436
- }
437
- const shape = getXmlAncestor(imagedata, 'shape');
438
- const style = (shape === null || shape === void 0 ? void 0 : shape.getAttribute('style')) || undefined;
439
- const role = inferVmlFallbackRole(partPath, shape, style);
440
- const key = role === 'watermark'
441
- ? `${role}:${sourcePath}`
442
- : `${role}:${partPath}:${sourcePath}:${(_a = getParagraphIndex(imagedata)) !== null && _a !== void 0 ? _a : 'end'}`;
443
- if (seen.has(key)) {
444
- continue;
445
- }
446
- seen.add(key);
447
- fallbacks.push({
448
- role,
449
- key,
450
- dataUrl,
451
- sourcePath,
452
- partPath,
453
- title: imagedata.getAttribute('o:title') || imagedata.getAttribute('title') || undefined,
454
- style,
455
- ...parseShapeSize(style),
456
- paragraphIndex: partPath === 'word/document.xml' ? getParagraphIndex(imagedata) : undefined
457
- });
458
- }
459
- }
460
- return fallbacks;
461
- }
462
- function parseCacheValues(element) {
463
- if (!element) {
464
- return [];
465
- }
466
- return getXmlElements(element, 'pt')
467
- .sort((left, right) => Number(left.getAttribute('idx') || 0) - Number(right.getAttribute('idx') || 0))
468
- .map(point => getXmlText(getFirstXmlElement(point, 'v')))
469
- .filter(Boolean);
470
- }
471
- function parseChartSeries(series) {
472
- const name = parseCacheValues(getFirstXmlElement(getFirstXmlElement(series, 'tx') || series, 'strCache'))[0]
473
- || parseCacheValues(getFirstXmlElement(getFirstXmlElement(series, 'tx') || series, 'numCache'))[0]
474
- || 'Series';
475
- const categories = parseCacheValues(getFirstXmlElement(getFirstXmlElement(series, 'cat') || series, 'strCache'));
476
- const numericCategories = parseCacheValues(getFirstXmlElement(getFirstXmlElement(series, 'cat') || series, 'numCache'));
477
- const values = parseCacheValues(getFirstXmlElement(getFirstXmlElement(series, 'val') || series, 'numCache'))
478
- .map(value => Number(value))
479
- .filter(value => Number.isFinite(value));
480
- return {
481
- name,
482
- categories: categories.length ? categories : numericCategories,
483
- values
484
- };
485
- }
486
- function parseChartFallback(chartDoc, sourcePath, chartElement, paragraphIndex) {
487
- const chartTypeElement = ['lineChart', 'barChart', 'pieChart', 'areaChart', 'scatterChart']
488
- .map(type => getXmlElements(chartDoc, type)[0])
489
- .find(Boolean);
490
- const chartType = chartTypeElement ? getXmlLocalName(chartTypeElement) : 'chart';
491
- const title = getXmlText(getFirstXmlElement(getFirstXmlElement(chartDoc, 'title') || chartDoc, 't'))
492
- || sourcePath.split('/').pop() || 'Chart';
493
- const series = (chartTypeElement ? getXmlElements(chartTypeElement, 'ser') : getXmlElements(chartDoc, 'ser'))
494
- .map(parseChartSeries)
495
- .filter(item => item.values.length);
496
- const { width, height } = getExtentSize(chartElement);
497
- if (!series.length) {
498
- return undefined;
499
- }
500
- return {
501
- key: `chart:${sourcePath}:${paragraphIndex !== null && paragraphIndex !== void 0 ? paragraphIndex : 'end'}`,
502
- title,
503
- type: chartType,
504
- sourcePath,
505
- series,
506
- width,
507
- height,
508
- paragraphIndex
509
- };
510
- }
511
- async function collectDocxChartFallbacks(zip, target) {
512
- const partPath = 'word/document.xml';
513
- const documentFile = zip.file(partPath);
514
- if (!documentFile) {
515
- return [];
516
- }
517
- const documentDoc = parseXml(await documentFile.async('text'), target);
518
- if (!documentDoc) {
519
- return [];
520
- }
521
- const relationships = await readDocxRelationships(zip, partPath, target);
522
- const fallbacks = [];
523
- const seen = new Set();
524
- for (const chart of getXmlElements(documentDoc, 'chart')) {
525
- const relationshipId = getXmlAttribute(chart, 'id', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
526
- const relationship = relationshipId ? relationships.get(relationshipId) : undefined;
527
- if (!relationship || relationship.targetMode === 'External' || !relationship.type.includes('/chart')) {
528
- continue;
529
- }
530
- const sourcePath = resolveRelationshipTarget(partPath, relationship.target);
531
- const chartFile = zip.file(sourcePath);
532
- if (!chartFile) {
533
- continue;
534
- }
535
- const chartDoc = parseXml(await chartFile.async('text'), target);
536
- const paragraphIndex = getParagraphIndex(chart);
537
- const fallback = chartDoc ? parseChartFallback(chartDoc, sourcePath, chart, paragraphIndex) : undefined;
538
- if (!fallback || seen.has(fallback.key)) {
539
- continue;
540
- }
541
- seen.add(fallback.key);
542
- fallbacks.push(fallback);
543
- }
544
- return fallbacks;
545
- }
546
- function escapeHtml(value) {
547
- return value
548
- .replace(/&/g, '&amp;')
549
- .replace(/</g, '&lt;')
550
- .replace(/>/g, '&gt;')
551
- .replace(/"/g, '&quot;');
552
- }
553
- function buildChartSvg(chart) {
554
- var _a;
555
- const width = Math.max(360, Math.round(chart.width || 520));
556
- const height = Math.max(220, Math.round(chart.height || 320));
557
- const padding = { top: 52, right: 30, bottom: 56, left: 54 };
558
- const plotWidth = width - padding.left - padding.right;
559
- const plotHeight = height - padding.top - padding.bottom;
560
- const allValues = chart.series.flatMap(item => item.values);
561
- const maxValue = Math.max(...allValues, 1);
562
- const minValue = Math.min(...allValues, 0);
563
- const valueSpan = Math.max(maxValue - minValue, 1);
564
- const colors = ['#2563eb', '#10b981', '#f97316', '#8b5cf6', '#ef4444'];
565
- const maxPoints = Math.max(...chart.series.map(item => item.values.length), 1);
566
- const pointX = (index) => padding.left + (maxPoints === 1 ? plotWidth / 2 : index * plotWidth / (maxPoints - 1));
567
- const pointY = (value) => padding.top + plotHeight - ((value - minValue) / valueSpan) * plotHeight;
568
- const seriesPaths = chart.series.map((series, seriesIndex) => {
569
- const color = colors[seriesIndex % colors.length];
570
- const points = series.values.map((value, index) => `${pointX(index).toFixed(1)},${pointY(value).toFixed(1)}`).join(' ');
571
- const circles = series.values.map((value, index) => {
572
- const x = pointX(index).toFixed(1);
573
- const y = pointY(value).toFixed(1);
574
- return `<circle cx="${x}" cy="${y}" r="3.5" fill="${color}"><title>${escapeHtml(series.name)}: ${escapeHtml(String(value))}</title></circle>`;
575
- }).join('');
576
- return `<polyline points="${points}" fill="none" stroke="${color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>${circles}`;
577
- }).join('');
578
- const categories = ((_a = chart.series.find(item => item.categories.length)) === null || _a === void 0 ? void 0 : _a.categories) || [];
579
- const labels = categories.slice(0, maxPoints).map((label, index) => {
580
- const x = pointX(index);
581
- const shown = label.length > 14 ? `${label.slice(0, 13)}...` : label;
582
- return `<text x="${x.toFixed(1)}" y="${height - 22}" text-anchor="middle" fill="#64748b" font-size="11">${escapeHtml(shown)}</text>`;
583
- }).join('');
584
- const legend = chart.series.slice(0, 5).map((series, index) => {
585
- const x = padding.left + index * 98;
586
- const y = 30;
587
- const color = colors[index % colors.length];
588
- return `<g transform="translate(${x} ${y})"><rect width="10" height="10" rx="2" fill="${color}"/><text x="15" y="9" fill="#475569" font-size="11">${escapeHtml(series.name)}</text></g>`;
589
- }).join('');
590
- return `<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(chart.title)}">
591
- <rect x="0" y="0" width="${width}" height="${height}" rx="8" fill="#ffffff"/>
592
- <text x="${padding.left}" y="22" fill="#0f172a" font-size="15" font-weight="700">${escapeHtml(chart.title)}</text>
593
- ${legend}
594
- <line x1="${padding.left}" y1="${padding.top + plotHeight}" x2="${padding.left + plotWidth}" y2="${padding.top + plotHeight}" stroke="#cbd5e1"/>
595
- <line x1="${padding.left}" y1="${padding.top}" x2="${padding.left}" y2="${padding.top + plotHeight}" stroke="#cbd5e1"/>
596
- <text x="${padding.left - 8}" y="${padding.top + 4}" text-anchor="end" fill="#64748b" font-size="11">${escapeHtml(maxValue.toFixed(1))}</text>
597
- <text x="${padding.left - 8}" y="${padding.top + plotHeight}" text-anchor="end" fill="#64748b" font-size="11">${escapeHtml(minValue.toFixed(1))}</text>
598
- ${seriesPaths}
599
- ${labels}
600
- </svg>`;
601
- }
602
- function getDocxSections(target) {
603
- return Array.from(target.querySelectorAll('section.docx'));
604
- }
605
- function getDocxArticles(target) {
606
- return Array.from(target.querySelectorAll('section.docx > article'));
607
- }
608
- function getDocxParagraphAnchor(target, paragraphIndex) {
609
- if (paragraphIndex === undefined) {
610
- return undefined;
611
- }
612
- const paragraphs = Array.from(target.querySelectorAll('section.docx > article p'));
613
- return paragraphs[Math.min(Math.max(paragraphIndex, 0), Math.max(paragraphs.length - 1, 0))];
614
- }
615
- function insertDocxFallback(target, node, paragraphIndex) {
616
- const anchor = getDocxParagraphAnchor(target, paragraphIndex);
617
- if (anchor) {
618
- anchor.after(node);
619
- return;
620
- }
621
- const article = getDocxArticles(target)[0];
622
- if (article) {
623
- article.appendChild(node);
624
- }
625
- }
626
- function injectDocxImageFallbacks(target, fallbacks) {
627
- const sections = getDocxSections(target);
628
- if (!sections.length) {
629
- return;
630
- }
631
- fallbacks.forEach(fallback => {
632
- if (fallback.role === 'watermark') {
633
- sections.forEach(section => {
634
- const image = target.ownerDocument.createElement('img');
635
- image.className = 'docx-vml-watermark';
636
- image.src = fallback.dataUrl;
637
- image.alt = fallback.title || '';
638
- image.dataset.docxFallback = fallback.key;
639
- section.prepend(image);
640
- });
641
- return;
642
- }
643
- const figure = target.ownerDocument.createElement('figure');
644
- figure.className = 'docx-vml-fallback';
645
- figure.dataset.docxFallback = fallback.key;
646
- if (fallback.width) {
647
- figure.style.width = `${Math.round(fallback.width)}px`;
648
- }
649
- const image = target.ownerDocument.createElement('img');
650
- image.src = fallback.dataUrl;
651
- image.alt = fallback.title || (fallback.role === 'ole-preview' ? 'Embedded object preview' : 'Document image');
652
- if (fallback.width) {
653
- image.style.width = `${Math.round(fallback.width)}px`;
654
- }
655
- if (fallback.height) {
656
- image.style.height = `${Math.round(fallback.height)}px`;
657
- }
658
- figure.appendChild(image);
659
- insertDocxFallback(target, figure, fallback.paragraphIndex);
660
- });
661
- }
662
- function injectDocxChartFallbacks(target, fallbacks) {
663
- fallbacks.forEach(fallback => {
664
- const figure = target.ownerDocument.createElement('figure');
665
- figure.className = 'docx-chart-fallback';
666
- figure.dataset.docxFallback = fallback.key;
667
- if (fallback.width) {
668
- figure.style.width = `${Math.round(fallback.width)}px`;
669
- }
670
- figure.innerHTML = buildChartSvg(fallback);
671
- insertDocxFallback(target, figure, fallback.paragraphIndex);
672
- });
673
- }
674
- async function enhanceDocxFallbacks(buffer, target) {
675
- try {
676
- const { default: JSZip } = await import('jszip');
677
- const zip = await JSZip.loadAsync(buffer.slice(0));
678
- const [imageFallbacks, chartFallbacks] = await Promise.all([
679
- collectDocxVmlFallbacks(zip, target),
680
- collectDocxChartFallbacks(zip, target)
681
- ]);
682
- if (imageFallbacks.length) {
683
- injectDocxImageFallbacks(target, imageFallbacks);
684
- }
685
- if (chartFallbacks.length) {
686
- injectDocxChartFallbacks(target, chartFallbacks);
687
- }
688
- }
689
- catch (error) {
690
- console.warn('[file-viewer] DOCX 兼容增强解析失败,已保留 @file-viewer/docx 原始渲染结果。', error);
691
- }
692
- }
693
- function installResponsiveStyle(target) {
694
- const style = target.ownerDocument.createElement('style');
695
- style.textContent = DOCX_RESPONSIVE_CSS;
696
- target.prepend(style);
697
- return style;
698
- }
699
- function clonePageShell(section, article, pageHeight) {
700
- const nextPage = section.cloneNode(false);
701
- nextPage.innerHTML = '';
702
- nextPage.dataset.docxPaginated = 'true';
703
- nextPage.style.minHeight = `${pageHeight}px`;
704
- nextPage.style.height = `${pageHeight}px`;
705
- nextPage.style.overflow = 'hidden';
706
- const nextArticle = article.cloneNode(false);
707
- nextPage.appendChild(nextArticle);
708
- Array.from(section.children).forEach(child => {
709
- if (child !== article) {
710
- nextPage.appendChild(child.cloneNode(true));
711
- }
712
- });
713
- return { page: nextPage, article: nextArticle };
714
- }
715
- function getDocxPageHeight(section) {
716
- var _a;
717
- const style = (_a = section.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.getComputedStyle(section);
718
- const minHeight = style ? parseFloat(style.minHeight) : 0;
719
- return Number.isFinite(minHeight) && minHeight > 0 ? minHeight : section.offsetHeight;
720
- }
721
- function paginateOversizedSections(target) {
722
- const wrapper = target.querySelector('.docx-wrapper');
723
- if (!wrapper) {
724
- return;
725
- }
726
- Array.from(wrapper.children).forEach(child => {
727
- if (!isTargetHTMLElement(child, target) || !child.matches('section.docx')) {
728
- return;
729
- }
730
- const article = child.querySelector(':scope > article');
731
- if (!isTargetHTMLElement(article, target)) {
732
- return;
733
- }
734
- const pageHeight = getDocxPageHeight(child);
735
- const originalNodes = Array.from(article.childNodes);
736
- if (!pageHeight || originalNodes.length < 2 || child.scrollHeight <= pageHeight * 1.15) {
737
- return;
738
- }
739
- // 新 DOCX 引擎会优先使用 Word 保存的分页;这里保留预览层兜底分页,覆盖缺少分页标记的旧文件。
740
- let current = clonePageShell(child, article, pageHeight);
741
- child.before(current.page);
742
- originalNodes.forEach(node => {
743
- current.article.appendChild(node);
744
- if (current.page.scrollHeight <= pageHeight + 1 || current.article.childNodes.length === 1) {
745
- return;
746
- }
747
- current.article.removeChild(node);
748
- current = clonePageShell(child, article, pageHeight);
749
- child.before(current.page);
750
- current.article.appendChild(node);
751
- });
752
- child.remove();
753
- });
754
- }
755
- function wrapDocxSections(target, pagedLayout) {
756
- const wrapper = target.querySelector('.docx-wrapper');
757
- if (!wrapper) {
758
- return [];
759
- }
760
- return Array.from(wrapper.children).flatMap(child => {
761
- if (!isTargetHTMLElement(child, target) || !child.matches('section.docx')) {
762
- return [];
763
- }
764
- const frame = target.ownerDocument.createElement('div');
765
- frame.className = pagedLayout ? 'docx-page-frame' : 'docx-flow-frame';
766
- child.before(frame);
767
- frame.appendChild(child);
768
- return [frame];
769
- });
770
- }
771
- function makeDocxResponsive(target, context) {
772
- target.classList.add('docx-fit-viewer');
773
- const style = installResponsiveStyle(target);
774
- const pagedLayout = shouldPaginateOversizedDocxSections(context);
775
- if (pagedLayout) {
776
- paginateOversizedSections(target);
777
- }
778
- const frames = wrapDocxSections(target, pagedLayout);
779
- const view = getTargetWindow(target);
780
- const ResizeObserverCtor = view === null || view === void 0 ? void 0 : view.ResizeObserver;
781
- let resizeFrame = 0;
782
- let userZoom = 1;
783
- let currentScale = 1;
784
- let currentFitScale = 1;
785
- const zoomEmitter = createZoomChangeEmitter();
786
- const clampScale = (scale) => {
787
- return Math.min(DOCX_MAX_SCALE, Math.max(DOCX_MIN_SCALE, Number(scale.toFixed(2))));
788
- };
789
- const resize = () => {
790
- if (!view) {
791
- return;
792
- }
793
- view.cancelAnimationFrame(resizeFrame);
794
- resizeFrame = view.requestAnimationFrame(() => {
795
- let firstScale = 1;
796
- frames.forEach(frame => {
797
- const page = frame.firstElementChild;
798
- if (!isTargetHTMLElement(page, target)) {
799
- return;
800
- }
801
- page.style.transform = 'translateX(-50%)';
802
- const pageWidth = page.offsetWidth;
803
- const contentHeight = pagedLayout
804
- ? page.offsetHeight
805
- : Math.max(page.scrollHeight, page.offsetHeight);
806
- if (!pageWidth || !contentHeight) {
807
- return;
808
- }
809
- const availableWidth = Math.max(target.clientWidth - 28, 120);
810
- const fitScale = Math.min(1, Math.max(DOCX_MIN_SCALE, availableWidth / pageWidth));
811
- const scale = clampScale(fitScale * userZoom);
812
- firstScale = scale;
813
- currentFitScale = fitScale;
814
- page.style.transform = `translateX(-50%) scale(${scale})`;
815
- frame.style.width = `${Math.ceil(Math.max(pageWidth * scale, target.clientWidth - 28, 120))}px`;
816
- frame.style.maxWidth = 'none';
817
- frame.style.height = `${Math.ceil(contentHeight * scale)}px`;
818
- });
819
- currentScale = firstScale;
820
- zoomEmitter.emit();
821
- });
822
- };
823
- const getZoomState = () => ({
824
- scale: currentScale,
825
- label: `${Math.round(currentScale * 100)}%`,
826
- canZoomIn: currentScale < DOCX_MAX_SCALE,
827
- canZoomOut: currentScale > DOCX_MIN_SCALE,
828
- canReset: userZoom !== 1,
829
- minScale: DOCX_MIN_SCALE,
830
- maxScale: DOCX_MAX_SCALE
831
- });
832
- const setUserZoom = (nextZoom) => {
833
- userZoom = Math.min(6, Math.max(0.2, Number(nextZoom.toFixed(2))));
834
- resize();
835
- return getZoomState();
836
- };
837
- target.dataset.viewerZoomProvider = 'docx';
838
- registerFileViewerZoomProvider(target, {
839
- zoomIn: () => setUserZoom(userZoom + DOCX_ZOOM_STEP),
840
- zoomOut: () => setUserZoom(userZoom - DOCX_ZOOM_STEP),
841
- resetZoom: () => setUserZoom(1),
842
- setZoom: scale => setUserZoom(scale / Math.max(currentFitScale, 0.01)),
843
- getState: getZoomState,
844
- subscribe: zoomEmitter.subscribe
845
- });
846
- const observer = ResizeObserverCtor ? new ResizeObserverCtor(resize) : null;
847
- observer === null || observer === void 0 ? void 0 : observer.observe(target);
848
- frames.forEach(frame => {
849
- const page = getDocxPageElement(frame);
850
- if (page) {
851
- observer === null || observer === void 0 ? void 0 : observer.observe(page);
852
- }
853
- });
854
- resize();
855
- return () => {
856
- view === null || view === void 0 ? void 0 : view.cancelAnimationFrame(resizeFrame);
857
- observer === null || observer === void 0 ? void 0 : observer.disconnect();
858
- unregisterFileViewerZoomProvider(target);
859
- style.remove();
860
- target.classList.remove('docx-fit-viewer');
861
- };
862
- }
863
- function getDocxPageElement(frame) {
864
- var _a;
865
- const page = frame.firstElementChild;
866
- const HTMLElementCtor = (_a = frame.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.HTMLElement;
867
- return HTMLElementCtor && page instanceof HTMLElementCtor ? page : null;
868
- }
869
- function isDocxFlowFrame(frame) {
870
- return !!(frame === null || frame === void 0 ? void 0 : frame.classList.contains('docx-flow-frame'));
871
- }
872
- function getDocxFramePrintSize(frame) {
873
- const page = frame ? getDocxPageElement(frame) : null;
874
- if (!page) {
875
- return DOCX_DEFAULT_PAGE_SIZE;
876
- }
877
- const size = getElementPrintPageSize(page, DOCX_DEFAULT_PAGE_SIZE);
878
- if (!isDocxFlowFrame(frame)) {
879
- return size;
880
- }
881
- return {
882
- width: size.width,
883
- height: Math.max(page.scrollHeight || 0, page.offsetHeight || 0, DOCX_DEFAULT_PAGE_SIZE.height)
884
- };
885
- }
886
- function normalizeDocxPageForPrint(frame, pageSize) {
887
- const flowLayout = isDocxFlowFrame(frame);
888
- const pageWidth = formatCssPixels(pageSize.width);
889
- const pageHeight = formatCssPixels(pageSize.height);
890
- applyPrintPageSize(frame, pageSize, { heightMode: flowLayout ? 'min' : 'fixed' });
891
- frame.style.margin = '0 auto 18px';
892
- const page = getDocxPageElement(frame);
893
- if (!page) {
894
- return;
895
- }
896
- page.style.position = 'relative';
897
- page.style.top = 'auto';
898
- page.style.left = 'auto';
899
- page.style.width = pageWidth;
900
- page.style.maxWidth = 'none';
901
- page.style.minHeight = flowLayout ? '0' : pageHeight;
902
- page.style.height = flowLayout ? 'auto' : pageHeight;
903
- page.style.margin = '0 auto';
904
- page.style.transform = 'none';
905
- page.style.transformOrigin = 'top left';
906
- page.style.overflow = flowLayout ? 'visible' : 'hidden';
907
- page.style.boxShadow = 'none';
908
- }
909
- function buildDocxPrintStyle(target) {
910
- const firstFrame = target.querySelector('.docx-page-frame, .docx-flow-frame');
911
- const pageSize = getDocxFramePrintSize(firstFrame || undefined);
912
- const selector = (firstFrame === null || firstFrame === void 0 ? void 0 : firstFrame.classList.contains('docx-flow-frame'))
913
- ? '.viewer-export-content .docx-flow-frame'
914
- : '.viewer-export-content .docx-page-frame';
915
- return buildPrintPageStyle({
916
- selector,
917
- width: pageSize.width,
918
- height: (firstFrame === null || firstFrame === void 0 ? void 0 : firstFrame.classList.contains('docx-flow-frame'))
919
- ? DOCX_DEFAULT_PAGE_SIZE.height
920
- : pageSize.height,
921
- heightMode: (firstFrame === null || firstFrame === void 0 ? void 0 : firstFrame.classList.contains('docx-flow-frame')) ? 'min' : 'fixed'
922
- });
923
- }
924
- function prepareDocxCloneForExport(target) {
925
- const liveFrames = Array.from(target.querySelectorAll('.docx-page-frame, .docx-flow-frame'));
926
- const clone = target.cloneNode(true);
927
- const printDocument = target.ownerDocument.createElement('div');
928
- printDocument.className = 'docx-print-document';
929
- const scopedStyles = Array.from(clone.querySelectorAll('style'))
930
- .filter(style => { var _a; return !((_a = style.textContent) === null || _a === void 0 ? void 0 : _a.includes('.docx-fit-viewer')); })
931
- .map(style => style.outerHTML)
932
- .join('');
933
- clone.querySelectorAll('.docx-page-frame, .docx-flow-frame').forEach((frame, index) => {
934
- normalizeDocxPageForPrint(frame, getDocxFramePrintSize(liveFrames[index]));
935
- printDocument.appendChild(frame.cloneNode(true));
936
- });
937
- return printDocument.childElementCount ? `${scopedStyles}${printDocument.outerHTML}` : clone.innerHTML;
938
- }
939
- /**
940
- * 渲染docx文件
941
- */
942
- export default async function (buffer, target, context) {
943
- var _a;
944
- assertValidDocxPackage(buffer);
945
- let hasNotifiedProgressiveRender = false;
946
- const notifyProgressiveRender = () => {
947
- var _a;
948
- if (hasNotifiedProgressiveRender) {
949
- return;
950
- }
951
- hasNotifiedProgressiveRender = true;
952
- (_a = context === null || context === void 0 ? void 0 : context.onProgressiveRender) === null || _a === void 0 ? void 0 : _a.call(context);
953
- };
954
- const docxOptions = createDocxOptions(target, context, notifyProgressiveRender);
955
- const { defaultOptions, renderAsync } = await loadLibrary();
956
- target.dataset.docxWorker = docxOptions.useWorker ? 'self' : 'false';
957
- await renderAsync(buffer, target, undefined, {
958
- ...defaultOptions,
959
- ...docxOptions
960
- });
961
- notifyProgressiveRender();
962
- await enhanceDocxFallbacks(buffer, target);
963
- const disposeResponsive = makeDocxResponsive(target, context);
964
- (_a = context === null || context === void 0 ? void 0 : context.registerExportAdapter) === null || _a === void 0 ? void 0 : _a.call(context, {
965
- includeDocumentStyles: false,
966
- beforeSnapshot: () => {
967
- const view = getTargetWindow(target);
968
- if (view) {
969
- view.dispatchEvent(new view.Event('resize'));
970
- }
971
- },
972
- printStyle: () => buildDocxPrintStyle(target),
973
- toHtml: () => prepareDocxCloneForExport(target)
974
- });
975
- return {
976
- $el: target,
977
- unmount() {
978
- var _a;
979
- (_a = context === null || context === void 0 ? void 0 : context.registerExportAdapter) === null || _a === void 0 ? void 0 : _a.call(context, null);
980
- disposeResponsive();
981
- delete target.dataset.docxWorker;
982
- target.innerHTML = '';
983
- }
984
- };
985
- }