Sync snapshot (2026-09-09) (#271)

- **New app: GenOffice HTML.** Open, edit and generate .html pages: a source pane with a sandboxed live preview, click-to-select elements with a floating toolbar and style panel, device-size preview, image tools and a present mode. AI generates whole pages from a brief with style directions and offers page-wide Restyle, Theme and Summarize. Export to Word runs locally through the built-in html2docx converter (native, editable OOXML; no print-to-PDF detour).
- **AI:** separate BYOK providers for web search, image generation and image/video analysis; new Codex App Server provider; Ask AI quotes the selected text and keeps it highlighted while it runs; custom AI panel text size; blocked requests retry through the Chromium network stack.
- **App:** global AutoSave setting shared by every editor; AI panel text size and chat spellcheck toggles (genoffice#249); Czech (cs) UI locale (genoffice#259); Save As defaults to the document's folder; PDF export no longer aborts on CJK file paths on Windows.
- **Docs:** Export as HTML; comments and replies edit in place from the comments pane; the caret can leave a trailing table (genoffice#266); spellcheck re-marks text as soon as it is re-enabled; AI edits are character-precise on partial selections; zoom keeps the scroll position; pasting a cell from Sheets takes the destination font.
- **Sheets:** Find no longer freezes on wide or streamed grids; Replace searches as you type; cached values of external-workbook formulas are kept instead of #ERROR! (genoffice#235); "number stored as text" is a warning, not an error (genoffice#236); paste repeats into the target range like Excel; filter criteria survive save/reopen; saves retry when Windows locks the file; many Excel-fidelity fixes for column widths, row heights, charts, slicers, number formats and CJK fonts.
- **Slides:** PDF export works for large presentations (genoffice#264); EMF/WMF picture fonts and East Asian theme fonts resolve correctly; decks with missing layouts or embedded styles still open; outline-only pie slices render.
- **PDF:** highlight and underline geometry aligns with the text; Shift+arrows extend the selection instead of paging.
- **Markdown:** Find and replace (Ctrl+F / Ctrl+H) (genoffice#253); mermaid code blocks render as diagrams (genoffice#263); better print quality.
- Thanks to community contributors @GoodScholar, @aniruddhaadak80 and @Sun8854, and to @hanyscz, @qgzln, @zyp997, @bisslot, @krakotay and @Ben03151 for the reports.

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-09-09 18:19:13 +08:00
committed by GitHub
co-authored by GenOffice
parent fa58fff047
commit d24c964a3e
678 changed files with 75586 additions and 7492 deletions
+719
View File
@@ -0,0 +1,719 @@
# HTML → DOCX Conversion Logic and Architecture
This document describes the conversion logic implemented in `packages/html2docx`. It is not a strict attribute-by-attribute translator from the HTML spec to the OOXML spec, but a hybrid converter based on "real browser rendering + document intent recognition + native Word reconstruction".
## 1. Goals and basic principles
The goals of the converter are:
1. Run on Linux or macOS without depending on Microsoft Word.
2. Keep body text, headings, lists, tables, and forms editable as much as possible.
3. Keep layout and visual effects as close as possible to the HTML rendered in Chromium.
4. Use local screenshots for effects that Word is not good at expressing, rather than rasterizing the whole page.
5. Keep the converter independent and not modify existing business code.
The most important design principle currently is "structure first, visual fallback second":
- Content that can be reliably mapped to Word is generated as native OOXML.
- Gradients, complex SVGs, badges, and pure decoration that cannot be reliably mapped are rendered as local images.
- Page backgrounds and absolute-positioned decorations are generated as floating images that do not enter the body text flow.
- No PDF intermediate format is used, to avoid losing semantics, text structure, and editability.
## 2. Overall pipeline
```text
HTML file or URL
│
▼
Headless Chromium loads the page
│
├─ Wait for network resources and web fonts
├─ Detect the HTML's design width
└─ Re-render at the design width
│
▼
Read the DOM, computed style, and real geometric dimensions
│
▼
Recognize document structure, generate an intermediate representation (IR)
│
├─ Editable structures: paragraphs, headings, lists, tables, cards, forms
└─ Image fallback: gradients, SVG, badges, page decoration, backgrounds
│
▼
Collect DOM elements that need screenshots according to the IR
│
▼
Use the docx library to generate native OOXML
│
▼
DOCX
│
▼
Microsoft Word exports PDF/PNG, compared against HTML screenshots for regression
```
Code responsibilities:
- `tools/cli.ts`: command-line entry point (Playwright driver over a local Chrome).
- `src/convert.ts`: orchestrates browser loading, IR extraction, screenshot collection, and the generation flow.
- `src/extract.ts`: a lightweight assembly entry point for the browser extraction functions.
- `src/browser/core/`: shared-scope extraction modules for style, text, lists, layout, classifiers, etc.
- `src/browser/`: independent browser modules for tables, pages, form media, and visual fallback.
- `src/generate.ts`: a lightweight orchestration entry point for the DOCX generation flow.
- `src/generate/`: modules for page setup, rendering context, Word styles, streaming nodes, and table rendering.
Because the browser extraction layer needs to be serialized by `page.evaluate` into a single self-contained function, `src/browser/core/` uses function-body fragments split by responsibility, which `extract.ts` assembles on the Node side in a fixed order. Peripheral, independent capabilities are injected via `page.addScriptTag`, rather than stuffing every implementation back into a single file.
## 3. Browser rendering stage
### 3.1 Chrome selection
`convert.ts` looks for a browser in the following order:
1. The `CHROME_PATH` environment variable
2. Google Chrome on macOS
3. Common Google Chrome / Chromium paths on Linux
The package talks to the browser through the `BrowserDriver` interface (`src/driver.ts`); the CLI and tests use the Playwright implementation over a locally installed Chrome, the app uses Electron's own webContents. Nothing downloads Chromium. When deploying to Linux, Chromium must be installed in the image, or `CHROME_PATH` must be set.
### 3.2 Initial A4 viewport
The initial viewport is:
```text
794 × 1123 CSS px
```
This is the approximate size of A4 at 96 DPI. `deviceScaleFactor` is set to 2 to improve the clarity of local screenshots.
### 3.3 Design-width detection
Many AI-generated documents use:
```css
body {
max-width: 880px;
}
```
If extraction is done directly in a 794px-wide viewport, extra line wrapping occurs, and table row heights are also enlarged. The current logic reads the computed `max-width` of `body`:
- If the design width is greater than the initial A4 viewport;
- and does not exceed 1600px;
- then the page is reloaded using a design viewport no smaller than 1024px.
This way, the line wrapping and line height extracted reflect the author's designed size, rather than the result of being squeezed by an overly narrow viewport beforehand.
If a flow document is roughly 0.96-1.22 page-heights tall in the browser (converted to an A4 ratio based on the design canvas width), it is treated as having single-page design intent, and `pageFitSqueeze` applies a light, whole-document compression to geometry and fonts, to avoid Word's slightly looser layout pushing the last block (an invoice stamp, a footer note) onto a second page. Table-heavy documents do not get the benefit of "Word layout being denser," so above 1.05 pages, no compression discount is applied. When generating OOXML, native font size, spacing, padding, line height, and borders are then scaled by `target page width / design viewport width`; local screenshots are scaled proportionally to the target content-area width.
### 3.4 Waiting for resources
While the page loads:
- it prefers to wait for `networkidle0`;
- after a timeout it proceeds with the conversion anyway, to avoid external resources blocking the whole task;
- it waits for `document.fonts.ready`;
- then waits for a brief settling period to let layout and fonts finish reflowing.
Inaccessible images are identified as broken during extraction and discarded.
## 4. Extraction layer: DOM and computed style
The `extractIR` function assembled by `extract.ts` is injected into the browser page and executed there, so it can directly access:
- DOM nodes;
- `getComputedStyle`;
- `getBoundingClientRect`;
- `::before` / `::after` pseudo-elements;
- image loading state;
- the real coordinates of text nodes.
The extracted content falls into four categories.
### 4.1 Text runs
Text is not handled crudely by DOM tag alone; instead it is converted into styled runs. Currently supported:
- font family and size;
- bold, italic, underline, strikethrough;
- font color;
- inline background color;
- letter spacing;
- superscript, subscript;
- `text-transform: uppercase`;
- hyperlinks;
- line breaks (including author line breaks split by line inside `white-space: pre-wrap/pre-line` text);
- small inline images;
- column positions and tab stops produced by wide spaces.
Consecutive text nodes and inline elements are merged into a single paragraph, so that not every `<span>` produces a separate paragraph.
### 4.2 Paragraph styling
Paragraph-level styling includes:
- left, center, right, and justified alignment;
- spacing above/below;
- line-height ratio;
- left indent;
- background color;
- left and bottom borders;
- the exact height of single-line color bars;
- CJK and Latin text markers.
The converter distinguishes between Word font leading for English and CJK:
- Latin line spacing uses a smaller compensation;
- CJK line spacing uses a larger compensation;
- single-line background heading bars use an exact line height, to prevent Word from stretching the color bar taller.
### 4.3 Geometry information
Structural nodes store the browser's measured dimensions, for example:
- table column widths;
- table row heights;
- flex/grid child widths;
- card padding;
- block margins;
- image width/height;
- absolute-positioned element coordinates;
- page content-area width/height;
- body's four-sided margins.
This data is used to suppress Word's AutoFit and default paragraph leading.
### 4.4 Page setup
After extraction, a `docsettings` node is generated, which stores body's actual four-sided margins:
```js
{
type: 'docsettings',
marginsPx: {
top,
bottom,
left,
right,
},
}
```
The DOCX no longer uniformly uses a fixed 2cm top/bottom margin; instead it tries to use the HTML's actual page padding. This resolves the issue of "the content size is correct, but the last form box is pushed to a second page by the fixed page margin."
## 5. Intent-recognition layer: DOM → IR
The IR is an intermediate representation between browser structure and Word structure. It proactively discards unimportant HTML implementation details and retains only the document intent needed to generate Word output.
Current main node types:
| IR type | Meaning | Word output |
| ------------- | ------------------------------------------- | ----------------------------------------------- |
| `docsettings` | Page margins | Section page margin |
| `heading` | Heading | Heading Paragraph |
| `para` | Ordinary paragraph | Paragraph + TextRun |
| `list` | Ordered/unordered list | Native Word numbering |
| `table` | HTML/CSS Grid table | Fixed-layout Word Table |
| `card` | Card with background, border, and padding | Single-cell Table |
| `kpirow` | flex/grid horizontal layout | Single-row, multi-column table |
| `formfield` | Input box, textarea, select box | Underlined paragraph or single-cell table |
| `code` | Multi-line monospace text | Monospace-shaded paragraph |
| `image` | Ordinary image or local screenshot | Inline ImageRun |
| `floatimg` | Page decoration, signature, footer | Floating ImageRun |
| `pagebg` | Page background | Floating image/background color behind the page |
| `pagebreak` | Forced page break | PageBreak |
| `hr` | Horizontal rule or pseudo-element color bar | Paragraph bottom border |
| `spacer` | Large vertical blank space | Empty paragraph with exact height |
### 5.1 Classification order
The classification order matters a great deal. `processElement` currently handles things roughly in the following priority:
1. Skip invisible elements and irrelevant tags such as `script/style`.
2. Recognize large signatures at the bottom of the page.
3. Recognize absolute-positioned or fixed decoration.
4. Extract page breaks and large top-of-page blank space.
5. Handle native semantic tags:
- headings;
- HTML tables;
- lists;
- code;
- HR;
- images;
- forms.
6. Handle SVG, canvas, checkbox/radio.
7. Recognize badges, pills, decorative leaves, and gradient containers.
8. Recognize CSS Grid tables.
9. Recognize page-level multi-column layout.
10. Recognize multi-row, structurally uniform grid/flex layouts.
11. Recognize single-row flex/grid layouts.
12. Recognize cards.
13. Fall back to an ordinary paragraph and recurse into child nodes.
High-fidelity rules must come before generic block-level recursion; otherwise a complex component would be split into ordinary paragraphs prematurely.
## 6. Main structure-recognition logic
### 6.1 HTML tables
A native `<table>` has the following extracted:
- measured width of each column;
- measured height of each row;
- colspan;
- cell padding;
- borders on all four sides;
- background color;
- horizontal and vertical alignment;
- header rows;
- paragraphs or nested structures inside cells.
When generating:
- a fixed table layout is used;
- table grid column widths are written;
- cell widths are written at the same time;
- adjacent grid widths are merged according to colspan;
- row heights use the browser's measured values;
- `HeightRule.EXACT` is used when strict fidelity is required.
Setting both the table grid and cell widths at the same time is meant to stop Word's AutoFit from redistributing column widths based on text length.
### 6.2 CSS Grid tables
If a container contains multiple rows of a structurally identical Grid:
- the number of visible child items is the same in each row;
- the number of columns is within a reasonable range;
- the widths of each row are close to each other;
- there are enough rows or a clear outer border;
then it is converted into a `table`, rather than a set of independent text blocks.
This is used for questionnaires, class schedules, survey forms, and other templates that don't use `<table>`.
### 6.3 Flex/Grid horizontal rows
Side-by-side KPIs, personal-info bars, tag rows, page headers, etc. are converted into `kpirow`:
- column widths are computed from the real bounds of the child elements and the midpoints of the gaps between them;
- the left/center/right position of each child element within its corresponding column is detected;
- the parent container's row height and padding are stored;
- on the Word side, a fixed-layout, single-row, multi-column table is generated.
The default cap on child-element height is 500px (taller than that is treated as a page-level two-column layout); however, tall card rows (pricing plans) with ≥3 columns of similar width are relaxed to 950px — a Word page can still fit one such row, preserving the side-by-side structure.
If there is an absolute-positioned color block on the left side of the container:
- the color block becomes the first column on its own;
- the body content becomes the second column;
- the color block's width uses the browser's measured value;
- the body's left indent, which was originally relative to the whole container, is corrected.
This is how the header color block on the Service Evaluation page is handled.
### 6.4 Cards
Blocks with a background, border, left accent line, or noticeable padding are recognized as a `card`.
Cards are output as single-cell Word tables, preserving:
- background color;
- full border;
- left or top accent border;
- padding on all four sides;
- top/bottom margin;
- editable inner content.
A table rather than paragraph shading is used because Word's paragraph shading cannot reliably express four-sided padding and a complete card border.
**Flattening**: a light-colored top-level card (a full-page section) that is taller than half a page and allowed to break across pages cannot be expressed as a single-row table — Word nested tables cannot break across pages — so it is flattened into a sequential paragraph flow. During flattening, the card's shading is propagated to all child blocks: paragraph shading for para/heading, spacer paragraphs, list items, kpirow cells and gaps, and table cells; the spacing before/after each child block itself is marked with `ambientShading` for the surrounding section's background color, to avoid exposing the page background and creating stripes.
### 6.5 Page-level two columns
Page-level two-column layouts such as resumes are output as:
- a single row, two columns;
- a borderless Word table;
- each column placed in full inside its corresponding cell;
- table rows are allowed to break across pages;
- column background and inner padding are preserved.
The page is not sliced into a large number of small rows by Y coordinate, because that approach is prone to left/right column misalignment once Word paginates.
Paragraph and card spacing within columns is moderately compressed, to reduce extra pages caused by differences between the HTML and Word pagination engines.
### 6.6 Forms
Currently, real Word Content Controls are not generated; instead, visually editable forms are generated:
- input boxes with only a bottom border → a paragraph with a bottom border;
- boxed inputs, textareas, selects → a single-cell table;
- width/height, border, background, padding, and existing text are preserved;
- checkbox/radio → Unicode box or circle characters.
This approach is highly compatible but lacks the validation and field properties of real Word form controls.
### 6.7 Lists
Two sources are supported:
1. native `<ul>` / `<ol>`;
2. pseudo-lists exported by Word, e.g. Symbol-font characters such as "·", "•", "▪".
For pseudo-lists, the fake bullet is stripped from the text and converted into native Word numbering, avoiding duplicate dots.
### 6.8 Horizontal rules and pseudo-elements
`<hr>` and qualifying `::before` / `::after` bars have the following extracted:
- width proportion;
- height;
- color;
- left-aligned or centered.
On the Word side, these are rebuilt using an indented paragraph bottom border.
## 7. Image fallback strategy
### 7.1 Why not screenshot everything
A full-page screenshot achieves the highest static visual consistency, but leads to:
- text that cannot be edited;
- inability to search and copy;
- large file size;
- inability to paginate normally;
- unsuitability as a DOCX.
For this reason, only the local areas that Word struggles to express are currently screenshotted.
### 7.2 Content that gets screenshotted
Mainly includes:
- ordinary `<img>`;
- SVG and canvas;
- gradient-background containers;
- rounded pills and complex badges;
- small decorative shapes;
- icon-font elements with no text, whose glyph lives in `::before/::after`;
- complex badge grids;
- page background images;
- absolute-positioned decoration;
- oversized bottom signatures.
Elements to be screenshotted are given a unique `data-h2d-id`. `convert.ts` walks the IR to collect these IDs, then screenshots the corresponding DOM elements via Puppeteer.
### 7.3 Page background
The page background is copied to an offscreen backdrop:
- background color, image, size, position, and repeat mode are preserved;
- body/html backgrounds are supported;
- simple `::before` background overlays are supported.
While screenshotting, the other body child elements are temporarily hidden and only the background is kept, to avoid the body content being captured twice into the background image.
When generating the DOCX, the background image is placed behind the page as a behind-document floating image.
### 7.4 Absolute-positioned decoration
Absolute-positioned or fixed elements do not enter the body flow. Elements that satisfy the size and page-range limits are:
- screenshotted locally;
- stored with coordinates relative to the body content area;
- stored with the content area's width/height;
- scaled proportionally to the content area in Word;
- positioned as a floating image in the page-margin coordinate system.
Absolute-positioned elements that don't fall within the safe range are discarded, to avoid incorrect decoration covering the body content.
**In-ancestor decoration (`inParent`)**: if a decoration falls entirely within the nearest positioned ancestor box (a leaf icon to the right of a banner, a watermark numeral in the top-left corner of a section), the classifier additionally records its coordinates and the ancestor's width/height relative to that ancestor. Note that the positioned ancestor must be found by manually walking the parent chain — SVG elements have no `offsetParent`. On the generation side, when that ancestor is rendered as a card, the decoration is anchored to the card cell (`relativeFrom: column/paragraph`) and drawn on top of the shading (an underlying image would otherwise be covered by the cell shading); when the card is flattened, it is anchored to the zero-height anchor paragraph at the start of the flattened output, and the top blank space is only compressed down to a height that can still accommodate the decoration. This kind of decoration is not subject to the "first page only" restriction; when there is no card context to fall back on and it falls beyond the page-anchored path, decoration beyond the first page is discarded by the generation side (consistent with prior behavior).
## 8. DOCX generation logic
### 8.1 Units
Under the 794px A4 viewport, the base conversion relationships are:
```text
1 CSS px ≈ 15 twips
1 CSS px ≈ 1.5 half-points
1 CSS px ≈ 9525 EMU
```
Used respectively for:
- paragraphs, margins, table width/height;
- font size;
- floating-image coordinates.
When the HTML uses a wider design viewport, the above text and box-model sizes are also multiplied by the page scale ratio. Fonts retain a small amount of width compensation, because Word's Arial is usually narrower than Inter/Roboto as rendered in the browser; without this, the original line wrapping would be lost.
### 8.2 Font mapping
Word and browsers have different available fonts, so the generator includes a font-family mapping:
- monospace → Consolas;
- common sans-serif / Inter → Arial;
- common serif → Times New Roman;
- DM Serif / Playfair / Cormorant → Georgia;
- Archivo / Bebas / Oswald → Arial Narrow;
- script/cursive → Segoe Script;
- CJK sans-serif → Microsoft YaHei;
- CJK serif → SimSun.
If a Latin-font run actually contains CJK characters, it is switched to the corresponding CJK font, to avoid arbitrary Word fallback.
### 8.3 Paragraphs
Paragraph generation handles:
- TextRun styling;
- hyperlinks;
- tab stops;
- alignment;
- indentation;
- spacing above/below;
- line spacing;
- background and border;
- native bullets.
Headings enable `keepNext` and `keepLines`, to reduce cases where a heading lands at the bottom of a page and the body text gets pushed to the next page.
### 8.4 Tables
Word tables are the core of the current layout system, used not only for HTML tables but also for:
- flex horizontal rows;
- cards;
- page two-column layouts;
- form boxes;
- KPIs;
- color-block titles.
This makes it possible to take advantage of Word's:
- fixed column widths;
- cell shading;
- cell margins;
- row height;
- vertical alignment;
- row pagination control.
### 8.5 Spacing
Ordinary paragraphs use Word paragraph spacing.
A table itself cannot reliably carry block-level margin above/below, so a spacer paragraph with an exact height is inserted before and after the table. Small spacing is not forced to write a visible character; larger spacing uses a zero-width character to prevent Word from collapsing it.
The current spacing priority is:
1. HTML computed margin;
2. HTML padding;
3. the browser's measured line height;
4. Word's minimum compatible default value.
Uniformly compressing all table padding to force a single page is no longer done, because it makes tables, cards, and body content overly cramped as a whole.
### 8.6 Pagination
The current pagination strategy:
- CSS `break-before: page` → an explicit page break;
- headings try to stay with the following paragraph;
- ordinary data-table rows are not split by default;
- page-level two-column tables are allowed to break across pages;
- KPI horizontal rows are kept whole;
- large cards are preferentially moved to the next page as a whole;
- a signature at the bottom of the page can be converted into a floating image fixed at the bottom.
Word and Chromium use different line-breaking algorithms, so pagination can only be approximated, not made mathematically identical.
## 9. Core lessons from current quality fixes
### 9.1 Color blocks becoming narrower
Cause:
- setting only the Table Grid width is not enough;
- Word's AutoFit keeps squeezing blank columns narrower.
Fix:
- use a fixed table layout;
- set both the grid column width and cell width at the same time;
- sum the actual spanned width for colspan.
### 9.2 Tables becoming overall too cramped
Cause:
- cell padding was once uniformly compressed in order to keep everything on a single page;
- table rows did not use the browser's measured height.
Fix:
- restore the computed padding;
- preserve the browser's row height;
- use an exact row height when strict fidelity is required;
- prioritize fixing the page margins instead of compressing the body content.
### 9.3 Incorrect line spacing
Cause:
- Word's built-in font leading;
- Latin and CJK have different leading;
- uniformly using the CJK compensation makes English text too cramped.
Fix:
- detect CJK per paragraph;
- use different line-height compensation for Latin and CJK;
- use an exact line height for single-line color blocks.
### 9.4 Content pushed to a second page
Cause:
- the DOCX fixedly used roughly a 2cm top/bottom page margin;
- the HTML actually might have only 32px of page padding.
Fix:
- extract the actual four-sided margins from body;
- write them into the DOCX section margin;
- preserve the content size instead of solving pagination by compressing tables.
### 9.5 A narrow viewport produces extra line wrapping
Cause:
- the template is designed at 880px;
- extracting directly in a 794px A4 viewport causes premature line wrapping.
Fix:
- detect body's `max-width`;
- re-render at the author's designed width;
- then map the structure onto an A4 Word page.
## 10. Verification process
Final quality must be judged against Microsoft Word:
1. Chrome captures a screenshot of the source HTML.
2. Run the converter to generate the DOCX.
3. Open the DOCX with Microsoft Word.
4. Word exports a PDF.
5. Convert the PDF to PNG.
6. Generate an HTML/Word side-by-side comparison image per page.
7. Check:
- number of document pages;
- page margins;
- font, font size, and line spacing;
- color block size;
- table column width and row height;
- card padding and inter-block spacing;
- image size and position;
- whether the content is still editable.
LibreOffice can quickly check whether a file is corrupted, but it cannot serve as the visual regression baseline, because its pagination, font, table, and background rules differ from Word's.
Regression baselines (source HTML, converted `.docx`, the PDF Word exports from it, and a side-by-side comparison image per template) are kept outside the repository.
## 11. Known limitations
### 11.1 Word and the browser are not the same layout engine
The following cannot be guaranteed to match exactly:
- automatic line wrapping;
- font fallback;
- font leading;
- pagination;
- the free-form layout of flex/grid;
- margin collapsing.
### 11.2 CSS support is not a complete spec implementation
This is currently not a general-purpose CSS-to-OOXML engine; it focuses on the high-frequency structures found in document templates. Complex selectors themselves are handled by the browser, but the mapping from computed style to Word properties remains a limited set.
### 11.3 Screenshotted areas are not editable
Fallback areas such as gradients, SVG, badges, page decoration, and backgrounds become images.
Native Word tables do not support the CSS `border-radius`. Currently, wide rounded title bars use a local screenshot while keeping the body text editable; the light-colored outer border of a rounded card is preferentially omitted, rather than outputting an incorrect right-angle border. If the rounded outer border must be fully preserved, a decorative background image or a screenshot of the whole card is needed as a further step.
### 11.4 Real Word forms are not yet implemented
Currently, forms are editable text and table appearances, not Content Controls, Legacy Form Fields, or ActiveX controls.
### 11.5 Multi-page backgrounds
Page background images are currently handled with the page-floating-image approach; a complete section/background model for complex, different backgrounds across multiple pages has not yet been formed.
### 11.6 Headers and footers
Currently, absolute-positioned headers/footers are mainly handled as page floating decoration, and have not been converted into native Word Header/Footer Parts.
### 11.7 Nesting depth
When cards and tables are nested too deeply, they are downgraded to ordinary paragraphs, to avoid generating deeply nested tables that Word doesn't support or that are extremely unstable.
## 12. Future direction
Suggested order for continued improvement:
1. Establish automated Word regression testing over a fixed set of templates.
2. Output the IR as JSON, to make it easier to pinpoint whether an issue is in extraction or generation.
3. Add element-level diagnostic logging: DOM selector → IR node → OOXML node.
4. Support native Word Header/Footer.
5. Support real Content Control forms.
6. Add multi-section, landscape pages, and custom paper sizes.
7. Establish font-availability detection and a font-substitution configuration.
8. Establish separate visual-diff thresholds for images, cards, and tables.
9. Consolidate template special cases into configurable rules, to reduce hardcoding.
10. Add timeouts, a browser pool, and resource-size and concurrency limits when running on a server.
## 13. Usage
Command line:
```bash
npx tsx packages/html2docx/tools/cli.ts input.html output.docx --verbose
```
Linux:
```bash
CHROME_PATH=/usr/bin/chromium npx tsx packages/html2docx/tools/cli.ts input.html output.docx
```
As a module: see [README.md](./README.md) — `convertHtmlToDocx({ url }, driver, options)` returns the DOCX bytes together with the IR and stats; the IR can be saved for debugging, rule analysis, or as a test snapshot.
## 14. Empirically observed behavior of the Word (Mac) pagination engine (measured in experiments, 2026-07)
The following conclusions were all obtained by manually constructing variant docx files and rendering/comparing them with the same build of Word; they are the basis for several defensive design choices in the converter — read this section before touching related code.
1. **A forced ~26px inset at the top of the page**: even with `pgMar top=0`, the first line still starts roughly 26px (~405 twips) below the top of the page, and this is unrelated to image height, paragraph-mark font size, or docGrid. Full-page screenshot slicing must therefore reserve a margin for this: the slice budget is 96% of the page height (pages.js), and the rendering fallback is content height − 45px (renderer.js pageScale). Otherwise the bottom ~25px of a slice gets silently cut off (this once caused the last line of a resume's CONTACT card to be lost).
2. **`keepNext` semantics only extend to the next paragraph**: when a heading has `keepNext` plus an ordinary spacer paragraph, Word only guarantees that "heading + spacer" stay on the same page — the body text still gets paginated away → an orphaned heading. Every spacer (and at most one subheading paragraph) between the heading and the body must carry `keepNext`.
3. **A keep-chain fallback drags along the table before it**: when the large block at the tail of a keepNext chain (a `cantSplit` card row) doesn't fit, Word doesn't just move the chain to the next page — it also drags along the table before the chain, even across paragraphs with kn=0 in between (neither empty paragraphs nor ZWSP paragraphs stop this). Therefore the trailing spacer must never carry `keepNext`, otherwise the entire document links into one chain, and Word paginates at an absurd point (an entire page with nothing but a heading).
4. **Body text ending with a table produces a ghost blank page**: when the last block in the body is a `tbl`, Word automatically appends a paragraph mark with the default line height; if the table happens to exactly fill the last page, that mark overflows into an entire extra page with nothing but the background. The generation layer must terminate with a 1px EXACT empty paragraph (page-settings.js renderSection); the same applies to table cells (the docx library likewise appends a default paragraph to a cell that ends with a table).
5. **Screenshots of transparent wrapper elements get embedded at the full box height**: a stretched photo container in a column layout (box height 1591px, with only the top ~300px actually visible) embedded as an inline image occupies space at the full box height, immediately pushing out an extra page. `markForScreenshot` crops elements that have "no own drawing, box height ≥600, and an invisible tail ≥150px" down to the bottom of the visible content.
## 15. Findings from the fourth round of fixes (2026-07-20, 30 samples)
1. **`w:lang w:val="zh-CN"` makes Word break Latin words character-by-character using CJK rules** (e.g. "Report" → "Rep/ort"). Controlled experiments show that the `w:wordWrap` element runs in the opposite direction and doesn't rescue this (val=0 = allow character-level breaking; under CJK lang, val=1 is also ineffective); the only effective fix is to keep docDefaults' `w:lang w:val` fixed at en-US, marking only `eastAsia` as CJK (page-settings.js). Note that the docx library silently drops the wordWrap option for ordinary paragraphs.
2. **Nested fixed-layout tables must have an explicit `tcW`**: Word for Mac collapses a nested fixed-layout table without `tcW` down to the grid's placeholder width (a ~100dxa sliver). `renderCard` now always emits the trio FIXED + columnWidths + cell width; an autofit nested card can get blown out by an unbreakable inner run (an nbsp used to fill a blank line) and pushed out past the right edge of its container, getting clipped.
3. **The centering offset from a wide-viewport reload is not a page margin**: after reloading at 1024px, body's auto-margin centers it; `docsettings` uses `canvasWidth = min(innerWidth, max(pageSizePx, bodyWidth))` as the measurement baseline and strips out the `centerOffset` — otherwise the whole document ends up narrowed by ~20% plus a false ~3cm margin.
4. **`oneLineWidthPx` must re-measure using the font after Word's mapping**: `convert.ts` injects `__h2dWordFontLineWidth` (with FONT_RULES serialized into the page); Cormorant → Georgia is 15-40% wider, and measuring directly with the browser's narrower font causes heading letters to drop to the next line (e.g. "EDUCATIO/N").
5. **`kpirow` widening order**: gap track → spare room in generator.avail (widen the table) → compress sibling columns. Widening the table directly when there's already spare room in the browser's layout is faithful to the source.
6. **Inline merging for deep flatten (`inlineCellPara`)**: a single para / a small checkbox formfield (box mode ≤20px) / a nested kpirow are recursively merged into one line of runs; the checkbox run must carry `text: ''` (`tabStopsFor` assumes `text` exists). This restored horizontal layouts such as "COMBUSTIBLE: ☐ GASOLINA ☐ DIÉSEL ☐ GAS".
7. **List bullet determination looks at the `li`, not the `ul`**: frameworks such as pico.css set `list-style: none` on `ul` but set the marker individually on `li`; `extractList` decides plain based on the `li`'s computed `listStyleType` (tables-lists.js).
8. **Circular badges** (`circularBadge`: border-radius ≥ height/2, width and height similar, no whitespace-only text): `display:flex` can also be screenshotted inline (`inlineBgHex` rejects non-inline, needing `bgHex` as a fallback), and the displayed size is capped at the parent font size × 1.35 — otherwise a 42px badge embedded at its original height raises the line box, pushing an ~800px `cantSplit` card (with Word's ×1.2 factor) over the page limit, producing an isolated hint-box page plus a fully blank page. After capping, 12 pages return to normal. Rectangular text chips still go through the text-run path so they remain searchable.
9. **`isBoxRow` column-count limit only counts child elements wider than 40px**: a "step ▶ step" flow diagram with 7 child elements (4 steps + 3 arrows) is no longer stacked vertically; geometric symbols such as ▶◀◆ (U+25A0-25FF) now go through SYMBOL_RE and render as text glyphs (Arial Unicode MS + FE0E), instead of turning into blue emoji; `align-self: center` child elements are mapped to cell-level `vAlign`.
10. **The hallucination rate of vision-LLM scoring is measured to be extremely high**: in this round, more than half of the "below-100" findings were disproved programmatically (line-merging in a `pdftotext` count, a `document.xml` count, an actual render). Review discipline: for any "missing content" finding, first run a `pdftotext | tr -d '\n' | grep -o` count and compare it against the HTML source before deciding whether to fix it.
+46
View File
@@ -0,0 +1,46 @@
# @genoffice/html2docx
HTML → DOCX conversion for the HTML app's "Export as Word": the page is rendered
in a real browser, reduced to a document intent tree (headings, paragraphs,
lists, tables, cards, KPI rows, form fields, page backgrounds…) and written out
as native OOXML with the `docx` library. Only visuals that have no Word
counterpart (charts, icons, decorated boxes) are screenshotted.
See [ARCHITECTURE.md](./ARCHITECTURE.md) for the pipeline, IR and OOXML
mapping.
## Usage
```ts
import { convertHtmlToDocx } from '@genoffice/html2docx'
const { docx, stats } = await convertHtmlToDocx({ url }, driver, {
onProgress: ({ stage, pct }) => …, // load | extract | screenshot | generate
signal, // AbortSignal
})
```
`driver` is a `BrowserDriver` (`src/driver.ts`): the host owns the browser and
supplies a page-like adapter. `src/drivers/playwright.ts` implements it over
playwright-core and a locally installed Chrome for tests and the CLI; the app
supplies an Electron `webContents` implementation. The converter never closes
the driver.
CLI (single file, needs Chrome; `CHROME_PATH` overrides the lookup):
```bash
npx tsx packages/html2docx/tools/cli.ts input.html output.docx --verbose
```
## Layout
- `src/browser/` — in-page code, plain JS kept verbatim: `core/*.js` are slices
of one `extractIR()` function body (assembled in `src/extract.ts` from `?raw`
imports), the other files install `__html2docx*` helper globals.
- `src/convert.ts` — orchestration: viewport/authored-width detection, lazy
image warm-up, extractor injection, element screenshots, generation.
- `src/generate/` — IR → OOXML (`docx` library).
- `tests/features.test.ts` — 66 end-to-end cases, each rendering in Chrome.
The generation layer was ported from untyped CommonJS with `strict: false`;
types are tightened file by file without logic changes.
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@genoffice/html2docx",
"version": "0.1.0",
"license": "Apache-2.0",
"private": true,
"type": "module",
"description": "HTML \u2192 DOCX conversion: in-browser intent-tree extraction, screenshots for unmappable visuals, native OOXML generation",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"docx": "^9.7.1"
},
"devDependencies": {
"@types/node": "^24.10.1",
"jszip": "^3.10.1",
"playwright-core": "^1.61.1",
"typescript": "^5.9.3",
"vite": "^7.3.6",
"vitest": "^4.1.11"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,245 @@
// Rendered math (KaTeX / MathJax / MathML): the internal spans are layout
// hacks — walking them yields garbage text runs ("y=ncx"). Screenshot the
// whole formula instead.
function isMathContainer(el) {
const tag = el.tagName;
if (tag === 'MATH' || tag === 'MJX-CONTAINER') return true;
const cls = el.classList;
return Boolean(
cls && (cls.contains('katex') || cls.contains('katex-display') || cls.contains('MathJax')),
);
}
function pseudoBullet(el) {
const s = getComputedStyle(el, '::before');
if (!s || s.content === 'none' || s.content === 'normal') return false;
const content = s.content.replace(/^['"]|['"]$/g, '').trim();
return BULLET_GLYPHS.has(content);
}
// Real-element twin of the painted ::before dot below: a small empty
// painted first child (<div class="dot"></div>) is a list marker, not a
// block — classifier would silently drop it.
function chipBulletRun(el) {
const first = [...el.children].find((child) => isVisible(child));
if (!first || first.childElementCount || (first.innerText || '').trim()) return null;
const r = first.getBoundingClientRect();
if (r.width < 4 || r.width > 14 || r.height < 4 || r.height > 14) return null;
const color = toHex(cs(first).backgroundColor);
if (!color) return null;
const round = parseFloat(cs(first).borderRadius) >= r.width / 2 - 1;
return {
text: `${round ? '●' : '■'} `,
color,
// the dot glyph inks ~60% of its em box: scale up to match the chip
sizePx: Math.max(8, Math.round(Math.min(r.width, r.height) / 0.6)),
};
}
function pseudoBulletRun(el) {
const s = getComputedStyle(el, '::before');
if (!s || s.content === 'none' || s.content === 'normal') return null;
const content = s.content.replace(/^['"]|['"]$/g, '').trim();
if (!content) {
// Painted dot bullet: empty ::before drawn as a small colored circle
// or square \u2014 emit an equivalent colored glyph run.
const dotW = parseFloat(s.width);
const dotH = parseFloat(s.height);
const dotColor = toHex(s.backgroundColor);
// Composite icon: ::before circle + ::after strokes (check-in-circle
// list markers) \u2014 a flat glyph drops the checkmark, so clip-screenshot
// the drawn icon box instead.
const after = getComputedStyle(el, '::after');
const afterPaints =
after &&
after.content !== 'none' &&
(parseFloat(after.borderLeftWidth) >= 1 ||
parseFloat(after.borderBottomWidth) >= 1 ||
Boolean(toHex(after.backgroundColor)));
if (
dotColor &&
afterPaints &&
s.position === 'absolute' &&
dotW >= 10 &&
dotW <= 28 &&
dotH >= 10 &&
dotH <= 28
) {
const host = el.getBoundingClientRect();
const x = host.left + (parseFloat(s.left) || 0);
const y = host.top + (parseFloat(s.top) || 0);
if (x >= 0 && y >= 0) {
const gapPx = 6;
return {
text: '',
inlineImage: true,
shotId: `h2d-${shotCounter++}`,
clip: {
x: Math.round(x),
y: Math.round(y),
width: Math.round(dotW + gapPx),
height: Math.round(dotH),
},
width: Math.round(dotW + gapPx),
height: Math.round(dotH),
};
}
}
if (dotColor && dotW >= 4 && dotW <= 14 && dotH >= 4 && dotH <= 14) {
const round = parseFloat(s.borderRadius) >= dotW / 2 - 1;
return {
text: `${round ? '\u25cf' : '\u25a0'}\u00a0`,
color: dotColor,
// the dot glyph inks ~60% of its em box: scale up to match the chip
sizePx: Math.max(8, Math.round(Math.min(dotW, dotH) / 0.6)),
};
}
return null;
}
// Numbered circle badge: content:counter(x) painted as a colored circle
// with a light number.
if (content.includes('counter(') && el.parentElement) {
const badgeW = parseFloat(s.width);
// gradient badges have a transparent backgroundColor: take the first
// gradient stop as the representative color
const gradientStop = s.backgroundImage.match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}/i)?.[0];
const badgeColor =
toHex(s.backgroundColor) ||
(gradientStop && toHex(gradientStop, { dropWhite: false }));
// Pseudo-elements have no DOM node to screenshot, but an absolutely
// positioned badge's rendered box is computable from the host rect +
// its own offsets/size — clip-screenshot it so size and gradient
// survive exactly.
const badgeH = parseFloat(s.height) || badgeW;
if (
badgeColor &&
s.position === 'absolute' &&
badgeW >= 14 &&
badgeW <= 72 &&
badgeH >= 14 &&
badgeH <= 72 &&
parseFloat(s.borderRadius) >= badgeW / 2 - 2
) {
const host = el.getBoundingClientRect();
const x = host.left + (parseFloat(s.left) || 0);
const y = host.top + (parseFloat(s.top) || 0);
if (x >= 0 && y >= 0) {
const gapPx = 8; // right whitespace baked in as the text gap
return {
text: '',
inlineImage: true,
shotId: `h2d-${shotCounter++}`,
clip: {
x: Math.round(x),
y: Math.round(y),
width: Math.round(badgeW + gapPx),
height: Math.round(badgeH),
},
width: Math.round(badgeW + gapPx),
height: Math.round(badgeH),
};
}
}
// Word has no circular chips — a negative circled digit (❶❷…) in the
// badge color reads the same.
if (badgeColor && badgeW >= 14 && parseFloat(s.borderRadius) >= badgeW / 2 - 2) {
const siblings = [...el.parentElement.children].filter(
(sibling) => sibling.tagName === el.tagName && isVisible(sibling),
);
const index = siblings.indexOf(el) + 1;
const glyph =
index >= 1 && index <= 10
? String.fromCodePoint(0x2775 + index)
: `${index}.`;
return {
text: `${glyph} `,
color: badgeColor,
sizePx: Math.max(10, Math.round(parseFloat(s.fontSize) * 1.15) || 16),
};
}
}
// Authored visible text prefixes ("◆ SLIDE ") count too, not only
// single-glyph markers.
const literalListMarker =
content.length <= 24 &&
!content.includes('counter(') &&
!content.includes('attr(') &&
!content.includes('url(');
if (!BULLET_GLYPHS.has(content) && !literalListMarker) return null;
return {
text: `${content}\u00a0`,
color: toHex(s.color) || undefined,
sizePx: parseFloat(s.fontSize) || undefined,
fontFamily: BULLET_GLYPHS.has(content) ? s.fontFamily || undefined : 'Arial Unicode MS',
};
}
function hrNode(el) {
const s = cs(el);
const r = el.getBoundingClientRect();
const body = document.body.getBoundingClientRect();
const border = borderSideOf(el, 'top') || borderSideOf(el, 'bottom');
return {
type: 'hr',
color: border?.color || bgHex(el) || 'CCCCCC',
heightPx: border?.widthPx || Math.max(1, Math.min(r.height, 8)),
widthFrac: body.width > 0 ? Math.min(1, r.width / body.width) : 1,
align:
Math.abs(r.left + r.width / 2 - (body.left + body.width / 2)) < 12
? 'center'
: 'left',
};
}
function thinRuleNode(el) {
if ((el.innerText || '').trim() || el.children.length) return null;
const r = el.getBoundingClientRect();
const parentWidth = el.parentElement?.getBoundingClientRect().width || r.width;
if (r.height < 1 || r.height > 8 || r.width < parentWidth * 0.5) return null;
const border = borderSideOf(el, 'top') || borderSideOf(el, 'bottom');
const color = border?.color || bgHex(el);
if (!color) return null;
return {
type: 'hr',
color,
heightPx: border?.widthPx || Math.max(1, r.height),
widthFrac: Math.min(1, r.width / document.body.getBoundingClientRect().width),
align: 'left',
spacingBeforePx: Math.max(0, Math.round(parseFloat(cs(el).marginTop) || 0)),
spacingAfterPx: Math.max(0, Math.round(parseFloat(cs(el).marginBottom) || 0)),
};
}
function isOverlaidInfographic(el) {
const rect = el.getBoundingClientRect();
if (rect.width < 200 || rect.height < 160 || rect.width > 1000 || rect.height > 1000) {
return false;
}
const children = [...el.children].filter((child) => isVisible(child));
const layoutChild = children.find((child) => {
const display = cs(child).display;
return display === 'grid' || display === 'flex';
});
if (!layoutChild) return false;
const layoutRect = layoutChild.getBoundingClientRect();
return children.some((child) => {
if (child === layoutChild || cs(child).position !== 'absolute') return false;
const childRect = child.getBoundingClientRect();
if (childRect.width < 40 || childRect.height < 40) return false;
return (
childRect.left < layoutRect.right &&
childRect.right > layoutRect.left &&
childRect.top < layoutRect.bottom &&
childRect.bottom > layoutRect.top
);
});
}
function needsVisualEffectScreenshot(el) {
return globalThis.__html2docxVisualEffects.needsScreenshot(el, {
bgHex,
cs,
fullBorderOf,
});
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,294 @@
function makePara(runs, style) {
const first = runs[0];
const marker = first && first.text.trim();
if (marker && BULLET_GLYPHS.has(marker)) {
if (first.color && first.color !== '000000') {
return { type: 'para', runs, style };
}
let rest = runs.slice(1);
// swallow the separator gap right after the marker
if (rest.length && !rest[0].text.replace(/[\s\u00a0\t]/g, '')) rest = rest.slice(1);
if (rest.length) return { type: 'para', runs: rest, style: { ...style, bullet: true } };
}
if (first && /^[·•●▪‣◦∙]\s+/.test(first.text)) {
if (first.color && first.color !== '000000') {
return { type: 'para', runs, style };
}
const runsCopy = runs.slice();
runsCopy[0] = { ...first, text: first.text.replace(/^[·•●▪‣◦∙]\s+/, '') };
return { type: 'para', runs: runsCopy, style: { ...style, bullet: true } };
}
return { type: 'para', runs, style };
}
function makeParaNodes(runs, style) {
if (style.align !== 'justify' || !runs.some((run) => (run.text || '').includes('\n'))) {
return [makePara(runs, style)];
}
const lines = [[]];
for (const run of runs) {
if (run.inlineImage) {
lines[lines.length - 1].push(run);
continue;
}
const parts = (run.text || '').split('\n');
parts.forEach((part, index) => {
if (part) lines[lines.length - 1].push({ ...run, text: part });
if (index < parts.length - 1) lines.push([]);
});
}
const nonEmptyLines = lines.filter((line) => line.length);
if (nonEmptyLines.length <= 1) return [makePara(runs, style)];
return nonEmptyLines.map((line, index) => {
const lineStyle = { ...style };
if (index < nonEmptyLines.length - 1) delete lineStyle.align;
if (index > 0) delete lineStyle.spacingBeforePx;
if (index < nonEmptyLines.length - 1) delete lineStyle.spacingAfterPx;
return makePara(line, lineStyle);
});
}
function paraNodesFrom(el, decorations = true) {
// A painted display:block span inside a paragraph (scripture-line quote
// boxes with border-left + tint) renders as its own bordered block in
// the browser — merging it into the parent's runs loses both the
// paragraph break and the decoration. Split the paragraph around it.
const paintedBlocks = [...el.children].filter((child) => {
if (SKIP_TAGS.has(child.tagName) || !isVisible(child)) return false;
const childStyle = cs(child);
const painted = Boolean(bgHex(child)) || Boolean(borderLeftOf(child));
if (!painted) return false;
if (childStyle.display === 'block') return true;
// Inline quote box (scripture-line): border/tint + padding wrapping
// multiple lines reads as a block quote even at display:inline —
// short painted chips stay inline via the single-line guard.
if (parseFloat(childStyle.paddingLeft) < 6) return false;
if ((child.innerText || '').trim().length < 40) return false;
const lineHeight = parseFloat(childStyle.lineHeight) || 20;
return child.getBoundingClientRect().height > lineHeight * 1.4;
});
if (paintedBlocks.length && el.children.length <= 8) {
const style = paraStyleOf(el, decorations);
const nodes = [];
let pending = [];
const flushPending = () => {
const runs = trimRuns(runsFromNodes(pending, el));
pending = [];
if (runs.length) nodes.push(...makeParaNodes(runs, { ...style }));
};
for (const node of el.childNodes) {
if (paintedBlocks.includes(node)) {
flushPending();
const quoteRuns = trimRuns(runsFromNodes([...node.childNodes], node));
if (quoteRuns.length) {
const quoteStyle = paraStyleOf(node, decorations);
const bl = borderLeftOf(node);
if (bl) quoteStyle.borderLeft = bl;
const shading = bgHex(node);
if (shading) quoteStyle.shading = shading;
const padLeft = parseFloat(cs(node).paddingLeft) || 0;
const marginLeft = parseFloat(cs(node).marginLeft) || 0;
if (padLeft + marginLeft > 2) quoteStyle.indentLeftPx = Math.round(padLeft + marginLeft);
nodes.push(...makeParaNodes(quoteRuns, quoteStyle));
}
} else pending.push(node);
}
flushPending();
if (nodes.length) return nodes;
}
const runs = collectRuns(el);
if (!runs.length) return [];
if (el.tagName !== 'LI') {
const pseudoRun = pseudoBulletRun(el);
if (pseudoRun) runs.unshift(pseudoRun);
}
return makeParaNodes(runs, paraStyleOf(el, decorations));
}
const PHRASING_TAGS = new Set([
'STRONG', 'B', 'EM', 'I', 'U', 'S', 'SPAN', 'A', 'CODE', 'SMALL', 'SUB', 'SUP', 'MARK', 'ABBR', 'Q', 'CITE', 'KBD',
]);
function isInlineNode(node) {
if (node.nodeType === Node.TEXT_NODE) return true;
if (node.nodeType !== Node.ELEMENT_NODE) return false;
if (SKIP_TAGS.has(node.tagName)) return false;
if (node.tagName === 'IMG' || node.tagName === 'CANVAS' || node.tagName === 'svg') return false;
if (node.tagName === 'IFRAME' || node.tagName === 'VIDEO' || node.tagName === 'AUDIO') return false;
if (node.tagName === 'TEXTAREA' || node.tagName === 'SELECT') return false;
// checkbox inputs flow inline with their label; other inputs are blocks
if (node.tagName === 'INPUT') return isCheckboxLike(node);
// Compact circular number badges (30×30 inline-flex chips) must go through
// processElement for screenshot — otherwise they flatten to white bars.
// Wider tag pills stay inline so wrap/flow is preserved.
if (isCompactCircleBadge(node)) return false;
const d = cs(node).display;
if (
d === 'inline-block' &&
node.getBoundingClientRect().width >= 120 &&
fullBorderOf(node) &&
(parseFloat(cs(node).paddingLeft) >= 2 || parseFloat(cs(node).paddingTop) >= 2)
) {
return false;
}
if (d === 'inline' || d.startsWith('inline-') || d === 'contents') return true;
// Chrome reports display:block for phrasing elements that are actually
// laid out inline (flex containers blockify children; some elements
// compute block with no matching rule at all). Trust the geometry: if
// the element shares a line with adjacent text, it flows inline.
if (PHRASING_TAGS.has(node.tagName) && node.children.length === 0) {
const sameLine = (textNode, textEdge) => {
try {
const range = document.createRange();
range.selectNodeContents(textNode);
const rects = range.getClientRects();
const box = textEdge === 'last' ? rects[rects.length - 1] : rects[0];
const r = node.getBoundingClientRect();
if (!box) return false;
if (textEdge === 'last') return r.top < box.bottom - 2 && r.left >= box.right - 4;
return box.top < r.bottom - 2 && box.left >= r.right - 4;
} catch (e) {
return false;
}
};
const prev = node.previousSibling;
if (prev && prev.nodeType === Node.TEXT_NODE && prev.textContent.trim() && sameLine(prev, 'last')) {
return true;
}
const next = node.nextSibling;
if (next && next.nodeType === Node.TEXT_NODE && next.textContent.trim() && sameLine(next, 'first')) {
return true;
}
}
return false;
}
function attachBookmark(nodes, id) {
if (!id) return false;
for (const node of nodes) {
if (node.type === 'para' || node.type === 'heading') {
node.bookmarks = [...new Set([...(node.bookmarks || []), id])];
return true;
}
if (node.type === 'list' && node.items?.length) {
const item = node.items[0];
item.bookmarks = [...new Set([...(item.bookmarks || []), id])];
return true;
}
if (node.children && attachBookmark(node.children, id)) return true;
for (const cell of node.cells || []) {
if (cell.children && attachBookmark(cell.children, id)) return true;
}
}
return false;
}
// Walk a block container: consecutive inline siblings merge into one paragraph,
// block-level children are classified recursively.
function processChildren(el, depth, opts = {}) {
const decorations = opts.decorations !== false;
const out = [];
const containerStyle = cs(el);
const singleColumnGrid =
containerStyle.display === 'grid' &&
containerStyle.gridTemplateColumns.split(' ').filter(Boolean).length === 1;
const columnFlex =
containerStyle.display === 'flex' &&
(containerStyle.flexDirection === 'column' || containerStyle.flexDirection === 'column-reverse');
const stackGapPx =
singleColumnGrid || columnFlex
? Math.min(
120,
Math.max(
0,
parseFloat(containerStyle.rowGap) || parseFloat(containerStyle.gap) || 0,
),
)
: 0;
let emittedGroup = false;
let inlineBuffer = [];
const appendGroup = (nodes) => {
if (!nodes.length) return;
if (emittedGroup && stackGapPx > 0) out.push({ type: 'spacer', px: stackGapPx });
out.push(...nodes);
emittedGroup = true;
};
const flush = () => {
if (!inlineBuffer.length) return;
const runs = trimRuns(runsFromNodes(inlineBuffer, el));
if (runs.length) appendGroup(makeParaNodes(runs, paraStyleOf(el, decorations)));
inlineBuffer = [];
};
// CSS `order` / *-reverse reorders flex/grid items visually without
// touching the DOM: walking childNodes would emit e.g. the photo/content
// stack in authored order while the browser shows the reverse. Only
// reorder when the author opted in and no bare text is in play.
let iterNodes = el.childNodes;
if (
(containerStyle.display === 'grid' || containerStyle.display === 'flex') &&
([...el.children].some((c) => (parseInt(cs(c).order, 10) || 0) !== 0) ||
containerStyle.flexDirection.endsWith('-reverse')) &&
[...el.childNodes].every(
(n) => n.nodeType !== Node.TEXT_NODE || !n.textContent.trim(),
)
) {
iterNodes = [...el.children].sort((a, b) => {
const ra = a.getBoundingClientRect();
const rb = b.getBoundingClientRect();
return ra.top - rb.top || (DOC_RTL ? rb.left - ra.left : ra.left - rb.left);
});
}
for (const node of iterNodes) {
if (isInlineNode(node)) {
// An inline-block that starts on a fresh line below the buffered
// content is a visual block (inline-block heading + inline-block
// paragraph stacked by wrapping): break the paragraph between them.
if (
inlineBuffer.length &&
node.nodeType === Node.ELEMENT_NODE &&
cs(node).display.startsWith('inline-')
) {
const r = node.getBoundingClientRect();
// skip buffered whitespace-only text nodes to find the last element
let prevEl = null;
for (let i = inlineBuffer.length - 1; i >= 0; i--) {
const b = inlineBuffer[i];
if (b.nodeType === Node.TEXT_NODE && !b.textContent.trim()) continue;
if (b.nodeType === Node.ELEMENT_NODE) prevEl = b;
break;
}
const pr = prevEl && prevEl.getBoundingClientRect();
if (
pr &&
r.height > 0 &&
pr.height > 0 &&
r.top >= pr.bottom - 2 &&
r.width >= el.getBoundingClientRect().width * 0.4
) {
flush();
appendGroup(processElement(node, depth));
continue;
}
}
inlineBuffer.push(node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
flush();
const children = processElement(node, depth);
attachBookmark(children, node.id);
appendGroup(children);
}
}
flush();
return out;
}
return globalThis.__html2docxPages.build({
cs,
docRTL: DOC_RTL,
isVisible,
markForScreenshot,
nextShotId: () => `h2d-${shotCounter++}`,
processChildren,
processElement,
toHex,
});
@@ -0,0 +1,745 @@
// Regional_Indicator pairs (flag emoji \uD83C\uDDEC\uD83C\uDDE7) are not Extended_Pictographic, so
// match them explicitly or they stay in the body-font run and render as the
// bare letters ("GB").
const EMOJI_RE = /\p{Extended_Pictographic}|\p{Regional_Indicator}/u;
const EMOJI_SEQUENCE_RE =
/(\p{Regional_Indicator}{2}|\p{Extended_Pictographic}(?:\uFE0E|\uFE0F)?(?:\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0E|\uFE0F)?(?:\p{Emoji_Modifier})?)*)/gu;
// Arrows and misc technical symbols (↔ → ⇄ …): CJK body fonts often lack
// the glyph in Word and render a box. Split them into symbol-font runs.
const SYMBOL_RE = /[←-⇿■-◿⤀-⥿⬀-⯿]/;
const SYMBOL_SEQUENCE_RE = /([←-⇿■-◿⤀-⥿⬀-⯿]+)/g;
function splitEmojiRuns(runs) {
return runs
.flatMap((run) => {
// Arrows first: U+2194-21FF are Extended_Pictographic, but in prose
// they are text glyphs — the emoji font would paint them as blue
// emoji chips.
if (!run.text || !SYMBOL_RE.test(run.text)) return [run];
return run.text
.split(SYMBOL_SEQUENCE_RE)
.filter(Boolean)
// No VS15 injection: the symbol-font assignment already forces text
// presentation, and the selector pollutes copied/searched text.
.map((text) =>
SYMBOL_RE.test(text) ? { ...run, text, symbol: true } : { ...run, text },
);
})
.flatMap((run) => {
if (run.symbol || !run.text || !EMOJI_RE.test(run.text)) return [run];
return run.text
.split(EMOJI_SEQUENCE_RE)
.filter(Boolean)
.map((text) => ({ ...run, text, emoji: isColorEmoji(text) }));
});
}
// Only default-emoji-presentation glyphs (📘 🇬🇧 ⭐), a VS16-forced one
// (★️), or a flag pair get the unset-font color-emoji path. Text-presentation
// dingbats (★ ☆ ● ■ U+2605…) stay in the body font so they keep the run's
// color instead of turning into a colored emoji star.
const COLOR_EMOJI_RE = /\p{Emoji_Presentation}|\p{Regional_Indicator}/u;
function isColorEmoji(text) {
return COLOR_EMOJI_RE.test(text) || /️/.test(text);
}
// Collect styled text runs from a list of DOM nodes (text + inline elements).
// baseEl provides the coordinate frame for tab-stop measurement.
function runsFromNodes(nodes, baseEl) {
const runs = [];
const baseRect = baseEl ? baseEl.getBoundingClientRect() : null;
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
// A long run of spaces/nbsp is a column separator (Word-exported HTML
// spreads columns and right-aligns dates this way). Emit a tab marker
// and measure where the following content actually starts so the
// generator can place an equivalent tab stop.
const raw = node.textContent;
// newline-preserving white-space (pre-wrap message bodies): authored
// \n are real line/paragraph breaks, not collapsible spaces
if (raw.includes('\n') && node.parentElement) {
const ws = cs(node.parentElement).whiteSpace || '';
if (ws.startsWith('pre') || ws === 'break-spaces') {
const style = runStyleOf(node.parentElement);
raw.split('\n').forEach((line, i) => {
if (i) runs.push({ text: '\n', ...style });
const text = line.replace(/\s+/g, ' ');
if (text.trim()) runs.push({ text, ...style });
});
return;
}
}
const parts = raw.split(/(\s{6,})/);
let offset = 0;
for (const part of parts) {
if (part) {
let isSeparator = false;
let tabFrac = null;
if (/^\s{6,}$/.test(part) && baseRect && baseRect.width > 0) {
// Only a *rendered* wide gap is a column separator. Raw source
// may contain long space runs that the browser collapses to a
// single space (Word-exported HTML) — those must stay spaces.
try {
const range = document.createRange();
range.setStart(node, offset);
range.setEnd(node, offset + part.length);
const rect = range.getBoundingClientRect();
if (rect && rect.width > 14) {
isSeparator = true;
tabFrac = (rect.right - baseRect.left) / baseRect.width;
}
} catch (e) { /* fall through as plain space */ }
}
if (isSeparator && tabFrac != null && tabFrac >= 0.6) {
// Gap pushing content to the far right: right-aligned tab (dates).
runs.push({ text: '\t', tabFrac, ...runStyleOf(node.parentElement) });
} else if (isSeparator) {
// Mid-line column gap: fixed wide space (tab stops in Word are
// too fragile to reproduce arbitrary column positions).
runs.push({ text: '\u00a0\u00a0\u00a0 ', ...runStyleOf(node.parentElement) });
} else {
const text = part.replace(/\s+/g, ' ');
if (text) runs.push({ text, ...runStyleOf(node.parentElement) });
}
}
offset += part.length;
}
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
if (SKIP_TAGS.has(node.tagName)) return;
if (node.tagName === 'BR') {
// BR has a 0x0 rect, so this must come before the visibility check
runs.push({ text: '\n', ...runStyleOf(node.parentElement) });
return;
}
// Empty underline blanks can report ~1px height and fail isVisible.
{
const fillInEarly = fillInLineNode(node);
if (fillInEarly?.inline) {
const style = cs(node);
const fontSize = parseFloat(style.fontSize) || 14;
const spaceWidth = Math.max(3, fontSize * 0.45);
const count = Math.max(3, Math.round(fillInEarly.width / spaceWidth));
const bottom = fillInEarly.borders?.bottom;
runs.push({
text: '\u00a0'.repeat(count),
underline: true,
underlineStyle: bottom?.style || 'solid',
color: bottom?.color || '000000',
sizePx: fontSize,
preserveWhitespace: true,
});
return;
}
}
if (!isVisible(node)) return;
// Preceding content glued to this element in the source (no whitespace
// text node): a block child renders on its own LINE in the browser
// (August 16<span class="h3-sub" style="display:block">Arrival…), and
// an inline sibling separated by CSS margin needs a space — without
// either, the words fuse in Word ("August 16Arrival").
if (
runs.length &&
runs[runs.length - 1].text &&
!/\s$/.test(runs[runs.length - 1].text)
) {
if (cs(node).display === 'block') {
runs.push({ text: '\n', ...runStyleOf(node.parentElement || node) });
} else {
const prevSibling = node.previousSibling;
if (
prevSibling &&
prevSibling.nodeType === Node.TEXT_NODE &&
/\S$/.test(prevSibling.textContent)
) {
try {
const lastGlyph = document.createRange();
lastGlyph.setStart(prevSibling, prevSibling.textContent.length - 1);
lastGlyph.setEnd(prevSibling, prevSibling.textContent.length);
const prevRight = lastGlyph.getBoundingClientRect().right;
const glyphs = document.createRange();
glyphs.selectNodeContents(node);
const nodeLeft = glyphs.getBoundingClientRect().left;
if (nodeLeft - prevRight >= 3) {
runs.push({ text: ' ', ...runStyleOf(node.parentElement || node) });
}
} catch (e) {
/* no gap detected, nothing to add */
}
}
}
}
if (isMathContainer(node)) {
const r = node.getBoundingClientRect();
if (r.width >= 3 && r.height >= 6) {
const shot = markForScreenshot(node);
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: shot.width,
height: shot.height,
});
}
return;
}
if (node.tagName === 'SVG' || node.tagName === 'svg' || node.tagName === 'IMG') {
const r = node.getBoundingClientRect();
if (r.width <= 64 && r.height <= 64) {
const shot = markForScreenshot(node);
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: shot.width,
height: shot.height,
});
const style = cs(node);
const parentStyle = node.parentElement ? cs(node.parentElement) : null;
const gapPx = Math.max(
parseFloat(style.marginRight) || 0,
parseFloat(parentStyle?.columnGap) || parseFloat(parentStyle?.gap) || 0,
);
if (gapPx >= 4) {
const spaceWidth = Math.max(3, (parseFloat(parentStyle?.fontSize) || 14) * 0.3);
const count = Math.max(1, Math.round((gapPx - spaceWidth) / spaceWidth));
runs.push({
text: '\u00a0'.repeat(count),
...runStyleOf(node.parentElement || node),
preserveWhitespace: true,
});
}
}
return;
}
// Empty painted chip (legend color swatch, status dot): no text, no
// children, just a small background/border box \u2014 dropping it loses the
// color-to-meaning key, so inline-embed it like a small icon.
{
const chipStyle = cs(node);
const r = node.getBoundingClientRect();
if (
!node.childElementCount &&
!(node.innerText || '').trim() &&
r.width >= 4 && r.width <= 28 &&
r.height >= 4 && r.height <= 28 &&
(bgHex(node) ||
(chipStyle.backgroundImage || '').includes('gradient') ||
(parseFloat(chipStyle.borderTopWidth) > 0 && parseFloat(chipStyle.borderRadius) > 0))
) {
const shot = markForScreenshot(node);
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: shot.width,
height: shot.height,
});
const parentStyle = node.parentElement ? cs(node.parentElement) : null;
const gapPx = Math.max(
parseFloat(chipStyle.marginRight) || 0,
parseFloat(parentStyle?.columnGap) || parseFloat(parentStyle?.gap) || 0,
);
if (gapPx >= 4) {
const spaceWidth = Math.max(3, (parseFloat(parentStyle?.fontSize) || 14) * 0.3);
const count = Math.max(1, Math.round((gapPx - spaceWidth) / spaceWidth));
runs.push({
text: '\u00a0'.repeat(count),
...runStyleOf(node.parentElement || node),
preserveWhitespace: true,
});
}
return;
}
}
if (isCheckboxLike(node)) {
runs.push(checkboxNode(node));
return;
}
const nodeStyle = cs(node);
const nodeRect = node.getBoundingClientRect();
// A circular painted badge (numbered day markers) has no text-run
// equivalent — the round paint is the point. Plain rectangular chips
// stay text so they remain searchable.
const circularBadge =
(parseFloat(nodeStyle.borderRadius) || 0) >= nodeRect.height / 2 - 1 &&
Math.abs(nodeRect.width - nodeRect.height) <= nodeRect.height * 0.4 &&
!/\s/.test((node.innerText || '').trim());
const compactPaintedLabel =
(['inline-block', 'inline-flex', 'inline-grid'].includes(nodeStyle.display) ||
// a circular badge centering its digit with flex/grid still sits
// inline in its heading row
(circularBadge && ['flex', 'grid'].includes(nodeStyle.display))) &&
(nodeStyle.whiteSpace === 'nowrap' || circularBadge) &&
// inlineBgHex rejects non-inline displays; a flex badge paints its
// own background directly
Boolean(inlineBgHex(node) || (circularBadge && bgHex(node))) &&
(node.innerText || '').trim().length <= 30 &&
nodeRect.width >= 12 &&
nodeRect.width <= 220 &&
nodeRect.height >= 12 &&
nodeRect.height <= 50;
if (compactPaintedLabel) {
const shot = markForScreenshot(node);
// Label crushed by a too-narrow column (letters stacked vertically):
// ask the screenshot pass to relax it to its natural one-line size,
// and record that relaxed size (measured under nowrap) so the docx
// shows the image at its true aspect.
const crushed = node.scrollWidth > node.clientWidth + 2;
if (crushed) {
shot.unwrap = true;
const previousWhiteSpace = node.style.whiteSpace;
node.style.whiteSpace = 'nowrap';
shot.width = Math.min(220, node.scrollWidth + 2);
shot.height = node.clientHeight || shot.height;
node.style.whiteSpace = previousWhiteSpace || '';
}
// A circular badge taller than its line's text inflates the Word row
// height and pushes near-page-height cards past the page. Display it
// at the surrounding text's line scale; the PNG keeps full detail.
let displayWidth = shot.width;
let displayHeight = shot.height;
if (circularBadge && node.parentElement) {
const parentFont = parseFloat(cs(node.parentElement).fontSize) || 16;
const cap = Math.round(parentFont * 1.35);
if (displayHeight > cap) {
displayWidth = Math.round((shot.width * cap) / shot.height);
displayHeight = cap;
}
}
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: displayWidth,
height: displayHeight,
unwrap: shot.unwrap,
});
return;
}
if (
!(node.innerText || '').trim() &&
node.children.length === 0 &&
(nodeStyle.display === 'inline' || nodeStyle.display === 'inline-block') &&
nodeRect.width >= 4 &&
nodeRect.width <= 32 &&
nodeRect.height >= 4 &&
nodeRect.height <= 32
) {
const swatch = bgHex(node);
if (swatch) {
runs.push({
text: '\u25a0 ',
color: swatch,
sizePx: Math.max(nodeRect.width, nodeRect.height),
});
return;
}
}
const highlightedInline =
nodeStyle.display.startsWith('inline-') &&
Boolean(inlineBgHex(node)) &&
Boolean((node.innerText || '').trim());
const paddedSpaces = (px) => {
if (px < 2) return '';
const spaceWidth = Math.max(3, (parseFloat(nodeStyle.fontSize) || 14) * 0.3);
return '\u00a0'.repeat(Math.max(1, Math.round(px / spaceWidth)));
};
if (highlightedInline) {
const leftPad = paddedSpaces(parseFloat(nodeStyle.paddingLeft) || 0);
if (leftPad) runs.push({ text: leftPad, ...runStyleOf(node), preserveWhitespace: true });
}
const inlinePseudoRun = pseudoBulletRun(node);
if (inlinePseudoRun) runs.push(inlinePseudoRun);
for (const child of node.childNodes) walk(child);
// Symmetric to the block-BEFORE rule above: a block child also ends
// its own line, so following content (an eyebrow <span
// class="section-num" style="display:block"> glued before heading
// text) must not fuse onto it. trimRuns drops a trailing break.
if (
nodeStyle.display === 'block' &&
runs.length &&
runs[runs.length - 1].text &&
!/\n$/.test(runs[runs.length - 1].text)
) {
runs.push({ text: '\n', ...runStyleOf(node.parentElement || node) });
}
if (highlightedInline) {
const rightPad = paddedSpaces(parseFloat(nodeStyle.paddingRight) || 0);
if (rightPad) runs.push({ text: rightPad, ...runStyleOf(node), preserveWhitespace: true });
}
// Inline chip followed directly by text with no space character in the
// source (<span class="q-mark">Q</span>How...): the visual gap comes
// from min-width/margin/padding. Keep a space or the words glue.
const next = node.nextSibling;
if (
next &&
next.nodeType === Node.TEXT_NODE &&
/^\S/.test(next.textContent) &&
runs.length &&
runs[runs.length - 1].text &&
!/\s$/.test(runs[runs.length - 1].text)
) {
try {
const glyphs = document.createRange();
glyphs.selectNodeContents(node);
const glyphRight = glyphs.getBoundingClientRect().right;
const first = document.createRange();
first.setStart(next, 0);
first.setEnd(next, 1);
const nextLeft = first.getBoundingClientRect().left;
if (nextLeft - glyphRight >= 3) {
runs.push({ text: ' ', ...runStyleOf(node.parentElement || node) });
}
} catch (e) {
/* no gap detected, nothing to add */
}
}
}
for (const node of nodes) walk(node);
// Latin fragments with neutral punctuation inside an RTL context get
// bidi-reordered by Word ("Motorola 68010, supplier A" -> "Motorola
// supplier ,68010 A"): bracket them with LRM so the whole fragment
// stays one LTR segment. Runs carrying RTL script keep native ordering.
const isolated = runs.map((run) => {
if (!run.rtl || !run.text || run.inlineImage) return run;
if (/[֐-ࣿיִ-ﻼ]/.test(run.text)) return run;
if (!/[A-Za-z0-9]/.test(run.text)) return run;
if (!/[()[\]{}+*/,.:%~=-]/.test(run.text)) return run;
return { ...run, text: `‎${run.text}‎` };
});
return splitEmojiRuns(isolated);
}
// Measured gap between the element's left edge and its first visible glyph
// (covers both CSS padding-left and leading nbsp used as manual inset).
function textInsetLeft(el, rect) {
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
const m = node.textContent.match(/[^\s\u00a0]/);
if (!m) continue;
try {
const range = document.createRange();
range.setStart(node, m.index);
range.setEnd(node, m.index + 1);
const glyph = range.getBoundingClientRect();
if (glyph.width > 0) return glyph.left - rect.left;
} catch (e) {
return 0;
}
return 0;
}
return 0;
}
function trimRuns(runs) {
if (runs.length) {
if (!runs[0].preserveWhitespace) runs[0].text = runs[0].text.replace(/^\s+/, '');
if (!runs[runs.length - 1].preserveWhitespace) {
runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/\s+$/, '');
}
}
return runs.filter((r) => r.inlineImage || r.text.length > 0);
}
function collectRuns(el) {
return trimRuns(runsFromNodes([...el.childNodes], el));
}
function hasBlockChildren(el) {
let prevRect = null;
for (const child of el.children) {
if (SKIP_TAGS.has(child.tagName)) continue;
const d = cs(child).display;
if (d !== 'inline' && !d.startsWith('inline-')) return true;
// Two wide inline-blocks that render on separate lines (an inline-block
// heading too wide to share its line with the following inline-block
// paragraph) are visually blocks; merging them glues the texts. The
// width guard keeps small wrapping chips/badges on the inline path.
if (d.startsWith('inline-')) {
const r = child.getBoundingClientRect();
const wide = r.width >= el.getBoundingClientRect().width * 0.4;
if (prevRect && wide && r.height > 0 && r.top >= prevRect.bottom - 2) return true;
if (r.height > 0 && wide) prevRect = r;
else if (r.height > 0) prevRect = null;
}
}
return false;
}
// Replaced elements (img/svg/canvas) are excluded from inline runs, so a
// wrapper holding only an inline <img> must still walk children as blocks
// or the image silently disappears.
function isReplacedTag(el) {
const t = el.tagName;
if (
t === 'IMG' ||
t === 'CANVAS' ||
t === 'SVG' ||
t === 'svg' ||
t === 'IFRAME' ||
t === 'VIDEO' ||
t === 'AUDIO'
) {
return true;
}
if (t === 'TEXTAREA' || t === 'SELECT') return true;
if (t === 'INPUT') return !isCheckboxLike(el);
return false;
}
function hasReplacedDescendant(el) {
if (isReplacedTag(el)) return true;
for (const d of el.querySelectorAll(
'img, svg, canvas, iframe, video, audio, textarea, select, input:not([type=checkbox]):not([type=radio])',
)) {
if (isVisible(d)) return true;
}
return false;
}
// needs full block walk (vs a single merged paragraph)
function needsBlockWalk(el) {
return hasBlockChildren(el) || hasReplacedDescendant(el);
}
// decorations=false: only text-level styling (align/spacing/line-height).
// Used for paragraphs inside cards/cells where the container already owns
// the border and shading (avoids double-drawn vertical bars).
function paraStyleOf(el, decorations = true) {
const s = cs(el);
const style = {};
style.cjk = /[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]/.test(
el.textContent || '',
);
if (isRTL(el)) style.rtl = true;
const align = textAlignOf(el);
if (align) style.align = align;
const mb = parseFloat(s.marginBottom);
if (mb > 2) style.spacingAfterPx = Math.min(mb, 40);
const mt = parseFloat(s.marginTop);
if (mt > 2) style.spacingBeforePx = Math.min(mt, 40);
if (
style.spacingBeforePx &&
el.parentElement === document.body &&
!el.nextElementSibling
) {
// Large decorative signatures/flourishes at the end of a one-page
// document should use the remaining page space, not force a blank page.
style.spacingBeforePx = Math.min(style.spacingBeforePx, 2);
}
const ti = parseFloat(s.textIndent);
if (ti > 2) style.firstLineIndentPx = Math.min(ti, 100);
const lh = parseFloat(s.lineHeight);
const fsz = parseFloat(s.fontSize);
if (lh && fsz && lh / fsz > 1.25) style.lineRatio = Math.min(lh / fsz, 2.2);
if (style.cjk && lh && fsz) style.exactLineHeightPx = lh;
// Heading-like paragraph (bold, short, followed by content): keep it on
// the same page as what it introduces - FAQ questions, styled pseudo-
// headings etc. are divs/ps in HTML but behave like headings in print.
const headText = (el.innerText || '').trim();
if (
parseFloat(s.fontWeight) >= 600 &&
headText.length > 0 &&
headText.length <= 120 &&
!headText.includes('\n') &&
el.nextElementSibling
) {
style.keepNext = true;
// A short bold heading-like line must also not split across pages
// mid-word ("EDUCATIO" / "N").
style.keepLines = true;
}
// Short text rendered on ONE browser line: record the measured width so
// the generator can size narrow cells (or shrink display banners)
// instead of letting Word wrap "Sub Total :" or "INVOICE" mid-word.
if (fsz >= 10 && headText.length > 0 && headText.length <= 40 && !headText.includes('\n')) {
try {
const range = document.createRange();
range.selectNodeContents(el);
const textRect = range.getBoundingClientRect();
if (textRect.width > 0 && textRect.height <= fsz * 2.1) {
// Word's substituted font may run much wider than the webfont.
const wordWidth = window.__h2dWordFontLineWidth
? window.__h2dWordFontLineWidth(el)
: 0;
style.oneLineWidthPx = Math.round(Math.max(textRect.width, wordWidth));
}
} catch (e) {
/* leave unset */
}
}
if (!decorations) {
// decorations=false suppresses the container-owned paint, but a child
// with its own distinct background (label chips, "OBJECTION 1 OF 6"
// bars inside cards) must keep it.
const ownBg = bgHex(el);
if (ownBg && (!el.parentElement || ownBg !== bgHex(el.parentElement))) {
style.shading = ownBg;
}
return style;
}
// manual left inset (decoration: containers that own their inset skip it)
const padL = parseFloat(s.paddingLeft) + parseFloat(s.marginLeft);
if (padL >= 12) style.indentLeftPx = Math.min(padL, 200);
let shading = paintedBgHex(el);
// authored vertical padding on unshaded wrappers (e.g. a card body div)
// reads as spacing; shaded bars handle their padding via exact height
if (!shading) {
const pt = parseFloat(s.paddingTop) || 0;
const pb = parseFloat(s.paddingBottom) || 0;
if (pt > 2) style.spacingBeforePx = Math.min((style.spacingBeforePx || 0) + pt, 40);
if (pb > 2) style.spacingAfterPx = Math.min((style.spacingAfterPx || 0) + pb, 40);
}
if (shading) {
const textColor = toHex(s.color) || '000000';
const shadeLum = hexLuminance(shading);
const textLum = hexLuminance(textColor);
// Near-white chip on a colored parent + light text would become an
// invisible full-width white bar (benefit-num / step circles). Skip.
if (shadeLum > 230 && textLum > 200) {
shading = null;
}
}
if (shading) {
style.shading = shading;
// Word's single spacing for CJK fonts has much taller leading than the
// browser's, which fattens shaded bars. For single-line shaded
// paragraphs, pin the rendered height as an exact line height.
// Elements with a left accent border are note cards, not header bars -
// the color bar table would drop the accent, keep them as paragraphs.
const rect = el.getBoundingClientRect();
const lineH = lh || fsz * 1.35;
const radius = parseFloat(s.borderTopLeftRadius) || 0;
// Compact circular badges are not full-width header bars.
const compactBadge = rect.width > 0 && rect.width <= 72 && radius >= rect.height * 0.4;
if (
rect.height > 0 &&
lineH &&
rect.height < lineH * 1.9 &&
!borderLeftOf(el) &&
!compactBadge
) {
style.exactLineHeightPx = rect.height;
// single-line bar: safe to render as a fixed-height color bar table.
// (exactLineHeightPx alone also gets set for CJK line control and
// must NOT trigger the bar path - it would clip multi-line text.)
style.colorBar = true;
// Text inset inside the bar (padding-left and/or leading nbsp runs,
// which trimRuns strips from the text itself).
const inset = textInsetLeft(el, rect);
if (inset > 1) style.barInsetLeftPx = Math.min(inset, 60);
}
}
const bl = borderLeftOf(el);
if (bl) {
style.borderLeft = bl;
const paddingLeft = parseFloat(s.paddingLeft) || 0;
if (paddingLeft > 0) style.borderLeftSpacePx = Math.min(paddingLeft, 40);
}
const br = borderRightOf(el);
if (br) {
style.borderRight = br;
const paddingRight = parseFloat(s.paddingRight) || 0;
if (paddingRight > 0) style.borderRightSpacePx = Math.min(paddingRight, 40);
}
const bt = borderSideOf(el, 'top');
if (bt) style.borderTop = bt;
const bw = parseFloat(s.borderBottomWidth);
if (bw >= 1 && s.borderBottomStyle !== 'none') {
const color = toHex(s.borderBottomColor);
if (color) {
style.borderBottom = { color, widthPx: bw };
// dotted/dashed TOC separators must not harden into solid rules
if (s.borderBottomStyle === 'dotted' || s.borderBottomStyle === 'dashed') {
style.borderBottom.style = s.borderBottomStyle;
}
}
}
return style;
}
// Lowest visible pixel row (relative to the element top) of the element's
// own paint and descendants: text lines, replaced elements, painted boxes.
function visibleContentBottom(el, rect) {
let bottom = rect.top;
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const textNode = walker.currentNode;
if (!textNode.textContent.trim()) continue;
const range = document.createRange();
range.selectNodeContents(textNode);
for (const lineRect of range.getClientRects()) {
if (lineRect.height > 0 && lineRect.width > 0) bottom = Math.max(bottom, lineRect.bottom);
}
}
for (const child of el.querySelectorAll('*')) {
if (!isVisible(child)) continue;
const childRect = child.getBoundingClientRect();
if (childRect.height <= 0 || childRect.width <= 0) continue;
const childStyle = cs(child);
const painted =
child.matches('img, svg, canvas, video, iframe, input, textarea, select, button, hr') ||
childStyle.backgroundImage !== 'none' ||
childStyle.boxShadow !== 'none' ||
Boolean(toHex(childStyle.backgroundColor, { dropWhite: false })) ||
parseFloat(childStyle.borderTopWidth) > 0 ||
parseFloat(childStyle.borderBottomWidth) > 0;
if (painted) bottom = Math.max(bottom, Math.min(childRect.bottom, rect.bottom));
}
return bottom - rect.top;
}
function markForScreenshot(el) {
const id = `h2d-${shotCounter++}`;
el.setAttribute('data-h2d-id', id);
const r = el.getBoundingClientRect();
const s = cs(el);
const body = document.body.getBoundingClientRect();
const offLeft = r.left - body.left;
const offRight = body.right - r.right;
const align =
offLeft > 8 && offRight > 8 && Math.abs(offLeft - offRight) < Math.max(12, r.width * 0.08)
? 'center'
: offLeft > offRight * 3
? 'right'
: 'left';
// A transparent wrapper much taller than its visible content (e.g. a
// photo container stretched by the column) would embed a page-height
// mostly-empty image and strand a phantom page. Crop the invisible tail;
// painted elements keep their full box (the paint IS content).
let height = Math.round(r.height);
let clip;
const paintedSelf =
s.backgroundImage !== 'none' ||
s.boxShadow !== 'none' ||
Boolean(toHex(s.backgroundColor, { dropWhite: false })) ||
parseFloat(s.borderTopWidth) > 0 ||
parseFloat(s.borderBottomWidth) > 0;
if (r.height >= 600 && !paintedSelf) {
const contentBottom = visibleContentBottom(el, r);
if (contentBottom > 0 && r.height - contentBottom >= 150) {
height = Math.round(Math.min(r.height, contentBottom + 12));
clip = {
x: Math.max(0, Math.round(r.left)),
y: Math.max(0, Math.round(r.top)),
width: Math.round(r.width),
height,
};
}
}
return {
type: 'image',
shotId: id,
width: Math.round(r.width),
height,
...(clip ? { clip } : {}),
align,
spacingBeforePx: Math.max(0, Math.round(parseFloat(s.marginTop) || 0)),
spacingAfterPx: Math.max(0, Math.round(parseFloat(s.marginBottom) || 0)),
};
}
@@ -0,0 +1,460 @@
const SKIP_TAGS = new Set([
'SCRIPT', 'STYLE', 'LINK', 'META', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'TITLE',
]);
let shotCounter = 0;
const styleCache = new WeakMap();
function cs(el) {
if (!styleCache.has(el)) styleCache.set(el, getComputedStyle(el));
return styleCache.get(el);
}
function isVisible(el) {
const s = cs(el);
if (s.display === 'none' || s.visibility === 'hidden' || parseFloat(s.opacity) === 0) return false;
const r = el.getBoundingClientRect();
return r.width > 1 && r.height > 1;
}
function parseColor(colorStr) {
if (!colorStr) return null;
const m = colorStr.match(/rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,\s/]+([\d.]+))?\s*\)/);
if (!m) return null;
return {
r: +m[1],
g: +m[2],
b: +m[3],
a: m[4] === undefined ? 1 : parseFloat(m[4]),
};
}
function compositeRgb(color, backdrop) {
const a = color.a;
return {
r: Math.round(color.r * a + backdrop.r * (1 - a)),
g: Math.round(color.g * a + backdrop.g * (1 - a)),
b: Math.round(color.b * a + backdrop.b * (1 - a)),
a: 1,
};
}
function backdropRgbOf(el) {
const ancestors = [];
for (let cur = el?.parentElement; cur; cur = cur.parentElement) ancestors.push(cur);
let backdrop = { r: 255, g: 255, b: 255, a: 1 };
for (const ancestor of ancestors.reverse()) {
let color = parseColor(cs(ancestor).backgroundColor);
// A gradient-painted ancestor (background-image, not backgroundColor)
// is invisible to this walk otherwise: a translucent white overlay
// nested inside it composites against the default white backdrop and
// reads as near-white, so paintedBgHex's white-preserve fallback then
// hardcodes opaque FFFFFF — white text on a white cell, content
// effectively invisible. Approximate with the first gradient stop,
// same fallback bgHex uses for the gradient element itself.
if (!color || color.a < 0.05) {
const stop = gradientBaseStop(cs(ancestor).backgroundImage);
if (stop) color = parseColor(stop);
}
if (color && color.a >= 0.05) backdrop = compositeRgb(color, backdrop);
}
return backdrop;
}
// 'rgb(a)' -> 'RRGGBB' hex, or null for transparent / near-white.
// Light documents retain white-backed tints; dark documents pass their
// resolved ancestor paint so alpha colors keep their authored contrast.
function toHex(colorStr, { dropWhite = false, backdrop = null } = {}) {
const color = parseColor(colorStr);
if (!color) return null;
let { r, g, b, a } = color;
if (a < 0.05) return null;
if (a < 1) {
({ r, g, b } = compositeRgb(color, backdrop || { r: 255, g: 255, b: 255 }));
}
if (dropWhite && r > 250 && g > 250 && b > 250) return null;
const hex = (n) => n.toString(16).padStart(2, '0');
return (hex(r) + hex(g) + hex(b)).toUpperCase();
}
function hexLuminance(hex) {
if (!hex || hex.length < 6) return 0;
const n = parseInt(hex.slice(0, 6), 16);
if (Number.isNaN(n)) return 0;
const r = (n >> 16) & 255;
const g = (n >> 8) & 255;
const b = n & 255;
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Representative paint of a (possibly multi-layer) gradient background:
// the first sufficiently-opaque stop of the BOTTOM layer. CSS paints the
// first listed layer on top, so decorative low-alpha radial accents come
// first and the base gradient last — grabbing the first color in the whole
// string painted a dark hero with its 0.18-alpha gold accent (near-white
// shading under white text) instead of its dark base.
function gradientBaseStop(bgImage) {
if (!bgImage || !bgImage.includes('gradient')) return null;
const lastLayerStart = bgImage.lastIndexOf('-gradient(');
const layer = lastLayerStart >= 0 ? bgImage.slice(lastLayerStart) : bgImage;
let first = null;
for (const match of layer.matchAll(/rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}/g)) {
first = first || match[0];
const color = parseColor(match[0]);
// #hex tokens don't parse -> opaque; skip translucent overlay stops
if (!color || color.a >= 0.5) return match[0];
}
return first;
}
function bgHex(el) {
const solid = toHex(cs(el).backgroundColor, { dropWhite: true, backdrop: backdropRgbOf(el) });
if (solid) return solid;
// gradient-painted box with no solid backgroundColor: approximate with
// a representative stop, or light foreground text lands on a white page
const stop = gradientBaseStop(cs(el).backgroundImage);
if (stop) return toHex(stop, { dropWhite: true });
return null;
}
// True when el sits on a solid tint or a CSS background-image/gradient.
// White cards on those surfaces must keep FFFFFF or the backdrop shows through.
function hasTintedBackdrop(el) {
let anc = el.parentElement;
while (anc) {
if (bgHex(anc)) return true;
const s = cs(anc);
if (s.backgroundImage && s.backgroundImage !== 'none') return true;
if (anc === document.documentElement) break;
anc = anc.parentElement;
}
return false;
}
// Like bgHex, but keeps authored white/near-white paint when it covers a
// tinted or gradient backdrop (page wash, section band, etc.).
function paintedBgHex(el) {
const shaded = bgHex(el);
if (shaded) return shaded;
const raw = toHex(cs(el).backgroundColor);
if (!raw || !hasTintedBackdrop(el)) return null;
return 'FFFFFF';
}
// A compact painted pill/badge (inline-block, nowrap, own background):
// shared signal that a container's exact visual row must be screenshot.
function isCompactPaintedLabel(child) {
const childStyle = cs(child);
return (
childStyle.display === 'inline-block' &&
childStyle.whiteSpace === 'nowrap' &&
Boolean(bgHex(child)) &&
(child.innerText || '').trim().length <= 30 &&
child.getBoundingClientRect().height <= 50
);
}
function isMono(s) {
return /mono|consolas|courier|menlo|jetbrains/i.test(s.fontFamily);
}
const DOC_RTL =
getComputedStyle(document.body).direction === 'rtl' ||
getComputedStyle(document.documentElement).direction === 'rtl';
function isRTL(el) {
return cs(el).direction === 'rtl';
}
// Resolve text-align to a physical alignment, accounting for direction.
// In an RTL block, 'start' (the browser default) means the right side —
// Word's w:bidi paragraphs already default to right, so return undefined
// and let the bidi default apply; an explicit left/end must survive as
// physical left.
function textAlignOf(el) {
const s = cs(el);
const ta = s.textAlign;
if (ta === 'center') return 'center';
if (ta.startsWith('justify')) return 'justify';
if (s.direction === 'rtl') {
if (ta === 'left' || ta === 'end') return 'left';
return undefined; // start / right == bidi paragraph default
}
if (ta === 'right' || ta === 'end') return 'right';
return undefined;
}
function borderLeftOf(el) {
const s = cs(el);
const w = parseFloat(s.borderLeftWidth);
if (w >= 2 && s.borderLeftStyle !== 'none') {
const color = toHex(s.borderLeftColor);
if (color) return { color, widthPx: w };
}
// ::before painted as a narrow vertical accent bar (▎ section headings,
// timeline rails): visually a left border, but authored as a
// pseudo-element; gradient rails take their first color stop.
const before = getComputedStyle(el, '::before');
if (before && before.content === '""') {
const bw = parseFloat(before.width);
const bh = parseFloat(before.height);
const gradientStop = before.backgroundImage.match(/rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}/)?.[0];
const color = toHex(before.backgroundColor) || (gradientStop && toHex(gradientStop));
if (color && bw >= 2 && bw <= 10 && bh >= 10) {
return { color, widthPx: bw };
}
}
return null;
}
function borderRightOf(el) {
const s = cs(el);
const w = parseFloat(s.borderRightWidth);
if (w >= 2 && s.borderRightStyle !== 'none') {
const color = toHex(s.borderRightColor);
if (color) return { color, widthPx: w };
}
return null;
}
// ::before/::after painted as a full-width horizontal bar (decorative
// section rules). Not in the DOM, so probed via computed pseudo styles.
function pseudoBar(el, which) {
const s = getComputedStyle(el, which);
if (!s || s.content === 'none') return null;
if (s.position === 'fixed') return null;
const h = parseFloat(s.height);
if (!(h >= 1 && h <= 8)) return null;
const w = parseFloat(s.width);
const elW = el.getBoundingClientRect().width;
const fullRule = w >= elW * 0.5;
// absolute pseudos are usually dropped (not in flow), but a thin
// full-width bar hugging the element is a decorative underline that
// should survive (section-title::after { position:absolute; bottom:-5px })
if (s.position === 'absolute') {
const top = Math.abs(parseFloat(s.top));
const bottom = Math.abs(parseFloat(s.bottom));
const hugsEdge = Math.min(isNaN(top) ? 99 : top, isNaN(bottom) ? 99 : bottom) <= 12;
if (!fullRule || !hugsEdge) return null;
}
if (s.position !== 'absolute' && s.display !== 'block') return null;
const shortAccent = w >= 20 && w <= 120;
if (!(w > 0) || (!fullRule && !shortAccent)) return null;
const color = toHex(s.backgroundColor, { dropWhite: true });
if (!color) return null;
return {
type: 'hr',
color,
heightPx: h,
widthFrac: Math.min(1, w / elW),
short: shortAccent && !fullRule,
spacingBeforePx: Math.max(0, parseFloat(s.marginTop) || 0),
spacingAfterPx: Math.max(0, parseFloat(s.marginBottom) || 0),
};
}
function pseudoMarker(el) {
for (const which of ['::before', '::after']) {
const s = getComputedStyle(el, which);
if (!s || s.content === 'none' || s.content === 'normal') continue;
const content = s.content.replace(/^['"]|['"]$/g, '');
if (content.trim()) continue;
const width = parseFloat(s.width);
const height = parseFloat(s.height);
if (
width < 5 ||
width > 24 ||
height < 5 ||
height > 24 ||
Math.abs(width - height) > 6
) {
continue;
}
const color =
toHex(s.backgroundColor, { dropWhite: true }) ||
toHex(s.borderTopColor, { dropWhite: true });
if (!color) continue;
return {
text: s.transform && s.transform !== 'none' ? '\u25c6 ' : '\u25a0 ',
color,
sizePx: Math.max(width, height),
bold: false,
};
}
return null;
}
// Timeline entry decorations: an absolutely positioned pseudo dot (round
// marker) and/or a thin vertical connector rail in the left padding gutter.
// Both are position:absolute, so the flow rules drop them; callers
// reproduce the rail as a paragraph left border and the dot as a colored
// disc run.
function timelineDecorOf(el) {
const s = cs(el);
if (s.position !== 'relative') return null;
const padL = parseFloat(s.paddingLeft) || 0;
if (padL < 12 || padL > 60) return null;
let dot = null;
let rail = null;
for (const which of ['::before', '::after']) {
const p = getComputedStyle(el, which);
if (!p || p.content === 'none' || p.content === 'normal') continue;
if (p.position !== 'absolute') continue;
if (p.content.replace(/^['"]|['"]$/g, '').trim()) continue;
const w = parseFloat(p.width);
const h = parseFloat(p.height);
const left = parseFloat(p.left);
if (!(left >= -2 && left < padL)) continue;
const color = toHex(p.backgroundColor, { dropWhite: true });
if (!color) continue;
if (w >= 5 && w <= 24 && h >= 5 && h <= 24 && Math.abs(w - h) <= 6) {
dot = { color, sizePx: Math.max(w, h) };
} else if (w >= 1 && w <= 4 && h > 30) {
rail = { color, widthPx: Math.max(1, Math.round(w)), leftPx: left };
}
}
return dot || rail ? { dot, rail, padL, railLeftPx: rail?.leftPx } : null;
}
function borderTopOf(el) {
const s = cs(el);
const w = parseFloat(s.borderTopWidth);
if (w >= 2 && s.borderTopStyle !== 'none') {
const color = toHex(s.borderTopColor);
if (color) return { color, widthPx: w };
}
return null;
}
function borderSideOf(el, side) {
const s = cs(el);
const cap = side[0].toUpperCase() + side.slice(1);
const width = parseFloat(s[`border${cap}Width`]);
if (width < 1 || s[`border${cap}Style`] === 'none') return null;
const color = toHex(s[`border${cap}Color`]);
return color ? { color, widthPx: width, style: s[`border${cap}Style`] } : null;
}
function bordersOf(el) {
const borders = {};
for (const side of ['top', 'bottom', 'left', 'right']) {
const border = borderSideOf(el, side);
if (border) borders[side] = border;
}
return Object.keys(borders).length ? borders : null;
}
function cellPaddingOf(el) {
const s = cs(el);
return {
top: Math.max(0, Math.round(parseFloat(s.paddingTop) || 0)),
bottom: Math.max(0, Math.round(parseFloat(s.paddingBottom) || 0)),
left: Math.max(0, Math.round(parseFloat(s.paddingLeft) || 0)),
right: Math.max(0, Math.round(parseFloat(s.paddingRight) || 0)),
};
}
// Background painted by an *inline* ancestor (text highlight). Block-level
// backgrounds are handled as paragraph/cell shading, so stop at the first
// non-inline ancestor to avoid double-painting.
// Marker-pen highlight: linear-gradient(transparent 60%, color 40%) on an
// inline span. Word has no partial-height run shading, so the marker color
// becomes a full-height run highlight.
function markerGradientHex(el) {
const bgImage = cs(el).backgroundImage;
if (!bgImage || !bgImage.startsWith('linear-gradient')) return null;
const stops = [...bgImage.matchAll(/rgba?\(([\d.\s,]+)\)/g)];
if (!stops.length) return null;
const last = stops[stops.length - 1][1].split(',').map(parseFloat);
const [r, g, b, a = 1] = last;
if (!(a >= 0.15)) return null;
const mix = (c) => Math.round(c * a + 255 * (1 - a));
return toHex(`rgb(${mix(r)}, ${mix(g)}, ${mix(b)})`, { dropWhite: true });
}
function inlineBgHex(el) {
let cur = el;
while (cur && cur.nodeType === Node.ELEMENT_NODE) {
const d = cs(cur).display;
if (!(d === 'inline' || d.startsWith('inline-') || d === 'contents')) return null;
const bg = bgHex(cur) || markerGradientHex(cur);
if (bg) return bg;
cur = cur.parentElement;
}
return null;
}
function runStyleOf(el) {
const s = cs(el);
const style = {
bold: parseInt(s.fontWeight, 10) >= 600,
italic: s.fontStyle === 'italic',
underline: s.textDecorationLine.includes('underline'),
strike: s.textDecorationLine.includes('line-through'),
color: toHex(s.color) || '000000',
sizePx: parseFloat(s.fontSize),
mono: isMono(s),
letterSpacing: parseFloat(s.letterSpacing) || 0,
fontFamily: s.fontFamily,
};
// Inline(-block) span underlined via border-bottom (recipient names,
// signature lines): text-decoration never sees it, so map the lone
// bottom border to a run underline. Boxed chips (any other side) skip.
if (
!style.underline &&
(s.display || '').startsWith('inline') &&
s.borderBottomStyle !== 'none' &&
parseFloat(s.borderBottomWidth) >= 1 &&
s.borderTopStyle === 'none' &&
s.borderLeftStyle === 'none' &&
s.borderRightStyle === 'none'
) {
style.underline = true;
if (s.borderBottomStyle === 'dotted' || s.borderBottomStyle === 'dashed') {
style.underlineStyle = s.borderBottomStyle;
}
const underlineHex = toHex(s.borderBottomColor);
if (underlineHex) style.underlineColor = underlineHex;
}
// Inline boxed chip (O/X answer labels, small tags): a same-color border
// on every side of a short inline element is a character box — map it to a
// run border (w:bdr). Word can't round the corners, but the frame survives.
// Restricted to short text so a bordered inline phrase isn't boxed whole.
if (
(s.display || '').startsWith('inline') &&
(el.innerText || '').trim().length <= 8 &&
parseFloat(s.borderTopWidth) >= 1 &&
s.borderTopStyle !== 'none'
) {
const bc = toHex(s.borderTopColor);
if (
bc &&
toHex(s.borderRightColor) === bc &&
toHex(s.borderBottomColor) === bc &&
toHex(s.borderLeftColor) === bc
) {
style.charBorder = { color: bc, widthPx: parseFloat(s.borderTopWidth) };
}
}
const hl = inlineBgHex(el);
if (hl) style.highlight = hl;
if (s.verticalAlign === 'super' || el.closest('sup')) style.superscript = true;
else if (s.verticalAlign === 'sub' || el.closest('sub')) style.subscript = true;
if (s.textTransform === 'uppercase') style.uppercase = true;
if (s.direction === 'rtl') style.rtl = true;
const a = el.closest('a[href]');
if (a) {
const href = a.getAttribute('href') || '';
if (href.startsWith('#') && href.length > 1) {
try {
style.anchor = decodeURIComponent(href.slice(1));
} catch {
style.anchor = href.slice(1);
}
} else if (href && !/^javascript:/i.test(href)) {
style.href = a.href;
}
}
return style;
}
@@ -0,0 +1,516 @@
function extractTable(el) {
const rect = el.getBoundingClientRect();
const hasCompactPaintedLabel = [...el.querySelectorAll('td *, th *')].some(isCompactPaintedLabel);
if (hasCompactPaintedLabel && rect.height <= 900) return markForScreenshot(el);
return globalThis.__html2docxTable.extractTable(el, {
bgHex,
isCompactPaintedLabel,
bordersOf,
cellPaddingOf,
collectRuns,
cs,
hasBlockChildren,
isRTL,
isVisible,
markForScreenshot,
processChildren,
textAlignOf,
toHex,
});
}
// A CSS-grid table whose direct children are grid rows with the same number
// of columns (for example a Likert survey built from divs instead of table).
function gridTableRows(el) {
const rows = [...el.children].filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c));
if (rows.length < 2) return null;
const cssTable =
cs(el).display === 'table' &&
rows.every(
(row) =>
cs(row).display === 'table-row' &&
[...row.children]
.filter((cell) => !SKIP_TAGS.has(cell.tagName) && isVisible(cell))
.every((cell) => cs(cell).display === 'table-cell'),
);
const counts = rows.map((row) => {
const s = cs(row);
if (s.display !== 'grid' && !(cssTable && s.display === 'table-row')) return 0;
return [...row.children].filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c)).length;
});
const base = Math.max(...counts);
if (base < 2 || base > 12) return null;
// CSS tables tolerate short rows (a lone header cell): the browser leaves
// the missing columns empty, so extractGridTable pads them with fillers.
// Grid rows keep the strict equal-count rule.
if (counts.some((count) => count !== base && !(cssTable && count >= 1))) return null;
if (counts.filter((count) => count === base).length < 2) return null;
const widths = rows.map((row) => Math.round(row.getBoundingClientRect().width));
if (Math.max(...widths) - Math.min(...widths) > 8) return null;
// Cells must sit in the same columns in every row: alternating layouts
// (timeline cards flipping left/right around a center rail) are grids of
// rows too, but mapping their cells positionally scrambles the columns.
const leftsOf = (row) =>
[...row.children]
.filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c))
.map((c) => Math.round(c.getBoundingClientRect().left))
.sort((a, b) => a - b);
const firstLefts = leftsOf(rows[counts.indexOf(base)]);
for (const row of rows) {
const lefts = leftsOf(row);
if (lefts.length === base) {
if (lefts.some((left, i) => Math.abs(left - firstLefts[i]) > 12)) return null;
} else if (
lefts.some((left) => !firstLefts.some((columnLeft) => Math.abs(left - columnLeft) <= 12))
) {
return null;
}
}
// Avoid classifying arbitrary stacks of small grids as a data table.
if (!cssTable && rows.length < 4 && !fullBorderOf(el)) return null;
return rows;
}
function extractGridTable(el, gridRows, depth) {
const cellsOf = (row) =>
[...row.children].filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c));
const baseRow = gridRows.reduce(
(best, row) => (cellsOf(row).length > cellsOf(best).length ? row : best),
gridRows[0],
);
const firstCells = cellsOf(baseRow);
const colWidths = firstCells.map((c) => Math.round(c.getBoundingClientRect().width));
const colLefts = firstCells.map((c) => Math.round(c.getBoundingClientRect().left));
const rows = gridRows.map((row, rowIdx) => {
const domCells = cellsOf(row);
let cells = domCells.map((cell) => {
const textAlign = textAlignOf(cell);
const entry = {
shading: bgHex(cell) || bgHex(row),
borders: bordersOf(cell),
padPx: cellPaddingOf(cell),
vAlign: cs(row).alignItems === 'center' ? 'center' : undefined,
rtl: isRTL(cell) || undefined,
};
if (textAlign === 'center' || textAlign === 'right') entry.align = textAlign;
entry.children = needsBlockWalk(cell)
? processChildren(cell, depth + 1, { decorations: false })
: paraNodesFrom(cell, false);
return entry;
});
// Short row (lone header cell in a CSS table): seat each cell in its
// geometric column and fill the rest with empty cells — unshaded, so
// they inherit the table background, same as the browser leaves them.
if (cells.length && cells.length < colWidths.length) {
const placed = new Array(colWidths.length).fill(null);
domCells.forEach((cell, i) => {
const left = Math.round(cell.getBoundingClientRect().left);
let col = colLefts.findIndex((columnLeft) => Math.abs(columnLeft - left) <= 12);
if (col < 0 || placed[col]) col = placed.findIndex((slot) => !slot);
placed[col] = cells[i];
});
cells = placed.map((entry) => entry || { children: [] });
}
const renderedHeight = Math.round(row.getBoundingClientRect().height);
return {
cells,
// Let text-driven rows use Word's natural compact height. Preserve
// only genuinely tall visual rows (planners / empty writing areas).
heightPx: renderedHeight >= 80 ? renderedHeight : undefined,
// Only a short strip reads as a repeatable header; a tall first row
// is content (card stacks) and would reprint on every page.
header: rowIdx === 0 && renderedHeight < 60,
};
});
return [{
type: 'table',
gridTable: true,
rows,
colWidths,
outerBorder: bordersOf(el),
shading: bgHex(el),
padPx: cellPaddingOf(el),
heightPx: Math.round(el.getBoundingClientRect().height),
rtl: isRTL(el) || undefined,
}];
}
function extractCode(el) {
const shading = bgHex(el) || 'F5F5F5';
const lines = el.innerText.replace(/\n$/, '').split('\n');
const { color, sizePx } = runStyleOf(el);
return [{ type: 'code', lines, shading, color, sizePx }];
}
function extractList(el, ordered, depth = 1) {
const listItems = [...el.children].filter((li) => li.tagName === 'LI' && isVisible(li));
// list-style:none -> the author wants plain paragraphs, not numbering.
// Judge by the items, not the UL: frameworks (pico.css) re-style the LI
// marker even when the UL itself says none.
const plain = listItems.length
? listItems.every(
(li) => cs(li).listStyleType === 'none' || cs(li).display !== 'list-item',
)
: cs(el).listStyleType === 'none';
const needsExactPseudoMarker = (li) =>
/[☑☐❋]/u.test(pseudoBulletRun(li)?.text || '');
const hasCompactPaintedLabels = listItems.some((li) =>
[...li.querySelectorAll(':scope > *')].some(isCompactPaintedLabel),
);
if (hasCompactPaintedLabels) return [markForScreenshot(el)];
// CSS multi-column list (columns: 2 on a TOC): reproduce as a layout
// table with one cell per rendered column. Numbering continues across
// columns, so synthesize literal number prefixes instead of Word lists.
const columnCount = parseInt(cs(el).columnCount, 10);
if (
depth <= 2 &&
Number.isFinite(columnCount) &&
columnCount >= 2 &&
listItems.length >= columnCount &&
listItems.every((li) => !hasBlockChildren(li))
) {
const lefts = listItems.map((li) => Math.round(li.getBoundingClientRect().left));
const uniqueLefts = [...new Set(lefts)].sort((a, b) => a - b);
if (uniqueLefts.length >= 2) {
const groups = uniqueLefts.map(() => []);
listItems.forEach((li, index) => {
groups[uniqueLefts.indexOf(lefts[index])].push({ li, index });
});
const cells = groups.map((group) => ({
children: group.flatMap(({ li, index }) => {
if (plain && needsExactPseudoMarker(li)) return [markForScreenshot(li)];
const runs = collectRuns(li);
if (!runs.length) return [];
const pseudoRun = pseudoBulletRun(li);
let prefixed = Boolean(pseudoRun);
if (pseudoRun) runs.unshift(pseudoRun);
else if (ordered) {
runs.unshift({ text: `${index + 1}. `, ...runStyleOf(li) });
prefixed = true;
} else if (!plain) {
runs.unshift({ text: '\u2022\u00a0', ...runStyleOf(li) });
prefixed = true;
}
const style = { ...paraStyleOf(el, false), ...paraStyleOf(li, false) };
delete style.indentLeftPx;
if (prefixed) {
const em = parseFloat(cs(li).fontSize) || 16;
style.indentHangingPx = Math.round(em * (ordered ? 1.1 : 0.8));
}
return [{ type: 'para', runs, style }];
}),
}));
const width = el.getBoundingClientRect().width || 1;
return [{
type: 'table',
layout: true,
rows: [{ cells: cells.map((cell, i) => ({ ...cell, gridStart: i, colspan: 1 })) }],
colWidths: uniqueLefts.map((left, i) =>
Math.round((i + 1 < uniqueLefts.length ? uniqueLefts[i + 1] : el.getBoundingClientRect().right) - left) || Math.round(width / uniqueLefts.length),
),
}];
}
}
// Layout list: display:flex items (numbered chip + content column) need
// the full classifier. Flattening them to runs drops the chip and
// inlines nested callout boxes into the text. Items too tall for a table
// row (isBoxRow rejects them) still get a block walk so nested dialogue
// bubbles / sub-lists survive.
// CSS-counter numbering ("counter(toc-counter)") never resolves through
// getComputedStyle; synthesize it from the item's position.
const counterPrefix = (li, index) => {
const pseudoStyle = getComputedStyle(li, '::before');
const content = pseudoStyle.content || '';
const counterStart = content.indexOf('counter(');
if (counterStart < 0) return null;
const counterEnd = content.indexOf(')', counterStart);
const quotedText = (part) =>
[...part.matchAll(/"([^"]*)"|'([^']*)'/g)]
.map((match) => match[1] ?? match[2] ?? '')
.join('');
const prefix = quotedText(content.slice(0, counterStart));
const suffix = quotedText(content.slice(counterEnd + 1));
let value = `${prefix}${index + 1}${suffix}`;
if (pseudoStyle.textTransform === 'uppercase') value = value.toUpperCase();
if (pseudoStyle.textTransform === 'lowercase') value = value.toLowerCase();
return value.endsWith(' ') ? value : `${value} `;
};
if (plain && listItems.some((li) => isBoxRow(li) || hasBlockChildren(li))) {
return listItems.flatMap((li, index) => {
if (isBoxRow(li)) return processElement(li, depth + 1);
// A counter badge glyph (❶) already carries the number — adding the
// synthesized plain counter text would double-number the item.
const bulletRun = pseudoBulletRun(li) || chipBulletRun(li);
const prefix = bulletRun ? null : counterPrefix(li, index);
if (hasBlockChildren(li)) {
const nodes = processChildren(li, depth + 1);
const first = nodes.find((n) => n.type === 'para');
if (first && bulletRun) first.runs = [bulletRun, ...first.runs];
if (first && prefix) first.runs = [{ text: prefix, ...runStyleOf(li) }, ...first.runs];
return nodes;
}
const runs = collectRuns(li);
if (!runs.length) return [];
if (prefix) runs.unshift({ text: prefix, ...runStyleOf(li) });
if (bulletRun) runs.unshift(bulletRun);
const style = { ...paraStyleOf(el), ...paraStyleOf(li) };
return [{ type: 'para', runs, style }];
});
}
const nativeMarkerOf = (li) => {
const itemStyle = cs(li);
if (itemStyle.display !== 'list-item' || itemStyle.listStyleType === 'none') return null;
const glyphs = {
disc: '\u2022',
circle: '\u25e6',
square: '\u25aa',
};
const glyph = glyphs[itemStyle.listStyleType];
if (!glyph) return null;
const runStyle = runStyleOf(li);
return {
run: {
text: `${glyph}\u00a0`,
color: runStyle.color,
sizePx: runStyle.sizePx,
fontFamily: runStyle.fontFamily,
},
widthPx: Math.max(10, Math.round((runStyle.sizePx || 14) * 1.05)),
};
};
const markers = listItems.map((li) => {
const first = [...li.children].find((child) => isVisible(child));
const nativeMarker = nativeMarkerOf(li);
if (first && isCheckboxLike(first)) {
const rect = first.getBoundingClientRect();
const itemStyle = cs(li);
return {
element: first,
widthPx: rect.width,
gapPx: parseFloat(itemStyle.columnGap) || parseFloat(itemStyle.gap) || 8,
nativeMarker,
};
}
const marker = pseudoCheckbox(li);
return marker ? { ...marker, nativeMarker } : null;
});
const checklist =
plain &&
listItems.length > 1 &&
markers.every(Boolean);
if (checklist) {
const listRect = el.getBoundingClientRect();
const firstColWidth = Math.round(
Math.max(
...markers.map(
(marker) => marker.widthPx + marker.gapPx + (marker.nativeMarker?.widthPx || 0),
),
),
);
const rows = listItems.map((li, index) => {
const children = [...li.children].filter((child) => isVisible(child));
const marker = markers[index];
const label = marker.element ? children.find((child) => child !== marker.element) : null;
const rowBorders = bordersOf(li);
const pad = cellPaddingOf(li);
const itemStyle = cs(li);
const itemParaStyle = paraStyleOf(li);
delete itemParaStyle.spacingBeforePx;
delete itemParaStyle.spacingAfterPx;
// The marker table already consumes the list item's left padding.
// Keeping it on the label paragraph would indent the text twice.
delete itemParaStyle.indentLeftPx;
const markerRuns = [];
if (marker.nativeMarker) markerRuns.push(marker.nativeMarker.run);
markerRuns.push(marker.element ? checkboxNode(marker.element) : checkboxRun(marker));
return {
heightPx: Math.round(
li.getBoundingClientRect().height + Math.max(0, parseFloat(itemStyle.marginBottom) || 0),
),
cells: [
{
runs: markerRuns,
borders: rowBorders || {},
padPx: { top: pad.top, bottom: pad.bottom, left: 0, right: marker.gapPx },
},
{
runs: label ? collectRuns(label) : collectRuns(li),
style: itemParaStyle,
borders: rowBorders || {},
padPx: { top: pad.top, bottom: pad.bottom, left: 0, right: 0 },
},
],
last: index === listItems.length - 1,
};
});
const listStyle = cs(el);
return [{
type: 'table',
checklist: true,
noHeader: true,
rows,
colWidths: [firstColWidth, Math.max(1, Math.round(listRect.width) - firstColWidth)],
spacingBeforePx: Math.max(0, Math.round(parseFloat(listStyle.marginTop) || 0)),
spacingAfterPx: Math.max(0, Math.round(parseFloat(listStyle.marginBottom) || 0)),
rtl: isRTL(el) || undefined,
}];
}
const items = [];
for (const li of listItems) {
items.push({ runs: collectRuns(li), style: paraStyleOf(li) });
}
if (!items.length) return [];
if (plain) {
return items
.filter((it) => it.runs.length)
.map((it, index) => {
const li = listItems[index];
if (needsExactPseudoMarker(li)) return markForScreenshot(li);
const style = { ...paraStyleOf(el), ...it.style };
const itemStyle = cs(li);
const paddingTop = parseFloat(itemStyle.paddingTop) || 0;
const paddingBottom = parseFloat(itemStyle.paddingBottom) || 0;
if (paddingTop > 0) style.spacingBeforePx = (style.spacingBeforePx || 0) + paddingTop;
if (paddingBottom > 0) style.spacingAfterPx = (style.spacingAfterPx || 0) + paddingBottom;
const bulletRun = pseudoBulletRun(li) || chipBulletRun(li);
if (bulletRun) it.runs.unshift(bulletRun);
else {
// list-style:none + ::before counter() (self-numbered rule
// lists): the marker lives in the pseudo-element, not the runs
const prefix = counterPrefix(li, index);
if (prefix) {
const pseudoWeight = parseInt(getComputedStyle(li, '::before').fontWeight, 10);
it.runs.unshift({
text: prefix,
...runStyleOf(li),
...(pseudoWeight >= 600 ? { bold: true } : {}),
});
const em = parseFloat(itemStyle.fontSize) || 16;
style.indentHangingPx = Math.round(em * 1.1);
}
}
return { type: 'para', runs: it.runs, style };
});
}
// <ol start="951">: Word numbering always restarts at 1 (startOverride
// is fixed), so lists with an authored start keep literal number
// prefixes instead — the TOC must match the 951-975 headings it links.
const startAt = ordered ? parseInt(el.getAttribute('start'), 10) : NaN;
if (Number.isFinite(startAt) && startAt !== 1 && listItems.every((li) => !hasBlockChildren(li))) {
return listItems.flatMap((li, index) => {
const runs = collectRuns(li);
if (!runs.length) return [];
runs.unshift({ text: `${startAt + index}. `, ...runStyleOf(li) });
const style = { ...paraStyleOf(el, false), ...paraStyleOf(li, false) };
const em = parseFloat(cs(li).fontSize) || 16;
style.indentHangingPx = Math.round(em * 1.6);
return [{ type: 'para', runs, style }];
});
}
const nestedItems = [];
// liIndex = ordinal of the top-level li each item came from, so column
// slicing can split a tall bullet list at li boundaries.
const appendListItems = (listEl, level, parentIndentPx, rootIndex) => {
const listStyle = cs(listEl);
const indentLeftPx = parentIndentPx + Math.max(0, parseFloat(listStyle.paddingLeft) || 0);
const childItems = [...listEl.children].filter(
(child) => child.tagName === 'LI' && isVisible(child),
);
for (let liOrdinal = 0; liOrdinal < childItems.length; liOrdinal++) {
const li = childItems[liOrdinal];
const liIndex = level === 0 ? liOrdinal : rootIndex;
// Walk li children in DOM order, splitting content around nested
// lists: text after a nested list must stay after it (a trailing
// "to perform..." clause hoisted above its sub-items inverts the
// reading order).
const segments = [];
let current = [];
for (const node of li.childNodes) {
const isList =
node.nodeType === Node.ELEMENT_NODE &&
(node.tagName === 'UL' || node.tagName === 'OL');
if (isList) {
if (isVisible(node)) {
segments.push({ content: current });
current = [];
segments.push({ list: node });
}
} else current.push(node);
}
segments.push({ content: current });
const style = paraStyleOf(li);
if (segments.some((seg) => seg.list)) delete style.spacingAfterPx;
let leading = true;
for (const seg of segments) {
if (seg.list) {
appendListItems(seg.list, level + 1, indentLeftPx, liIndex);
continue;
}
const runs = trimRuns(runsFromNodes(seg.content, li));
if (!runs.length) continue;
// A justified li with an explicit <br> keeps the break as \n in one
// paragraph — Word stretches the line BEFORE a manual break under
// justify (CSS never does), blowing huge gaps into short label
// lines. Split at the breaks like makeParaNodes: only the final
// fragment keeps justify (Word never stretches a last line).
const fragments = [runs];
if (style.align === 'justify' && runs.some((run) => (run.text || '').includes('\n'))) {
fragments.length = 0;
let currentLine = [];
for (const run of runs) {
const parts = (run.text || '').split('\n');
parts.forEach((part, partIndex) => {
if (part) currentLine.push({ ...run, text: part });
if (partIndex < parts.length - 1 && currentLine.length) {
fragments.push(currentLine);
currentLine = [];
}
});
}
if (currentLine.length) fragments.push(currentLine);
if (!fragments.length) fragments.push(runs);
}
fragments.forEach((fragmentRuns, fragmentIndex) => {
const fragmentStyle =
fragments.length > 1 && fragmentIndex < fragments.length - 1
? { ...style, align: undefined }
: style;
if (leading) {
nestedItems.push({
runs: fragmentRuns,
style: fragmentStyle,
level,
// ::before counter() numbering counts as ordered even on a UL
ordered:
listEl.tagName === 'OL' ||
(getComputedStyle(li, '::before').content || '').includes('counter('),
markerType: cs(li).listStyleType || listStyle.listStyleType,
indentLeftPx,
liIndex,
});
leading = false;
} else {
// continuation text of the same li: no marker, text-aligned indent
nestedItems.push({
runs: fragmentRuns,
style: fragmentStyle,
level,
continuation: true,
indentLeftPx,
liIndex,
});
}
});
}
}
};
appendListItems(el, 0, 0, 0);
return [{
type: 'list',
ordered,
items: nestedItems,
rtl: isRTL(el) || undefined,
}];
}
// A horizontal row of >=2 similar boxes (flex row / grid columns) -> kpirow
@@ -0,0 +1,176 @@
(function installFormsAndMediaExtractor(global) {
// Empty block/inline with only a bottom border is a fill-in underline
// (consent forms, contract blanks). Without this they collapse away.
function fillInLineNode(el, deps) {
const { bordersOf, cs } = deps;
if ((el.innerText || '').trim() || el.children.length) return null;
const borders = bordersOf(el);
// A signature rule drawn as border-top on a zero-height div is the same
// fill-in line as a border-bottom one.
const line =
borders?.bottom && !borders.top && !borders.left && !borders.right
? borders.bottom
: borders?.top && !borders.bottom && !borders.left && !borders.right
? borders.top
: null;
if (!line) return null;
const rect = el.getBoundingClientRect();
const style = cs(el);
const display = style.display;
const inline = display === 'inline' || display.startsWith('inline-');
// Empty inline blanks often report ~1px height (border only) while
// min-width still reserves the fill-in gap in the line.
const minWidth = parseFloat(style.minWidth) || 0;
const width = Math.max(rect.width, minWidth);
if (inline) {
if (width < 24 || width > 480 || rect.height > 40) return null;
} else if (width < 40 || rect.height > 48) {
return null;
}
return {
type: 'formfield',
mode: 'line',
controlType: 'text',
width: Math.round(width),
height: Math.round(Math.max(rect.height, 16)),
runs: [],
borders: { bottom: line },
inline,
};
}
// Empty fully-bordered writing area (form answer boxes with min-height).
// These are not checkboxes and must keep their authored height.
function fillInBoxNode(el, deps) {
const { bordersOf, cs, toHex, paintedBgHex, runStyleOf } = deps;
if ((el.innerText || '').trim() || el.children.length) return null;
const borders = bordersOf(el);
if (!borders?.top || !borders?.bottom || !borders?.left || !borders?.right) {
return null;
}
const style = cs(el);
const rect = el.getBoundingClientRect();
// An image container is not a fill-in blank: a div painted by
// background-image (even one whose URL now 404s and shows only the
// border ring) or shaped as a circle must stay on the screenshot path —
// as a formfield it rendered an opaque white box over the title.
if ((style.backgroundImage || '').includes('url(')) return null;
const radius = String(style.borderTopLeftRadius || '');
const radiusValue = parseFloat(radius) || 0;
// computed border-radius keeps authored percentages ("50%") as-is
const circle = radius.includes('%')
? radiusValue >= 40
: radiusValue >= Math.min(rect.width, rect.height) * 0.4;
if (circle) return null;
const minH = parseFloat(style.minHeight) || 0;
const height = Math.max(rect.height, minH);
if (height < 28 || rect.width < 48) return null;
// checkbox-sized squares stay on the checkbox path
if (rect.width <= 32 && height <= 32) return null;
const rawBg = toHex(style.backgroundColor);
// contenteditable answer boxes show their hint via
// :empty::before { content: attr(data-placeholder) } — resolve it so
// the box isn't exported empty
let placeholder = '';
const pseudo = getComputedStyle(el, '::before');
const pseudoContent = pseudo?.content || '';
const attrRef = pseudoContent.match(/attr\(([-\w]+)\)/);
if (attrRef) placeholder = el.getAttribute(attrRef[1]) || '';
else if (pseudoContent && pseudoContent !== 'none' && pseudoContent !== 'normal') {
placeholder = pseudoContent.replace(/^["']|["']$/g, '');
}
const placeholderColor = placeholder && pseudo ? toHex(pseudo.color) : null;
return {
type: 'formfield',
mode: 'box',
controlType: 'multiline',
width: Math.round(rect.width),
height: Math.round(height),
value: placeholder || undefined,
valueColor: placeholderColor || undefined,
runs: placeholder
? [{
text: placeholder,
...(runStyleOf ? runStyleOf(el) : {}),
...(placeholderColor ? { color: placeholderColor } : {}),
}]
: [],
borders,
shading: (paintedBgHex && paintedBgHex(el)) || rawBg || 'FFFFFF',
};
}
function formFieldNode(el, deps) {
const { bgHex, bordersOf, cellPaddingOf, cs, runStyleOf } = deps;
const rect = el.getBoundingClientRect();
cs(el);
const value = el.value || el.getAttribute('placeholder') || '';
const inputType = (el.getAttribute('type') || 'text').toLowerCase();
const controlType =
el.tagName === 'SELECT'
? 'dropdown'
: el.tagName === 'TEXTAREA'
? 'multiline'
: inputType === 'checkbox'
? 'checkbox'
: inputType === 'radio'
? 'radio'
: 'text';
const borders = bordersOf(el);
const hasOnlyBottomBorder =
borders &&
borders.bottom &&
!borders.top &&
!borders.left &&
!borders.right;
return {
type: 'formfield',
mode: hasOnlyBottomBorder ? 'line' : 'box',
controlType,
name: el.name || el.id || undefined,
alias: el.getAttribute('aria-label') || el.name || el.id || undefined,
value,
checked: Boolean(el.checked),
options:
el.tagName === 'SELECT'
? [...el.options].map((option) => ({
value: option.value,
label: option.textContent || option.value,
selected: option.selected,
}))
: undefined,
width: Math.round(rect.width),
height: Math.round(rect.height),
runs: value ? [{ text: value, ...runStyleOf(el) }] : [],
borders,
shading: bgHex(el),
padPx: cellPaddingOf(el),
};
}
function embeddedMediaNode(el, { markForScreenshot }) {
const rawHref =
el.tagName === 'IFRAME'
? el.src
: el.tagName === 'VIDEO' || el.tagName === 'AUDIO'
? el.currentSrc || el.src
: '';
const href = /^https?:/i.test(rawHref || '') ? rawHref : undefined;
return {
...markForScreenshot(el),
mediaType: el.tagName.toLowerCase(),
href,
fallbackText:
el.getAttribute('title') ||
el.getAttribute('aria-label') ||
`${el.tagName === 'IFRAME' ? 'Embedded content' : el.tagName === 'VIDEO' ? 'Video' : 'Audio'}`,
};
}
global.__html2docxFormsMedia = {
embeddedMediaNode,
fillInBoxNode,
fillInLineNode,
formFieldNode,
};
})(globalThis);
+779
View File
@@ -0,0 +1,779 @@
(function installPageExtractor(global) {
function build(deps) {
const {
cs,
docRTL,
isVisible,
markForScreenshot,
nextShotId,
processChildren,
processElement,
toHex,
} = deps;
const rootBodyStyle = cs(document.body);
const absoluteRootChildren = [...document.body.children].filter(
(child) => isVisible(child) && cs(child).position === 'absolute',
);
const bodyHeight = document.body.getBoundingClientRect().height;
const visibleBodyChildren = [...document.body.children].filter(isVisible);
const authoredPageRoots = visibleBodyChildren.filter(
(child) => child.hasAttribute('data-docx-page') || child.hasAttribute('data-page'),
);
const inferredPageRoots = visibleBodyChildren.filter((child) => {
if (authoredPageRoots.includes(child)) return false;
if (!isVisible(child)) return false;
const style = cs(child);
const rect = child.getBoundingClientRect();
return (
(style.breakAfter === 'page' || style.pageBreakAfter === 'always') &&
rect.width >= 300 &&
rect.height >= 400
);
});
const multiPageComposition = authoredPageRoots.length >= 2;
const mixedPageComposition = !multiPageComposition && inferredPageRoots.length >= 2;
const renderedPageHeight = window.innerHeight;
// Fixed-composition slide pages: page-sized relative sections whose
// direct children are absolutely positioned (coordinate layouts authored
// without data-docx-page). Flow classification drops the positioned
// content entirely, so rasterize each page like authored pages.
const slidePageRoots = visibleBodyChildren.filter((child) => {
if (authoredPageRoots.includes(child)) return false;
const style = cs(child);
if (style.position !== 'relative' && style.position !== 'absolute') return false;
const rect = child.getBoundingClientRect();
if (Math.abs(rect.height - renderedPageHeight) > renderedPageHeight * 0.08) return false;
if (rect.width < window.innerWidth * 0.8) return false;
const absoluteKids = [...child.children].filter(
(kid) => isVisible(kid) && cs(kid).position === 'absolute',
);
return absoluteKids.length >= 2 && (child.innerText || '').trim().length >= 20;
});
const slidePageComposition =
!multiPageComposition &&
!mixedPageComposition &&
slidePageRoots.length >= 2 &&
slidePageRoots.length >= visibleBodyChildren.length - 1;
const multiPageAbsoluteComposition =
!multiPageComposition &&
!mixedPageComposition &&
bodyHeight > renderedPageHeight &&
bodyHeight <= renderedPageHeight * 10 &&
absoluteRootChildren.some(
(child) => child.getBoundingClientRect().top >= renderedPageHeight - 2,
);
const activePageView = [...document.body.children].find(
(child) =>
isVisible(child) &&
child.classList.contains('page-view') &&
child.classList.contains('active-page'),
);
const fixedNavigation = [...document.body.children].some((child) => {
if (!isVisible(child)) return false;
const style = cs(child);
return (
(child.tagName === 'NAV' || child.tagName === 'HEADER') &&
(style.position === 'fixed' || style.position === 'sticky')
);
});
const webPageComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
Boolean(activePageView) &&
fixedNavigation &&
bodyHeight > renderedPageHeight &&
activePageView.querySelector('img') &&
activePageView.querySelector('.container, .row, [class*="grid"]');
const pageComposition =
(rootBodyStyle.position === 'relative' || rootBodyStyle.position === 'absolute') &&
rootBodyStyle.overflow === 'hidden' &&
bodyHeight >= 700 &&
bodyHeight <= 1600 &&
absoluteRootChildren.length >= 3 &&
(document.body.innerText || '').trim().length >= 20;
const singleVisualPageRoot = visibleBodyChildren.length === 1 ? visibleBodyChildren[0] : null;
const singleVisualPageRect = singleVisualPageRoot?.getBoundingClientRect();
const singleVisualPageStyle = singleVisualPageRoot ? cs(singleVisualPageRoot) : null;
const singleVisualPagePaint =
singleVisualPageStyle &&
(singleVisualPageStyle.backgroundImage !== 'none' ||
Boolean(toHex(singleVisualPageStyle.backgroundColor, { dropWhite: true })));
const singleVisualPageLayout = singleVisualPageRoot
? [...singleVisualPageRoot.querySelectorAll('*')].some((element) => {
const style = cs(element);
return (
(style.display === 'grid' && style.gridTemplateColumns.split(' ').length >= 2) ||
(style.display === 'flex' &&
(style.flexDirection === 'row' || style.flexDirection === ''))
);
})
: false;
const flowingVisualComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!pageComposition &&
Boolean(singleVisualPageRoot) &&
singleVisualPageStyle.position === 'relative' &&
(singleVisualPageStyle.overflow === 'hidden' ||
singleVisualPageStyle.overflow === 'clip') &&
singleVisualPagePaint &&
singleVisualPageLayout &&
singleVisualPageRect.width >= window.innerWidth * 0.7 &&
singleVisualPageRect.height > renderedPageHeight * 1.05 &&
singleVisualPageRect.height <= renderedPageHeight * 3 &&
(singleVisualPageRoot.innerText || '').trim().length >= 20;
const singlePageVisualComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!pageComposition &&
!flowingVisualComposition &&
Boolean(singleVisualPageRoot) &&
(singleVisualPageStyle.position === 'relative' ||
singleVisualPageStyle.position === 'absolute') &&
(singleVisualPageStyle.overflow === 'hidden' ||
singleVisualPageStyle.overflow === 'clip') &&
singleVisualPagePaint &&
singleVisualPageRect.width >= window.innerWidth * 0.7 &&
singleVisualPageRect.height >= renderedPageHeight * 0.7 &&
singleVisualPageRect.height <= renderedPageHeight * 1.35 &&
(singleVisualPageRoot.innerText || '').trim().length >= 20;
const bodySinglePageVisualComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!pageComposition &&
!singlePageVisualComposition &&
rootBodyStyle.position === 'relative' &&
rootBodyStyle.backgroundImage !== 'none' &&
rootBodyStyle.maxWidth !== 'none' &&
visibleBodyChildren.length >= 2 &&
visibleBodyChildren.length <= 5 &&
bodyHeight >= renderedPageHeight * 0.7 &&
bodyHeight <= renderedPageHeight * 1.35 &&
(document.body.innerText || '').trim().length >= 20;
const bodyRect = document.body.getBoundingClientRect();
// Word (Mac) insets the first line ~26px below the page top even at zero
// margins, so a slice scaled to the full content height loses its bottom
// rows to the page edge. Budget slices below the page height so the
// width-driven scale governs every slice (uniform scale across pages)
// and Word never clips a pixel row. Matches the 45px renderer headroom:
// 1 - 45/1123.
const sliceBudget = Math.round(renderedPageHeight * 0.96);
// Bands (y ranges relative to body top) a slice boundary must not cross:
// text lines and replaced elements always; painted card boxes when small
// enough to move to the next page whole.
const collectCutBands = () => {
const lineBands = [];
const boxBands = [];
const push = (bands, rect) => {
if (rect.height > 0 && rect.width > 0) {
bands.push({ top: rect.top - bodyRect.top, bottom: rect.bottom - bodyRect.top });
}
};
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const textNode = walker.currentNode;
if (!textNode.textContent.trim()) continue;
const range = document.createRange();
range.selectNodeContents(textNode);
for (const rect of range.getClientRects()) push(lineBands, rect);
}
for (const element of document.body.querySelectorAll('*')) {
if (!isVisible(element)) continue;
const rect = element.getBoundingClientRect();
if (rect.height <= 0 || rect.width <= 0) continue;
if (
element.matches('img, svg, canvas, video, iframe, input, textarea, select, button')
) {
push(lineBands, rect);
continue;
}
if (rect.height < 40 || rect.height > sliceBudget * 0.9) continue;
const style = cs(element);
// dropWhite:false — an explicit white card on a tinted page is still
// a visual card whose rows must not be split across pages.
const painted =
style.backgroundImage !== 'none' ||
style.boxShadow !== 'none' ||
Boolean(toHex(style.backgroundColor, { dropWhite: false })) ||
parseFloat(style.borderTopWidth) > 0 ||
parseFloat(style.borderBottomWidth) > 0;
if (painted) push(boxBands, rect);
}
return { lineBands, boxBands };
};
const chooseCut = (ideal, minCut, bands) => {
const clearance = 3;
for (let y = ideal; y >= minCut; y -= 2) {
const blocked = bands.some(
(band) => band.top < y + clearance && band.bottom > y - clearance,
);
if (!blocked) return y;
}
return null;
};
const sliceBoundaries = () => {
// A composition only slightly taller than one page reads as a
// single-page design (e.g. a resume): render one full slice and let
// the renderer's page scale absorb the few percent, instead of
// stranding a couple of lines on a second page.
if (bodyHeight <= sliceBudget * 1.12) return [Math.round(bodyHeight)];
const { lineBands, boxBands } = collectCutBands();
const allBands = [...lineBands, ...boxBands];
const boundaries = [];
let cursor = 0;
while (bodyHeight - cursor > sliceBudget) {
const ideal = cursor + sliceBudget;
const minCut = cursor + Math.round(sliceBudget * 0.6);
// Whole cards move to the next page when a gap exists; otherwise cut
// between text lines inside the card; otherwise hard-cut.
const cut =
chooseCut(ideal, minCut, allBands) ??
chooseCut(ideal, minCut, lineBands) ??
ideal;
boundaries.push(cut);
cursor = cut;
}
boundaries.push(Math.round(bodyHeight));
// Trailing sliver: absorb a short final slice into the previous page
// when the merged slice still fits with a small page-scale shrink.
if (boundaries.length >= 2) {
const previousStart = boundaries.length >= 3 ? boundaries[boundaries.length - 3] : 0;
const lastStart = boundaries[boundaries.length - 2];
if (
bodyHeight - lastStart <= sliceBudget * 0.25 &&
bodyHeight - previousStart <= sliceBudget * 1.12
) {
boundaries.splice(boundaries.length - 2, 1);
}
}
return boundaries;
};
const screenshotPageSlices = ({ authoredPageHeights = false } = {}) => {
// Absolutely-positioned multi-page canvases are authored in exact
// viewport-height pages: gap-aware cuts would shift authored page
// boundaries, so slice at the authored pitch and let the renderer
// headroom shrink each page to fit.
const boundaries = authoredPageHeights
? Array.from(
{ length: Math.ceil(bodyHeight / renderedPageHeight) },
(_, index) => Math.min(bodyHeight, (index + 1) * renderedPageHeight),
)
: sliceBoundaries();
// Decorative absolutes bleeding past the body's box (half-out hero
// circles) get flat-cut by a body-width clip. Extend the horizontal
// extent to overhanging descendants that still touch the body band —
// capped so parked off-screen decorations (left/right: -10000px)
// never drag the clip away.
let paintLeft = bodyRect.left;
let paintRight = bodyRect.right;
const maxBleed = 200;
for (const d of document.body.querySelectorAll('*')) {
const dr = d.getBoundingClientRect();
if (!dr.width || !dr.height) continue;
if (dr.right <= bodyRect.left - maxBleed || dr.left >= bodyRect.right + maxBleed) continue;
if (dr.left < paintLeft) paintLeft = Math.max(dr.left, bodyRect.left - maxBleed);
if (dr.right > paintRight) paintRight = Math.min(dr.right, bodyRect.right + maxBleed);
}
paintLeft = Math.max(0, Math.round(paintLeft));
const paintWidth = Math.round(paintRight - paintLeft);
let previousBoundary = 0;
return boundaries.map((boundary) => {
const sliceHeight = Math.round(boundary - previousBoundary);
const sliceTop = previousBoundary;
previousBoundary = boundary;
return {
type: 'image',
shotId: nextShotId(),
width: paintWidth,
height: sliceHeight,
align: 'center',
pageComposition: true,
capturesDocumentText: true,
clip: {
x: paintLeft,
y: Math.max(0, Math.round(bodyRect.top + sliceTop)),
width: paintWidth,
height: sliceHeight,
},
};
});
};
const buildMixedPageIr = () => {
const output = [];
const pageRoots = new Set(inferredPageRoots);
let pendingPageBreak = false;
let previousPageRootFillsPage = false;
const append = (nodes) => {
for (const node of nodes) {
if (
node.type === 'pagebreak' &&
(!output.length || output[output.length - 1].type === 'pagebreak')
) {
continue;
}
output.push(node);
}
};
for (const child of visibleBodyChildren) {
const style = cs(child);
const isPageRoot = pageRoots.has(child);
const breaksBefore =
style.breakBefore === 'page' || style.pageBreakBefore === 'always';
const naturalPageAdvance = pendingPageBreak && previousPageRootFillsPage;
if (
!naturalPageAdvance &&
(pendingPageBreak || (isPageRoot && breaksBefore)) &&
output.length
) {
append([{ type: 'pagebreak' }]);
}
const nodes = isPageRoot
? [{ ...markForScreenshot(child), pageComposition: true }]
: processElement(child, 0);
if (naturalPageAdvance && nodes[0]?.type === 'pagebreak') nodes.shift();
append(nodes);
pendingPageBreak =
style.breakAfter === 'page' || style.pageBreakAfter === 'always';
previousPageRootFillsPage =
isPageRoot &&
child.getBoundingClientRect().height >= renderedPageHeight - 12;
}
return output;
};
const ir = multiPageComposition
? authoredPageRoots.flatMap((page, index) => [
...(index > 0 ? [{ type: 'pagebreak' }] : []),
{ ...markForScreenshot(page), pageComposition: true },
])
: slidePageComposition
? slidePageRoots.flatMap((page, index) => [
...(index > 0 ? [{ type: 'pagebreak' }] : []),
{ ...markForScreenshot(page), pageComposition: true },
])
: mixedPageComposition
? buildMixedPageIr()
: webPageComposition
? screenshotPageSlices()
: multiPageAbsoluteComposition
? screenshotPageSlices({ authoredPageHeights: true })
: flowingVisualComposition
? screenshotPageSlices()
: singlePageVisualComposition
? [{ ...markForScreenshot(singleVisualPageRoot), pageComposition: true }]
: bodySinglePageVisualComposition
? [{ ...markForScreenshot(document.body), pageComposition: true }]
: pageComposition
? [{ ...markForScreenshot(document.body), pageComposition: true }]
: processChildren(document.body, 0);
while (ir.length && ir[0].type === 'pagebreak') ir.shift();
for (let index = ir.length - 1; index >= 0; index--) {
const node = ir[index];
if (
node.type !== 'image' ||
node.clip ||
node.pageComposition ||
node.height <= 1000
) {
continue;
}
const element = document.querySelector(`[data-h2d-id="${node.shotId}"]`);
if (!element) continue;
const rect = element.getBoundingClientRect();
const maxSliceHeight = 700;
const sliceCount = Math.ceil(rect.height / maxSliceHeight);
const slices = Array.from({ length: sliceCount }, (_, sliceIndex) => {
const sliceHeight = Math.min(
maxSliceHeight,
rect.height - sliceIndex * maxSliceHeight,
);
return {
...node,
shotId: sliceIndex === 0 ? node.shotId : nextShotId(),
height: Math.round(sliceHeight),
spacingBeforePx: sliceIndex === 0 ? node.spacingBeforePx : 0,
spacingAfterPx:
sliceIndex === sliceCount - 1 ? node.spacingAfterPx : 0,
clip: {
x: Math.max(0, Math.round(rect.left)),
y: Math.max(0, Math.round(rect.top + sliceIndex * maxSliceHeight)),
width: Math.round(rect.width),
height: Math.round(sliceHeight),
},
};
});
ir.splice(index, 1, ...slices);
}
// A centered "paper sheet" holding all the content on a tinted desk
// backdrop (body bg + one max-width/box-shadow child): the desk color is
// screen chrome, the sheet IS the page — take its paint instead.
const paperSheet = (() => {
const kids = [...document.body.children].filter(
(child) =>
isVisible(child) &&
((child.innerText || '').trim() || child.querySelector('img,svg,canvas,table')),
);
if (kids.length !== 1) return null;
const el = kids[0];
const st = cs(el);
if (!toHex(st.backgroundColor, { dropWhite: false })) return null;
const rect = el.getBoundingClientRect();
const centered = Math.abs(rect.left - (window.innerWidth - rect.right)) <= 24;
const coversContent = rect.height >= document.body.scrollHeight * 0.8;
const sheetLike = st.boxShadow !== 'none' || parseFloat(st.maxWidth) > 0;
return centered && coversContent && sheetLike ? el : null;
})();
const bodyBackground = toHex(cs(document.body).backgroundColor, {
dropWhite: false,
});
// The desk-vs-sheet call only holds for neutral backdrops: a saturated
// color or gradient behind the sheet is poster design, not screen chrome.
const backdropDesigned = (() => {
if (cs(document.body).backgroundImage.includes('gradient')) return true;
if (!bodyBackground) return false;
const channels = [0, 2, 4].map((i) => parseInt(bodyBackground.slice(i, i + 2), 16));
return Math.max(...channels) - Math.min(...channels) > 24;
})();
const deskSheet = backdropDesigned ? null : paperSheet;
const pageBg = deskSheet
? toHex(cs(deskSheet).backgroundColor, { dropWhite: true })
: bodyBackground
? toHex(cs(document.body).backgroundColor, { dropWhite: true })
: toHex(cs(document.documentElement).backgroundColor, { dropWhite: true });
const bodyHasPaint =
!deskSheet &&
(cs(document.body).backgroundImage !== 'none' || Boolean(bodyBackground));
const bgSource = bodyHasPaint ? document.body : document.documentElement;
const bgStyle = cs(bgSource);
const pagePseudoPaints = (which) => {
const pseudo = getComputedStyle(bgSource, which);
if (!pseudo || pseudo.content === 'none' || pseudo.content === 'normal') return false;
const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some(
(side) =>
parseFloat(pseudo[`border${side}Width`]) >= 1 &&
pseudo[`border${side}Style`] !== 'none',
);
return (
hasBorder ||
pseudo.backgroundImage !== 'none' ||
Boolean(toHex(pseudo.backgroundColor, { dropWhite: true }))
);
};
// a flat solid body color needs no backdrop screenshot: w:background
// renders the exact hex, while the header-image route's resampled tone
// visibly differs from same-color shading fills on content blocks
const backdropHasArt =
bgStyle.backgroundImage !== 'none' ||
pagePseudoPaints('::before') ||
pagePseudoPaints('::after') ||
Boolean(paperSheet && backdropDesigned);
if (
!pageComposition &&
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!flowingVisualComposition &&
!singlePageVisualComposition &&
!bodySinglePageVisualComposition &&
backdropHasArt
) {
const backdrop = document.createElement('div');
const width = window.innerWidth;
const height = window.innerHeight;
// park off-screen on the side the document ignores for overflow:
// in RTL, left-side overflow extends the scrollable area and shifts
// the capture surface origin, blanking every later element screenshot
const rtlDoc =
cs(document.documentElement).direction === 'rtl' ||
cs(document.body).direction === 'rtl';
Object.assign(backdrop.style, {
position: 'absolute',
[rtlDoc ? 'right' : 'left']: '-10000px',
top: '0',
width: `${width}px`,
height: `${height}px`,
backgroundColor: pageBg ? `#${pageBg}` : bgStyle.backgroundColor,
backgroundImage: bgStyle.backgroundImage,
backgroundSize: bgStyle.backgroundSize,
backgroundPosition: bgStyle.backgroundPosition,
backgroundRepeat: bgStyle.backgroundRepeat,
pointerEvents: 'none',
});
const appendPagePseudo = (which) => {
const pseudo = getComputedStyle(bgSource, which);
if (!pseudo || pseudo.content === 'none' || pseudo.content === 'normal') return;
const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some(
(side) =>
parseFloat(pseudo[`border${side}Width`]) >= 1 &&
pseudo[`border${side}Style`] !== 'none',
);
const hasPaint =
pseudo.backgroundImage !== 'none' ||
Boolean(toHex(pseudo.backgroundColor, { dropWhite: true }));
if (!hasBorder && !hasPaint) return;
const overlay = document.createElement('div');
Object.assign(overlay.style, {
position: 'absolute',
top: pseudo.top === 'auto' ? '0' : pseudo.top,
right: pseudo.right === 'auto' ? '0' : pseudo.right,
bottom: pseudo.bottom === 'auto' ? '0' : pseudo.bottom,
left: pseudo.left === 'auto' ? '0' : pseudo.left,
boxSizing: 'border-box',
backgroundColor: pseudo.backgroundColor,
backgroundImage: pseudo.backgroundImage,
backgroundSize: pseudo.backgroundSize,
backgroundPosition: pseudo.backgroundPosition,
backgroundRepeat: pseudo.backgroundRepeat,
borderTop: pseudo.borderTop,
borderRight: pseudo.borderRight,
borderBottom: pseudo.borderBottom,
borderLeft: pseudo.borderLeft,
opacity: pseudo.opacity,
});
backdrop.appendChild(overlay);
};
appendPagePseudo('::before');
appendPagePseudo('::after');
// Designed backdrop with a content sheet on top (poster on gradient):
// paint the sheet's box into the backdrop so page chrome = backdrop +
// sheet, and the flowing text keeps its readable card behind it.
if (paperSheet && backdropDesigned) {
const sheetRect = paperSheet.getBoundingClientRect();
const sheetStyle = cs(paperSheet);
const sheet = document.createElement('div');
Object.assign(sheet.style, {
position: 'absolute',
left: `${Math.round(sheetRect.left)}px`,
top: `${Math.round(Math.max(0, sheetRect.top))}px`,
width: `${Math.round(sheetRect.width)}px`,
height: `${Math.round(Math.max(100, height - Math.max(0, sheetRect.top)))}px`,
backgroundColor: sheetStyle.backgroundColor,
borderRadius: sheetStyle.borderRadius,
boxShadow: sheetStyle.boxShadow,
});
backdrop.appendChild(sheet);
}
document.body.appendChild(backdrop);
const shot = markForScreenshot(backdrop);
ir.unshift({
type: 'pagebg',
color: pageBg,
shotId: shot.shotId,
width,
height,
});
} else if (pageBg) {
ir.unshift({ type: 'pagebg', color: pageBg });
}
for (let index = ir.length - 1; index > 0; index--) {
if (ir[index].type === 'pagebreak' && ir[index - 1].type === 'spacer') {
ir.splice(index - 1, 1);
}
}
// Section boundaries stack spacers (padding-bottom + divider walk +
// padding-top emitted by different branches): the real CSS gap is the
// two paddings, so keep the two largest of a run and drop the rest.
for (let index = ir.length - 1; index >= 0; index--) {
if (ir[index].type !== 'spacer' || ir[index].bindsNeighbors) continue;
let first = index;
while (first > 0 && ir[first - 1].type === 'spacer' && !ir[first - 1].bindsNeighbors) first--;
if (first === index) continue;
const run = ir.slice(first, index + 1).map((node) => node.px || 0).sort((a, b) => b - a);
const merged = Math.min(260, run[0] + (run[1] || 0));
ir.splice(first, index - first + 1, { type: 'spacer', px: merged });
index = first;
}
const lastContent = ir[ir.length - 1];
if (lastContent?.spacingAfterPx != null) lastContent.spacingAfterPx = 0;
if (lastContent?.style?.spacingAfterPx != null) lastContent.style.spacingAfterPx = 0;
const bodyStyle = cs(document.body);
const cssLengthPx = (value) => {
const match = String(value || '').trim().match(/^([\d.]+)(px|pt|in|cm|mm)?$/i);
if (!match) return null;
const amount = parseFloat(match[1]);
return (
amount *
({ px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 }[
(match[2] || 'px').toLowerCase()
] || 1)
);
};
const namedPageSizes = {
a3: [1123, 1587],
a4: [794, 1123],
a5: [559, 794],
letter: [816, 1056],
legal: [816, 1344],
tabloid: [1056, 1632],
ledger: [1632, 1056],
};
let pageSizePx = null;
for (const sheet of [...document.styleSheets]) {
let rules;
try {
rules = [...sheet.cssRules];
} catch {
continue;
}
for (const rule of rules) {
if (rule.type !== CSSRule.PAGE_RULE) continue;
const parts = (rule.style.getPropertyValue('size') || '').trim().toLowerCase().split(/\s+/);
const orientation = parts.find((part) => part === 'landscape' || part === 'portrait');
const named = parts.find((part) => namedPageSizes[part]);
if (named) {
pageSizePx = [...namedPageSizes[named]];
} else {
const lengths = parts.map(cssLengthPx).filter((value) => value != null);
if (lengths.length >= 2) pageSizePx = [lengths[0], lengths[1]];
else if (lengths.length === 1) pageSizePx = [lengths[0], lengths[0] * Math.SQRT2];
}
if (pageSizePx && orientation === 'landscape' && pageSizePx[0] < pageSizePx[1]) {
pageSizePx.reverse();
}
if (pageSizePx && orientation === 'portrait' && pageSizePx[0] > pageSizePx[1]) {
pageSizePx.reverse();
}
break;
}
if (pageSizePx) break;
}
if (!pageSizePx && (multiPageComposition || mixedPageComposition)) {
const pageRect = (authoredPageRoots[0] || inferredPageRoots[0]).getBoundingClientRect();
pageSizePx = [pageRect.width, pageRect.height];
} else if (!pageSizePx && multiPageAbsoluteComposition) {
pageSizePx = [bodyRect.width, renderedPageHeight];
} else if (!pageSizePx && pageComposition) {
pageSizePx = [bodyRect.width, bodyRect.height];
}
pageSizePx ||= [794, 1123];
const composed =
pageComposition ||
multiPageComposition ||
slidePageComposition ||
mixedPageComposition ||
multiPageAbsoluteComposition ||
webPageComposition ||
flowingVisualComposition ||
singlePageVisualComposition ||
bodySinglePageVisualComposition;
// A natively-rendered flow document slightly taller than one page (e.g. a
// resume that strands two lines on page 2) reads as a one-page design.
// Word lays such docs out ~10% denser than the browser proxy (narrower
// Arial + width scale), so browser ratios up to ~1.22 are recoverable
// with a small whole-document squeeze applied to geometry and fonts.
// ratio against the page height at the ACTUAL viewport width — the
// viewport height is not resized when the authored width differs, so
// innerHeight is the wrong denominator there (880-wide doc in a
// 1024-proportioned window read as 0.95 pages instead of 1.11)
const flowCanvasWidth = Math.min(
window.innerWidth,
Math.max(Math.round(pageSizePx[0]), Math.ceil(bodyRect.width)),
);
const flowPageHeight = flowCanvasWidth * (pageSizePx[1] / pageSizePx[0]);
const flowRatio = bodyHeight / flowPageHeight;
const squeezableFlow = !composed && !authoredPageRoots.length && !inferredPageRoots.length;
(globalThis.__h2dTrace ||= []).push({
where: 'pageFitSqueeze',
flowRatio: Math.round(flowRatio * 1000) / 1000,
bodyHeight: Math.round(bodyHeight),
renderedPageHeight,
composed: Boolean(composed),
authoredRoots: authoredPageRoots.length,
inferredRoots: inferredPageRoots.length,
});
// Word lays text-heavy docs ~10% denser than the browser proxy (narrower
// Arial), which the 0.9 fudge credits. Table/fixed-height-heavy docs get
// no such densening, so past ~1.05 the fudge under-squeezes and the last
// block still strands (invoice stamp boxes) — taper the credit away.
const pageFitSqueeze =
squeezableFlow && flowRatio > 1.05 && flowRatio <= 1.22
? // table/fixed-height-heavy docs (invoices) get none of the Arial
// densening the 0.9 fudge below assumes — squeeze at face value
// plus slack so the trailing block doesn't strand by one line
// 0.90/0.82 (was 0.92/0.84): Word (Mac) lays these table-heavy
// docs up to ~9% taller than the browser proxy — the old floor
// left a marginal one-pager's footer stranding on page 2
Math.max(0.8, Math.min(1, 0.88 / flowRatio))
: squeezableFlow && flowRatio > 1.02 && flowRatio <= 1.05
? Math.max(0.88, Math.min(1, 0.98 / (flowRatio * 0.9)))
: // A doc filling exactly one browser page (invoices, forms) is a
// one-page design; Word's layout runs a few percent taller (table
// leading, min row heights), so squeeze preemptively.
squeezableFlow && flowRatio > 0.96 && flowRatio <= 1.02
? 0.94
: 1;
// A viewport wider than the authored canvas (1024 reload of a
// letter-width design) centers the body with auto margins — a viewport
// artifact, not an authored page margin. Measure against the canvas and
// strip the centering offset, or the page gets ~3cm fake margins and the
// content shrinks by the canvas/viewport ratio.
const canvasWidth = Math.min(
window.innerWidth,
Math.max(Math.round(pageSizePx[0]), Math.ceil(bodyRect.width)),
);
const centerOffset = Math.max(0, (window.innerWidth - canvasWidth) / 2);
// flowed documents get a small margin floor: an authored padding:0 body
// puts Word text hard against the physical page edge, which no print
// layout intends; composed pages keep exact geometry. The floor widens
// the margins beyond the measured geometry, so the reported canvas must
// widen by the same amount or the px->page scale over-sizes the content
// and Word clips it at the right margin.
const rawLeftPx = composed
? Math.max(0, Math.round(bodyRect.left - centerOffset))
: Math.max(
0,
Math.round(bodyRect.left - centerOffset + (parseFloat(bodyStyle.paddingLeft) || 0)),
);
const rawRightPx = Math.max(
0,
composed
? Math.round(canvasWidth - (bodyRect.right - centerOffset))
: Math.round(
canvasWidth -
(bodyRect.right - centerOffset) +
(parseFloat(bodyStyle.paddingRight) || 0),
),
);
const leftPx = composed ? rawLeftPx : Math.max(24, rawLeftPx);
const rightPx = composed ? rawRightPx : Math.max(24, rawRightPx);
const metaContent = (name) =>
document.querySelector(`meta[name="${name}" i]`)?.content?.trim() || undefined;
ir.unshift({
type: 'docsettings',
viewportWidthPx: canvasWidth + (leftPx - rawLeftPx) + (rightPx - rawRightPx),
rtl: docRTL || undefined,
lang: document.documentElement.lang || undefined,
meta: {
title: (document.title || '').trim() || undefined,
author: metaContent('author'),
description: metaContent('description'),
keywords: metaContent('keywords'),
},
composed: composed || undefined,
pageFitSqueeze: pageFitSqueeze < 1 ? pageFitSqueeze : undefined,
pageSizePx: { width: Math.round(pageSizePx[0]), height: Math.round(pageSizePx[1]) },
marginsPx: {
top: composed
? Math.max(0, Math.round(bodyRect.top))
: Math.max(24, Math.round(bodyRect.top + (parseFloat(bodyStyle.paddingTop) || 0))),
bottom: composed
? 0
: Math.max(24, Math.round(parseFloat(bodyStyle.paddingBottom) || 0)),
left: leftPx,
right: rightPx,
},
});
return ir;
}
global.__html2docxPages = { build };
})(globalThis);
+295
View File
@@ -0,0 +1,295 @@
(function installHtmlTableExtractor(global) {
function extractTable(el, deps) {
const {
bgHex,
isCompactPaintedLabel,
bordersOf,
cellPaddingOf,
collectRuns,
cs,
hasBlockChildren,
isRTL,
isVisible,
markForScreenshot,
processChildren,
textAlignOf,
toHex,
} = deps;
// Gradient-painted cells (th { background: linear-gradient(...) }) have a
// transparent backgroundColor; approximate with the first gradient stop so
// white header text doesn't land on a white cell.
const gradHex = (node) => {
const bgImage = cs(node).backgroundImage;
if (!bgImage || !bgImage.includes('gradient')) return null;
const m = bgImage.match(/rgba?\([^)]*\)|#[0-9a-fA-F]{3,8}/);
return m ? toHex(m[0]) : null;
};
const cellShading = (cell, tr) => {
const own = bgHex(cell) || gradHex(cell);
if (own) return own;
const behind = bgHex(tr) || gradHex(tr);
if (!behind) return null;
// A cell's own opaque paint (even white, which bgHex drops) covers the
// row color — without this the row bleeds through and the cell's dark
// text lands on dark row shading.
return toHex(cs(cell).backgroundColor) || behind;
};
const rows = [];
const boundarySamples = [];
const activeSpans = [];
let gridColumnCount = 0;
const tableRect = el.getBoundingClientRect();
const tableRows = [...el.querySelectorAll(
':scope > thead > tr, :scope > tbody > tr, :scope > tfoot > tr, :scope > tr',
)];
for (let rowIndex = 0; rowIndex < tableRows.length; rowIndex++) {
const tr = tableRows[rowIndex];
if (!isVisible(tr)) continue;
const cells = [];
const rowBorders = bordersOf(tr);
const occupied = new Set();
for (const span of activeSpans) {
if (span.endRow <= rowIndex) continue;
for (let col = span.gridStart; col < span.gridStart + span.colspan; col++) {
occupied.add(col);
}
cells.push({
...span.cell,
runs: [],
children: undefined,
gridStart: span.gridStart,
verticalMerge: 'continue',
});
}
const directCells = [...tr.children].filter(
(cell) => cell.tagName === 'TD' || cell.tagName === 'TH',
);
const exactVisualRow = directCells.some(
(cell) => [...cell.children].filter(isCompactPaintedLabel).length >= 2,
);
if (exactVisualRow && !activeSpans.some((span) => span.endRow > rowIndex)) {
const colspan = directCells.reduce((sum, cell) => sum + (cell.colSpan || 1), 0);
cells.push({
colspan,
rowspan: 1,
gridStart: 0,
children: [markForScreenshot(tr)],
borders: {},
padPx: { top: 0, right: 0, bottom: 0, left: 0 },
});
const rect = tr.getBoundingClientRect();
(boundarySamples[0] ||= []).push(rect.left - tableRect.left);
(boundarySamples[colspan] ||= []).push(rect.right - tableRect.left);
gridColumnCount = Math.max(gridColumnCount, colspan);
rows.push({ cells, heightPx: Math.round(rect.height) });
continue;
}
let nextColumn = 0;
for (const cell of tr.children) {
if (cell.tagName !== 'TD' && cell.tagName !== 'TH') continue;
const colspan = cell.colSpan || 1;
while (
[...Array(colspan).keys()].some((offset) => occupied.has(nextColumn + offset))
) {
nextColumn++;
}
const rowspan = cell.rowSpan || 1;
const entry = {
colspan,
rowspan,
gridStart: nextColumn,
verticalMerge: rowspan > 1 ? 'restart' : undefined,
shading: cellShading(cell, tr),
bold: cell.tagName === 'TH' || undefined,
borders: bordersOf(cell) || rowBorders,
padPx: cellPaddingOf(cell),
rtl: isRTL(cell) || undefined,
};
const textAlign = textAlignOf(cell);
if (textAlign === 'center' || textAlign === 'right') entry.align = textAlign;
const verticalAlign = cs(cell).verticalAlign;
if (verticalAlign === 'middle') entry.vAlign = 'center';
else if (verticalAlign === 'bottom') entry.vAlign = 'bottom';
// decorations: false - the cell entry already owns border/shading;
// paragraphs merged from the cell's inline children must not inherit
// the td's border as a paragraph border (drew stray lines inside cells)
if (hasBlockChildren(cell)) {
entry.children = processChildren(cell, 2, { decorations: false });
}
else {
entry.runs = collectRuns(cell);
// CJK cell text: with no explicit line height Word applies the CJK
// font's own leading (Yu Mincho ≈1.7x) — uncapped, invoice rows
// balloon and push a one-page layout onto a second page. Pin the
// browser's line box; skip tight leadings that EXACT would clip.
const lineHeightPx = parseFloat(cs(cell).lineHeight);
const fontSizePx = parseFloat(cs(cell).fontSize);
const hasCJK = (entry.runs || []).some((run) =>
/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]/.test(run.text || ''),
);
if (hasCJK && lineHeightPx && fontSizePx && lineHeightPx / fontSizePx >= 1.3) {
entry.style = { ...entry.style, cjk: true, exactLineHeightPx: lineHeightPx };
}
}
// Empty cell showing placeholder text via ::before content
// ("Click to edit..." on contenteditable template cells): keep the
// rendered placeholder so the grid doesn't collapse into blank space.
if (!entry.children && !(entry.runs || []).length) {
const pseudo = getComputedStyle(cell, '::before');
const m = (pseudo.content || '').match(/^"(.*)"$/);
if (m && m[1].trim()) {
const run = { text: m[1], color: toHex(pseudo.color) || '999999' };
if (pseudo.fontStyle === 'italic') run.italic = true;
const sz = parseFloat(pseudo.fontSize);
if (sz) run.sizePx = sz;
entry.runs = [run];
}
}
// Short cell content ("Wave 1" pills, "11." numbers): record the
// forced single-line width (nowrap min-content, works even when the
// browser already crushed the column) so the generator can guarantee
// the column never wraps it letter-by-letter into a fake vertical
// stack.
{
const cellText = (cell.innerText || '').trim();
if (cellText && cellText.length <= 40 && !cellText.includes('\n')) {
// nowrap + Range: the true single-line CONTENT width. Plain
// scrollWidth reports the stretched layout width for uncrushed
// cells, which would inflate every column's floor equally.
// inner width BEFORE forcing nowrap — nowrap reflows the auto
// table layout and stretches the cell to fit the text
const pad = cellPaddingOf(cell);
const innerWidth =
cell.getBoundingClientRect().width - (pad.left || 0) - (pad.right || 0);
const previousWhiteSpace = cell.style.whiteSpace;
cell.style.whiteSpace = 'nowrap';
try {
const range = document.createRange();
range.selectNodeContents(cell);
let textWidth = range.getBoundingClientRect().width;
// Only short label-like content that the browser itself renders
// on one line gets a keep-on-one-line floor. A cell the browser
// already wrapped must be allowed to wrap in Word too — floors
// from wrapped cells starve the remaining columns (a 5-column
// table's last column collapsed to 600 twips).
if (textWidth > 0 && textWidth <= 160 && textWidth <= innerWidth + 2) {
// Word's substituted font may run much wider than the webfont.
const wordWidth = window.__h2dWordFontLineWidth
? window.__h2dWordFontLineWidth(cell)
: 0;
entry.oneLineWidthPx = Math.round(Math.max(textWidth, wordWidth));
}
} catch (e) {
/* leave unset */
}
cell.style.whiteSpace = previousWhiteSpace || '';
}
}
cells.push(entry);
const rect = cell.getBoundingClientRect();
const startPx = isRTL(el) ? tableRect.right - rect.right : rect.left - tableRect.left;
const endPx = isRTL(el) ? tableRect.right - rect.left : rect.right - tableRect.left;
(boundarySamples[nextColumn] ||= []).push(startPx);
(boundarySamples[nextColumn + colspan] ||= []).push(endPx);
if (rowspan > 1) {
activeSpans.push({
gridStart: nextColumn,
colspan,
endRow: rowIndex + rowspan,
cell: {
colspan,
shading: entry.shading,
borders: entry.borders,
padPx: entry.padPx,
rtl: entry.rtl,
align: entry.align,
vAlign: entry.vAlign,
},
});
for (let col = nextColumn; col < nextColumn + colspan; col++) occupied.add(col);
}
nextColumn += colspan;
}
if (!cells.length) continue;
cells.sort((a, b) => a.gridStart - b.gridStart);
gridColumnCount = Math.max(
gridColumnCount,
...cells.map((cell) => cell.gridStart + (cell.colspan || 1)),
);
const renderedHeight = Math.round(tr.getBoundingClientRect().height);
const rowText = (tr.innerText || '').trim();
// Only a real header row repeats across pages: flagging plain first
// rows duplicates a data row at every page break.
const isHeaderRow =
tr.parentElement?.tagName === 'THEAD' ||
(directCells.length > 0 && directCells.every((cell) => cell.tagName === 'TH'));
rows.push({
cells,
header: isHeaderRow || undefined,
rawHeightPx: renderedHeight,
// Compact text rows should use Word's natural height. Keeping the
// browser's measured minimum double-counts small font-metric/padding
// differences and makes ordinary data tables visibly too loose.
heightPx:
renderedHeight >= 80 || (renderedHeight >= 30 && !rowText)
? renderedHeight
: undefined,
});
}
if (!rows.length) return [];
// Uniform form grid (fill-in sheets sized for handwriting): the author
// gave every body row the same generous height. Preserving it only on
// the EMPTY rows (rule above) makes filled rows collapse to text height
// and the grid uneven — carry the shared height to all of them.
{
const body = rows.slice(1);
const heights = body.map((row) => row.rawHeightPx);
if (
body.length >= 4 &&
Math.min(...heights) >= 32 &&
Math.max(...heights) - Math.min(...heights) <= 4
) {
for (const row of body) row.heightPx = row.rawHeightPx;
}
for (const row of rows) delete row.rawHeightPx;
}
const boundaries = Array(gridColumnCount + 1).fill(null);
boundaries[0] = 0;
boundaries[gridColumnCount] = tableRect.width;
for (let index = 1; index < gridColumnCount; index++) {
const samples = boundarySamples[index];
if (samples?.length) {
const sorted = [...samples].sort((a, b) => a - b);
boundaries[index] = sorted[Math.floor(sorted.length / 2)];
}
}
let previousKnown = 0;
for (let index = 1; index <= gridColumnCount; index++) {
if (boundaries[index] == null) continue;
const span = index - previousKnown;
const start = boundaries[previousKnown];
const end = boundaries[index];
for (let fill = 1; fill < span; fill++) {
boundaries[previousKnown + fill] = start + ((end - start) * fill) / span;
}
previousKnown = index;
}
const colWidths = boundaries
.slice(0, -1)
.map((start, index) => Math.max(1, Math.round(boundaries[index + 1] - start)));
return [{
type: 'table',
rows,
colWidths,
outerBorder: bordersOf(el),
shading: bgHex(el),
preserveRowHeights: true,
// rendered height drives the keep-together call: a table that fits on
// one page should jump to the next page whole instead of splitting
heightPx: Math.round(tableRect.height),
rtl: isRTL(el) || undefined,
}];
}
global.__html2docxTable = { extractTable };
})(globalThis);
@@ -0,0 +1,51 @@
(function installVisualEffectClassifier(global) {
function needsScreenshot(el, deps) {
const { bgHex, cs, fullBorderOf } = deps;
// A broken image's rendered box is Chrome's placeholder chrome (icon +
// clipped alt text), never the author's design — even when transformed
// or shadowed, let the IMG branch fall back to alt text instead.
if (el.tagName === 'IMG' && (!el.complete || el.naturalWidth === 0)) return false;
const style = cs(el);
const rect = el.getBoundingClientRect();
if (rect.width < 20 || rect.height < 12 || rect.width > 1000 || rect.height > 1000) {
return false;
}
const transformed = style.transform && style.transform !== 'none';
const shadowed = style.boxShadow && style.boxShadow !== 'none';
const filtered =
(style.filter && style.filter !== 'none') ||
(style.backdropFilter && style.backdropFilter !== 'none');
const radii = [
style.borderTopLeftRadius,
style.borderTopRightRadius,
style.borderBottomRightRadius,
style.borderBottomLeftRadius,
].map((value) => parseFloat(value) || 0);
const complexRadius =
Math.max(...radii) >= 8 &&
(Boolean(bgHex(el)) || Boolean(fullBorderOf(el))) &&
(new Set(radii.map((radius) => Math.round(radius))).size > 1 ||
style.overflow === 'hidden' ||
Math.max(...radii) >= Math.min(rect.width, rect.height) * 0.25);
// Text-heavy cards must stay editable/searchable: soft shadows, filters
// and rounded corners are not worth rasterizing paragraphs of content.
// Transforms still rasterize (flowed text would land in the wrong place).
// CJK counts double: a 60-char Japanese question carries as much content
// as a 120-char English sentence.
const text = (el.innerText || '').trim();
const cjkCount = (text.match(/[\u3000-\u9fff\uf900-\ufaff\uff66-\uff9f]/g) || []).length;
const weightedTextLength = text.length + cjkCount;
// Many short lines (schedule cards, subject lists) are as content-heavy
// as long prose \u2014 a 5-day timetable trapped in pixels is uneditable.
const lineCount = text ? text.split('\n').filter((line) => line.trim()).length : 0;
const textHeavy = weightedTextLength > 80 || (lineCount >= 4 && text.length >= 30);
const compactRoundedCard =
complexRadius && rect.height <= 160 && weightedTextLength <= 200 && lineCount < 4;
return Boolean(
transformed ||
((shadowed || filtered || complexRadius) && (!textHeavy || compactRoundedCard)),
);
}
global.__html2docxVisualEffects = { needsScreenshot };
})(globalThis);
+499
View File
@@ -0,0 +1,499 @@
/**
* Orchestration: render the HTML in the host's browser, extract the intent
* tree, screenshot image-like elements, generate the DOCX.
*/
import type { BrowserDriver, ClipRect } from './driver'
import { BROWSER_HELPER_SCRIPTS, EXTRACTOR_CALL } from './extract'
import { generateDocx } from './generate'
import { FONT_RULES } from './generate/fonts'
export type ConvertStage = 'load' | 'extract' | 'screenshot' | 'generate'
export interface ConvertOptions {
onProgress?: (progress: { stage: ConvertStage; pct: number }) => void
signal?: AbortSignal
log?: (message: string) => void
/** Debug: in-page probes record `__h2dTrace` entries for elements matching this selector. */
traceSelector?: string
/** Debug: receives the extracted IR and trace probes before generation. */
onIr?: (ir: any[], trace: unknown[]) => void
}
export interface ConvertResult {
docx: Uint8Array
ir: any[]
/** Text that only survives as pixels (inside screenshots); lets evaluations
* tell "intentionally rasterized" from "actually lost". */
screenshotText: string
stats: { screenshots: number; rasterizedDocumentText: boolean }
}
/** A4 at 96dpi so layout (line wraps, column gaps) matches print. */
const A4_VIEWPORT = { width: 794, height: 1123, deviceScaleFactor: 2 }
const NAVIGATION_TIMEOUT_MS = 30000
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) throw new DOMException('html2docx conversion aborted', 'AbortError')
}
export async function convertHtmlToDocx(
input: { url: string },
driver: BrowserDriver,
options: ConvertOptions = {},
): Promise<ConvertResult> {
const { signal, traceSelector, onIr } = options
const log = options.log ?? (() => {})
const progress = (stage: ConvertStage, pct: number) => options.onProgress?.({ stage, pct })
const { url } = input
progress('load', 0)
await driver.setViewport(A4_VIEWPORT)
if (traceSelector) {
await driver.addInitScript(`globalThis.__h2dTraceSelector = ${JSON.stringify(traceSelector)};`)
}
log(`[html2docx] loading ${url}`)
await driver.goto(url, { timeoutMs: NAVIGATION_TIMEOUT_MS })
await driver.evaluate(() => document.fonts.ready.catch(() => {}))
await sleep(300)
throwIfAborted(signal)
// Authoring templates commonly use an 880px design canvas and are then
// scaled to A4. Extract at that authored width so narrower A4 reflow does
// not create artificial wraps and inflated table-row heights.
const authoredWidth = await driver.evaluate<number | null>(() => {
// Some document templates constrain body directly; responsive webpages
// more often constrain repeated `.inner`/`.container` wrappers. At the
// initial A4 viewport those pages may already have crossed into their
// mobile breakpoint, destroying desktop grids before extraction.
const candidates = [document.body, ...document.body.querySelectorAll('*')]
const widths = candidates.flatMap((el) => {
const rect = el.getBoundingClientRect()
const maxWidth = parseFloat(getComputedStyle(el).maxWidth)
return Number.isFinite(maxWidth) &&
maxWidth > window.innerWidth &&
maxWidth <= 1600 &&
rect.width >= window.innerWidth * 0.55 &&
rect.height >= 20
? [maxWidth]
: []
})
return widths.length ? Math.round(Math.max(...widths)) : null
})
// Content that overflows the A4 viewport horizontally (a 6-column table
// whose last column collapses to 1px) renders broken at 794px while the
// evaluation baseline at 1024px shows it intact. Reload wider whenever
// the layout visibly does not fit.
const overflowsA4 =
!authoredWidth &&
(await driver.evaluate<boolean>(() => {
if (document.documentElement.scrollWidth > window.innerWidth + 8) return true
if (
[...document.querySelectorAll('table')].some(
(table) => table.scrollWidth > table.clientWidth + 4,
)
) {
return true
}
// table-layout:auto absorbs overflow by crushing cells instead of
// scrolling — a cell whose content no longer fits on one word is the
// telltale ("Wave 1" pills stacking letter-by-letter).
return [...document.querySelectorAll('td, th')].some(
(cell) => cell.scrollWidth > cell.clientWidth + 2,
)
}))
if (authoredWidth || overflowsA4) {
const renderWidth = Math.max(1024, authoredWidth || 0)
await driver.setViewport({
width: renderWidth,
height: Math.round((1123 * renderWidth) / 794),
deviceScaleFactor: 2,
})
await driver.goto(url, { timeoutMs: NAVIGATION_TIMEOUT_MS })
await driver.evaluate(() => document.fonts.ready.catch(() => {}))
await sleep(300)
}
throwIfAborted(signal)
progress('load', 60)
// Offscreen website images may remain deferred even without an explicit
// loading="lazy" attribute. Visit the full page before screenshot-based
// extraction, then wait for every reachable image to decode.
await driver.evaluate(async () => {
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
const originalY = window.scrollY
const htmlScrollBehavior = document.documentElement.style.scrollBehavior
const bodyScrollBehavior = document.body.style.scrollBehavior
document.documentElement.style.scrollBehavior = 'auto'
document.body.style.scrollBehavior = 'auto'
const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight)
const step = Math.max(400, Math.round(window.innerHeight * 0.75))
for (let y = 0; y <= maxY; y += step) {
window.scrollTo(0, y)
await wait(60)
}
window.scrollTo(0, maxY)
await wait(100)
const imageWaits = [...document.images].map((image) => {
if (image.complete && image.naturalWidth > 0) {
return image.decode?.().catch(() => {})
}
return new Promise<void>((resolve) => {
const finish = () => resolve()
image.addEventListener('load', finish, { once: true })
image.addEventListener('error', finish, { once: true })
setTimeout(finish, 15000)
})
})
await Promise.all(imageWaits)
window.scrollTo(0, originalY)
await wait(100)
document.documentElement.style.scrollBehavior = htmlScrollBehavior
document.body.style.scrollBehavior = bodyScrollBehavior
})
await sleep(200)
throwIfAborted(signal)
progress('load', 100)
// Word substitutes unavailable webfonts (Cormorant → Georgia, Playfair →
// Georgia, …) with often much wider glyphs. Expose a measurement helper
// that re-measures a one-line label under the substituted font so width
// floors reflect what Word will render, not the authored webfont.
await driver.evaluate(
(rules: [string, string, string][]) => {
const parsed = rules.map(
([source, flags, name]) => [new RegExp(source, flags), name] as [RegExp, string],
)
const w = window as any
w.__h2dWordFontLineWidth = (el: HTMLElement) => {
let family: string
try {
family = getComputedStyle(el).fontFamily || ''
} catch {
return 0
}
let mapped = 'Arial'
for (const [re, name] of parsed) {
if (re.test(family)) {
mapped = name
break
}
}
const prevFont = el.style.fontFamily
const prevWhiteSpace = el.style.whiteSpace
let width = 0
try {
el.style.fontFamily = mapped
el.style.whiteSpace = 'nowrap'
const range = document.createRange()
range.selectNodeContents(el)
width = range.getBoundingClientRect().width
} catch {
/* keep 0 */
}
el.style.fontFamily = prevFont || ''
el.style.whiteSpace = prevWhiteSpace || ''
return width
}
},
FONT_RULES.map(([re, name]) => [re.source, re.flags, name]),
)
for (const source of BROWSER_HELPER_SCRIPTS) {
await driver.addScript(source)
}
log('[html2docx] extracting intent tree')
progress('extract', 0)
const ir = await driver.evaluate<any[]>(EXTRACTOR_CALL)
if (onIr) {
const trace = await driver.evaluate<unknown[]>(() => (globalThis as any).__h2dTrace || [])
onIr(ir, trace)
}
log(`[html2docx] extracted ${ir.length} top-level nodes`)
throwIfAborted(signal)
progress('extract', 100)
// Broken images render Chrome's placeholder chrome (icon + clipped alt
// text) — never authored design. Hide them so they can't bleed into any
// element screenshot (extraction already emitted their alt-text fallback).
await driver.evaluate(() => {
for (const img of document.querySelectorAll('img')) {
if (!img.complete || img.naturalWidth === 0) img.style.visibility = 'hidden'
}
})
// screenshot every element marked as image-like
const images: Record<string, Uint8Array> = {}
const shotIds: string[] = []
const shotNodes = new Map<string, any>()
const pageBgShotIds = new Set<string>(
ir.filter((node) => node.type === 'pagebg' && node.shotId).map((node) => node.shotId),
)
const collectRunShots = (runs: any[] | undefined) => {
for (const run of runs || []) {
if (run.inlineImage && run.shotId) {
shotIds.push(run.shotId)
if (run.unwrap || run.clip) shotNodes.set(run.shotId, run)
}
}
}
;(function collectShots(nodes: any[]) {
for (const n of nodes) {
if (n.type === 'image' || n.type === 'floatimg' || (n.type === 'pagebg' && n.shotId)) {
shotIds.push(n.shotId)
shotNodes.set(n.shotId, n)
}
collectRunShots(n.runs)
for (const item of n.items || []) collectRunShots(item.runs)
for (const key of ['children', 'cells']) {
if (Array.isArray(n[key])) {
for (const sub of n[key]) {
collectRunShots(sub.runs)
if (sub.children) collectShots(sub.children)
}
if (key === 'children') collectShots(n[key])
}
}
if (n.rows) {
for (const row of n.rows) {
for (const cell of row.cells) {
collectRunShots(cell.runs)
if (cell.children) collectShots(cell.children)
}
}
}
}
})(ir)
const uniqueShotIds = [...new Set(shotIds)]
let shotIndex = 0
for (const id of uniqueShotIds) {
throwIfAborted(signal)
progress('screenshot', Math.round((shotIndex++ / Math.max(1, uniqueShotIds.length)) * 100))
const shotNode = shotNodes.get(id)
const selector = `[data-h2d-id="${id}"]`
const hasElement = shotNode?.clip ? false : await driver.elementExists(selector)
if (!hasElement && !shotNode?.clip) continue
try {
if (shotNode?.unwrap) {
// Crushed inline label (letters stacked in a too-narrow column):
// relax to its natural one-line size for the screenshot.
await driver.evaluate((shotId: string) => {
const target = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)
if (!target) return
target.setAttribute('data-h2d-unwrap-style', target.getAttribute('style') || '')
target.style.whiteSpace = 'nowrap'
target.style.width = 'max-content'
target.style.maxWidth = 'none'
}, id)
}
if (shotNode?.isolate) {
await driver.evaluate((shotId: string) => {
const target = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)
if (!target) return
for (const candidate of document.body.querySelectorAll<HTMLElement>('*')) {
if (candidate === target || candidate.contains(target) || target.contains(candidate)) {
continue
}
candidate.setAttribute('data-h2d-isolate-visibility', candidate.style.visibility || '')
candidate.style.visibility = 'hidden'
}
// surrounding paint must not leak into the shot: the page and
// the target's ancestors (white content sheet) otherwise give
// the capture an opaque bounding box that occludes neighboring
// floats in Word
let scrub = target.parentElement
while (scrub) {
scrub.setAttribute('data-h2d-isolate-bg', scrub.getAttribute('style') || '')
scrub.style.background = 'transparent'
scrub = scrub.parentElement
}
}, id)
}
if (pageBgShotIds.has(id)) {
await driver.evaluate((shotId: string) => {
const backdrop = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)!
for (const child of document.body.children as HTMLCollectionOf<HTMLElement>) {
child.setAttribute('data-h2d-old-visibility', child.style.visibility || '')
child.style.visibility = child === backdrop ? 'visible' : 'hidden'
}
backdrop.setAttribute('data-h2d-old-style', backdrop.getAttribute('style') || '')
Object.assign(backdrop.style, {
position: 'fixed',
left: '0',
top: '0',
zIndex: '2147483647',
visibility: 'visible',
})
}, id)
}
// Badges/ribbons absolutely positioned to overhang their card's box
// (top: -12px "MOST VALUE" pills) are cut in half by an element
// screenshot — expand the capture to the union of the element and
// its near overhanging children, and resize the node to match.
let overhang: ClipRect | null = null
if (hasElement && shotNode?.type === 'image' && !shotNode.pageComposition && !shotNode.clip) {
overhang = await driver.evaluate<ClipRect | null>((shotId: string) => {
const target = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)
if (!target) return null
const ts = getComputedStyle(target)
if (ts.overflow === 'hidden' || ts.overflow === 'clip') return null
const r = target.getBoundingClientRect()
const box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom }
for (const d of target.querySelectorAll('*')) {
if (getComputedStyle(d).position !== 'absolute') continue
const dr = d.getBoundingClientRect()
if (!dr.width || !dr.height) continue
// near overhangs only — far-flung decorations stay dropped
if (
dr.left < r.left - 48 ||
dr.right > r.right + 48 ||
dr.top < r.top - 48 ||
dr.bottom > r.bottom + 48
)
continue
box.left = Math.min(box.left, dr.left)
box.top = Math.min(box.top, dr.top)
box.right = Math.max(box.right, dr.right)
box.bottom = Math.max(box.bottom, dr.bottom)
}
if (
box.left >= r.left - 1 &&
box.top >= r.top - 1 &&
box.right <= r.right + 1 &&
box.bottom <= r.bottom + 1
)
return null
// rects are viewport-relative and earlier element screenshots
// may have scrolled the page; the clip needs page coordinates.
// In RTL the horizontal overflow hides LEFT of the viewport, so
// page x = viewport x + overflow + scrollLeft (scrollLeft <= 0).
const doc = document.documentElement
const rtlShift =
getComputedStyle(doc).direction === 'rtl' ||
getComputedStyle(document.body).direction === 'rtl'
? Math.max(0, doc.scrollWidth - doc.clientWidth)
: 0
const x = Math.max(0, Math.round(box.left + window.scrollX + rtlShift))
const y = Math.max(0, Math.round(box.top + window.scrollY))
return {
x,
y,
width: Math.round(box.right - box.left),
height: Math.round(box.bottom - box.top),
}
}, id)
}
if (overhang) {
images[id] = await driver.screenshot({ clip: overhang })
shotNode.width = overhang.width
shotNode.height = overhang.height
} else if (shotNode?.clip) {
images[id] = await driver.screenshot({ clip: shotNode.clip })
} else {
// Element screenshots hand viewport coordinates to CDP, whose clip
// origin is the LEFTMOST scrollable content. An RTL document with
// horizontal overflow hides that overflow left of the viewport, so
// the two origins differ by the overflow width and the capture
// lands shifted (TOC numbers / line starts cut off). Take an
// explicit page-coordinate clip instead.
const rtlBox = await driver.evaluate<ClipRect | null>((shotId: string) => {
const doc = document.documentElement
const rtl =
getComputedStyle(doc).direction === 'rtl' ||
getComputedStyle(document.body).direction === 'rtl'
const shift = rtl ? Math.max(0, doc.scrollWidth - doc.clientWidth) : 0
if (!shift) return null
const target = document.querySelector(`[data-h2d-id="${shotId}"]`)
if (!target) return null
const r = target.getBoundingClientRect()
return {
x: Math.max(0, Math.round(r.left + shift + doc.scrollLeft)),
y: Math.max(0, Math.round(r.top + window.scrollY)),
width: Math.round(r.width),
height: Math.round(r.height),
}
}, id)
const omitBackground = Boolean(shotNode?.isolate)
const shot = rtlBox
? await driver.screenshot({ clip: rtlBox, omitBackground })
: await driver.screenshotElement(selector, { omitBackground })
if (shot) images[id] = shot
}
if (images[id]) log(`[html2docx] screenshot ${id}: ${images[id].length} bytes`)
} catch (e) {
log(`[html2docx] screenshot ${id} failed: ${e instanceof Error ? e.message : String(e)}`)
} finally {
if (shotNode?.unwrap) {
await driver.evaluate((shotId: string) => {
const target = document.querySelector(`[data-h2d-id="${shotId}"]`)
if (!target) return
target.setAttribute('style', target.getAttribute('data-h2d-unwrap-style') || '')
target.removeAttribute('data-h2d-unwrap-style')
}, id)
}
if (shotNode?.isolate) {
await driver.evaluate(() => {
for (const candidate of document.querySelectorAll<HTMLElement>(
'[data-h2d-isolate-visibility]',
)) {
candidate.style.visibility = candidate.getAttribute('data-h2d-isolate-visibility') || ''
candidate.removeAttribute('data-h2d-isolate-visibility')
}
for (const scrubbed of document.querySelectorAll('[data-h2d-isolate-bg]')) {
scrubbed.setAttribute('style', scrubbed.getAttribute('data-h2d-isolate-bg') || '')
scrubbed.removeAttribute('data-h2d-isolate-bg')
}
})
}
if (pageBgShotIds.has(id)) {
await driver.evaluate((shotId: string) => {
const backdrop = document.querySelector(`[data-h2d-id="${shotId}"]`)
if (backdrop) {
backdrop.setAttribute('style', backdrop.getAttribute('data-h2d-old-style') || '')
backdrop.removeAttribute('data-h2d-old-style')
}
for (const child of document.body.children as HTMLCollectionOf<HTMLElement>) {
child.style.visibility = child.getAttribute('data-h2d-old-visibility') || ''
child.removeAttribute('data-h2d-old-visibility')
}
}, id)
}
}
}
progress('screenshot', 100)
// Text living inside rasterized elements: it is present in the DOCX as
// pixels, not as runs. Exported for evaluation so text-coverage checks
// can distinguish "intentionally rasterized" from "actually lost".
const rasterizedDocumentText = [...shotNodes.values()].some((node) => node.capturesDocumentText)
const screenshotText = await driver.evaluate<string>((includeBodyText: boolean) => {
const parts: string[] = []
if (includeBodyText) {
const bodyText = (document.body.innerText || '').trim()
if (bodyText) parts.push(bodyText)
}
for (const el of document.querySelectorAll<HTMLElement>('[data-h2d-id]')) {
const text = (
el.innerText ||
(el.tagName === 'IMG' ? el.getAttribute('alt') : '') ||
''
).trim()
if (text) parts.push(text)
}
return parts.join('\n')
}, rasterizedDocumentText)
throwIfAborted(signal)
log('[html2docx] generating docx')
progress('generate', 0)
const docx = new Uint8Array(await generateDocx(ir, images))
log(`[html2docx] generated ${docx.length} bytes`)
progress('generate', 100)
return {
docx,
ir,
screenshotText,
stats: { screenshots: Object.keys(images).length, rasterizedDocumentText },
}
}
+46
View File
@@ -0,0 +1,46 @@
/**
* The browser the converter renders in. The extraction layer runs inside the
* page (DOM + computed style + element screenshots), so the host supplies a
* page-like driver: Playwright for tests and the CLI, Electron's webContents
* in the app. Implementations share the contract test in tests/.
*/
export interface Viewport {
width: number
height: number
deviceScaleFactor: number
}
export interface ClipRect {
x: number
y: number
width: number
height: number
}
export interface ScreenshotOptions {
/** Page-coordinate clip; captures beyond the viewport. */
clip?: ClipRect
/** Transparent instead of the page background (isolated floats). */
omitBackground?: boolean
}
export interface BrowserDriver {
setViewport(viewport: Viewport): Promise<void>
/** Resolves once the network is idle; a timeout resolves too (the page is used as-is). */
goto(url: string, options: { timeoutMs: number }): Promise<void>
/** `fn` is serialized with toString() and gets one JSON-serializable argument; a string is evaluated as an expression. */
evaluate<T>(fn: string | ((arg?: any) => T | Promise<T>), arg?: unknown): Promise<T>
/** Inject a classic script (the in-page extractor helpers). */
addScript(source: string): Promise<void>
/** Runs before any page script on every navigation (debug tracing only). */
addInitScript(source: string): Promise<void>
screenshot(options: ScreenshotOptions): Promise<Uint8Array>
/** Screenshot of the first element matching `selector`'s box (even when hidden or
* zero-opacity — never wait for visibility); null when absent or empty. */
screenshotElement(
selector: string,
options: Pick<ScreenshotOptions, 'omitBackground'>,
): Promise<Uint8Array | null>
elementExists(selector: string): Promise<boolean>
close(): Promise<void>
}
@@ -0,0 +1,119 @@
/**
* BrowserDriver over playwright-core driving a locally installed Chrome. Used
* by the tests and the CLI; the app uses the Electron driver instead. Not
* re-exported from the package index so app bundles never pull in Playwright.
*/
import { existsSync } from 'node:fs'
import { chromium } from 'playwright-core'
import type { Browser, BrowserContext, Page } from 'playwright-core'
import type { BrowserDriver, ScreenshotOptions, Viewport } from '../driver'
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/google-chrome',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/chromium-browser',
].filter((p): p is string => Boolean(p))
export function findChrome(): string {
const found = CHROME_CANDIDATES.find((p) => existsSync(p))
if (!found) throw new Error('Chrome/Chromium not found. Set the CHROME_PATH env variable.')
return found
}
export function launchChrome(): Promise<Browser> {
return chromium.launch({
executablePath: findChrome(),
headless: true,
args: ['--no-sandbox', '--disable-dev-shm-usage', '--force-device-scale-factor=2'],
})
}
export class PlaywrightDriver implements BrowserDriver {
private constructor(
private readonly context: BrowserContext,
private readonly page: Page,
) {}
/** One isolated context per conversion; the browser is shared by the caller. */
static async create(browser: Browser, viewport: Viewport): Promise<PlaywrightDriver> {
const context = await browser.newContext({
viewport: { width: viewport.width, height: viewport.height },
deviceScaleFactor: viewport.deviceScaleFactor,
})
return new PlaywrightDriver(context, await context.newPage())
}
async setViewport(viewport: Viewport): Promise<void> {
// deviceScaleFactor is fixed per context (set in create); the converter
// only ever changes width/height afterwards.
await this.page.setViewportSize({ width: viewport.width, height: viewport.height })
}
async goto(url: string, { timeoutMs }: { timeoutMs: number }): Promise<void> {
try {
await this.page.goto(url, { waitUntil: 'networkidle', timeout: timeoutMs })
} catch {
// network never went idle: convert whatever has rendered (matches the CLI's behavior)
}
}
evaluate<T>(fn: string | ((arg?: any) => T | Promise<T>), arg?: unknown): Promise<T> {
if (typeof fn === 'string') return this.page.evaluate(fn) as Promise<T>
return this.page.evaluate(fn as (arg: unknown) => T, arg)
}
async addScript(source: string): Promise<void> {
await this.page.addScriptTag({ content: source })
}
async addInitScript(source: string): Promise<void> {
await this.page.addInitScript(source)
}
async screenshot(options: ScreenshotOptions): Promise<Uint8Array> {
// fullPage makes `clip` a document-coordinate rect captured beyond the
// viewport (CDP captureBeyondViewport); without it Playwright trims the
// clip to the viewport and below-the-fold shots come back empty.
return this.page.screenshot({
type: 'png',
fullPage: Boolean(options.clip),
clip: options.clip,
omitBackground: options.omitBackground,
})
}
async screenshotElement(
selector: string,
options: Pick<ScreenshotOptions, 'omitBackground'>,
): Promise<Uint8Array | null> {
const el = await this.page.$(selector)
if (!el) return null
// Not elementHandle.screenshot(): that waits for the element to be visible
// and stable, but the converter also shoots boxes it has just hidden
// (broken-image placeholders). Clip the element's page box instead.
// Origin clamped like the converter's own clips: a box overhanging the
// document's top/left edge is captured from the edge instead.
const box = await el.evaluate((node) => {
const r = node.getBoundingClientRect()
return {
x: Math.max(0, Math.round(r.left + window.scrollX)),
y: Math.max(0, Math.round(r.top + window.scrollY)),
width: Math.round(r.width),
height: Math.round(r.height),
}
})
if (box.width <= 0 || box.height <= 0) return null
return this.screenshot({ clip: box, omitBackground: options.omitBackground })
}
async elementExists(selector: string): Promise<boolean> {
return (await this.page.$(selector)) !== null
}
async close(): Promise<void> {
await this.context.close()
}
}
+41
View File
@@ -0,0 +1,41 @@
/**
* The in-page extractor is one self-contained function: every core fragment
* is a slice of its body (they share one scope), assembled here at build time
* from raw sources. The helper scripts install `__html2docx*` globals the body
* calls into, so they are injected first.
*/
import stylesSource from './browser/core/styles.js?raw'
import runsScreenshotsSource from './browser/core/runs-screenshots.js?raw'
import tablesListsSource from './browser/core/tables-lists.js?raw'
import layoutsControlsSource from './browser/core/layouts-controls.js?raw'
import decoratorsSource from './browser/core/decorators.js?raw'
import classifierSource from './browser/core/classifier.js?raw'
import paragraphsDocumentSource from './browser/core/paragraphs-document.js?raw'
import tableHelperSource from './browser/table.js?raw'
import formsMediaHelperSource from './browser/forms-media.js?raw'
import visualEffectsHelperSource from './browser/visual-effects.js?raw'
import pagesHelperSource from './browser/pages.js?raw'
const EXTRACTOR_BODY = [
stylesSource,
runsScreenshotsSource,
tablesListsSource,
layoutsControlsSource,
decoratorsSource,
classifierSource,
paragraphsDocumentSource,
].join('\n')
/** Source of `function extractIR() { … }`; evaluate `${EXTRACTOR_SOURCE}` then call it. */
export const EXTRACTOR_SOURCE = `function extractIR() {\n${EXTRACTOR_BODY}\n}`
/** Expression that runs the extractor in the page and yields the IR. */
export const EXTRACTOR_CALL = `(${EXTRACTOR_SOURCE})()`
/** Classic scripts to inject before running the extractor, in order. */
export const BROWSER_HELPER_SCRIPTS: readonly string[] = [
tableHelperSource,
formsMediaHelperSource,
visualEffectsHelperSource,
pagesHelperSource,
]
+32
View File
@@ -0,0 +1,32 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
/**
* Generation layer: intent tree (IR) -> native OOXML via the `docx` library.
*
* Layout vocabulary used (deliberately no floating text boxes):
* card -> single-cell borderless table with shading / left border
* kpirow -> single-row N-column borderless table
* code -> shaded paragraphs with a monospace font
*/
import { Packer } from 'docx'
import {
addPageBackgroundFloat,
createDocument,
partitionIr,
renderSection,
} from './generate/page-settings'
import { createRenderContext } from './generate/render-context'
import { Generator } from './generate/renderer'
async function generateDocx(ir, images) {
const parts = partitionIr(ir)
const context = createRenderContext(parts.docSettings)
const generator = new Generator(images, context)
addPageBackgroundFloat(generator, parts.pageBgNode)
const rendered = renderSection(generator, parts)
const document = createDocument(context, parts, rendered, generator)
return Packer.toBuffer(document)
}
export { generateDocx }
@@ -0,0 +1,25 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { Bookmark } from 'docx'
function bookmarkName(id) {
const value = String(id || '')
let hash = 2166136261
for (const char of value) {
hash ^= char.codePointAt(0)
hash = Math.imul(hash, 16777619)
}
const safe = value.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24) || 'anchor'
return `h2d_${safe}_${(hash >>> 0).toString(36)}`.slice(0, 40)
}
function withBookmarks(children, bookmarks = []) {
let wrapped = children
for (const id of [...bookmarks].reverse()) {
wrapped = [new Bookmark({ id: bookmarkName(id), children: wrapped })]
}
return wrapped
}
export { bookmarkName, withBookmarks }
@@ -0,0 +1,60 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { CheckBox, ImportedXmlComponent, TextRun } from 'docx'
function createContentControlFactory(startId = 1000) {
let nextId = startId
return function contentControl(node) {
if (node.controlType === 'checkbox') {
return new CheckBox({
alias: node.alias || node.name || 'Checkbox',
checked: Boolean(node.checked),
})
}
if (node.controlType === 'radio') {
return new TextRun({ text: node.checked ? '\u25c9' : '\u25cb', noProof: true })
}
const sdt = new ImportedXmlComponent('w:sdt')
const properties = new ImportedXmlComponent('w:sdtPr')
if (node.alias || node.name) {
properties.push(new ImportedXmlComponent('w:alias', { 'w:val': node.alias || node.name }))
}
if (node.name) {
properties.push(new ImportedXmlComponent('w:tag', { 'w:val': node.name }))
}
properties.push(new ImportedXmlComponent('w:id', { 'w:val': String(nextId++) }))
if (node.controlType === 'dropdown') {
const dropdown = new ImportedXmlComponent('w:dropDownList')
for (const option of node.options || []) {
dropdown.push(
new ImportedXmlComponent('w:listItem', {
'w:displayText': option.label,
'w:value': option.value,
}),
)
}
properties.push(dropdown)
} else {
properties.push(
new ImportedXmlComponent('w:text', {
'w:multiLine': node.controlType === 'multiline' ? '1' : '0',
}),
)
}
const content = new ImportedXmlComponent('w:sdtContent')
content.push(
new TextRun({
text: node.value || '\u00a0',
noProof: true,
// placeholder hints keep their authored light gray
color: node.valueColor || undefined,
}),
)
sdt.push(properties)
sdt.push(content)
return sdt
}
}
export { createContentControlFactory }
@@ -0,0 +1,69 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { CJK_RE } from './fonts'
function forEachRunText(ir, fn) {
;(function walk(nodes) {
for (const node of nodes) {
for (const run of node.runs || []) fn(run.text || '')
if (node.children) walk(node.children)
if (node.cells) for (const cell of node.cells) walk(cell.children || [])
if (node.rows) {
for (const row of node.rows) {
for (const cell of row.cells) walk(cell.children || (cell.runs ? [cell] : []))
}
}
if (node.items) {
for (const item of node.items) {
walk([{ runs: Array.isArray(item) ? item : item.runs }])
}
}
}
})(ir)
}
function detectCJK(ir) {
let cjk = 0
let total = 0
forEachRunText(ir, (text) => {
total += text.length
for (const char of text) if (CJK_RE.test(char)) cjk++
})
return total > 0 && cjk / total > 0.05
}
// w:lang eastAsia drives Word's CJK line breaking and proofing. The html
// lang attribute is declared intent; script counting is the fallback for
// the common lang-less AI page.
function eastAsiaLangOf(lang = '', ir = []) {
const lower = lang.toLowerCase()
const primary = lower.split('-')[0]
if (primary === 'ja') return 'ja-JP'
if (primary === 'ko') return 'ko-KR'
if (primary === 'zh') {
return /hant|tw|hk|mo/.test(lower) ? 'zh-TW' : 'zh-CN'
}
let kana = 0
let hangul = 0
forEachRunText(ir, (text) => {
for (const char of text) {
const code = char.codePointAt(0)
if ((code >= 0x3040 && code <= 0x30ff) || (code >= 0x31f0 && code <= 0x31ff)) kana++
else if ((code >= 0xac00 && code <= 0xd7af) || (code >= 0x1100 && code <= 0x11ff)) hangul++
}
})
if (hangul > kana && hangul > 10) return 'ko-KR'
if (kana > 10) return 'ja-JP'
return 'zh-CN'
}
function bidiLangOf(lang = '') {
const primary = lang.toLowerCase().split('-')[0]
return (
{ ar: 'ar-SA', he: 'he-IL', fa: 'fa-IR', ur: 'ur-PK' }[primary] ||
(lang.includes('-') ? lang : 'ar-SA')
)
}
export { bidiLangOf, detectCJK, eastAsiaLangOf }
+60
View File
@@ -0,0 +1,60 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
// Han + kana + Hangul: Korean previously fell outside this class and whole
// Korean documents took the Latin/Arial branch (serif Hangul fallback).
const CJK_RE =
/[\u1100-\u11ff\u3000-\u30ff\u3130-\u318f\u3400-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/
const HANGUL_RE = /[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/
const KANA_RE = /[\u3040-\u30ff\u31f0-\u31ff]/
const FONT_RULES: Array<[RegExp, string]> = [
[/jetbrains|consolas|menlo|courier|mono/i, 'Consolas'],
[/fredoka/i, 'Arial Rounded MT Bold'],
[
/brush script|lucida handwriting|pacifico|dancing script|great vibes|cursive|comic sans/i,
'Segoe Script',
],
[/dm serif|playfair|cormorant/i, 'Georgia'],
[/archivo|bebas|oswald/i, 'Arial Narrow'],
[/malgun|맑은/i, 'Malgun Gothic'],
[/yu gothic|meiryo|hiragino kaku|ms gothic|noto sans jp/i, 'Yu Gothic'],
[/batang|바탕|noto serif kr/i, 'Batang'],
[/yu mincho|ms mincho|hiragino mincho|noto serif jp/i, 'Yu Mincho'],
[
/noto sans cjk|noto sans sc|noto sans tc|noto sans kr|yahei|pingfang|heiti|source han sans|\u5fae\u8f6f\u96c5\u9ed1|\u9ed1\u4f53/i,
'Microsoft YaHei',
],
[
/noto serif cjk|noto serif sc|songti|stsong|simsun|kaiti|fangsong|source han serif|\u5b8b\u4f53/i,
'SimSun',
],
[/arial unicode/i, 'Arial Unicode MS'],
[/arial|helvetica|verdana|tahoma|segoe|roboto|inter|lato|open sans|sans/i, 'Arial'],
[/times|georgia|garamond|cambria|palatino|book antiqua|serif/i, 'Times New Roman'],
[/.*/, 'Arial'],
]
function mapFont(fontFamily = '', mono = false, text = '') {
if (mono) return 'Consolas'
let font = 'Arial'
for (const [pattern, name] of FONT_RULES) {
if (pattern.test(fontFamily)) {
font = name
break
}
}
if (CJK_RE.test(text)) {
const sans = HANGUL_RE.test(text)
? 'Malgun Gothic'
: KANA_RE.test(text)
? 'Yu Gothic'
: 'Microsoft YaHei'
const serif = HANGUL_RE.test(text) ? 'Batang' : KANA_RE.test(text) ? 'Yu Mincho' : 'SimSun'
if (font === 'Arial') font = sans
if (font === 'Times New Roman') font = serif
}
return font
}
export { CJK_RE, HANGUL_RE, KANA_RE, FONT_RULES, mapFont }
@@ -0,0 +1,77 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { LevelFormat, LevelSuffix } from 'docx'
function orderedNumberingLevels(format: any = LevelFormat.DECIMAL) {
return Array.from({ length: 9 }, (_, level) => ({
level,
format,
text: `%${level + 1}.`,
suffix: LevelSuffix.SPACE,
start: 1,
style: {
paragraph: {
indent: { left: 360 * (level + 1), hanging: 240 },
},
},
}))
}
function orderedReference(markerType) {
return (
{
'decimal-leading-zero': 'h2d-ol-decimal-zero',
'lower-alpha': 'h2d-ol-lower-letter',
'lower-latin': 'h2d-ol-lower-letter',
'upper-alpha': 'h2d-ol-upper-letter',
'upper-latin': 'h2d-ol-upper-letter',
'lower-roman': 'h2d-ol-lower-roman',
'upper-roman': 'h2d-ol-upper-roman',
}[markerType] || 'h2d-ol'
)
}
function bulletNumberingLevels(text) {
return Array.from({ length: 9 }, (_, level) => ({
level,
format: LevelFormat.BULLET,
text,
style: {
paragraph: {
indent: { left: 360 * (level + 1), hanging: 240 },
},
},
}))
}
function buildNumberingConfig() {
return [
{ reference: 'h2d-ol', levels: orderedNumberingLevels() },
{
reference: 'h2d-ol-decimal-zero',
levels: orderedNumberingLevels(LevelFormat.DECIMAL_ZERO),
},
{
reference: 'h2d-ol-lower-letter',
levels: orderedNumberingLevels(LevelFormat.LOWER_LETTER),
},
{
reference: 'h2d-ol-upper-letter',
levels: orderedNumberingLevels(LevelFormat.UPPER_LETTER),
},
{
reference: 'h2d-ol-lower-roman',
levels: orderedNumberingLevels(LevelFormat.LOWER_ROMAN),
},
{
reference: 'h2d-ol-upper-roman',
levels: orderedNumberingLevels(LevelFormat.UPPER_ROMAN),
},
{ reference: 'h2d-ul', levels: bulletNumberingLevels('\u2022') },
{ reference: 'h2d-ul-circle', levels: bulletNumberingLevels('\u25e6') },
{ reference: 'h2d-ul-square', levels: bulletNumberingLevels('\u25aa') },
]
}
export { buildNumberingConfig, orderedReference }
@@ -0,0 +1,280 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import {
Document,
Footer,
Header,
ImageRun,
LineRuleType,
Paragraph,
Table,
TextWrappingType,
} from 'docx'
import { bidiLangOf, detectCJK, eastAsiaLangOf } from './document-meta'
import { buildNumberingConfig } from './numbering'
import { spacerParagraph } from './word-utils'
import zlib from 'node:zlib'
function partitionIr(ir) {
const docSettings = ir.find((node) => node.type === 'docsettings')
const pageBgNode = ir.find((node) => node.type === 'pagebg')
const headerNode = ir.find((node) => node.type === 'headerpart')
const footerNode = ir.find((node) => node.type === 'footerpart')
const bodyIr = ir.filter(
(node) =>
node.type !== 'docsettings' &&
node.type !== 'pagebg' &&
node.type !== 'headerpart' &&
node.type !== 'footerpart',
)
return { bodyIr, docSettings, footerNode, headerNode, pageBgNode }
}
// Word ignores <w:background> when printing / exporting PDF, so a plain
// page color must also become a behind-text float. A 1×1 PNG stretched to
// page size costs ~70 bytes.
function solidColorPng(hex) {
const rgb = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) || 0)
const chunk = (type, data) => {
const body = Buffer.concat([Buffer.from(type, 'ascii'), data])
const out = Buffer.alloc(body.length + 8)
out.writeUInt32BE(data.length, 0)
body.copy(out, 4)
out.writeUInt32BE(zlib.crc32(body) >>> 0, body.length + 4)
return out
}
const ihdr = Buffer.alloc(13)
ihdr.writeUInt32BE(1, 0)
ihdr.writeUInt32BE(1, 4)
ihdr[8] = 8 // bit depth
ihdr[9] = 2 // color type: RGB
const idat = zlib.deflateSync(Buffer.from([0, ...rgb]))
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', idat),
chunk('IEND', Buffer.alloc(0)),
])
}
function addPageBackgroundFloat(generator, pageBgNode) {
const shotData = pageBgNode?.shotId ? generator.images[pageBgNode.shotId] : null
const data = shotData || (pageBgNode?.color ? solidColorPng(pageBgNode.color) : null)
if (!data) return
const context = generator.context
generator.pageBackgroundFloat = new ImageRun({
type: 'png',
data,
transformation: {
width: Math.round(context.pageWidthDxa / 15),
height: Math.round(context.pageHeightDxa / 15),
},
floating: {
horizontalPosition: { relative: 'page', offset: 0 },
verticalPosition: { relative: 'page', offset: 0 },
behindDocument: true,
wrap: { type: TextWrappingType.NONE },
margins: { top: 0, bottom: 0, left: 0, right: 0 },
},
})
}
function renderSection(generator, { bodyIr, footerNode, headerNode }) {
const headerChildren = []
if (generator.pageBackgroundFloat) {
headerChildren.push(
new Paragraph({
children: [generator.pageBackgroundFloat],
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
)
}
if (headerNode) {
headerChildren.push(...generator.render(withPageNumberFields(headerNode.children || [])))
}
const footerChildren = footerNode
? generator.render(withPageNumberFields(footerNode.children || []))
: []
const children = generator.render(bodyIr)
// Trailing spacers render nothing at document end but can overflow onto a
// phantom background-only last page when the content fills its final page.
// A table must not end the body either: Word then auto-inserts a
// default-height paragraph mark, which overflows the same way. End on one
// minimal explicit paragraph instead.
while (children.length > 1 && children[children.length - 1]?.__h2dSpacerPx) {
children.pop()
}
if (!(children[children.length - 1] instanceof Paragraph)) {
children.push(
new Paragraph({
children: [],
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
)
}
// Final-card top margin: a closing footer card stranded on a fresh page
// still shows its authored top gap, so the gap buys nothing — collapse the
// whole run of spacers before it to improve the chance the card fits the
// previous page's tail instead.
let lastBlock = children.length - 1
while (lastBlock >= 0 && children[lastBlock] instanceof Paragraph) lastBlock--
if (children[lastBlock] instanceof Table) {
let firstSpacer = lastBlock
while (firstSpacer > 0 && children[firstSpacer - 1]?.__h2dSpacerPx) firstSpacer--
const runPx = children
.slice(firstSpacer, lastBlock)
.reduce((sum, spacer) => sum + spacer.__h2dSpacerPx, 0)
if (runPx > 16) {
children.splice(firstSpacer, lastBlock - firstSpacer, spacerParagraph(generator.context, 8))
}
}
if (generator.floats.length) {
children.unshift(
new Paragraph({
children: generator.floats,
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
)
}
return { children, footerChildren, headerChildren }
}
// Literal page numbers in a real header/footer ("Page 1 of 3" and the CJK
// "page N / total M" form) are frozen at whatever the browser rendered — replace the
// digits with native PAGE / NUMPAGES fields so Word keeps them true.
const LATIN_PAGE_RE = /\b((?:page|pg\.?|p\.)\s*)(\d+)((?:\s*(?:of|\/|de)\s*)(\d+))?/i
const CJK_PAGE_RE =
/(\u7b2c\s*)(\d+)(\s*[\u9875\u9801])((?:\s*[,\uff0c/]?\s*\u5171\s*)(\d+)(\s*[\u9875\u9801]))?/
function pageFieldSegments(run) {
const text = run.text || ''
const match = LATIN_PAGE_RE.exec(text) || CJK_PAGE_RE.exec(text)
if (!match) return null
const isCjk = match.length > 5
const segments = []
const push = (t) => t && segments.push({ ...run, text: t })
push(text.slice(0, match.index) + match[1])
segments.push({ ...run, text: '', pageNumberField: 'current' })
if (isCjk) {
push(match[3])
if (match[5]) {
push(match[4].slice(0, match[4].length - match[5].length - match[6].length))
segments.push({ ...run, text: '', pageNumberField: 'total' })
push(match[6])
}
push(text.slice(match.index + match[0].length))
} else {
if (match[4]) {
push(match[3].slice(0, match[3].length - match[4].length))
segments.push({ ...run, text: '', pageNumberField: 'total' })
}
push(text.slice(match.index + match[0].length))
}
return segments
}
function withPageNumberFields(nodes) {
const mapCells = (cells) =>
(cells || []).map((cell) => ({
...cell,
runs: cell.runs ? cell.runs.flatMap((run) => pageFieldSegments(run) || [run]) : cell.runs,
children: cell.children ? withPageNumberFields(cell.children) : cell.children,
}))
return (nodes || []).map((node) => {
const mapped = { ...node }
if (node.runs) {
mapped.runs = node.runs.flatMap((run) => pageFieldSegments(run) || [run])
}
if (node.children) mapped.children = withPageNumberFields(node.children)
if (node.rows) {
mapped.rows = node.rows.map((row) => ({ ...row, cells: mapCells(row.cells) }))
}
if (node.cells) mapped.cells = mapCells(node.cells)
if (node.items) mapped.items = withPageNumberFields(node.items)
return mapped
})
}
function createDocument(context, parts, rendered, generator) {
const isCJK = detectCJK(parts.bodyIr)
const docRTL = Boolean(parts.docSettings?.rtl)
const bidiLang = docRTL ? bidiLangOf(parts.docSettings?.lang) : undefined
// A solid-color pagebg (no shotId) still becomes a header-anchored float
// via addPageBackgroundFloat's solidColorPng fallback — the header-distance
// reservation must be zeroed for that case too, or Word pads a ~1.25cm gap
// above the body on every page (the header area is reserved regardless of
// how empty its content looks).
const hasPageBackgroundHeader = Boolean(generator?.pageBackgroundFloat) && !parts.headerNode
const needsTopBleed = hasPageBackgroundHeader && context.pageMargins.top === 0
const pageMargins = hasPageBackgroundHeader
? {
...context.pageMargins,
top: needsTopBleed ? -context.pxToTwips(14) : context.pageMargins.top,
header: 0,
}
: context.pageMargins
const meta = parts.docSettings?.meta || {}
return new Document({
title: meta.title,
creator: meta.author || 'html2docx',
description: meta.description,
keywords: meta.keywords,
background: parts.pageBgNode?.color ? { color: parts.pageBgNode.color } : undefined,
numbering: { config: buildNumberingConfig() },
styles: {
default: {
document: {
// OOXML default is OFF unless a style sets it; Word's own new-doc
// template enables it — match that so no stranded single lines
paragraph: { widowControl: true } as any,
run: isCJK
? {
// ascii/hAnsi stay Latin-proportional: a CJK font on Latin
// runs renders SimSun-style monospaced glyphs.
font: {
ascii: 'Arial',
hAnsi: 'Arial',
eastAsia:
{ 'ja-JP': 'Yu Gothic', 'ko-KR': 'Malgun Gothic' }[
eastAsiaLangOf(parts.docSettings?.lang, parts.bodyIr)
] || 'Microsoft YaHei',
},
size: Math.round(21 * context.fontScale),
// w:lang w:val must stay Latin: tagging it zh-CN makes Word
// apply CJK line breaking to Latin words ("Rep/ort").
language: {
value: 'en-US',
eastAsia: eastAsiaLangOf(parts.docSettings?.lang, parts.bodyIr),
},
}
: {
font: 'Arial',
size: Math.round(21 * context.fontScale),
language: docRTL
? { value: bidiLang, bidirectional: bidiLang }
: { value: 'en-US' },
},
},
},
},
sections: [
{
properties: {
page: {
size: { width: context.pageWidthDxa, height: context.pageHeightDxa },
margin: pageMargins,
},
},
headers: rendered.headerChildren.length
? { default: new Header({ children: rendered.headerChildren }) }
: undefined,
footers: rendered.footerChildren.length
? { default: new Footer({ children: rendered.footerChildren }) }
: undefined,
children: rendered.children,
},
],
})
}
export { addPageBackgroundFloat, createDocument, partitionIr, renderSection }
@@ -0,0 +1,54 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
const DEFAULT_PAGE_WIDTH_PX = 794
const DEFAULT_PAGE_HEIGHT_PX = 1123
const MARGIN_DXA = 1134
function createRenderContext(docSettings: any = {}) {
const marginsPx = docSettings.marginsPx || {}
const pageWidthDxa = Math.max(
1440,
Math.round((docSettings.pageSizePx?.width || DEFAULT_PAGE_WIDTH_PX) * 15),
)
const pageHeightDxa = Math.max(
1440,
Math.round((docSettings.pageSizePx?.height || DEFAULT_PAGE_HEIGHT_PX) * 15),
)
const baseScale = docSettings.viewportWidthPx
? Math.min(1, pageWidthDxa / 15 / docSettings.viewportWidthPx)
: 1
// Extractor-provided whole-document squeeze for flow docs slightly taller
// than one page: shrinks geometry and fonts together a few percent so a
// two-line tail does not strand on its own page.
const squeeze = docSettings.pageFitSqueeze || 1
const measurementScale = baseScale * squeeze
// Arial is narrower than the browser's common Inter/Roboto fonts. Scaling
// it as aggressively as box geometry removes authored line wraps, so retain
// part of the original font size while still fitting the page.
const fontScale = Math.min(1, baseScale * 1.04) * squeeze
const pxToTwips = (px) => Math.round(px * 15 * measurementScale)
const pageMargins = {
top: pxToTwips(marginsPx.top ?? MARGIN_DXA / 15),
bottom: pxToTwips(marginsPx.bottom ?? MARGIN_DXA / 15),
left: pxToTwips(marginsPx.left ?? MARGIN_DXA / 15),
right: pxToTwips(marginsPx.right ?? MARGIN_DXA / 15),
header: docSettings.composed ? 0 : undefined,
footer: docSettings.composed ? 0 : undefined,
}
return {
pageWidthDxa,
pageHeightDxa,
pageMargins,
contentDxa: pageWidthDxa - pageMargins.left - pageMargins.right,
measurementScale,
fontScale,
marginDxa: MARGIN_DXA,
pxToHalfPoints: (px) => Math.round(px * 1.5 * fontScale),
pxToTwips,
pxToBorderEighths: (px) => Math.max(4, Math.round(px * 6 * measurementScale)),
}
}
export { createRenderContext }
+706
View File
@@ -0,0 +1,706 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import {
AlignmentType,
BorderStyle,
ExternalHyperlink,
HeightRule,
ImageRun,
LineRuleType,
PageBreak,
Paragraph,
ShadingType,
Table,
TableCell,
TableLayoutType,
TableRow,
TextRun,
TextWrappingType,
VerticalPositionAlign,
WidthType,
} from 'docx'
import { withBookmarks } from './bookmarks'
import { createContentControlFactory } from './content-controls'
import { orderedReference } from './numbering'
import { renderCard, renderColorBar, renderKpiRow, renderTable } from './table-renderers'
import {
HEADING_LEVELS,
NO_BORDERS,
NO_TABLE_BORDERS,
makeNodeRuns,
paraOptions,
spacerParagraph,
tabStopsFor,
wordBorder,
} from './word-utils'
function splitVerticalBorderSpacing(style: any = {}) {
if (!style.borderLeft && !style.borderRight) {
return { paragraphStyle: style, spacingAfterPx: 0, spacingBeforePx: 0 }
}
const spacingBeforePx = style.spacingBeforePx || 0
const spacingAfterPx = style.spacingAfterPx || 0
return {
paragraphStyle: {
...style,
spacingBeforePx: 0,
spacingAfterPx: 0,
},
spacingAfterPx,
spacingBeforePx,
}
}
function withExternalBorderSpacing(
context,
paragraph,
spacingBeforePx,
spacingAfterPx,
shading = null,
) {
const output = []
if (spacingBeforePx) output.push(spacerParagraph(context, spacingBeforePx, { shading }))
output.push(paragraph)
if (spacingAfterPx) output.push(spacerParagraph(context, spacingAfterPx, { shading }))
return output
}
class Generator {
[key: string]: any
constructor(images, context) {
this.images = images // shotId -> { buffer, width, height }
this.context = context
this.contentControl = createContentControlFactory()
// width (dxa) available to the node being rendered; shrinks inside table cells
this.avail = context.contentDxa
// page-anchored floating images, attached to the first paragraph
this.floats = []
// Repeated from the header so printed pages retain the authored backdrop.
this.pageBackgroundFloat = null
this.olInstance = 0
// Word promotes keepNext on in-cell paragraphs to row-level
// keep-with-next: rows chain into one unsplittable block that jumps to a
// fresh page whole. Set while rendering table-cell content.
this.suppressKeepNext = false
// Inverse of the above, set by cellChildren({keepWithNext}) for the
// non-last rows of a fits-on-one-page table: every paragraph rendered
// while true carries keepNext so the whole table stays together.
this.forceKeepNext = false
}
render(nodes, depth = 0) {
const out = []
// Word binds keepNext paragraph-to-paragraph only: a heading followed by
// a plain spacer is "kept" with just the spacer, and the section body
// still breaks to the next page leaving the heading orphaned. Extend the
// keep chain from a heading through its section head — spacers and at
// most one lede/subtitle paragraph — into the first substantive block.
// Trailing spacers must stay unbound or sections fuse into one
// document-wide keep chain and Word breaks pages far too early.
let chainActive = false
let ledeAllowance = 0
for (let index = 0; index < nodes.length; index++) {
const node = nodes[index]
let rendered
if (
!this.suppressKeepNext &&
node.type === 'para' &&
nodes[index + 1]?.type === 'spacer' &&
nodes[index + 1].bindsNeighbors
) {
// Paragraph before an authored in-flow gap (signature space): bind
// it through the gap to the following paragraph.
rendered = this.renderNode({ ...node, style: { ...node.style, keepNext: true } }, depth)
chainActive = false
} else if (
node.type === 'spacer' &&
nodes[index + 1]?.type === 'card' &&
(nodes[index + 1].heightPx || 0) > 700
) {
// A near-page-height unsplittable card cannot share its page with
// the authored gap before it — the card slides to the next page and
// the invisible gap strands a blank page. Collapse the gap; the
// page break itself provides the separation.
rendered = [
spacerParagraph(this.context, Math.min(node.px, 8), {
keepNext: chainActive,
shading: node.shading,
}),
]
} else if (
(chainActive || (node.bindsNeighbors && !this.suppressKeepNext)) &&
node.type === 'spacer'
) {
rendered = [
spacerParagraph(this.context, node.px, { keepNext: true, shading: node.shading }),
]
} else if (chainActive && node.type === 'para' && ledeAllowance > 0) {
// Only a real lede continues the chain: the next substantive node
// must be more section content. When it is another heading (or the
// end), this para IS the section body — it must terminate the chain,
// or trailing spacers bind section after section into one
// document-wide keep block that Word shoves onto a fresh page.
let next = index + 1
while (next < nodes.length && nodes[next].type === 'spacer') next += 1
if (next < nodes.length && nodes[next].type !== 'heading') {
ledeAllowance -= 1
rendered = this.renderNode({ ...node, style: { ...node.style, keepNext: true } }, depth)
} else {
rendered = this.renderNode(node, depth)
chainActive = false
}
} else {
rendered = this.renderNode(node, depth)
if (node.type === 'heading' && !this.suppressKeepNext) {
// A heading's trailing spacing also sits between it and the body.
const last = rendered.length - 1
if (rendered[last]?.__h2dSpacerPx) {
rendered[last] = spacerParagraph(this.context, rendered[last].__h2dSpacerPx, {
keepNext: true,
shading: rendered[last].__h2dSpacerShading,
borderLeft: rendered[last].__h2dSpacerBorderLeft,
})
}
} else if (chainActive && rendered[0]?.__h2dSpacerPx) {
// First substantive block: bind its own leading margin spacer.
rendered[0] = spacerParagraph(this.context, rendered[0].__h2dSpacerPx, {
keepNext: true,
shading: rendered[0].__h2dSpacerShading,
borderLeft: rendered[0].__h2dSpacerBorderLeft,
})
}
if (node.type === 'heading') {
chainActive = !this.suppressKeepNext
ledeAllowance = 1
} else {
chainActive = false
}
}
// A near-page-height unsplittable card cannot share a page with the
// gap that precedes it (the card slides on; the invisible gap strands
// a blank page) — collapse the previous block's trailing spacer.
if (
nodes[index + 1]?.type === 'card' &&
(nodes[index + 1].heightPx || 0) > 700 &&
!nodes[index + 1].allowSplit
) {
const last = rendered.length - 1
if ((rendered[last]?.__h2dSpacerPx || 0) > 8) {
rendered[last] = spacerParagraph(this.context, 8, {
shading: rendered[last].__h2dSpacerShading,
})
}
}
out.push(...rendered)
}
return out
}
renderNode(node, depth) {
const context = this.context
switch (node.type) {
case 'pagebreak':
return [
new Paragraph({
children: [new PageBreak()],
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
]
case 'spacer':
return [
spacerParagraph(context, node.px, {
keepNext: this.forceKeepNext,
shading: node.shading,
borderLeft: node.borderLeft,
}),
]
case 'heading': {
// shaded single-line section header bar (h2 with background +
// padding): same treatment as shaded paras, otherwise the text sits
// baseline-left in the bar with no inset or vertical centering
if (node.style?.shading && node.style?.colorBar) {
return renderColorBar(this, node)
}
node = this.fitOneLineRuns(node)
const { paragraphStyle, spacingAfterPx, spacingBeforePx } = splitVerticalBorderSpacing(
node.style,
)
const opts = paraOptions(context, paragraphStyle)
// Built-in Word heading styles add their own top/bottom spacing.
// Override both sides explicitly so CSS margin: 0 remains zero.
opts.spacing = {
...opts.spacing,
before: opts.spacing?.before ?? 0,
after: opts.spacing?.after ?? 0,
}
const stops = tabStopsFor(context, node.runs)
if (stops.length) opts.tabStops = stops
return withExternalBorderSpacing(
context,
new Paragraph({
heading: HEADING_LEVELS[Math.min(node.level, 6) - 1],
children: withBookmarks(makeNodeRuns(context, node, this.images), node.bookmarks),
keepNext: this.forceKeepNext
? true
: node.style?.keepNext === false || this.suppressKeepNext
? undefined
: true,
keepLines: true,
...opts,
}),
spacingBeforePx,
spacingAfterPx,
paragraphStyle.shading,
)
}
case 'para': {
if (!node.runs.length) return []
if (node.style?.shading && node.style?.colorBar) {
return renderColorBar(this, node)
}
node = this.fitFillInRuns(node)
node = this.fitOneLineRuns(node)
const { paragraphStyle, spacingAfterPx, spacingBeforePx } = splitVerticalBorderSpacing(
node.style,
)
const opts = paraOptions(context, paragraphStyle)
const stops = tabStopsFor(context, node.runs)
if (stops.length) opts.tabStops = stops
if (node.style?.bullet) {
opts.numbering = { reference: 'h2d-ul', level: 0 }
}
if (this.forceKeepNext || (node.style?.keepNext && !this.suppressKeepNext)) {
opts.keepNext = true
}
if (node.style?.keepLines) opts.keepLines = true
return withExternalBorderSpacing(
context,
new Paragraph({
children: withBookmarks(makeNodeRuns(context, node, this.images), node.bookmarks),
...opts,
}),
spacingBeforePx,
spacingAfterPx,
paragraphStyle.shading,
)
}
case 'list': {
// One numbering instance per sublist, emitted at level 0: docx's
// startOverride only restarts level 0, so real multi-level lists
// would inherit a document-wide running counter (nested a-e lists
// continuing f-j, r-bb...). Level 0 per instance restarts like the
// browser restarts each <ol>; visual nesting comes from indentLeftPx.
const instanceByLevel = []
return node.items.map((entry) => {
// Older IR snapshots stored runs directly; accept both shapes so
// callers that persist/debug IR remain compatible.
const item = Array.isArray(entry) ? { runs: entry, style: {} } : entry
const opts = paraOptions(context, item.style)
const markerWidthPx = Math.max(10, Math.min(16, (item.runs[0]?.sizePx || 14) * 0.8))
opts.indent = {
left: context.pxToTwips(item.indentLeftPx || node.indentLeftPx || 22),
hanging: context.pxToTwips(markerWidthPx),
}
if (node.rtl) opts.bidirectional = true
if (this.forceKeepNext) opts.keepNext = true
const ordered = item.ordered ?? node.ordered
const level = Math.max(0, Math.min(8, item.level || 0))
if (level < instanceByLevel.length - 1) instanceByLevel.length = level + 1
if (instanceByLevel[level] == null) instanceByLevel[level] = this.olInstance++
const bulletReference =
item.markerType === 'square'
? 'h2d-ul-square'
: item.markerType === 'circle'
? 'h2d-ul-circle'
: 'h2d-ul'
if (item.continuation) {
opts.indent = { left: context.pxToTwips(item.indentLeftPx || node.indentLeftPx || 22) }
} else {
opts.numbering = ordered
? {
reference: orderedReference(item.markerType),
level: 0,
instance: instanceByLevel[level],
}
: { reference: bulletReference, level }
}
return new Paragraph({
children: withBookmarks(
makeNodeRuns(context, { runs: item.runs, style: item.style }, this.images),
item.bookmarks,
),
...opts,
})
})
}
case 'code':
return node.lines.map(
(line) =>
new Paragraph({
children: [
new TextRun({
text: line || ' ',
font: 'Consolas',
size: node.sizePx ? context.pxToHalfPoints(node.sizePx) : 18,
color: node.color && node.color !== '000000' ? node.color : undefined,
noProof: true,
}),
],
shading: { type: ShadingType.CLEAR, fill: node.shading },
}),
)
case 'hr': {
const widthFrac = Math.max(0.05, Math.min(1, node.widthFrac || 1))
if (node.short) {
const width = Math.max(120, Math.round(this.avail * widthFrac))
const output = []
if (node.spacingBeforePx) {
output.push(
spacerParagraph(context, node.spacingBeforePx, { shading: node.ambientShading }),
)
}
output.push(
new Table({
borders: NO_TABLE_BORDERS,
rows: [
new TableRow({
height: {
value: context.pxToTwips(node.heightPx || 2),
rule: HeightRule.EXACT,
},
children: [
new TableCell({
children: [new Paragraph({ spacing: { before: 0, after: 0 } })],
shading: { type: ShadingType.CLEAR, fill: node.color || 'CCCCCC' },
borders: NO_BORDERS,
margins: { top: 0, bottom: 0, left: 0, right: 0 },
}),
],
}),
],
width: { size: width, type: WidthType.DXA },
columnWidths: [width],
layout: TableLayoutType.FIXED,
}),
spacerParagraph(context, node.spacingAfterPx || 2, { shading: node.ambientShading }),
)
return output
}
const spare = Math.round(this.avail * (1 - widthFrac))
const left = node.align === 'center' ? Math.round(spare / 2) : 0
const right = node.align === 'center' ? spare - left : spare
return [
new Paragraph({
indent: { left, right },
shading: node.ambientShading
? { type: ShadingType.CLEAR, fill: node.ambientShading }
: undefined,
// collapse the carrier paragraph to (almost) just the border line;
// a default-height empty line reads as a stray blank row
children: [new TextRun({ text: '', size: 2, noProof: true })],
spacing: {
before: context.pxToTwips(node.spacingBeforePx || 0),
after: context.pxToTwips(node.spacingAfterPx || 2),
line: context.pxToTwips(Math.max(2, node.heightPx || 2)),
lineRule: LineRuleType.EXACT,
},
border: {
bottom: {
style: BorderStyle.SINGLE,
size: node.heightPx ? Math.max(6, Math.round(node.heightPx * 8)) : 6,
color: node.color || 'CCCCCC',
},
},
}),
]
}
case 'formfield': {
if (node.controlType === 'checkbox' || node.controlType === 'radio') {
return [
new Paragraph({
children: [this.contentControl(node)],
spacing: { before: 0, after: 0 },
...paraOptions(context, node.style),
}),
]
}
if (node.mode === 'line') {
return [
new Paragraph({
children: [this.contentControl(node)],
border: { bottom: wordBorder(context, node.borders?.bottom) },
spacing: { before: 0, after: 0, line: 240 },
}),
]
}
const width = Math.min(this.avail, Math.max(300, context.pxToTwips(node.width || 100)))
const borders: any = {}
for (const side of ['top', 'bottom', 'left', 'right']) {
borders[side] = wordBorder(context, node.borders?.[side])
}
const pad = node.padPx || {}
return [
new Table({
borders: NO_TABLE_BORDERS,
rows: [
new TableRow({
cantSplit: true,
height: node.height
? { value: context.pxToTwips(node.height), rule: HeightRule.ATLEAST }
: undefined,
children: [
new TableCell({
children: [
new Paragraph({
children: [this.contentControl(node)],
spacing: { before: 0, after: 0 },
}),
],
borders,
shading: node.shading
? { type: ShadingType.CLEAR, fill: node.shading }
: undefined,
margins: {
top: context.pxToTwips(pad.top || 4),
bottom: context.pxToTwips(pad.bottom || 4),
left: context.pxToTwips(pad.left || 6),
right: context.pxToTwips(pad.right || 6),
},
}),
],
}),
],
width: { size: width, type: WidthType.DXA },
columnWidths: [width],
}),
spacerParagraph(context, 2),
]
}
case 'image':
return this.renderImage(node)
case 'floatimg':
return this.collectFloatingImage(node)
case 'table':
return renderTable(this, node, depth)
case 'card':
return renderCard(this, node, depth)
case 'kpirow':
return renderKpiRow(this, node, depth)
default:
return []
}
}
// Display text measured as one browser line but wider than the cell it
// landed in: Word would wrap it mid-word ("INVOIC/E"). Shrink the font
// proportionally so it stays on one line. Display sizes only — body text
// in narrow columns should wrap naturally, not shrink.
// A fill-in blank is an unbreakable nbsp run sized to its browser width.
// Inside a narrow table cell it overflows and blows up Word's fixed
// layout (the whole table widens past the page and clips) — shrink the
// blank to the width the cell actually has left.
fitFillInRuns(node) {
const runs = node.runs || []
const isBlank = (run) =>
run.underline && run.preserveWhitespace && /^\u00a0+$/.test(run.text || '')
if (!runs.some(isBlank)) return node
const availPx = this.avail / 15 / this.context.measurementScale
const spaceWidth = (run) => Math.max(3, (run.sizePx || 14) * 0.45)
const textPx = runs.reduce(
(sum, run) => (isBlank(run) ? sum : sum + (run.text || '').length * (run.sizePx || 14) * 0.6),
0,
)
const blankPx = runs.reduce(
(sum, run) => (isBlank(run) ? sum + run.text.length * spaceWidth(run) : sum),
0,
)
if (textPx + blankPx <= availPx * 0.92) return node
const budget = Math.max(0, availPx * 0.92 - textPx)
const scale = blankPx > 0 ? Math.min(1, budget / blankPx) : 1
return {
...node,
runs: runs.map((run) =>
isBlank(run)
? { ...run, text: '\u00a0'.repeat(Math.max(3, Math.floor(run.text.length * scale))) }
: run,
),
}
}
fitOneLineRuns(node) {
if (!node.style?.oneLineWidthPx) return node
// Headings never letter-wrap regardless of size; body text only when it
// is display-scale (small body copy should wrap naturally).
const sizeFloor = node.type === 'heading' || node.style?.keepLines ? 14 : 24
if (!node.runs.some((run) => (run.sizePx || 0) >= sizeFloor)) return node
const availPx = this.avail / 15 / this.context.measurementScale
if (node.style.oneLineWidthPx <= availPx * 0.94) return node
// 6% safety: Word's Arial runs slightly wider than browser fonts.
const fit = Math.max(0.55, (availPx * 0.94) / node.style.oneLineWidthPx)
return {
...node,
runs: node.runs.map((run) => (run.sizePx ? { ...run, sizePx: run.sizePx * fit } : run)),
}
}
renderImage(node) {
const img = this.images[node.shotId]
if (!img) {
const fallbackRun = new TextRun({
text: node.fallbackText || node.href || 'Unavailable embedded content',
color: node.href ? '0563C1' : '666666',
underline: node.href ? {} : undefined,
noProof: true,
})
return [
new Paragraph({
children: node.href
? [new ExternalHyperlink({ children: [fallbackRun], link: node.href })]
: [fallbackRun],
}),
]
}
const bleedLeftPx = node.bleedLeftPx || 0
const bleedRightPx = node.bleedRightPx || 0
const maxPx = Math.floor((this.avail + this.context.pxToTwips(bleedLeftPx + bleedRightPx)) / 15)
const pageContentHeightPx =
(this.context.pageHeightDxa -
this.context.pageMargins.top -
this.context.pageMargins.bottom) /
15
// Word (Mac) starts the first line ~26px below the page top even at zero
// margins, and the image line adds baseline descent below. A slice scaled
// to (content height - 4) therefore clipped its bottom ~25px at the page
// edge (lost resume contact rows). 45px absorbs the inset plus variance.
const pageScale = node.pageComposition
? Math.max(0.01, pageContentHeightPx - 45) / node.height
: Infinity
const scale = Math.min(this.context.measurementScale, maxPx / node.width, pageScale)
const output = []
// Full-page composition slides: the page margins already carry the
// authored offset — an extra spacer overflows the page and strands the
// slide image on a blank-page boundary.
if (node.spacingBeforePx > 2 && !node.pageComposition) {
output.push(spacerParagraph(this.context, node.spacingBeforePx))
}
const renderedWidthPx = Math.round(node.width * scale)
const renderedHeightPx = Math.round(node.height * scale)
const imageRun = new ImageRun({
type: 'png',
data: img,
transformation: {
width: renderedWidthPx,
height: renderedHeightPx,
},
})
output.push(
new Paragraph({
children: node.href
? [new ExternalHyperlink({ children: [imageRun], link: node.href })]
: [imageRun],
// wide short strips are section banners — never strand one at a
// page bottom with its section content on the next page
keepNext:
!this.suppressKeepNext &&
!node.pageComposition &&
renderedWidthPx >= (this.avail / 15) * 0.85 &&
renderedHeightPx <= 220
? true
: undefined,
alignment:
// Full-page slides: headroom scaling leaves a margin — split it
// symmetrically instead of piling white space on one side.
node.pageComposition || node.align === 'center'
? AlignmentType.CENTER
: node.align === 'right'
? AlignmentType.RIGHT
: undefined,
indent:
bleedLeftPx || bleedRightPx
? {
left: -this.context.pxToTwips(bleedLeftPx),
right: -this.context.pxToTwips(bleedRightPx),
}
: undefined,
spacing: {
before: 0,
after: 0,
line: Math.max(1, renderedHeightPx * 15),
// Word positions inline images relative to the text baseline.
// An exact line box equal to the image height clips the image's top
// and may push it to the next page. "At least" keeps the authored
// image height while allowing Word to include the full ascent.
lineRule: LineRuleType.AT_LEAST,
},
border: node.topEdgeFill
? {
top: {
style: BorderStyle.SINGLE,
size: 48,
color: node.topEdgeFill,
space: 0,
},
}
: undefined,
}),
)
if (node.spacingAfterPx > 2 && !node.pageComposition) {
output.push(spacerParagraph(this.context, node.spacingAfterPx))
}
return output
}
collectFloatingImage(node) {
const img = this.images[node.shotId]
if (!img) return []
// in-parent decorations beyond the first page reach here only when no
// card consumed them — page-anchoring would pin them to page 1
if (node.inParent && node.yPx + node.height > (node.pageHpx || 1123)) return []
const EMU = 9525 // per px @96dpi
// rescale browser coordinates: the DOCX content area is usually
// narrower/shorter than the HTML content box
const contentHeightDxa = this.context.pageHeightDxa - 2 * this.context.marginDxa
const sx = node.pageWpx ? this.context.contentDxa / 15 / node.pageWpx : 1
const sy = node.pageHpx ? contentHeightDxa / 15 / node.pageHpx : 1
this.floats.push(
new ImageRun({
type: 'png',
data: img,
transformation: {
width: Math.round(node.width * sx),
height: Math.round(node.height * sx),
},
floating: {
// margin origin = start of the content area, matching the
// body-content-box coordinates measured in the browser
horizontalPosition: { relative: 'margin', offset: Math.round(node.xPx * sx * EMU) },
verticalPosition: node.atPageBottom
? { relative: 'page', align: VerticalPositionAlign.BOTTOM }
: { relative: 'margin', offset: Math.round(node.yPx * Math.min(sy, 1) * EMU) },
// decorations painted under the HTML content layer (z<=0) go
// behind text; explicit z>0 art stays in front (table-cell shading
// would paint over a behind-text image, so only when needed)
behindDocument: Boolean(node.behindText),
wrap: { type: TextWrappingType.NONE },
},
}),
)
return []
}
}
export { Generator }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,359 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import {
AlignmentType,
BorderStyle,
CheckBox,
ExternalHyperlink,
HeadingLevel,
ImageRun,
InternalHyperlink,
PageNumber,
LineRuleType,
Paragraph,
ShadingType,
Tab,
TabStopType,
TextRun,
UnderlineType,
} from 'docx'
import { bookmarkName } from './bookmarks'
import { mapFont } from './fonts'
function makeRuns(context, runs, images: any = {}) {
const out = []
for (const r of runs) {
if (r.pageNumberField) {
out.push(
new TextRun({
children: [r.pageNumberField === 'total' ? PageNumber.TOTAL_PAGES : PageNumber.CURRENT],
bold: r.bold || undefined,
italics: r.italic || undefined,
color: r.color || undefined,
size: r.sizePx ? context.pxToHalfPoints(r.sizePx) : undefined,
font: mapFont(r.fontFamily, r.mono, r.text),
}),
)
continue
}
if (r.contentControl === 'checkbox') {
out.push(new CheckBox({ checked: Boolean(r.checked), alias: r.alias || 'Checkbox' }))
continue
}
if (r.inlineImage) {
const image = images[r.shotId]
if (image) {
out.push(
new ImageRun({
type: 'png',
data: image,
transformation: { width: r.width, height: r.height },
}),
)
}
continue
}
const underlineType =
r.underlineStyle === 'dotted'
? UnderlineType.DOTTED
: r.underlineStyle === 'dashed'
? (UnderlineType as any).DASHED
: UnderlineType.SINGLE
const style = {
bold: r.bold || undefined,
italics: r.italic || undefined,
underline: r.underline
? { type: underlineType, color: r.underlineColor || undefined }
: undefined,
strike: r.strike || undefined,
// always explicit: inherited styles (Heading1..6 theme blue) must not win
color: r.color || undefined,
size: r.sizePx ? context.pxToHalfPoints(r.sizePx) : undefined,
// Emoji: leave the font unset so Word's built-in emoji fallback picks the
// platform color-emoji font. Forcing 'Segoe UI Emoji' renders tofu boxes
// (and flags as "GB") on Mac Word, which lacks that font.
font: r.emoji
? undefined
: r.symbol
? 'Arial Unicode MS'
: mapFont(r.fontFamily, r.mono, r.text),
characterSpacing: r.letterSpacing > 0.5 ? context.pxToTwips(r.letterSpacing) : undefined,
superScript: r.superscript || undefined,
subScript: r.subscript || undefined,
allCaps: r.uppercase || undefined,
// w:rtl on the run so Arabic/Hebrew glyphs shape and order correctly
// (docx mirrors size/bold/italics into their complex-script twins)
rightToLeft: r.rtl || undefined,
// arbitrary hex needs character shading (w:highlight only takes named colors)
shading: r.highlight ? { type: ShadingType.CLEAR, fill: r.highlight } : undefined,
// inline boxed chip -> character border (w:bdr); space:1 keeps a hair of
// padding between glyph and frame like the authored chip padding
border: r.charBorder
? {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(r.charBorder.widthPx),
color: r.charBorder.color,
space: 1,
}
: undefined,
noProof: true,
}
const lines = (r.text || '').split('\n')
lines.forEach((line, i) => {
const segments = line.split('\t')
segments.forEach((segment, j) => {
const needsBreak = i > 0 && j === 0
const children = []
if (j > 0) children.push(new Tab())
if (segment) children.push(segment)
// standalone <br> produces an empty segment that must still emit the break
if (!children.length && !needsBreak) return
const run = new TextRun({ ...style, children, break: needsBreak ? 1 : undefined })
if (r.anchor) {
out.push(new InternalHyperlink({ children: [run], anchor: bookmarkName(r.anchor) }))
} else if (r.href) {
out.push(new ExternalHyperlink({ children: [run], link: r.href }))
} else {
out.push(run)
}
})
})
}
return out
}
function makeNodeRuns(context, node, images: any = {}) {
const runs = makeRuns(context, node.runs, images)
const insetPx = node.style?.borderLeftSpacePx || 0
if (insetPx > 0) {
const sample = node.runs.find((run) => run.text) || {}
const fontSizePx = sample.sizePx || 16
const count = Math.max(1, Math.ceil(insetPx / (fontSizePx * 0.65)))
runs.unshift(
new TextRun({
text: '\u00A0'.repeat(count),
size: context.pxToHalfPoints(fontSizePx),
font: mapFont(sample.fontFamily, sample.mono, sample.text),
noProof: true,
}),
)
}
return runs
}
// Rebuild tab stops from measured positions: a separator whose following
// content starts far right becomes a right-aligned stop at the margin
// (dates), otherwise a left stop at the measured column position.
function tabStopsFor(context, runs) {
const tabs = runs.filter((r) => r.text.includes('\t'))
if (!tabs.length) return []
const stops = []
const seen = new Set()
for (const r of tabs) {
// Column starting past 75% of the line is a right-aligned tail (dates);
// otherwise reproduce the measured column position with a left stop.
const stop =
r.tabFrac != null && r.tabFrac < 0.75
? { type: TabStopType.LEFT, position: Math.round(r.tabFrac * context.contentDxa) }
: { type: TabStopType.RIGHT, position: context.contentDxa }
const key = `${stop.type}:${stop.position}`
if (!seen.has(key)) {
seen.add(key)
stops.push(stop)
}
}
return stops
}
function paraOptions(context, style: any = {}) {
const opts: any = {}
// w:bidi: paragraph flows right-to-left (default alignment becomes right)
if (style.rtl) opts.bidirectional = true
if (style.align === 'center') opts.alignment = AlignmentType.CENTER
if (style.align === 'right') opts.alignment = AlignmentType.RIGHT
// explicit physical left (an RTL paragraph author-aligned to the left edge)
if (style.align === 'left' && style.rtl) opts.alignment = AlignmentType.LEFT
if (style.align === 'justify') opts.alignment = AlignmentType.JUSTIFIED
if (style.indentLeftPx || style.indentHangingPx) {
// hanging: first line carries the literal bullet/number prefix at
// indentLeftPx, wrapped lines align under the text after the prefix
const hang = style.indentHangingPx ? context.pxToTwips(style.indentHangingPx) : 0
opts.indent = {
left: context.pxToTwips(style.indentLeftPx || 0) + hang,
...(hang ? { hanging: hang } : {}),
}
} else if (style.firstLineIndentPx) {
// CSS text-indent (CJK-style opening indent) -> w:ind firstLine
opts.indent = { firstLine: context.pxToTwips(style.firstLineIndentPx) }
}
opts.spacing = {}
if (style.spacingAfterPx) opts.spacing.after = context.pxToTwips(style.spacingAfterPx)
if (style.spacingBeforePx) opts.spacing.before = context.pxToTwips(style.spacingBeforePx)
if (style.lineRatio) {
// Word's intrinsic leading is larger for CJK fonts than Latin fonts.
const effective = Math.max(1, style.lineRatio / (style.cjk ? 1.3 : 1.15))
opts.spacing.line = Math.round(effective * 240)
}
if (style.exactLineHeightPx) {
// Shaded single-line bars: force the browser-rendered height, otherwise
// Word's CJK leading makes the colored strip visibly taller.
// Bordered paragraphs (left accent bars) must not use EXACT: Word drops
// the text to the line bottom while the border hugs the paragraph box,
// so the accent bar floats visibly above the heading text.
opts.spacing.line = context.pxToTwips(style.exactLineHeightPx)
opts.spacing.lineRule =
style.borderLeft || style.borderRight ? LineRuleType.AT_LEAST : LineRuleType.EXACT
}
if (style.shading) opts.shading = { type: ShadingType.CLEAR, fill: style.shading }
if (style.borderLeft || style.borderRight || style.borderTop || style.borderBottom) {
opts.border = {}
if (style.borderLeft) {
opts.border.left = {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderLeft.widthPx),
color: style.borderLeft.color,
// w:space pushes the border left, away from the text (in points,
// capped at 31 by Word)
space: style.borderLeftOutsetPx
? Math.min(
31,
Math.max(1, Math.round(style.borderLeftOutsetPx * 0.75 * context.measurementScale)),
)
: undefined,
}
}
if (style.borderBottom) {
opts.border.bottom = {
style:
style.borderBottom.style === 'dotted'
? BorderStyle.DOTTED
: style.borderBottom.style === 'dashed'
? BorderStyle.DASHED
: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderBottom.widthPx),
color: style.borderBottom.color,
space: 4,
}
}
if (style.borderRight) {
opts.border.right = {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderRight.widthPx),
color: style.borderRight.color,
space: style.borderRightSpacePx
? Math.max(1, Math.round(style.borderRightSpacePx * 0.75 * context.measurementScale))
: undefined,
}
}
if (style.borderTop) {
opts.border.top = {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderTop.widthPx),
color: style.borderTop.color,
space: 4,
}
}
}
return opts
}
// Empty paragraph occupying an exact pixel height (spacing around tables,
// which can't carry before/after spacing themselves).
// keepNext binds the spacer to the following block: needed between a heading
// and its section body (else the heading's own keepNext only reaches the
// spacer and Word orphans the heading at a page bottom), but must NOT be on
// trailing spacers \u2014 a document-wide spacer chain would fuse sections and
// force Word to break pages far too early.
function spacerParagraph(
context,
px,
{ keepNext = false, shading = null, borderLeft = null } = {},
) {
const paragraph = new Paragraph({
// Word tables already contribute a few pixels of leading. Force only
// authored block gaps large enough to be visually meaningful.
children: [new TextRun({ text: px >= 24 ? '\u200B' : '', size: 2, noProof: true })],
...(keepNext ? { keepNext: true } : {}),
...(shading ? { shading: { type: ShadingType.CLEAR, fill: shading } } : {}),
// continues a flattened card's left rail through spacing gaps
...(borderLeft
? {
border: {
left: {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(borderLeft.widthPx),
color: borderLeft.color,
},
},
}
: {}),
spacing: {
before: 0,
after: 0,
line: context.pxToTwips(Math.max(px, 2)),
lineRule: LineRuleType.EXACT,
},
})
// Marker so Generator.render can swap a rendered block's leading spacer
// for a keepNext one when it directly follows a heading.
const marked = paragraph as any
marked.__h2dSpacerPx = px
marked.__h2dSpacerShading = shading
marked.__h2dSpacerBorderLeft = borderLeft
return paragraph
}
const NO_BORDER = { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' }
const NO_BORDERS = {
top: NO_BORDER,
bottom: NO_BORDER,
left: NO_BORDER,
right: NO_BORDER,
}
// Table-level: without it the docx library emits default single borders,
// and Word (Mac) paints them even where cells say val="none" — visible as
// a gray frame around dark panels.
const NO_TABLE_BORDERS = {
...NO_BORDERS,
insideHorizontal: NO_BORDER,
insideVertical: NO_BORDER,
}
function wordBorder(context, border) {
if (!border) return NO_BORDER
const styles = {
dotted: BorderStyle.DOTTED,
dashed: BorderStyle.DASHED,
double: BorderStyle.DOUBLE,
}
return {
style: styles[border.style] || BorderStyle.SINGLE,
// Floor at 0.75pt: a scaled 1px CSS border falls to 0.5pt and turns
// nearly invisible in Word at common zoom levels (same floor as cards).
size: Math.max(6, context.pxToBorderEighths(border.widthPx)),
color: border.color,
}
}
const HEADING_LEVELS = [
HeadingLevel.HEADING_1,
HeadingLevel.HEADING_2,
HeadingLevel.HEADING_3,
HeadingLevel.HEADING_4,
HeadingLevel.HEADING_5,
HeadingLevel.HEADING_6,
]
export {
HEADING_LEVELS,
NO_BORDER,
NO_BORDERS,
NO_TABLE_BORDERS,
makeNodeRuns,
makeRuns,
paraOptions,
spacerParagraph,
tabStopsFor,
wordBorder,
}
+6
View File
@@ -0,0 +1,6 @@
export { convertHtmlToDocx } from './convert'
export type { ConvertOptions, ConvertResult, ConvertStage } from './convert'
export type { BrowserDriver, ClipRect, ScreenshotOptions, Viewport } from './driver'
export { BROWSER_HELPER_SCRIPTS, EXTRACTOR_CALL, EXTRACTOR_SOURCE } from './extract'
export { generateDocx } from './generate'
export { FONT_RULES, mapFont } from './generate/fonts'
+4
View File
@@ -0,0 +1,4 @@
declare module '*?raw' {
const source: string
export default source
}
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
/**
* html2docx <input.html> <output.docx> [--verbose]
*
* Runs through Vite's SSR loader so the extractor's `?raw` fragment imports
* resolve the same way they do in the app bundle and in vitest:
* npx tsx packages/html2docx/tools/cli.ts in.html out.docx
*
* Debug env: H2D_SHOT_TEXT_PATH (write rasterized text), H2D_IR_PATH (dump
* IR + trace), H2D_TRACE_SELECTOR (in-page probes).
*/
import { writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { createServer } from 'vite'
import type { ConvertOptions, ConvertResult } from '../src'
import type { PlaywrightDriver as PlaywrightDriverType } from '../src/drivers/playwright'
const A4 = { width: 794, height: 1123, deviceScaleFactor: 2 }
async function main(): Promise<void> {
const verbose = process.argv.includes('--verbose') || process.argv.includes('-v')
const args = process.argv.slice(2).filter((a) => a !== '--verbose' && a !== '-v')
if (args.length < 2) {
console.error('Usage: html2docx <input.html> <output.docx> [--verbose]')
process.exit(1)
}
const [input, output] = args
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const vite = await createServer({
root,
configFile: false,
logLevel: 'error',
server: { middlewareMode: true, hmr: false },
optimizeDeps: { noDiscovery: true },
})
try {
const lib = (await vite.ssrLoadModule('/src/index.ts')) as {
convertHtmlToDocx: (
input: { url: string },
driver: PlaywrightDriverType,
options: ConvertOptions,
) => Promise<ConvertResult>
}
const { PlaywrightDriver, launchChrome } = (await vite.ssrLoadModule(
'/src/drivers/playwright.ts',
)) as typeof import('../src/drivers/playwright')
const browser = await launchChrome()
try {
const driver = await PlaywrightDriver.create(browser, A4)
const url = input.startsWith('http') ? input : pathToFileURL(resolve(input)).href
const result = await lib.convertHtmlToDocx({ url }, driver, {
log: verbose ? (m) => console.error(m) : undefined,
traceSelector: process.env.H2D_TRACE_SELECTOR,
onIr: process.env.H2D_IR_PATH
? (ir, trace) => {
writeFileSync(`${process.env.H2D_IR_PATH}.trace`, JSON.stringify(trace, null, 1))
writeFileSync(
process.env.H2D_IR_PATH!,
JSON.stringify(ir, (key, value) => (key === 'buffer' ? undefined : value), 1),
)
}
: undefined,
})
await driver.close()
writeFileSync(output, result.docx)
if (process.env.H2D_SHOT_TEXT_PATH) {
writeFileSync(process.env.H2D_SHOT_TEXT_PATH, result.screenshotText, 'utf8')
}
console.log(output)
} finally {
await browser.close()
}
} finally {
await vite.close()
}
}
main().catch((e) => {
console.error(e)
process.exit(1)
})
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
// DOM for the functions convert.ts serializes into the page
"lib": ["ES2022", "DOM", "DOM.Iterable"],
// ported from untyped JS; tightened file by file, no logic changes
"strict": false,
"noImplicitAny": false
},
"include": ["src", "tests", "tools"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
// every case renders in a real Chromium
testTimeout: 90000,
hookTimeout: 60000,
},
})