fix: a rule line a paragraph style declares is drawn

Only direct w:pPr/w:pBdr was read, so a Title style's line went missing and
everything under it sat 1.9mm high. The box now goes to the style registry,
where ParaProps' borders already render and round-trip.

Two thirds of that gap is the file's own w:pBdr w:space, carried as
ParaProps.borderPadding (ODF fo:padding) and applied to the ruled sides only —
padding the top as well pushes the paragraph's first line down.
Corpus 761 -> 739.
This commit is contained in:
Steffen Becker committed 2026-08-13 00:39:10 +00:00
1 parent 0656b606fb
commit c7e1f91d46
8 files changed
+141 -15

No files matched your search

+1
View File
@@ -39,6 +39,7 @@
- Word's Table Style Options as six checkboxes beside the gallery (header row, total row, first/last column, banded rows/columns): an area is painted only when the style defines it *and* the table opts in, and turning the header row off shifts the banding by one row. The toolbar's header row / first column buttons drive the same flags, so both surfaces always agree
- Table styles are edited in the same style manager (third tab: area picker for fill and font, outer / row line / column line controls, new / rename / remove), also reachable from the insert-table dropdown
- Round-trip: the style name travels as an ODF `style:family="table"` (`style:parent-style-name`) and DOCX `w:tblStyle`, the options as ODF's `table:use-*-styles` and Word's `w:tblLook`. Fills and borders are materialized into the cells and the region's font is baked onto the runs, so the table looks right in Word/LibreOffice even though ODF has no banding concept — the style definitions themselves live in the app, as LibreOffice's AutoFormats do
- A paragraph style's own rule line and colored field are read from the style, not only from direct formatting, so a Word Title keeps the line under it — with the gap the file asks for (`w:pBdr w:space` / ODF `fo:padding`), on the ruled sides only
- A Word table's indent follows the file's compatibility mode: up to Word 2010 `w:tblInd` is measured to the cell's text, so the table hangs its left cell margin into the page margin and the first column's text lines up with the body — from Word 2013 it is the table's edge
- A Word file's own table style is read the other way round: its conditional areas (`w:tblStylePr` — header row, banded rows, first/last column) are baked into the cells on import, shading, borders and bold/colour alike, so a document styled with Word's Light Grid or Medium Shading opens looking like it does in Word and LibreOffice
- A new document starts from the built-in styles, like Word's/LibreOffice's default template
+1 -1
View File
@@ -4,7 +4,7 @@ Covers the `src/lib/editor/extensions/` files carrying character effects, indent
list markers, paragraph boxes, date/time fields and cross-references.
- **`textEffects.ts`** (`TextEffects`, `UnderlineStyled`, `StrikeStyled`) — the character effects beyond bold/italic that both formats carry and CSS can draw: `caps` (`uppercase`/`lowercase`/`capitalize`/`smallCaps` → `text-transform`/`font-variant-caps`) and `textPosition` (pt above the baseline → `vertical-align`, independent of sub/superscript) as TextStyle attrs, plus `lineStyle`/`lineColor` on the **underline** mark and `lineStyle` on **strike** (the `<u>`/`<s>` element draws the line, so its shape belongs there). Replaces TipTap's bare Underline/Strike in `extensions.ts` **and** `hfExtensions`. `caps` is also a `TextProps` key, so a named style can carry it. **DOCX**: `w:caps`/`w:smallCaps` (toggles — a run may switch a style's off), `w:u w:val`+`w:color`, `w:dstrike`, `w:position` (`ST_SignedHpsMeasure`: a bare number is half-points, else a measure with its unit). **ODF**: `fo:text-transform`/`fo:font-variant`, `style:text-underline-style`/`-type`/`-color`, `style:text-line-through-type`, `style:text-position` (a percentage of the font size, so the pt value is converted against the run's own size). odf-kit's run formatting has a field for none of them, so `markTextEffects` prefixes the `TEF` sentinel (U+E00F) on the run and `applyTextEffects` folds the attributes into that run's automatic text style — before `applyCharacterStyles`, which then clones the style that already carries them. `tests/lo-roundtrip.test.ts` is what proves LibreOffice reads each one back.
- **`paragraphBox.ts`** (`ParagraphBox`) — paragraph/heading **background** (`backgroundColor`, "colored field") + per-side **borders** (`borderTop/Right/Bottom/Left`, "rule line"), as in Word/LibreOffice letterheads. Borders reuse table cells' canonical `'<W>pt solid #RRGGBB'` (from `tableCellBorders.ts`), but here `null`/absent = no border. Commands `setParagraphBackground`/`setParagraphBorders(preset, spec)`; `activeParagraphBorderPresets` drives the picker states. An input rule turns a paragraph typed as `---`/`___`/`===` into an empty bottom-rule line (the border-line AutoCorrect); attrs are `keepOnSplit: false` so the box doesn't cascade onto the next paragraph on Enter. In both `extensions.ts` (body) and `hfExtensions` (header/footer). **ODF**: import reads `fo:background-color`/`fo:border-*` in `blockAttrs` (body) and merges them across the collapsed header/footer paragraphs (`convertHfZone`, first/last heuristic — bottom rule from the last line); export emits them via `ParaStyle`/`paraStyleProps` for cells/lists, a `PBX`-sentinel post-process (`applyParagraphBoxes`, odf-kit has no such options) for top-level body paragraphs, and `applyHfPostProcess` for the Header/Footer styles. **DOCX**: `w:shd`/`w:pBdr` (import `readParaBox`, export `paraShadingOf`/`paraBordersOf`). UI: a paragraph-shading `ColorPicker` + `ParagraphBorderPicker.svelte` in `ToolbarExpanded.svelte` (route via `activeEditor`, so body and the active HF zone).
- **`paragraphBox.ts`** (`ParagraphBox`) — paragraph/heading **background** (`backgroundColor`, "colored field") + per-side **borders** (`borderTop/Right/Bottom/Left`, "rule line"), as in Word/LibreOffice letterheads. Borders reuse table cells' canonical `'<W>pt solid #RRGGBB'` (from `tableCellBorders.ts`), but here `null`/absent = no border. Commands `setParagraphBackground`/`setParagraphBorders(preset, spec)`; `activeParagraphBorderPresets` drives the picker states. An input rule turns a paragraph typed as `---`/`___`/`===` into an empty bottom-rule line (the border-line AutoCorrect); attrs are `keepOnSplit: false` so the box doesn't cascade onto the next paragraph on Enter. In both `extensions.ts` (body) and `hfExtensions` (header/footer). **ODF**: import reads `fo:background-color`/`fo:border-*` in `blockAttrs` (body) and merges them across the collapsed header/footer paragraphs (`convertHfZone`, first/last heuristic — bottom rule from the last line); export emits them via `ParaStyle`/`paraStyleProps` for cells/lists, a `PBX`-sentinel post-process (`applyParagraphBoxes`, odf-kit has no such options) for top-level body paragraphs, and `applyHfPostProcess` for the Header/Footer styles. **DOCX**: `w:shd`/`w:pBdr` (import `readParaBox`, export `paraShadingOf`/`paraBordersOf`). A *style's* box is not the block's: it goes to the **style registry** (`ParaProps.borderTop…`, `stylePara`/`DocxStyles.paragraphBorders`), so every paragraph the style governs draws it. `ParaProps.borderPadding` (pt) is the gap the file keeps between the text and its rule — Word's per-side `w:pBdr w:space`, ODF's `fo:padding-*` — and `declarations` puts it on the **ruled sides only**: a bottom rule that also padded the top would push the paragraph's first line down (measured: a Title's next block sat 1.4mm low). Where no file value exists, `editor.css`'s flat 0.04/0.08cm on a bordered block still applies. UI: a paragraph-shading `ColorPicker` + `ParagraphBorderPicker.svelte` in `ToolbarExpanded.svelte` (route via `activeEditor`, so body and the active HF zone).
- **`indent.ts`** (`Indent`) — `indent` attr in **cm** (rendered as `margin-left`), on paragraph/heading **and** bulletList/orderedList. `indentMore`/`indentLess` step a paragraph/heading by `INDENT_STEP_CM = 1.25` → `fo:margin-left` (odf-kit `indentLeft`); `indentListMore`/`indentListLess` step the innermost list's `indent`, shifting the whole list (export adds it to the L# list-style level margins, see `applyListIndents`). On a list the attr is **one level's step past the level above**, not its absolute position: both formats store a level's indent absolutely (`w:lvl/w:pPr/w:ind w:left`, the label-alignment `fo:margin-left`) while the editor nests one 1.27cm step per level, so import subtracts the level above and the ODF export adds the running sum back per level. That is what lets a file's own level geometry survive at any depth — measured, a 0.5cm/−0.6cm pair puts LibreOffice's two levels at 1.77cm and 2.44cm, where the editor draws them. `indentListForward`/`indentListBackward` apply one Word/LibreOffice step to the list point (bullet + text): **forward** shifts the whole list when the cursor is in the first item or the whole list is selected (`indentListMore`), otherwise nests the item (`sinkListItem`); **backward** is the inverse — it peels back the innermost list's own `indent` first (`indentListLess`), then lifts a *nested* item out one level (`liftListItem`), and at the base level (no margin, not nested) does nothing. So a list point steps left one tab-stop at a time and never gets dissolved into a paragraph — Shift-Tab keeps list points as list points. They return false outside a list. `indentRight` is the mirror of `indent` (`fo:margin-right` / `w:ind w:right`; ODF export rides the PBX sentinel, since odf-kit has no right-indent option). `setIndent(cm)`/`setIndentRight(cm)`/`setIndentFirst(cm)` write one indent outright (what the ruler drags; the buttons step relatively) — all go through the same `write` walk. The exported `listContext(state)` (cursor in a list? whole list targeted? innermost list indent? list nested inside a parent list item?) is their shared helper. Both the toolbar's `changeIndent` and the **Tab**/**Shift-Tab** keymap call these: in a list Tab/Shift-Tab run `indentListForward`/`indentListBackward`; outside a list Tab inserts a real tab character (`\t`, rendered via the document's `tab-size`) and Shift-Tab runs `indentLess` (`changeIndent` uses `indentMore`/`indentLess`). The keymap bails inside table cells so the Table extension's Tab keeps navigating between cells. `Indent` sets `priority: 1000` so its Tab/Shift-Tab win over `ListItem`'s built-in sink/lift bindings — without it, TipTap's reverse-then-priority-sort lets the later-registered `ListItem` handle the key first (its `liftListItem` would dissolve a top-level list item into a paragraph on Shift-Tab).
- **`tabStops.ts`** (`TabStops`) — per-paragraph tab stops (Word's `w:tabs`, ODF `style:tab-stops`). Global attr `tabStops` on paragraph/heading, rendered as `data-tab-stops`; canonical string `'<cm><align code>'` per stop, `;`-separated (`'6c;12r;16d'`, codes `l|c|r|d`), parsed only by the exported `parseTabStops`/`formatTabStops`. Positions are **cm from the left text margin** — the origin Word and ODF share, verified by probe (a Word stop at 100mm in a 30mm-indented paragraph stays 100mm in ODF and LibreOffice renders it there), so neither I/O side shifts them by the paragraph indent. **Rendering**: CSS only has the fixed `tab-size` grid, so a rAF measuring plugin (shaped like `pageBreaks.ts`, whose `FORCE_PAGE_RECALC` it both listens to and fires) computes each tab's advance from `coordsAtPos` against `.tiptap`'s content edge and emits `Decoration.inline(tab, tab+1, {style:'tab-size:0;margin-left:Npx'})` — `tab-size:0` collapses the tab's own advance, the inline margin supplies the exact width, so no `display` change and no baseline/line-height side effects. The margin is on the **left** because the gap is the tab's own advance: as `margin-right` a caret placed after the tab rendered before the gap, i.e. at the pre-tab x until the next keystroke. The pen is read from the DOM only at the **first tab of a line** (side −1, the end of the content before it) and then **carried along the line**: stop + the natural width of the segment that follows it. Reading each tab off the DOM instead measures the advance the *previous* pass gave the tab before it, so the layout takes another pass to settle — and on a long document, where pagination keeps moving lines for seconds, it may never get a stable one; the Math Guide's contributor columns landed 18mm out in one run of three. `nextStop` takes the first custom stop right of the tab, else leaves the tab undecorated (past the last custom stop the CSS grid already does the right thing, which is also why custom stops suppress the default ones to their left). A **negative `indentFirst` implies a stop at the block's indent** (the hanging-indent stop). Centre/right/decimal take back the segment up to the next tab, measured by `rangeWidth` as the **extent of each line it covers**, added up — a range crossing an inline element yields a rect for the element's box *and* for the text inside it, and adding those counts the text twice. The scale comes from the editor's **width**: `offsetHeight` is rounded, and a one-line zone is short enough for that to be half a percent. Passes converge (one more tab settles per pass, `MAX_PASSES`), since a stop can rewrap the line. **UI**: `Ruler.svelte`. A **header/footer zone** carries stops too — the left⇥centre⇥right layout rides on them — but an inactive one is static `generateHTML` output no plugin reaches, so `layOutZoneTabs` measures it straight on the DOM (`HeaderFooterLayer.svelte`, `use:layOutTabs`), wrapping each tab in a span of its own. Advances are layout px, so the zoom transform doesn't invalidate them. A decimal stop there behaves as right. Three things that zone needs and the body doesn't: the wrap marker is matched with `hasAttribute` (its value is `''`, which reads as falsy, and every pass nested another span with its own advance), the segment is measured with wrapping off (one already wrapped reads short by the space its break swallowed, which keeps it wrapped), and a stop past the line is drawn at the line's end — LibreOffice's own footer style puts its right stop at 18cm in a 17cm column. The body clamps the same way. A stop may carry a **leader** (`w:tab w:leader` / `style:leader-text`, one of `. - _ ·`), drawn as a `::before` clipped to the measured gap so the fill stays out of the document's text; on the ODF side odf-kit has no leader option and mints one automatic style per option set, so the leader rides `style:type` behind a `LEAD` sentinel that `applyTabLeaders` unpacks — a bare position+type lookup would give two stops that agree on both the same leader. Past the last custom stop the grid is the document's own **default tab interval** (`storage/tabInterval.ts`, 1.25cm for a new document — LibreOffice's; Word's is 1.27): imported from `w:defaultTabStop` / the paragraph default-style's `style:tab-stop-distance`, applied as the `--tab-interval` CSS var, and **always** written back on export. A file that declares none falls back to its format's own value — measured, LibreOffice puts a bare `A⇥X` at **2cm**, not at its UI default — so leaving ours implied would render differently everywhere else (`ODF_IMPLIED_TAB_CM`, `DOCX_IMPLIED_TAB_CM`).
+4 -1
View File
@@ -1304,7 +1304,10 @@ function ownStyleAttrs(style: { para: Record<string, unknown>; text: Record<stri
if (p.backgroundColor) para['fo:background-color'] = String(p.backgroundColor);
for (const [key, side] of [['borderTop', 'top'], ['borderRight', 'right'], ['borderBottom', 'bottom'], ['borderLeft', 'left']] as const) {
const v = p[key];
if (v && v !== 'none') para[`fo:border-${side}`] = String(v);
if (!v || v === 'none') continue;
para[`fo:border-${side}`] = String(v);
// The gap to the rule, on the ruled sides only — fo:padding would ring the block.
if (p.borderPadding != null) para[`fo:padding-${side}`] = `${p.borderPadding}pt`;
}
const text: Record<string, string> = {};
if (t.fontFamily) {
+38 -11
View File
@@ -680,6 +680,26 @@ function stylePara(ctx: Ctx, id: string | null): ParaProps {
else if (jc === 'left' || jc === 'start') out.textAlign = 'left';
const ind = ctx.styles.styleIndentTwip(id);
if (ind != null) out.indent = round2(twipToCm(ind));
// The style's own rule lines and colored field — a Title's rule lives here, not on the
// block, so every paragraph the style governs draws it (styleCss).
const shd = ctx.styles.paragraphShading(id);
const fill = shd ? hexColor(shd.getAttributeNS(W, 'fill')) : undefined;
if (fill) out.backgroundColor = fill;
let space: number | null = null;
for (const [wSide, attr] of PARA_BORDER_SIDES) {
for (const pBdr of ctx.styles.paragraphBorders(id)) {
const side = fc(pBdr, wSide);
if (!side) continue;
const v = paraBorderAttr(side);
if (v) {
out[attr] = v;
// w:space is in whole points, per side; the widest gap is the paragraph's.
space = Math.max(space ?? 0, intAttr(side, W, 'space') ?? 0);
}
break; // the nearest level that declares the side decides it
}
}
if (space) out.borderPadding = space;
return out;
}
@@ -949,22 +969,29 @@ function readParaBox(ppr: Element | null): Record<string, string> {
const pBdr = fc(ppr, 'pBdr');
if (pBdr) {
for (const [wSide, attr] of [
['top', 'borderTop'], ['right', 'borderRight'], ['bottom', 'borderBottom'], ['left', 'borderLeft'],
] as const) {
const b = fc(pBdr, wSide);
if (!b) continue;
const val = b.getAttributeNS(W, 'val');
if (!val || val === 'none' || val === 'nil') continue;
const sz = intAttr(b, W, 'sz'); // eighths of a point
const widthPt = sz != null ? Math.round((sz / 8) * 100) / 100 : 0.5;
const color = hexColor(b.getAttributeNS(W, 'color')) ?? '#000000';
out[attr] = `${widthPt}pt solid ${color}`;
for (const [wSide, attr] of PARA_BORDER_SIDES) {
const v = paraBorderAttr(fc(pBdr, wSide));
if (v) out[attr] = v;
}
}
return out;
}
const PARA_BORDER_SIDES = [
['top', 'borderTop'], ['right', 'borderRight'], ['bottom', 'borderBottom'], ['left', 'borderLeft'],
] as const;
// One w:pBdr side → the canonical '<W>pt solid #RRGGBB'. null when it draws nothing:
// unlike a table cell, a paragraph has no 0.5pt-black default to collapse against.
function paraBorderAttr(b: Element | null): string | null {
if (!b) return null;
const val = b.getAttributeNS(W, 'val');
if (!val || val === 'none' || val === 'nil') return null;
const sz = intAttr(b, W, 'sz'); // eighths of a point
const widthPt = sz != null ? Math.round((sz / 8) * 100) / 100 : 0.5;
return `${widthPt}pt solid ${hexColor(b.getAttributeNS(W, 'color')) ?? '#000000'}`;
}
function snapPt(v: number): number {
const r = Math.round(v * 100) / 100;
const i = Math.round(r);
+23
View File
@@ -181,6 +181,8 @@ export class DocxStyles {
private ownTabs = new Map<string, TabStop[]>(); // style's own w:pPr/w:tabs
private ownCellMar = new Map<string, Element>(); // table style's own w:tblPr/w:tblCellMar
private ownTblBorders = new Map<string, Element>(); // table style's own w:tblPr/w:tblBorders
private ownPBdr = new Map<string, Element>(); // style's own w:pPr/w:pBdr (rule lines)
private ownParaShd = new Map<string, Element>(); // style's own w:pPr/w:shd (colored field)
private ownCond = new Map<string, Map<string, Element>>(); // table styleId → w:type → w:tblStylePr
private ownBandSize = new Map<string, { row: number; col: number }>(); // w:tblStyle*BandSize
private defaultsWidow: boolean | null = null; // docDefaults w:pPrDefault/w:widowControl
@@ -257,6 +259,10 @@ export class DocxStyles {
const left = parseInt(ind.getAttributeNS(W, 'left') ?? ind.getAttributeNS(W, 'start') ?? '', 10);
if (Number.isFinite(left)) this.ownIndentTwip.set(id, left);
}
const pBdr = ppr && firstChild(ppr, 'pBdr');
if (pBdr) this.ownPBdr.set(id, pBdr);
const paraShd = ppr && firstChild(ppr, 'shd');
if (paraShd) this.ownParaShd.set(id, paraShd);
const tblPr = firstChild(style, 'tblPr');
const cellMar = tblPr && firstChild(tblPr, 'tblCellMar');
if (cellMar) this.ownCellMar.set(id, cellMar);
@@ -496,6 +502,23 @@ export class DocxStyles {
return own ? [own, ...rest] : rest;
}
// Every w:pPr/w:pBdr along the w:basedOn chain, leaf first — a paragraph style's rule
// lines, which the registry renders like any other style property.
paragraphBorders(styleId: string | null | undefined, seen = new Set<string>()): Element[] {
if (!styleId || seen.has(styleId)) return [];
seen.add(styleId);
const own = this.ownPBdr.get(styleId);
const rest = this.paragraphBorders(this.basedOn.get(styleId) ?? null, seen);
return own ? [own, ...rest] : rest;
}
// The nearest w:pPr/w:shd along the chain (the paragraph's own background).
paragraphShading(styleId: string | null | undefined, seen = new Set<string>()): Element | null {
if (!styleId || seen.has(styleId)) return null;
seen.add(styleId);
return this.ownParaShd.get(styleId) ?? this.paragraphShading(this.basedOn.get(styleId) ?? null, seen);
}
// The table style's conditional areas (w:tblStylePr) along the w:basedOn chain: Word's
// "first row", "banded row 1", … each carrying the w:tcPr and w:rPr it paints. Leaf wins
// per area, so a derived style replaces the whole area rather than merging into it.
+6 -1
View File
@@ -1141,10 +1141,15 @@ function paraPropsFromOdf(props: PropMap): ParaProps {
}
const bg = props['fo:background-color'];
if (bg && bg !== 'transparent') out.backgroundColor = normalizeColor(bg) ?? undefined;
let pad: number | null = null;
for (const [key, side] of [['borderTop', 'top'], ['borderRight', 'right'], ['borderBottom', 'bottom'], ['borderLeft', 'left']] as const) {
const v = props[`fo:border-${side}`] ?? props['fo:border'];
if (v && v !== 'none') out[key] = borderAttrFromOdf(v) ?? undefined;
if (!v || v === 'none') continue;
out[key] = borderAttrFromOdf(v) ?? undefined;
const p = lengthToPt(props[`fo:padding-${side}`] ?? props['fo:padding']);
if (p) pad = Math.max(pad ?? 0, p);
}
if (pad) out.borderPadding = snapPt(pad);
return out;
}
+12 -1
View File
@@ -16,6 +16,9 @@ export type ParaProps = {
borderRight?: string;
borderBottom?: string;
borderLeft?: string;
// pt between the text and its own rule lines (Word's w:pBdr w:space, ODF fo:padding).
// Only the sides that draw a border take it.
borderPadding?: number;
};
export type TextProps = {
@@ -255,9 +258,17 @@ function declarations(r: ResolvedStyle): string[] {
// Plus the section inset, which .tiptap's own padding can't draw (editor.css).
if (p.indent != null) out.push(`margin-left: calc(var(--sec-inset-left, 0px) + ${p.indent}cm)`);
if (p.backgroundColor) out.push(`background-color: ${p.backgroundColor}`);
const drawn: Record<string, boolean> = {};
for (const [key, side] of [['borderTop', 'top'], ['borderRight', 'right'], ['borderBottom', 'bottom'], ['borderLeft', 'left']] as const) {
const v = p[key];
if (v && v !== 'none') out.push(`border-${side}: ${v}`);
drawn[side] = !!v && v !== 'none';
if (drawn[side]) out.push(`border-${side}: ${v}`);
}
// The gap the file puts between the text and its rule, on the ruled sides only —
// a bottom rule must not indent the paragraph or push its first line down.
if (p.borderPadding != null) {
const pad = (side: string) => (drawn[side] ? `${p.borderPadding}pt` : '0');
out.push(`padding: ${pad('top')} ${pad('right')} ${pad('bottom')} ${pad('left')}`);
}
return out;
}
+56
View File
@@ -0,0 +1,56 @@
// A paragraph style's own rule line (Word's w:pBdr, ODF fo:border-*) and the gap it keeps
// to the text (w:space / fo:padding). Both live in the style registry, not on the block.
import { describe, it, expect } from 'vitest';
import { zipSync, unzipSync, strToU8, strFromU8 } from 'fflate';
import { importDocx } from '../../src/lib/import/docx';
import { importOdt } from '../../src/lib/import/odt';
import { buildOdt } from '../../src/lib/export/odt';
type N = any;
const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
const styles = (pBdr: string) => `<?xml version="1.0"?><w:styles xmlns:w="${W}">
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/>
<w:pPr>${pBdr}</w:pPr></w:style>
</w:styles>`;
const doc = `<?xml version="1.0"?><w:document xmlns:w="${W}"><w:body>
<w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Heading</w:t></w:r></w:p>
</w:body></w:document>`;
const imported = (pBdr: string) =>
importDocx(zipSync({ 'word/document.xml': strToU8(doc), 'word/styles.xml': strToU8(styles(pBdr)) })).styles.paragraph['Title'].para;
describe('a paragraph style’s rule line', () => {
const rule = '<w:pBdr><w:bottom w:val="single" w:sz="8" w:space="4" w:color="4F81BD"/></w:pBdr>';
it('is read from the style, not only from direct formatting', () => {
const para = imported(rule);
expect(para.borderBottom).toBe('1pt solid #4F81BD');
expect(para.borderTop).toBeUndefined();
expect(para.borderPadding).toBe(4);
});
it('keeps no padding where it draws no rule', () => {
expect(imported('').borderBottom).toBeUndefined();
expect(imported('<w:pBdr><w:bottom w:val="nil"/></w:pBdr>').borderPadding).toBeUndefined();
});
it('round-trips through an ODF export as fo:border + fo:padding on that side', async () => {
const res = importDocx(zipSync({ 'word/document.xml': strToU8(doc), 'word/styles.xml': strToU8(styles(rule)) }));
const bytes = await buildOdt(
res.content as N, { top: 2, bottom: 2, left: 2, right: 2 }, 'portrait',
undefined, null, 'A4', res.styles,
);
const xml = strFromU8(unzipSync(bytes)['styles.xml']);
expect(xml).toContain('fo:border-bottom="1pt solid #4F81BD"');
expect(xml).toContain('fo:padding-bottom="4pt"');
expect(xml).not.toContain('fo:padding-top');
const back = importOdt(bytes).styles.paragraph['Title'].para;
expect(back.borderBottom).toBe('1pt solid #4F81BD');
expect(back.borderPadding).toBe(4);
});
});