@file-viewer/renderer-word 3.1.2 → 3.2.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.
package/README.en.md CHANGED
@@ -1,74 +1,7 @@
1
1
  # @file-viewer/renderer-word
2
2
 
3
- Word and OpenDocument renderer package for Flyfish File Viewer. Standard/full includes DOCX/DOCM/DOTX/DOTM, legacy DOC/DOT, ODT, and ODP. RTF is enabled explicitly by `@file-viewer/capability-rtf`.
3
+ Runtime package version 3.2.1.
4
4
 
5
- ## Usage
5
+ Usage and API documentation: https://doc.file-viewer.app/guide/on-demand-renderers
6
6
 
7
- ```ts
8
- import FileViewer from '@file-viewer/vue3'
9
- import { wordRenderer } from '@file-viewer/renderer-word'
10
-
11
- const options = {
12
- rendererMode: 'replace',
13
- renderers: wordRenderer,
14
- }
15
- ```
16
-
17
- You can compose it with other renderers:
18
-
19
- ```ts
20
- import { wordRenderer } from '@file-viewer/renderer-word'
21
- import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
- import { presentationRenderer } from '@file-viewer/renderer-presentation'
23
-
24
- const options = {
25
- rendererMode: 'replace',
26
- renderers: [wordRenderer, pdfRenderer, presentationRenderer],
27
- }
28
- ```
29
-
30
- Use `@file-viewer/preset-all` when you want the same complete matrix as the official demo.
31
-
32
- ## Capabilities
33
-
34
- - DOCX / DOCM / DOTX / DOTM use the self-maintained `@file-viewer/docx` engine with Worker parsing, continuous reading layout, cached TOC fields, async batched rendering, and a dark document surface that follows the viewer theme.
35
- - DOC / DOT use `@file-viewer/doc` with a Word-like paper surface, zoom, print, and HTML export adapters.
36
- - With the RTF capability installed, RTF uses `rtf.js`; without it the viewer shows the exact CLI enablement command. ODT / ODP read `content.xml` from OpenDocument packages for safe structure previews.
37
- - The renderer reuses core search, zoom, print, export, lifecycle, and operation APIs.
38
-
39
- ## Text Revisions
40
-
41
- `options.docx.reviewMode` applies to DOC and DOCX: `all` (default) shows actual
42
- insertions underlined and deletions struck through; `final` shows revised text,
43
- and `original` shows text before those edits. Changing this option updates the
44
- current preview without replacing the file. It does not accept/reject revisions
45
- or rewrite the original bytes. Text revisions are not a claim of complete
46
- Word review-history, formatting-change, or move-tracking support.
47
-
48
- ## Offline Assets
49
-
50
- DOCX Worker defaults to viewer assets:
51
-
52
- - `vendor/docx/docx.worker.js`
53
- - `vendor/docx/jszip.min.js`
54
-
55
- Override them for private deployments:
56
-
57
- ```ts
58
- const options = {
59
- docx: {
60
- workerUrl: '/file-viewer/vendor/docx/docx.worker.js',
61
- workerJsZipUrl: '/file-viewer/vendor/docx/jszip.min.js',
62
- },
63
- }
64
- ```
65
-
66
- DOCX dark rendering follows `options.theme` by default: `dark` enables it, `light` disables it, and `system` follows the browser color scheme. Pass `options.docx.darkMode: true / false` when the host app needs a fixed result.
67
-
68
- DOC, DOCX, and RTF external links and HTTP(S) image relationships are blocked by default. Enable them explicitly with `options.docx.externalLinkPolicy: 'allow'` and `options.docx.externalResourcePolicy: 'allow'`; links are still limited to HTTP(S), `mailto:`, `tel:`, and safe relative addresses. Unknown and protocol-relative schemes are always rejected. Embedded images, internal bookmarks, and local `data:`/`blob:` image resources remain available.
69
-
70
- The standard renderer sanitizes the DOM produced by `rtf.js` before mounting it. Custom RTF integrations that consume HTML directly should first call `sanitizeFileViewerRtfHtml(document, markup, options)`; it uses the same link policy and DOMPurify boundary as the standard mount path. A strict Trusted Types CSP should allow the `file-viewer-document-sanitizer` policy name.
71
-
72
- ## Migration
73
-
74
- `@file-viewer/core` no longer depends on `@file-viewer/docx`, `@file-viewer/doc`, `rtf.js`, `linkedom`, or `@xmldom/xmldom` directly. Install and pass this renderer for full Word preview, or use `@file-viewer/preset-all`.
7
+ The package's own license is Apache-2.0. Included third-party notices apply to their respective components.
package/README.md CHANGED
@@ -1,69 +1,7 @@
1
1
  # @file-viewer/renderer-word
2
2
 
3
- Flyfish File Viewer 的 Word / OpenDocument renderer 包。standard/full 默认承接 DOCX/DOCM/DOTX/DOTM、旧版 DOC/DOT 与 ODT/ODP;RTF 由 `@file-viewer/capability-rtf` 显式启用。
3
+ Runtime package version 3.2.1.
4
4
 
5
- ## 用法
5
+ Usage and API documentation: https://doc.file-viewer.app/guide/on-demand-renderers
6
6
 
7
- ```ts
8
- import FileViewer from '@file-viewer/vue3'
9
- import { wordRenderer } from '@file-viewer/renderer-word'
10
-
11
- const options = {
12
- rendererMode: 'replace',
13
- renderers: wordRenderer,
14
- }
15
- ```
16
-
17
- 也可以和其他 renderer 一起组合:
18
-
19
- ```ts
20
- import { wordRenderer } from '@file-viewer/renderer-word'
21
- import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
- import { presentationRenderer } from '@file-viewer/renderer-presentation'
23
-
24
- const options = {
25
- rendererMode: 'replace',
26
- renderers: [wordRenderer, pdfRenderer, presentationRenderer],
27
- }
28
- ```
29
-
30
- 官方 Demo 和完整格式矩阵可以直接使用 `@file-viewer/preset-all`。
31
-
32
- ## 能力边界
33
-
34
- - DOCX / DOCM / DOTX / DOTM 使用自研 `@file-viewer/docx`,默认 Worker 解析、连续流式阅读、目录字段缓存、异步分批渲染,并跟随 viewer 主题启用暗黑文档面。
35
- - DOC / DOT 使用 `@file-viewer/doc`,并套用 Word 风格纸张阅读面、缩放、打印和 HTML 导出适配。
36
- - 安装 RTF capability 后才使用 `rtf.js`;未安装时会显示精确 CLI 启用命令。ODT / ODP 读取 OpenDocument 包内 `content.xml` 做安全结构预览。
37
- - 继续复用 core 的统一搜索、缩放、打印、导出、生命周期和操作能力。
38
-
39
- ## 文本修订
40
-
41
- `options.docx.reviewMode` 同时适用于 DOC 和 DOCX:`all`(默认)用下划线显示实际插入、用删除线显示实际删除;`final` 显示定稿,`original` 显示修订前文字。同一组件修改该参数后会更新预览,不需要重新选择文件,也不会接受、拒绝修订或重写原始文件。文本修订支持不等于完整支持 Word 审阅历史、格式修订或移动记录。
42
-
43
- ## 离线资产
44
-
45
- DOCX Worker 默认读取 viewer assets 下的:
46
-
47
- - `vendor/docx/docx.worker.js`
48
- - `vendor/docx/jszip.min.js`
49
-
50
- 私有化部署时可以通过 `options.docx.workerUrl` 和 `options.docx.workerJsZipUrl` 覆盖:
51
-
52
- ```ts
53
- const options = {
54
- docx: {
55
- workerUrl: '/file-viewer/vendor/docx/docx.worker.js',
56
- workerJsZipUrl: '/file-viewer/vendor/docx/jszip.min.js',
57
- },
58
- }
59
- ```
60
-
61
- DOCX 暗黑渲染默认由 `options.theme` 决定:`dark` 开启、`light` 关闭、`system` 跟随浏览器系统主题。需要业务固定效果时可传 `options.docx.darkMode: true / false`。
62
-
63
- DOC、DOCX 与 RTF 的外部链接及 HTTP(S) 图片关系默认阻断。只有显式设置 `options.docx.externalLinkPolicy: 'allow'` 和 `options.docx.externalResourcePolicy: 'allow'` 才会启用;链接仍只接受 HTTP(S)、`mailto:`、`tel:` 和安全相对地址,未知协议与协议相对地址始终拒绝。内嵌图片、内部书签以及本地 `data:`/`blob:` 图片资源不受影响。
64
-
65
- 标准 renderer 会在挂载前净化 `rtf.js` 产生的 DOM。自定义 RTF 集成若直接消费 HTML,应先调用 `sanitizeFileViewerRtfHtml(document, markup, options)`;该边界与标准挂载使用同一链接策略和 DOMPurify 配置。严格 Trusted Types CSP 需允许 `file-viewer-document-sanitizer` 策略名。
66
-
67
- ## 迁移说明
68
-
69
- `@file-viewer/core` 已不再直接依赖 `@file-viewer/docx`、`@file-viewer/doc`、`rtf.js`、`linkedom` 或 `@xmldom/xmldom`。需要 Word 完整预览时,请安装本包并通过 `renderers` 传入,或使用 `@file-viewer/preset-all`。
7
+ The package's own license is Apache-2.0. Included third-party notices apply to their respective components.
@@ -0,0 +1 @@
1
+ export declare function readDocxFlowPaperHeight(page: HTMLElement | null, fallback: number): number;
@@ -0,0 +1,9 @@
1
+ export function readDocxFlowPaperHeight(page, fallback) {
2
+ var _a;
3
+ if (!page)
4
+ return fallback;
5
+ const value = ((_a = page.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.getComputedStyle(page).minHeight) || '';
6
+ const match = /^(\d+(?:\.\d+)?)px$/.exec(value.trim());
7
+ const height = match ? Number(match[1]) : 0;
8
+ return Number.isFinite(height) && height > 0 ? height : fallback;
9
+ }
@@ -0,0 +1 @@
1
+ export declare function observeDocxFrames(target: HTMLElement, pagedLayout: boolean, onFrames: (frames: HTMLElement[]) => void): () => void;
@@ -0,0 +1,49 @@
1
+ export function observeDocxFrames(target, pagedLayout, onFrames) {
2
+ const wrapper = target.querySelector('.docx-wrapper');
3
+ if (!wrapper)
4
+ return () => { };
5
+ const view = target.ownerDocument.defaultView;
6
+ const Observer = view === null || view === void 0 ? void 0 : view.MutationObserver;
7
+ let disposed = false;
8
+ let frames = [];
9
+ const sync = () => {
10
+ if (disposed ||
11
+ wrapper.dataset.docxPaginating === 'true' ||
12
+ wrapper.dataset.docxPaginationScheduled === 'true')
13
+ return;
14
+ const next = [];
15
+ for (const child of Array.from(wrapper.children)) {
16
+ if (child.matches('section.docx')) {
17
+ const frame = target.ownerDocument.createElement('div');
18
+ frame.className = pagedLayout ? 'docx-page-frame' : 'docx-flow-frame';
19
+ frame.dataset.docxResponsiveFrame = 'true';
20
+ child.before(frame);
21
+ frame.appendChild(child);
22
+ next.push(frame);
23
+ }
24
+ else if (child.getAttribute('data-docx-responsive-frame') === 'true') {
25
+ next.push(child);
26
+ }
27
+ }
28
+ if (next.length !== frames.length || next.some((frame, i) => frame !== frames[i])) {
29
+ frames = next;
30
+ onFrames([...frames]);
31
+ }
32
+ };
33
+ const observer = Observer ? new Observer(sync) : null;
34
+ observer === null || observer === void 0 ? void 0 : observer.observe(wrapper, {
35
+ childList: true,
36
+ attributes: true,
37
+ attributeFilter: [
38
+ 'data-docx-paginating',
39
+ 'data-docx-pagination-scheduled',
40
+ 'data-docx-paginated'
41
+ ]
42
+ });
43
+ sync();
44
+ return () => {
45
+ disposed = true;
46
+ observer === null || observer === void 0 ? void 0 : observer.disconnect();
47
+ frames = [];
48
+ };
49
+ }
package/dist/index.d.ts CHANGED
@@ -5,13 +5,7 @@ export { createFileViewerRtfHyperlinkContainer, isSafeFileViewerRtfHyperlink, sa
5
5
  export type { FileViewerRtfExternalPolicy, FileViewerRtfSanitizeOptions, } from './sanitizeRtf.js';
6
6
  export declare const wordRendererDefinitions: RendererDefinition[];
7
7
  export declare const renderFileViewerWordDocx: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
8
- /**
9
- * A surprising number of legacy systems keep the `.doc` suffix after saving
10
- * an OOXML document. Route those ZIP-based files through the DOCX engine while
11
- * leaving genuine OLE/CFB `.doc` files on the binary parser. Word 2003 XML
12
- * has its own single-file container and is adapted lazily to the OOXML renderer.
13
- */
14
- export declare const resolveFileViewerWordContainer: (buffer: ArrayBuffer) => "openxml" | "wordml" | "binary";
8
+ export { resolveWordContainer as resolveFileViewerWordContainer } from './wordContainer.js';
15
9
  export declare const renderFileViewerWordDoc: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
16
10
  export declare const renderFileViewerOpenDocument: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
17
11
  export declare const wordRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
package/dist/index.js CHANGED
@@ -11,29 +11,14 @@ if (wordDefinitions.length !== wordRendererIds.length) {
11
11
  throw new Error('@file-viewer/renderer-word could not locate the shared Word renderer definitions.');
12
12
  }
13
13
  export const wordRendererDefinitions = wordDefinitions;
14
- export const renderFileViewerWordDocx = (buffer, target, _type, context) => import('./wordDocx.js').then(({ default: renderWordDocx }) => renderWordDocx(buffer, target, context));
15
- /**
16
- * A surprising number of legacy systems keep the `.doc` suffix after saving
17
- * an OOXML document. Route those ZIP-based files through the DOCX engine while
18
- * leaving genuine OLE/CFB `.doc` files on the binary parser. Word 2003 XML
19
- * has its own single-file container and is adapted lazily to the OOXML renderer.
20
- */
21
- export const resolveFileViewerWordContainer = (buffer) => {
22
- if (buffer.byteLength < 2) {
23
- return 'binary';
24
- }
25
- const bytes = new Uint8Array(buffer, 0, 2);
26
- if (bytes[0] === 0x50 && bytes[1] === 0x4b)
27
- return 'openxml';
28
- const prefix = new Uint8Array(buffer, 0, Math.min(buffer.byteLength, 8192));
29
- const utf16le = (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0x3c && bytes[1] === 0);
30
- const utf16be = (bytes[0] === 0xfe && bytes[1] === 0xff) || (bytes[0] === 0 && bytes[1] === 0x3c);
31
- const text = new TextDecoder(utf16le ? 'utf-16le' : utf16be ? 'utf-16be' : 'utf-8').decode(prefix);
32
- return /<(?:[\w.-]+:)?wordDocument(?:\s|>)/.test(text) &&
33
- text.includes('http://schemas.microsoft.com/office/word/2003/wordml') ? 'wordml' : 'binary';
34
- };
14
+ export const renderFileViewerWordDocx = (buffer, target, _type, context) => renderFileViewerWordDoc(buffer, target, _type, context);
15
+ export { resolveWordContainer as resolveFileViewerWordContainer } from './wordContainer.js';
16
+ import { resolveWordContainer } from './wordContainer.js';
35
17
  export const renderFileViewerWordDoc = (buffer, target, _type, context) => {
36
- const container = resolveFileViewerWordContainer(buffer);
18
+ const container = resolveWordContainer(buffer);
19
+ if (container === 'html' || container === 'text') {
20
+ return import('./wordText.js').then(({ renderWordText }) => renderWordText(buffer, target, container, context));
21
+ }
37
22
  if (container === 'wordml') {
38
23
  return Promise.all([import('./wordMl.js'), import('./wordDocx.js')])
39
24
  .then(async ([{ convertWordMlToDocx }, { default: renderWordDocx }]) => renderWordDocx(await convertWordMlToDocx(buffer, target), target, context));
@@ -3,12 +3,6 @@ export interface FileViewerRtfSanitizeOptions {
3
3
  externalLinkPolicy?: FileViewerRtfExternalPolicy;
4
4
  externalResourcePolicy?: FileViewerRtfExternalPolicy;
5
5
  }
6
- /**
7
- * Canonicalizes an RTF field hyperlink through the same policy used by DOC.
8
- * Word's `HYPERLINK \\l "bookmark"` field syntax is converted to a fragment
9
- * before external navigation is considered, so bookmarks remain available
10
- * even when the default external-link policy is `block`.
11
- */
12
6
  export declare const sanitizeFileViewerRtfHyperlink: (value: string, policy?: FileViewerRtfExternalPolicy) => string | null;
13
7
  export declare const isSafeFileViewerRtfHyperlink: (value: string, policy?: FileViewerRtfExternalPolicy) => boolean;
14
8
  export declare const createFileViewerRtfHyperlinkContainer: (documentRef: Document, create: () => HTMLElement, hyperlink: {
@@ -18,8 +12,4 @@ export declare const createFileViewerRtfHyperlinkContainer: (documentRef: Docume
18
12
  content: HTMLSpanElement;
19
13
  };
20
14
  export declare const sanitizeFileViewerRtfElement: (documentRef: Document, element: HTMLElement, options?: FileViewerRtfSanitizeOptions) => DocumentFragment;
21
- /**
22
- * Safe serialization boundary for integrations that consume renderer markup
23
- * directly instead of mounting through the standard File Viewer handler.
24
- */
25
15
  export declare const sanitizeFileViewerRtfHtml: (documentRef: Document, markup: string, options?: FileViewerRtfSanitizeOptions) => string;
@@ -1,5 +1,4 @@
1
1
  import { sanitizeFileViewerDocumentMarkup, sanitizeMsDocLinkHref } from '@file-viewer/doc';
2
- // eslint-disable-next-line no-control-regex -- remove URL controls before scheme validation
3
2
  const compactUrl = (value) => value.trim().replace(/[\u0000-\u0020\u007f-\u009f]/g, '');
4
3
  const schemeOf = (value) => {
5
4
  var _a, _b;
@@ -15,12 +14,6 @@ const normalizeRtfBookmarkHref = (value) => {
15
14
  const bookmark = (match[1] || match[2] || '').trim();
16
15
  return /^[A-Za-z_][A-Za-z0-9_]{0,39}$/.test(bookmark) ? `#${bookmark}` : null;
17
16
  };
18
- /**
19
- * Canonicalizes an RTF field hyperlink through the same policy used by DOC.
20
- * Word's `HYPERLINK \\l "bookmark"` field syntax is converted to a fragment
21
- * before external navigation is considered, so bookmarks remain available
22
- * even when the default external-link policy is `block`.
23
- */
24
17
  export const sanitizeFileViewerRtfHyperlink = (value, policy = 'block') => {
25
18
  const bookmarkHref = normalizeRtfBookmarkHref(value);
26
19
  return sanitizeMsDocLinkHref(bookmarkHref || value, policy);
@@ -138,10 +131,6 @@ const sanitizeFileViewerRtfMarkup = (documentRef, markup, fallbackText, options
138
131
  return fragment;
139
132
  };
140
133
  export const sanitizeFileViewerRtfElement = (documentRef, element, options = {}) => sanitizeFileViewerRtfMarkup(documentRef, element.outerHTML, element.textContent || '', options);
141
- /**
142
- * Safe serialization boundary for integrations that consume renderer markup
143
- * directly instead of mounting through the standard File Viewer handler.
144
- */
145
134
  export const sanitizeFileViewerRtfHtml = (documentRef, markup, options = {}) => {
146
135
  const container = documentRef.createElement('div');
147
136
  container.append(sanitizeFileViewerRtfMarkup(documentRef, markup, markup, options));
@@ -0,0 +1,2 @@
1
+ export type WordContainer = 'openxml' | 'wordml' | 'html' | 'text' | 'binary';
2
+ export declare function resolveWordContainer(buffer: ArrayBuffer): WordContainer;
@@ -0,0 +1,119 @@
1
+ import { decodeFileViewerTextBuffer, resolveFileViewerTextEncoding } from '@file-viewer/core';
2
+ const ole = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
3
+ const wordMlNamespace = 'http://schemas.microsoft.com/office/word/2003/wordml';
4
+ const xmlNameStart = String.raw `A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF` +
5
+ String.raw `\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F` +
6
+ String.raw `\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}`;
7
+ const xmlName = String.raw `[${xmlNameStart}][${xmlNameStart}.0-9\u00B7\u0300-\u036F\u203F-\u2040-]*`;
8
+ const wordMlRoot = new RegExp(String.raw `^<(?:(${xmlName}):)?wordDocument(?=[\t\n\r />])`, 'u');
9
+ function documentStart(text) {
10
+ let index = text.charCodeAt(0) === 0xfeff ? 1 : 0;
11
+ while (index <= text.length) {
12
+ while (index < text.length && /\s/.test(text[index]))
13
+ index++;
14
+ const closing = text.startsWith('<?', index) ? '?>' : text.startsWith('<!--', index) ? '-->' : null;
15
+ if (!closing)
16
+ return text.slice(index);
17
+ const end = text.indexOf(closing, index + 2);
18
+ if (end < 0)
19
+ return null;
20
+ index = end + closing.length;
21
+ }
22
+ return '';
23
+ }
24
+ function decodeNamespace(value) {
25
+ const named = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
26
+ return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (entity, name) => {
27
+ if (!name.startsWith('#'))
28
+ return named[name];
29
+ const point = name.startsWith('#x') ? Number.parseInt(name.slice(2), 16) : Number.parseInt(name.slice(1), 10);
30
+ return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff)
31
+ ? String.fromCodePoint(point) : entity;
32
+ });
33
+ }
34
+ function isWordMlRoot(start) {
35
+ var _a;
36
+ const root = wordMlRoot.exec(start);
37
+ if (!root)
38
+ return false;
39
+ const attributes = new Map();
40
+ const attributeName = new RegExp(String.raw `(?:${xmlName}:)?${xmlName}`, 'uy');
41
+ let index = root[0].length;
42
+ while (index < start.length) {
43
+ const beforeSpace = index;
44
+ while (index < start.length && /[\t\n\r ]/.test(start[index]))
45
+ index++;
46
+ if (start[index] === '>' || start.startsWith('/>', index)) {
47
+ return decodeNamespace(attributes.get(root[1] ? 'xmlns:' + root[1] : 'xmlns') || '') === wordMlNamespace;
48
+ }
49
+ if (index === beforeSpace)
50
+ return false;
51
+ attributeName.lastIndex = index;
52
+ const name = (_a = attributeName.exec(start)) === null || _a === void 0 ? void 0 : _a[0];
53
+ if (!name || attributes.has(name))
54
+ return false;
55
+ index = attributeName.lastIndex;
56
+ while (index < start.length && /[\t\n\r ]/.test(start[index]))
57
+ index++;
58
+ if (start[index++] !== '=')
59
+ return false;
60
+ while (index < start.length && /[\t\n\r ]/.test(start[index]))
61
+ index++;
62
+ const quote = start[index++];
63
+ if (quote !== '"' && quote !== "'")
64
+ return false;
65
+ const end = start.indexOf(quote, index);
66
+ if (end < 0 || start.slice(index, end).includes('<'))
67
+ return false;
68
+ attributes.set(name, start.slice(index, end));
69
+ index = end + 1;
70
+ }
71
+ return false;
72
+ }
73
+ function hasWordMlDocument(sample) {
74
+ var _a, _b;
75
+ const bytes = new Uint8Array(sample);
76
+ const utf16le = (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0x3c && bytes[1] === 0);
77
+ const utf16be = (bytes[0] === 0xfe && bytes[1] === 0xff) || (bytes[0] === 0 && bytes[1] === 0x3c);
78
+ const utf8Bom = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
79
+ const detected = utf16le ? 'utf-16le' : utf16be ? 'utf-16be' : utf8Bom ? 'utf-8' : null;
80
+ try {
81
+ const prefix = new TextDecoder(detected || 'windows-1252').decode(bytes.subarray(0, 1024));
82
+ const declaration = (_a = /^<\?xml\s[^?]*\?>/.exec(prefix)) === null || _a === void 0 ? void 0 : _a[0];
83
+ const declared = declaration && ((_b = /\sencoding\s*=\s*(["'])([A-Za-z][A-Za-z0-9._-]*)\1/.exec(declaration)) === null || _b === void 0 ? void 0 : _b[2]);
84
+ const start = documentStart(new TextDecoder(detected || declared || 'utf-8').decode(bytes));
85
+ return start !== null && isWordMlRoot(start);
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ export function resolveWordContainer(buffer) {
92
+ const bytes = new Uint8Array(buffer);
93
+ if (bytes[0] === 0x50 && bytes[1] === 0x4b)
94
+ return 'openxml';
95
+ if (!bytes.length || ole.every((byte, index) => bytes[index] === byte))
96
+ return 'binary';
97
+ const sample = buffer.slice(0, Math.min(buffer.byteLength, 65536));
98
+ const encoding = resolveFileViewerTextEncoding(new Uint8Array(sample)).encoding;
99
+ if (encoding.startsWith('utf-16') && buffer.byteLength % 2 !== 0)
100
+ return 'binary';
101
+ if (hasWordMlDocument(sample))
102
+ return 'wordml';
103
+ let text;
104
+ try {
105
+ text = decodeFileViewerTextBuffer(sample).text;
106
+ }
107
+ catch {
108
+ return 'binary';
109
+ }
110
+ const start = documentStart(text);
111
+ if (start === null)
112
+ return 'binary';
113
+ if (/^(?:<!doctype\s+html\b|<html\b|<head\b|<body\b)/i.test(start))
114
+ return 'html';
115
+ if (/^[<{]/.test(start) || /[\u0000-\u0008\u000b\u000e-\u001f\u007f]/.test(text))
116
+ return 'binary';
117
+ const replacements = (text.match(/\uFFFD/g) || []).length;
118
+ return replacements > Math.max(1, text.length * 0.01) ? 'binary' : 'text';
119
+ }
package/dist/wordDoc.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type FileRenderContext, type FileViewerRenderedInstance as AppWrapper } from '@file-viewer/core';
2
- /**
3
- * 渲染 doc 文件
4
- */
5
2
  export default function render(buffer: ArrayBuffer, target: HTMLDivElement, context?: FileRenderContext): Promise<AppWrapper>;
3
+ export declare function mountWordDocument(rendered: {
4
+ html: string;
5
+ css: string;
6
+ }, target: HTMLDivElement, context?: FileRenderContext): AppWrapper;
package/dist/wordDoc.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { clampWordScale, isPositiveFinite, readWordFitViewport } from './wordViewport.js';
1
2
  import { defaultMsDocCss, parseMsDocToHtml, sanitizeMsDocHtml } from '@file-viewer/doc';
2
3
  import { applyPrintPageSize, buildPrintPageStyle, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, formatCssPixels, registerFileViewerZoomProvider, resolveFileViewerFitScale, unregisterFileViewerZoomProvider, } from '@file-viewer/core';
3
4
  const PAGE_BREAK_MARKER = '<span class="msdoc-page-break"></span>';
@@ -40,7 +41,7 @@ const WORD_PAGE_CSS = `
40
41
  display:table;
41
42
  width:auto;
42
43
  max-width:100%;
43
- table-layout:auto!important;
44
+ table-layout:fixed;
44
45
  border-collapse:collapse;
45
46
  border-spacing:0;
46
47
  }
@@ -65,7 +66,7 @@ const WORD_PAGE_CSS = `
65
66
  margin-bottom:0;
66
67
  }
67
68
  .msdoc-page .msdoc-cell span{
68
- white-space:normal!important;
69
+ white-space:normal;
69
70
  }
70
71
  .msdoc-page .msdoc-page-break{
71
72
  display:none;
@@ -235,7 +236,7 @@ function makeMsDocResponsive(target) {
235
236
  let currentScale = 1;
236
237
  let currentFitScale = 1;
237
238
  const clampScale = (scale) => {
238
- return Math.min(MSDOC_MAX_SCALE, Math.max(MSDOC_MIN_SCALE, Number(scale.toFixed(2))));
239
+ return clampWordScale(scale, MSDOC_MIN_SCALE, MSDOC_MAX_SCALE);
239
240
  };
240
241
  const applyResponsiveLayout = () => {
241
242
  let firstScale = currentScale;
@@ -287,37 +288,54 @@ function makeMsDocResponsive(target) {
287
288
  maxScale: MSDOC_MAX_SCALE
288
289
  });
289
290
  const setUserZoom = (nextZoom) => {
290
- userZoom = Math.min(6, Math.max(0.2, Number(nextZoom.toFixed(2))));
291
+ if (!isPositiveFinite(nextZoom))
292
+ return getZoomState();
293
+ userZoom = nextZoom;
291
294
  view === null || view === void 0 ? void 0 : view.cancelAnimationFrame(resizeFrame);
292
295
  applyResponsiveLayout();
293
296
  return getZoomState();
294
297
  };
295
298
  const setAbsoluteScale = (scale) => {
296
- return setUserZoom(scale / Math.max(currentFitScale, 0.01));
299
+ if (!isPositiveFinite(scale))
300
+ return getZoomState();
301
+ return setUserZoom(clampScale(scale) / currentFitScale);
297
302
  };
298
303
  const readFitPageSize = () => {
299
304
  var _a;
300
305
  const root = (_a = pages[0]) === null || _a === void 0 ? void 0 : _a.querySelector('.msdoc-root');
306
+ if (!(root === null || root === void 0 ? void 0 : root.offsetWidth) || !root.offsetHeight)
307
+ return null;
301
308
  return {
302
- width: (root === null || root === void 0 ? void 0 : root.offsetWidth) || MSDOC_PAGE_SIZE.width,
303
- height: MSDOC_PAGE_SIZE.height
309
+ width: root.offsetWidth,
310
+ height: Math.max(root.scrollHeight, root.offsetHeight)
304
311
  };
305
312
  };
306
313
  const fitDoc = (request) => {
307
314
  var _a, _b;
308
315
  const pageSize = readFitPageSize();
316
+ const viewport = readWordFitViewport(target, request);
317
+ if (!pageSize || !viewport) {
318
+ return {
319
+ applied: false,
320
+ mode: request.mode,
321
+ resize: request.resize,
322
+ source: request.source,
323
+ reason: 'unmeasurable',
324
+ provider: 'zoom'
325
+ };
326
+ }
309
327
  const mode = request.mode === 'auto' ? 'width' : request.mode;
310
328
  const scale = resolveFileViewerFitScale({
311
329
  mode,
312
- viewportWidth: Math.max(1, request.viewportWidth || target.clientWidth || 0),
313
- viewportHeight: Math.max(1, request.viewportHeight || target.clientHeight || 0),
330
+ viewportWidth: viewport.width,
331
+ viewportHeight: viewport.height,
314
332
  contentWidth: pageSize.width,
315
333
  contentHeight: pageSize.height,
316
334
  currentScale,
317
335
  minScale: (_a = request.minScale) !== null && _a !== void 0 ? _a : MSDOC_MIN_SCALE,
318
336
  maxScale: (_b = request.maxScale) !== null && _b !== void 0 ? _b : MSDOC_MAX_SCALE
319
337
  });
320
- if (!scale) {
338
+ if (!scale || !isPositiveFinite(scale)) {
321
339
  return {
322
340
  applied: false,
323
341
  mode: request.mode,
@@ -364,37 +382,38 @@ function makeMsDocResponsive(target) {
364
382
  target.classList.remove('msdoc-zoom-viewer');
365
383
  };
366
384
  }
367
- /**
368
- * 渲染 doc 文件
369
- */
370
385
  export default async function render(buffer, target, context) {
371
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
386
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
372
387
  const rendered = await parseMsDocToHtml(buffer, {
373
388
  renderOptions: {
374
389
  reviewMode: (_c = (_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.reviewMode) !== null && _c !== void 0 ? _c : 'all',
375
- css: `${defaultMsDocCss()}\n${WORD_PAGE_CSS}`,
390
+ css: defaultMsDocCss(),
376
391
  externalLinkPolicy: (_f = (_e = (_d = context === null || context === void 0 ? void 0 : context.options) === null || _d === void 0 ? void 0 : _d.docx) === null || _e === void 0 ? void 0 : _e.externalLinkPolicy) !== null && _f !== void 0 ? _f : 'block',
377
392
  externalResourcePolicy: (_j = (_h = (_g = context === null || context === void 0 ? void 0 : context.options) === null || _g === void 0 ? void 0 : _g.docx) === null || _h === void 0 ? void 0 : _h.externalResourcePolicy) !== null && _j !== void 0 ? _j : 'block'
378
393
  }
379
394
  });
395
+ return mountWordDocument(rendered, target, context);
396
+ }
397
+ export function mountWordDocument(rendered, target, context) {
398
+ var _a, _b;
380
399
  const targetWindow = target.ownerDocument.defaultView;
381
400
  if (!targetWindow) {
382
401
  throw new Error('The DOC target must belong to a browser document');
383
402
  }
384
403
  const style = target.ownerDocument.createElement('style');
385
404
  style.dataset.msdoc = '';
386
- style.textContent = rendered.css;
405
+ style.textContent = `${rendered.css}\n${WORD_PAGE_CSS}`;
387
406
  const content = target.ownerDocument.createElement('div');
388
407
  content.append(sanitizeMsDocHtml(wrapAsWordPages(rendered.html), targetWindow));
389
408
  target.replaceChildren(style, ...Array.from(content.childNodes));
390
409
  const disposeResponsive = makeMsDocResponsive(target);
391
- (_k = context === null || context === void 0 ? void 0 : context.registerExportAdapter) === null || _k === void 0 ? void 0 : _k.call(context, {
410
+ (_a = context === null || context === void 0 ? void 0 : context.registerExportAdapter) === null || _a === void 0 ? void 0 : _a.call(context, {
392
411
  includeDocumentStyles: false,
393
412
  getPrintMaskPages: () => Array.from(target.querySelectorAll('.msdoc-page')),
394
413
  printStyle: buildMsDocPrintStyle,
395
414
  toHtml: () => prepareMsDocCloneForExport(target)
396
415
  });
397
- (_l = context === null || context === void 0 ? void 0 : context.registerThumbnailAdapter) === null || _l === void 0 ? void 0 : _l.call(context, {
416
+ (_b = context === null || context === void 0 ? void 0 : context.registerThumbnailAdapter) === null || _b === void 0 ? void 0 : _b.call(context, {
398
417
  getTarget: () => target.querySelector('.msdoc-page') || target
399
418
  });
400
419
  return {
@@ -1,31 +1,11 @@
1
- import type { Options, renderAsync } from '@file-viewer/docx';
1
+ import type { Options } from '@file-viewer/docx';
2
2
  import { type FileRenderContext, type FileViewerDocxOptions, type FileViewerRenderedInstance as AppWrapper } from '@file-viewer/core';
3
- type DocxRenderAsync = typeof renderAsync;
4
3
  type DocxExternalLinkPolicy = NonNullable<FileViewerDocxOptions['externalLinkPolicy']>;
5
4
  type DocxExternalResourcePolicy = NonNullable<FileViewerDocxOptions['externalResourcePolicy']>;
6
5
  type DocxRenderOptions = Partial<Options> & {
7
6
  externalLinkPolicy: DocxExternalLinkPolicy;
8
7
  externalResourcePolicy: DocxExternalResourcePolicy;
9
8
  };
10
- export declare const isMissingDocxHeaderFooterRootError: (error: unknown) => boolean;
11
- /**
12
- * Some malformed or partially generated DOCX files reference a header/footer
13
- * part whose parsed root is missing. @file-viewer/docx 0.3.21 skips that part;
14
- * this retry keeps older installed engines usable while the dependency update
15
- * rolls through lockfiles and private registries.
16
- */
17
- export declare const renderDocxWithHeaderFooterFallback: (render: DocxRenderAsync, buffer: ArrayBuffer, target: HTMLDivElement, options: Options) => Promise<boolean>;
18
- /**
19
- * WPS and Word can store a page background as a document-level VML fill. The
20
- * DOCX engine intentionally ignores that legacy drawing node, so resolve only
21
- * its package-local image relationship here and leave all body layout to it.
22
- */
23
- export declare const resolveDocxPageBackgroundImage: (buffer: ArrayBuffer, createXmlParser?: () => Pick<DOMParser, "parseFromString">) => Promise<string | undefined>;
24
- export declare const applyDocxPageBackgroundImage: (target: HTMLDivElement, imageUrl: string | undefined) => number;
25
- export declare const applyDocxExternalLinkPolicy: (target: Pick<ParentNode, "querySelectorAll">, policy: DocxExternalLinkPolicy) => number;
26
9
  export declare const createDocxOptions: (target: HTMLDivElement, context: FileRenderContext | undefined, notifyProgressiveRender: () => void) => DocxRenderOptions;
27
- /**
28
- * 渲染docx文件
29
- */
30
10
  export default function (buffer: ArrayBuffer, target: HTMLDivElement, context?: FileRenderContext): Promise<AppWrapper>;
31
11
  export {};