@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/dist/wordMl.js CHANGED
@@ -15,17 +15,31 @@ const aliases = {
15
15
  'first-line-chars': 'firstLineChars', 'left-chars': 'leftChars', 'right-chars': 'rightChars',
16
16
  };
17
17
  export function decodeWordMlBytes(buffer) {
18
+ var _a, _b;
18
19
  const bytes = new Uint8Array(buffer);
19
20
  const utf16le = (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0x3c && bytes[1] === 0);
20
21
  const utf16be = (bytes[0] === 0xfe && bytes[1] === 0xff) || (bytes[0] === 0 && bytes[1] === 0x3c);
21
- return new TextDecoder(utf16le ? 'utf-16le' : utf16be ? 'utf-16be' : 'utf-8').decode(bytes);
22
+ const utf8Bom = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
23
+ const detected = utf16le ? 'utf-16le' : utf16be ? 'utf-16be' : utf8Bom ? 'utf-8' : null;
24
+ const prefix = new TextDecoder(detected || 'windows-1252').decode(bytes.subarray(0, 1024));
25
+ const declaration = (_a = /^<\?xml\s[^?]*\?>/.exec(prefix)) === null || _a === void 0 ? void 0 : _a[0];
26
+ const encoding = declaration && ((_b = /\sencoding\s*=\s*(["'])([A-Za-z][A-Za-z0-9._-]*)\1/.exec(declaration)) === null || _b === void 0 ? void 0 : _b[2]);
27
+ let decoder;
28
+ try {
29
+ decoder = new TextDecoder(detected || encoding || 'utf-8', { fatal: true });
30
+ if (detected && encoding) {
31
+ const declared = new TextDecoder(encoding).encoding;
32
+ const genericUtf16 = /^utf-16$/i.test(encoding) && detected.startsWith('utf-16');
33
+ if (declared !== detected && !genericUtf16) {
34
+ throw new Error('Encoding declaration conflicts with the byte signature.');
35
+ }
36
+ }
37
+ return decoder.decode(bytes);
38
+ }
39
+ catch (error) {
40
+ throw new Error(`Invalid or unsupported Word 2003 XML encoding: ${error instanceof Error ? error.message : String(error)}`);
41
+ }
22
42
  }
23
- /**
24
- * Adapt the single-file Word 2003 XML container to the existing OOXML renderer.
25
- * This is structural conversion, not HTML insertion or remote conversion. Body,
26
- * styles, table properties, section geometry and VML remain renderer-owned.
27
- * Inline headers/footers become package parts; only embedded image data is read.
28
- */
29
43
  export async function convertWordMlToDocx(buffer, target) {
30
44
  var _a, _b, _c, _d;
31
45
  const source = decodeWordMlBytes(buffer);
@@ -42,11 +56,12 @@ export async function convertWordMlToDocx(buffer, target) {
42
56
  const body = Array.from(input.documentElement.children).find(element => element.namespaceURI === WORDML && element.localName === 'body');
43
57
  if (!body)
44
58
  throw new Error('Word 2003 XML document has no body.');
59
+ const fontTable = Array.from(input.documentElement.children).find(child => child.namespaceURI === WORDML && child.localName === 'fonts');
60
+ const defaultFonts = fontTable && Array.from(fontTable.children).find(child => child.namespaceURI === WORDML && child.localName === 'defaultFonts');
45
61
  const zip = new JSZip();
46
62
  const serializer = new Serializer();
47
63
  const overrides = [];
48
64
  const images = new Map();
49
- // Never resolve a WordML image name as a file/HTTP URL. It must have binData.
50
65
  for (const binary of Array.from(input.getElementsByTagNameNS(WORDML, 'binData'))) {
51
66
  const name = binary.getAttributeNS(WORDML, 'name') || '';
52
67
  if (images.has(name))
@@ -97,7 +112,6 @@ export async function convertWordMlToDocx(buffer, target) {
97
112
  if (isWord && element.localName === 'binData')
98
113
  return;
99
114
  if (element.namespaceURI === AUX) {
100
- // wx:sect and wx:sub-section are grouping hints, not content containers.
101
115
  for (const child of Array.from(element.childNodes))
102
116
  appendConverted(child, parent, part, depth + 1);
103
117
  return;
@@ -124,7 +138,6 @@ export async function convertWordMlToDocx(buffer, target) {
124
138
  for (const attribute of Array.from(element.attributes)) {
125
139
  if (attribute.namespaceURI === XMLNS)
126
140
  continue;
127
- // VML image references are replaced with package-local relationships below.
128
141
  if (namespace === VML && (localName === 'imagedata' || localName === 'fill') && (attribute.localName === 'src' || attribute.localName === 'href'))
129
142
  continue;
130
143
  const wordAttribute = attribute.namespaceURI === WORDML;
@@ -150,8 +163,6 @@ export async function convertWordMlToDocx(buffer, target) {
150
163
  document.documentElement.appendChild(outputBody);
151
164
  for (const child of Array.from(body.childNodes))
152
165
  appendConverted(child, outputBody, 'document.xml');
153
- // In OOXML only the final section properties may be a direct body child.
154
- // Earlier WordML wx:sect properties belong on the preceding paragraph.
155
166
  for (const section of Array.from(outputBody.children)) {
156
167
  if (section.localName !== 'sectPr' || section === outputBody.lastElementChild)
157
168
  continue;
@@ -175,11 +186,29 @@ export async function convertWordMlToDocx(buffer, target) {
175
186
  ['docPr', 'settings', 'settings.xml', 'settings'],
176
187
  ]) {
177
188
  const element = Array.from(input.documentElement.children).find(child => child.namespaceURI === WORDML && child.localName === sourceName);
178
- if (!element)
189
+ if (!element && !(sourceName === 'styles' && defaultFonts))
179
190
  continue;
180
191
  const part = createDocument(rootName);
181
- for (const child of Array.from(element.childNodes))
192
+ if (sourceName === 'styles' && defaultFonts) {
193
+ const defaults = part.createElementNS(WORD, 'w:docDefaults');
194
+ const runDefaults = part.createElementNS(WORD, 'w:rPrDefault');
195
+ const properties = part.createElementNS(WORD, 'w:rPr');
196
+ const fonts = part.createElementNS(WORD, 'w:rFonts');
197
+ for (const [legacy, modern] of [['ascii', 'ascii'], ['h-ansi', 'hAnsi'], ['fareast', 'eastAsia'], ['cs', 'cs']]) {
198
+ const value = defaultFonts.getAttributeNS(WORDML, legacy);
199
+ if (value !== null)
200
+ fonts.setAttributeNS(WORD, `w:${modern}`, value);
201
+ }
202
+ properties.appendChild(fonts);
203
+ runDefaults.appendChild(properties);
204
+ defaults.appendChild(runDefaults);
205
+ part.documentElement.appendChild(defaults);
206
+ }
207
+ for (const child of Array.from((element === null || element === void 0 ? void 0 : element.childNodes) || [])) {
208
+ if (child === defaultFonts)
209
+ continue;
182
210
  appendConverted(child, part.documentElement, path);
211
+ }
183
212
  zip.file(`word/${path}`, serialize(part));
184
213
  relate('document.xml', type, path);
185
214
  overrides.push([`/word/${path}`, `application/vnd.openxmlformats-officedocument.wordprocessingml.${type}+xml`]);
@@ -0,0 +1,2 @@
1
+ import { type FileRenderContext } from '@file-viewer/core';
2
+ export declare function renderWordText(buffer: ArrayBuffer, target: HTMLDivElement, kind: 'html' | 'text', context?: FileRenderContext): import("@file-viewer/core").FileViewerRenderedInstance;
@@ -0,0 +1,57 @@
1
+ import { decodeFileViewerTextBuffer } from '@file-viewer/core';
2
+ import { defaultMsDocCss } from '@file-viewer/doc';
3
+ import { mountWordDocument } from './wordDoc.js';
4
+ import { sanitizeFileViewerRtfHtml } from './sanitizeRtf.js';
5
+ let scopeNumber = 0;
6
+ export function renderWordText(buffer, target, kind, context) {
7
+ var _a, _b, _c, _d, _e, _f, _g;
8
+ const text = decodeFileViewerTextBuffer(buffer).text;
9
+ const document = target.ownerDocument;
10
+ const scope = `word-text-${++scopeNumber}`;
11
+ const body = document.createElement('div');
12
+ body.dataset.wordText = scope;
13
+ let rules = '';
14
+ if (kind === 'text') {
15
+ const pre = document.createElement('pre');
16
+ pre.style.cssText = 'white-space:pre-wrap;overflow-wrap:anywhere;font:inherit';
17
+ pre.textContent = text;
18
+ body.append(pre);
19
+ }
20
+ else {
21
+ const view = document.defaultView;
22
+ if (!view)
23
+ throw new Error('The Word HTML target must belong to a browser document');
24
+ const options = {
25
+ externalLinkPolicy: (_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.externalLinkPolicy) !== null && _c !== void 0 ? _c : 'block',
26
+ externalResourcePolicy: (_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.externalResourcePolicy) !== null && _f !== void 0 ? _f : 'block'
27
+ };
28
+ body.innerHTML = sanitizeFileViewerRtfHtml(document, text, options);
29
+ const parsed = new view.DOMParser().parseFromString(text, 'text/html');
30
+ const Sheet = view.CSSStyleSheet;
31
+ if (Sheet && typeof Sheet.prototype.replaceSync === 'function') {
32
+ const sheet = new Sheet();
33
+ const holder = document.createElement('span');
34
+ for (const style of Array.from(parsed.querySelectorAll('style'))) {
35
+ try {
36
+ sheet.replaceSync(style.textContent || '');
37
+ for (const rule of Array.from(sheet.cssRules)) {
38
+ if (rule.type !== 1)
39
+ continue;
40
+ const authorRule = rule;
41
+ const selectors = authorRule.selectorText.split(',').map(selector => selector.trim());
42
+ if (!selectors.every(selector => /^[\w\s.#>+~*-]+$/.test(selector)))
43
+ continue;
44
+ holder.style.cssText = authorRule.style.cssText;
45
+ const safe = document.createElement('template');
46
+ safe.innerHTML = sanitizeFileViewerRtfHtml(document, holder.outerHTML, options);
47
+ const declaration = (_g = safe.content.firstElementChild) === null || _g === void 0 ? void 0 : _g.style.cssText;
48
+ if (declaration)
49
+ rules += selectors.map(selector => `[data-word-text="${scope}"] ${selector}`).join(',') + `{${declaration}}\n`;
50
+ }
51
+ }
52
+ catch { }
53
+ }
54
+ }
55
+ }
56
+ return mountWordDocument({ html: body.outerHTML, css: `${defaultMsDocCss()}\n${rules}` }, target, context);
57
+ }
@@ -0,0 +1,7 @@
1
+ import type { FileViewerFitRequest } from '@file-viewer/core';
2
+ export declare function isPositiveFinite(value: number): boolean;
3
+ export declare function clampWordScale(value: number, minimum: number, maximum: number): number;
4
+ export declare function readWordFitViewport(target: HTMLElement, request: FileViewerFitRequest): {
5
+ width: number;
6
+ height: number;
7
+ } | null;
@@ -0,0 +1,15 @@
1
+ export function isPositiveFinite(value) {
2
+ return Number.isFinite(value) && value > 0;
3
+ }
4
+ export function clampWordScale(value, minimum, maximum) {
5
+ return Math.min(maximum, Math.max(minimum, value));
6
+ }
7
+ export function readWordFitViewport(target, request) {
8
+ var _a, _b;
9
+ const width = (_a = request.viewportWidth) !== null && _a !== void 0 ? _a : target.clientWidth;
10
+ const height = (_b = request.viewportHeight) !== null && _b !== void 0 ? _b : target.clientHeight;
11
+ if (![width, height, target.clientWidth, target.clientHeight].every(isPositiveFinite)) {
12
+ return null;
13
+ }
14
+ return { width, height };
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@file-viewer/renderer-word",
3
- "version": "3.1.2",
3
+ "version": "3.2.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Standalone DOCX, DOC, and OpenDocument renderer for File Viewer; RTF parsing is an explicit opt-in capability.",
@@ -28,8 +28,7 @@
28
28
  },
29
29
  "repository": {
30
30
  "type": "git",
31
- "url": "git+https://github.com/flyfish-dev/file-viewer.git",
32
- "directory": "packages/renderers/word"
31
+ "url": "git+https://github.com/flyfish-dev/file-viewer.git"
33
32
  },
34
33
  "homepage": "https://doc.file-viewer.app/guide/on-demand-renderers",
35
34
  "bugs": {
@@ -51,30 +50,47 @@
51
50
  "./package.json": "./package.json"
52
51
  },
53
52
  "files": [
54
- "dist",
53
+ "dist/docxExport.d.ts",
54
+ "dist/docxExport.js",
55
+ "dist/docxFrames.d.ts",
56
+ "dist/docxFrames.js",
57
+ "dist/index.d.ts",
58
+ "dist/index.js",
59
+ "dist/openDocument.d.ts",
60
+ "dist/openDocument.js",
61
+ "dist/optionalCapabilities.d.ts",
62
+ "dist/optionalCapabilities.js",
63
+ "dist/sanitizeRtf.d.ts",
64
+ "dist/sanitizeRtf.js",
65
+ "dist/wordContainer.d.ts",
66
+ "dist/wordContainer.js",
67
+ "dist/wordDoc.d.ts",
68
+ "dist/wordDoc.js",
69
+ "dist/wordDocx.d.ts",
70
+ "dist/wordDocx.js",
71
+ "dist/wordMl.d.ts",
72
+ "dist/wordMl.js",
73
+ "dist/wordText.d.ts",
74
+ "dist/wordText.js",
75
+ "dist/wordViewport.d.ts",
76
+ "dist/wordViewport.js",
55
77
  "file-viewer.capability.json",
56
- "README.md",
78
+ "LICENSE",
57
79
  "README.en.md",
58
- "LICENSE"
80
+ "README.md"
59
81
  ],
60
82
  "dependencies": {
61
- "@file-viewer/core": "3.1.2",
62
- "@file-viewer/doc": "3.1.2",
63
- "@file-viewer/docx": "0.3.32",
83
+ "@file-viewer/core": "3.2.1",
84
+ "@file-viewer/doc": "3.2.1",
85
+ "@file-viewer/docx": "0.3.35",
64
86
  "jszip": "3.10.2"
65
87
  },
66
- "devDependencies": {
67
- "rtf.js": "^3.0.9",
68
- "jsdom": "^27.4.0",
69
- "typescript": "^6.0.3"
70
- },
71
88
  "fileViewer": {
72
- "capabilityManifest": "./file-viewer.capability.json"
89
+ "capabilityManifest": "./file-viewer.capability.json",
90
+ "distribution": {
91
+ "schemaVersion": 1,
92
+ "mode": "runtime-only"
93
+ }
73
94
  },
74
- "license": "Apache-2.0",
75
- "scripts": {
76
- "build": "tsc -b tsconfig.json && node --test test/*.test.mjs",
77
- "type-check": "tsc -b tsconfig.json",
78
- "verify:rtf-security": "npm exec --yes --package playwright@1.61.1 -- node scripts/verify-rtf-link-policy.mjs"
79
- }
80
- }
95
+ "license": "Apache-2.0"
96
+ }
@@ -1,8 +0,0 @@
1
- /**
2
- * A paragraph-relative vertical anchor makes that paragraph an absolute-position
3
- * containing block. Its horizontal axis can still be relative to the column or
4
- * page margins: paragraph indentation must not be added to that authored offset.
5
- * Keep the engine's original CSS length and correct only the containing-block
6
- * origin. Recompute after fitting/resizing; never accumulate pixel corrections.
7
- */
8
- export declare function correctDocxMixedAnchorOrigins(section: HTMLElement): void;
@@ -1,60 +0,0 @@
1
- const authoredLeft = new WeakMap();
2
- const number = (value) => Number.parseFloat(value) || 0;
3
- /**
4
- * A paragraph-relative vertical anchor makes that paragraph an absolute-position
5
- * containing block. Its horizontal axis can still be relative to the column or
6
- * page margins: paragraph indentation must not be added to that authored offset.
7
- * Keep the engine's original CSS length and correct only the containing-block
8
- * origin. Recompute after fitting/resizing; never accumulate pixel corrections.
9
- */
10
- export function correctDocxMixedAnchorOrigins(section) {
11
- var _a;
12
- const view = section.ownerDocument.defaultView;
13
- if (!view)
14
- return;
15
- const pageRect = section.getBoundingClientRect();
16
- const pageStyle = view.getComputedStyle(section);
17
- const pageWidth = number(pageStyle.width) + (pageStyle.boxSizing === 'border-box' ? 0 :
18
- number(pageStyle.paddingLeft) + number(pageStyle.paddingRight) + number(pageStyle.borderLeftWidth) + number(pageStyle.borderRightWidth));
19
- const scale = pageWidth ? pageRect.width / pageWidth : 0;
20
- if (!Number.isFinite(scale) || scale <= 0)
21
- return;
22
- for (const anchor of section.querySelectorAll('[data-docx-anchor-horizontal="column"], [data-docx-anchor-horizontal="margin"]')) {
23
- const paragraph = anchor.closest('[data-docx-anchor-context="paragraph"]');
24
- if (!paragraph || anchor.offsetParent !== paragraph || view.getComputedStyle(anchor).position !== 'absolute' || !anchor.style.left)
25
- continue;
26
- // Cell-relative drawings are left to the engine's layoutInCell policy.
27
- if (paragraph.closest('td, th'))
28
- continue;
29
- const root = anchor.dataset.docxAnchorHorizontal === 'margin'
30
- ? section : paragraph.closest('article, header, footer');
31
- if (!root || !section.contains(root) && root !== section)
32
- continue;
33
- const rootStyle = view.getComputedStyle(root);
34
- const rootRect = root.getBoundingClientRect();
35
- let origin = rootRect.left + (number(rootStyle.borderLeftWidth) + number(rootStyle.paddingLeft)) * scale;
36
- const paragraphStyle = view.getComputedStyle(paragraph);
37
- const paragraphRect = paragraph.getBoundingClientRect();
38
- if (root !== section) {
39
- const count = number(rootStyle.columnCount);
40
- const width = number(rootStyle.columnWidth);
41
- if (count > 1 || width > 0) {
42
- const gap = rootStyle.columnGap === 'normal' ? number(rootStyle.fontSize) : number(rootStyle.columnGap);
43
- const contentWidth = root.clientWidth - number(rootStyle.paddingLeft) - number(rootStyle.paddingRight);
44
- const columns = count > 0 ? count : Math.max(1, Math.floor((contentWidth + gap) / (width + gap)));
45
- const stride = (contentWidth + gap) / columns;
46
- if (stride > 0) {
47
- const unindentedLeft = (paragraphRect.left - origin) / scale - number(paragraphStyle.marginLeft);
48
- origin += Math.round(unindentedLeft / stride) * stride * scale;
49
- }
50
- }
51
- }
52
- const containingOrigin = paragraphRect.left + number(paragraphStyle.borderLeftWidth) * scale;
53
- const correction = (origin - containingOrigin) / scale;
54
- if (!Number.isFinite(correction))
55
- continue;
56
- const left = (_a = authoredLeft.get(anchor)) !== null && _a !== void 0 ? _a : anchor.style.left;
57
- authoredLeft.set(anchor, left);
58
- anchor.style.left = Math.abs(correction) < 0.01 ? left : `calc(${left} + ${correction.toFixed(4)}px)`;
59
- }
60
- }