diff --git a/docs/architecture/formatting.md b/docs/architecture/formatting.md index b68da40..339a7a5 100644 --- a/docs/architecture/formatting.md +++ b/docs/architecture/formatting.md @@ -6,6 +6,8 @@ list markers, paragraph boxes and date/time fields. - **`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 ``/`` 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 `'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). - **`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`). `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 `''` 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 position is read with **side −1** (the end of the content before the tab), which lies outside the tab's own span — measuring the tab itself would fold the margin just applied back into the next pass's reading. `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 as the **sum of its client rects** (`rangeWidth`) — reading its span end to end instead made a segment that its own advance had pushed onto the next line measure as wrapped, and the alignment could never recover. 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. 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`, LibreOffice's 1.25cm; 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 written back on export — the ODF side only when it differs from LibreOffice's, so a file that never declared one doesn't gain it. +- **`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 `''` 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 position is read with **side −1** (the end of the content before the tab), which lies outside the tab's own span — measuring the tab itself would fold the margin just applied back into the next pass's reading. `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 as the **sum of its client rects** (`rangeWidth`) — reading its span end to end instead made a segment that its own advance had pushed onto the next line measure as wrapped, and the alignment could never recover. 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. 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`). + +A **run of tabs wider than the line** continues on the next one with the grid starting over, as LibreOffice lays it out; Chromium instead hangs the leftover tabs and starts the next line at the margin. `runBreaks` walks the run analytically from the pen *before* it — the one thing the fix can't move, so the answer is the same whether or not the break is already in place — and emits a `
` widget where the line runs out. Only runs of two or more are considered: reading a block's geometry forces a reflow, and doing it for every tab in a 48-page document slowed pagination enough to skew the parity harness. - **`listMarker.ts`** (`ListMarker`) — the marker's **family, weight, slant, size and color**, taken from the item's **first text portion** (`markerFormat`): a mark lives inside the item's paragraph and never reaches `::marker`, which only inherits the `li`'s own font, so a bold numbered heading would keep a light number. A **character style** on that portion is resolved through the registry (`charStyleProps`, handed in by the caller: the plugin from its `sheet` option, the exporters from their `exportSheet`); what a **named paragraph style** provides reaches the marker through `styleCss`'s `li:has(> …)` rule instead. First portion, not the whole line, is LibreOffice's own numbering rule (verified by probe: bold-then-plain gets a bold number, plain-then-bold does not; Word instead takes the paragraph mark). **Rendering**: a node decoration puts `--marker-family/-weight/-style/-size/-color` on **every** `listItem` — they inherit, so an item without its own format resets them to `initial` (the guaranteed-invalid value, so the `var(…, inherit)` in `editor.css` falls back; `inherit` would pull the parent item's value in), and `editor.css` has one rule reading them on the item block's `::before` — which is what **draws** the marker: `::marker` cannot be positioned, and Chromium sets it flush against the text, ~4mm right of the level's hanging indent (`LIST_HANGING_CM` 0.635cm, what both exports write). The pseudo is **absolutely positioned** at that indent, because in flow it grew every list line by a pixel. `list-style: none` drops only the marker box, so the `list-item` counter and `
    ` keep numbering, and `content: counter(list-item, …)`/`counters(list-item, '.')` per `data-eff-list-style` replaces `list-style-type`; a `bulletChar` rides `--bullet` (an `attr()` inside the pseudo would read the block, not the list). `export/pdf.ts` switches the pseudo off and injects the same marker as a real span, since html2canvas cannot paint counters. The bullet shim keeps the symbol font first and takes `--marker-family` as its fallback. The pass also re-runs on `FORCE_PAGE_RECALC`, so editing a character style repaints the markers. **Export**: both formats carry marker formatting **per level**, so `listMarkerFormat` returns one only when *every* item of the list agrees — ODF mints a **named** `style:family="text"` style **in styles.xml** and points the level definition at it via `text:style-name` (`collectListMarkerFormats`/`applyListMarkerFormats`) — LibreOffice ignores the reference when it resolves to an automatic style in content.xml (probed), DOCX writes the level's `w:rPr` (`markerRunProps` → `ILevelsOptions.style.run`). A **mixed** list gets no level format on purpose: LibreOffice then applies its first-portion rule and matches the editor, Word falls back to the paragraph mark (which only carries the size). Import needs nothing — the runs already carry the formatting. Nested lists that odf-kit restyles (`applyNestedListTypes`) and in-cell lists keep a plain marker. A character style **inside a list item** is handled by an ODF pre-pass (`bakeListCharStyles`) instead: odf-kit's list builder reads marks itself and knows nothing about `charStyle`, and `applyRuns` never sees a list paragraph, so the pre-pass does both of its jobs — bake the resolved props into direct marks (which is what gets the run a `` at all) and prefix the `CST` sentinel, so `applyCharacterStyles` re-points that span at the named style like everywhere else. Formatting and name both round-trip. `tests/unit/list-marker.test.ts` covers the four LibreOffice cases, the reset, and both export legs. - **`dateTimeField.ts`** (`DateTimeField`) — inline atom for an inserted date/time field (Word's "Insert Date and Time"). Attrs: `kind` (`'date'|'time'`), `format` (a catalog key), `fixed`, `value` (ISO local datetime captured at insert). A **fixed** field renders its stored `value`; an **auto** field renders the *current* moment on every load (`renderHTML`/`renderText` via `dateTimeFieldText`) — no plugin, Word/LibreOffice likewise only refresh on open. As an inline atom with no children it can't inherit the surrounding run's font from a sibling span, so it **carries that run's marks** on the node: insert adopts the cursor's stored marks, and both importers attach the field run's resolved marks (else it falls back to the editor default font). Command `insertDateTimeField({kind,format,fixed})`. Formats live in `utils/dateTime.ts` as a **token model** (one `Token[]` per format) so the three consumers stay in agreement: `renderFormat` (locale display via `Intl`), `odfNumberStyle` (``/`` body), `docxPicture` (Word field switch). `DateTimePicker.svelte` (a dropdown next to `SpecialCharPicker` in `ToolbarExpanded.svelte`) lists live samples + an "update automatically" checkbox. Not in the header/footer schema (there a ``/DATE field stays plain text). **ODF**: `replaceDateTimeFields`/`applyDateTimeFields` (sentinel U+E00A, mirrors images) emit ``/`` + a minted per-format number style (language from the export doc language; `ensureNumberNamespace` adds `xmlns:number`); import matches the referenced number style back to a format via `parseNumberStyleTokens` + `matchFormat` (unknown ⇒ keep the shown text). **DOCX**: auto → `SimpleField` `DATE`/`TIME \@ "picture"` with a cached run; fixed → a plain text run (Word has no fixed-date field); import maps a `DATE`/`TIME` `fldSimple`/complex field's picture back to a format (`dateTimeFieldFromInstr`). diff --git a/src/lib/editor/extensions/tabStops.ts b/src/lib/editor/extensions/tabStops.ts index 2b044d7..fcaaa5f 100644 --- a/src/lib/editor/extensions/tabStops.ts +++ b/src/lib/editor/extensions/tabStops.ts @@ -102,23 +102,80 @@ function tabPositions(node: PmNode, blockPos: number): number[] { } type TabWidth = { pos: number; width: number; leader: string | null }; +// Doc positions where a run of tabs has to start a new line. +type TabLayout = { widths: TabWidth[]; breaks: number[] }; -function measure(view: EditorView): TabWidth[] { +// Where the pen lands after a tab standing at x (cm from the line start): the first stop +// right of it, else the next multiple of the default interval. +export function nextStopCm(x: number, stops: number[], interval: number): number { + const custom = stops.find((s) => s > x + 0.01); + if (custom != null) return custom; + return Math.floor(x / interval + 1e-9) * interval + interval; +} + +// A run of tabs wider than the line continues on the next one, as LibreOffice lays it +// out; Chromium instead hangs the leftover tabs and starts the next line at the margin. +// Walked from the pen BEFORE the run — the one thing a break of ours can't move — so the +// answer is the same whether or not the break is already in place. +function runBreaks(view: EditorView, blockEl: HTMLElement, tabs: number[], stops: TabStop[], scale: number, originX: number): number[] { + // Only a run of two or more can outgrow a line, and reading the block's geometry + // forces a reflow — so the ordinary single tab costs nothing here. + const runs: [number, number][] = []; + for (let i = 0; i < tabs.length; ) { + let end = i + 1; + while (end < tabs.length && tabs[end] === tabs[end - 1] + 1) end++; + if (end - i > 1) runs.push([i, end]); + i = end; + } + if (!runs.length) return []; + + const cs = getComputedStyle(blockEl); + const interval = (parseFloat(cs.tabSize) || PX_PER_CM * 1.25) / PX_PER_CM; + const lineCm = (blockEl.clientWidth - parseFloat(cs.paddingLeft || '0') - parseFloat(cs.paddingRight || '0')) / PX_PER_CM; + if (!(interval > 0) || !(lineCm > 0)) return []; + // Stops are measured from the text margin, the grid from the line start. + const offsetCm = (blockEl.getBoundingClientRect().left - originX) / scale / PX_PER_CM + + parseFloat(cs.paddingLeft || '0') / PX_PER_CM; + const stopCms = stops.map((s) => s.pos - offsetCm); + const out: number[] = []; + + for (const [i, end] of runs) { + let x = (view.coordsAtPos(tabs[i], -1).left - originX) / scale / PX_PER_CM - offsetCm; + for (let j = i; j < end; j++) { + let next = nextStopCm(x, stopCms, interval); + // Never before the run's own first tab: that pen is what the walk starts from, so + // moving it would make the next pass decide differently. + if (next > lineCm + 0.01 && j > i) { + out.push(tabs[j]); + x = 0; + next = nextStopCm(0, stopCms, interval); + } + x = next; + } + } + return out; +} + +function measure(view: EditorView): TabLayout { const dom = view.dom as HTMLElement; const tipRect = dom.getBoundingClientRect(); // From the width, not the height: offsetWidth/Height are rounded, and a one-line // header/footer zone is short enough for that rounding to be half a percent. const scale = dom.offsetWidth ? tipRect.width / dom.offsetWidth : 1; - if (!scale) return []; + if (!scale) return { widths: [], breaks: [] }; // x = 0 is the left text margin (.tiptap's padding edge), the origin of a stop. const originX = tipRect.left + parseFloat(getComputedStyle(dom).paddingLeft || '0') * scale; const out: TabWidth[] = []; + const breaks: number[] = []; view.state.doc.descendants((node, pos) => { if (!node.isTextblock) return true; - const stops = stopsOf(node); - if (!stops.length) return false; const tabs = tabPositions(node, pos); + if (!tabs.length) return false; + const stops = stopsOf(node); + const blockEl = view.nodeDOM(pos); + if (blockEl instanceof HTMLElement) breaks.push(...runBreaks(view, blockEl, tabs, stops, scale, originX)); + if (!stops.length) return false; const blockEnd = pos + node.nodeSize - 1; for (let t = 0; t < tabs.length; t++) { @@ -145,7 +202,7 @@ function measure(view: EditorView): TabWidth[] { } return false; }); - return out; + return { widths: out, breaks }; } // Natural width of a doc range: the sum of its client rects, so a segment pushed onto @@ -326,14 +383,15 @@ export const TabStops = Extension.create({ view(view) { const calculate = () => { rafId = null; - let widths: TabWidth[] = []; + let layout: TabLayout = { widths: [], breaks: [] }; // coordsAtPos throws on a position the browser hasn't rendered yet; the // next change re-runs the pass anyway. - try { widths = measure(view); } catch { return; } - const next = widths.map((w) => `${w.pos}:${w.width}:${w.leader ?? ''}`).join(','); + try { layout = measure(view); } catch { return; } + const { widths, breaks } = layout; + const next = widths.map((w) => `${w.pos}:${w.width}:${w.leader ?? ''}`).join(',') + `|${breaks.join(',')}`; if (next === key) return; key = next; - const decos = widths.map((w) => + const decos: Decoration[] = widths.map((w) => // margin-LEFT: the gap is the tab's own advance, so a caret placed after // the tab has to sit behind it. As margin-right it stayed at the old x // until the next keystroke moved it into the following text node. @@ -343,6 +401,11 @@ export const TabStops = Extension.create({ ? { style: `tab-size:0;margin-left:${w.width}px;--leader-w:${w.width}px`, class: 'tab-leader', 'data-leader': w.leader } : { style: `tab-size:0;margin-left:${w.width}px` }), ); + // The tabs the line can't hold move to the next one, where the grid starts + // over — which is what CSS does after a
    anyway. + for (const at of breaks) { + decos.push(Decoration.widget(at, () => document.createElement('br'), { side: -1, key: 'tab-wrap' })); + } // The advances change line breaking, so pagination has to re-measure. view.dispatch(view.state.tr .setMeta(tabStopsKey, DecorationSet.create(view.state.doc, decos)) diff --git a/src/lib/export/odt.ts b/src/lib/export/odt.ts index ef55c70..a7a96e9 100644 --- a/src/lib/export/odt.ts +++ b/src/lib/export/odt.ts @@ -2033,12 +2033,11 @@ function rewriteStylesXml(odtBytes: Uint8Array, lang: { language: string; countr ' 0.001) { - styles = styles.replace('', '' - + ``); - } + // The document's tab interval, on the paragraph default-style. Always written: a file + // that declares none falls back to ODF's own 2cm, which is not what the editor shows + // (measured — LibreOffice puts a bare A⇥X at 2cm, not at its UI default of 1.25). + styles = styles.replace('', '' + + ``); // odf-kit's Standard style carries fo:margin-bottom="0.212cm", but the editor (like // LibreOffice and Word) has no paragraph spacing by default — every paragraph and list diff --git a/src/lib/import/docx.ts b/src/lib/import/docx.ts index 1bff518..01016a4 100644 --- a/src/lib/import/docx.ts +++ b/src/lib/import/docx.ts @@ -15,7 +15,7 @@ import { imageDataUrl, placeholderImage, type ConvertedImages } from './imageFor import { PX_PER_CM, cmToPx, type PageMargins } from '../storage/pageMargins'; import type { Orientation } from '../storage/pageOrientation'; import { formatFromCm, type PageFormat } from '../storage/pageFormat'; -import { clampTabInterval } from '../storage/tabInterval'; +import { clampTabInterval, DOCX_IMPLIED_TAB_CM } from '../storage/tabInterval'; import { languageFromOdf, NO_LANGUAGE, type DocumentLanguage } from '../storage/documentLanguage'; import { EMPTY_HF_SET, type HfDoc, type HfSet } from '../storage/headerFooter'; import { applyUniformRunFont, type OdtImportResult } from './odt'; @@ -1670,16 +1670,17 @@ function docHasEvenOddHeaders(files: Record): boolean { } } -// The grid every tab past the last custom stop falls on, also from settings.xml. -function docTabInterval(files: Record): number | null { +// The grid every tab past the last custom stop falls on, also from settings.xml. A file +// that declares none gets Word's own fallback of 720 twips. +function docTabInterval(files: Record): number { const bytes = files['word/settings.xml']; - if (!bytes) return null; + if (!bytes) return DOCX_IMPLIED_TAB_CM; try { const el = parseXml(strFromU8(bytes)).getElementsByTagNameNS(W, 'defaultTabStop')[0]; const tw = el && intAttr(el, W, 'val'); - return tw ? clampTabInterval(round2(twipToCm(tw))) : null; + return tw ? clampTabInterval(round2(twipToCm(tw))) : DOCX_IMPLIED_TAB_CM; } catch { - return null; + return DOCX_IMPLIED_TAB_CM; } } diff --git a/src/lib/import/odt.ts b/src/lib/import/odt.ts index 1347890..1c532ec 100644 --- a/src/lib/import/odt.ts +++ b/src/lib/import/odt.ts @@ -37,8 +37,9 @@ export interface OdtImportResult { margins: PageMargins | null; orientation: Orientation | null; format: PageFormat | null; - // The grid every tab past the last custom stop falls on; null = the file declares none. - tabIntervalCm: number | null; + // The grid every tab past the last custom stop falls on; the format's own fallback + // when the file declares none. + tabIntervalCm: number; // Single-paragraph docs in the hfExtensions schema; null = no zone. header: HfDoc; footer: HfDoc; diff --git a/src/lib/import/styleResolver.ts b/src/lib/import/styleResolver.ts index c943140..9624e81 100644 --- a/src/lib/import/styleResolver.ts +++ b/src/lib/import/styleResolver.ts @@ -1,6 +1,7 @@ import type { PageMargins } from '../storage/pageMargins'; import type { Orientation } from '../storage/pageOrientation'; import { formatFromCm, type PageFormat } from '../storage/pageFormat'; +import { ODF_IMPLIED_TAB_CM } from '../storage/tabInterval'; import { normalizeLeader, type TabAlign, type TabStop } from '../editor/extensions/tabStops'; // Resolves ODF style indirection for the importer: producers (our export, LibreOffice, @@ -319,9 +320,10 @@ export class StyleResolver { } // The grid every tab past the last custom stop falls on, from the paragraph - // default-style (Standard may override it). null when the file declares none. - defaultTabInterval(): number | null { - return lengthToCm(this.merged('paragraph', 'Standard').para['style:tab-stop-distance']); + // default-style (Standard may override it). A file that declares none gets ODF's own + // fallback, which is what LibreOffice renders it at. + defaultTabInterval(): number { + return lengthToCm(this.merged('paragraph', 'Standard').para['style:tab-stop-distance']) ?? ODF_IMPLIED_TAB_CM; } // Resolve a text-props map's font: fo:font-family wins, else style:font-name diff --git a/src/lib/storage/CLAUDE.md b/src/lib/storage/CLAUDE.md index 5a225a5..6eb90f7 100644 --- a/src/lib/storage/CLAUDE.md +++ b/src/lib/storage/CLAUDE.md @@ -3,7 +3,7 @@ ## Page layout settings - **`pageMargins.ts`** — `PageMargins` in **cm** (default `{ top: 2, bottom: 2, left: 2, right: 2 }` — LibreOffice's; clamped 0–10). `applyMarginVars` sets `--user-margin-*` (px) on `:root`; `PX_PER_CM = 96/2.54`. -- **`tabInterval.ts`** — the document's default tab interval in **cm** (`DEFAULT_TAB_INTERVAL_CM = 1.25`, LibreOffice's; Word's is 1.27; clamped 0.05–10). `applyTabIntervalVar` sets `--tab-interval`, which is `.tiptap`'s `tab-size`. +- **`tabInterval.ts`** — the document's default tab interval in **cm** (`DEFAULT_TAB_INTERVAL_CM = 1.25`, LibreOffice's for a new document; clamped 0.05–10). `applyTabIntervalVar` sets `--tab-interval`, which is `.tiptap`'s `tab-size`. A file that declares none falls back to its format's own value, neither of them ours: `ODF_IMPLIED_TAB_CM` 2cm (measured against LibreOffice), `DOCX_IMPLIED_TAB_CM` 1.27cm — so both exports always write the value out. - **`pageOrientation.ts`** — `'portrait' | 'landscape'`. `applyOrientationVars` sets `--user-page-{width,height}`; landscape swaps the A4 dimensions (matching odf-kit's automatic swap). Both margins and orientation are passed into the ODT export so the exported document's geometry/line-wrapping matches the on-screen preview. diff --git a/src/lib/storage/tabInterval.ts b/src/lib/storage/tabInterval.ts index 5a9d211..699b7a8 100644 --- a/src/lib/storage/tabInterval.ts +++ b/src/lib/storage/tabInterval.ts @@ -1,9 +1,14 @@ const KEY = 'odf-editor-tab-interval'; // The grid every tab past the last custom stop falls on (Word w:defaultTabStop, ODF -// style:tab-stop-distance). LibreOffice's default; Word's is 1.27cm. +// style:tab-stop-distance). LibreOffice's default for a new document. export const DEFAULT_TAB_INTERVAL_CM = 1.25; +// What a file that declares none falls back to. Both differ from the editor's default, +// so the exports always write the value out rather than leaving it implied. +export const ODF_IMPLIED_TAB_CM = 2; // measured against LibreOffice +export const DOCX_IMPLIED_TAB_CM = 1.27; // ECMA-376's w:defaultTabStop default, 720twip + const MIN_CM = 0.05; const MAX_CM = 10; diff --git a/tests/render-parity/README.md b/tests/render-parity/README.md index 117180a..06123fa 100644 --- a/tests/render-parity/README.md +++ b/tests/render-parity/README.md @@ -108,9 +108,6 @@ LibreOffice's 48, with 62 line-level differences, most of them the justification undrawable frame keeps its box and its label but not its picture (`imageFormats.ts`). Exporting writes the placeholder back out — the original is gone from the moment it is imported. -- **Tabs that wrap lose their advance.** Six consecutive tabs at a line end stay on that - line in Chromium and the continuation starts at the margin; LibreOffice carries the - tab positions onto it (91mm apart in the contract). - **A list level's own hanging indent is not read**, only the 0.635cm both exports write (`LIST_HANGING_CM`). The marker is drawn there and overflows if it is wider, where Word moves the text to the next list tab — reading `w:lvl/w:pPr/w:ind w:hanging` diff --git a/tests/unit/tab-interval.test.ts b/tests/unit/tab-interval.test.ts index 8625c48..3c3eae0 100644 --- a/tests/unit/tab-interval.test.ts +++ b/tests/unit/tab-interval.test.ts @@ -1,12 +1,12 @@ // The document's default tab interval: Word's w:defaultTabStop, ODF's // style:tab-stop-distance on the paragraph default-style. import { describe, it, expect } from 'vitest'; -import { unzipSync, strFromU8 } from 'fflate'; +import { unzipSync, zipSync, strFromU8 } from 'fflate'; import { buildOdt } from '../../src/lib/export/odt'; import { importOdt } from '../../src/lib/import/odt'; import { buildDocx } from '../../src/lib/export/docx'; import { importDocx } from '../../src/lib/import/docx'; -import { DEFAULT_TAB_INTERVAL_CM, clampTabInterval } from '../../src/lib/storage/tabInterval'; +import { DEFAULT_TAB_INTERVAL_CM, ODF_IMPLIED_TAB_CM, clampTabInterval } from '../../src/lib/storage/tabInterval'; const doc: any = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'a\tb' }] }] }; const opts = [undefined, 'portrait', undefined, undefined, 'A4', undefined] as const; @@ -19,10 +19,22 @@ describe('default tab interval', () => { expect(back.tabIntervalCm).toBeCloseTo(1.27, 3); }); - it('leaves LibreOffice’s own interval undeclared', async () => { + it('declares the editor default too', async () => { + // Left implied, a file falls back to ODF's own 2cm — measured against LibreOffice, + // which puts a bare A⇥X there and not at its UI default of 1.25. const styles = strFromU8(unzipSync(await odt(DEFAULT_TAB_INTERVAL_CM))['styles.xml']); - expect(styles).not.toContain('style:tab-stop-distance'); - expect((await importOdt(await odt(DEFAULT_TAB_INTERVAL_CM))).tabIntervalCm).toBe(null); + expect(styles).toContain('style:tab-stop-distance="1.25cm"'); + expect((await importOdt(await odt(DEFAULT_TAB_INTERVAL_CM))).tabIntervalCm).toBeCloseTo(1.25, 3); + }); + + it('falls back to ODF’s own implied default', async () => { + const stripped = await odt(1.25).then((b) => { + const files = unzipSync(b); + files['styles.xml'] = new TextEncoder().encode( + strFromU8(files['styles.xml']).replace(/[\s\S]*?<\/style:default-style>/, '')); + return zipSync(files); + }); + expect((await importOdt(stripped)).tabIntervalCm).toBeCloseTo(ODF_IMPLIED_TAB_CM, 3); }); it('rides a DOCX setting and comes back', async () => { diff --git a/tests/unit/tab-stops.test.ts b/tests/unit/tab-stops.test.ts index e7d4a57..e8442ae 100644 --- a/tests/unit/tab-stops.test.ts +++ b/tests/unit/tab-stops.test.ts @@ -7,7 +7,7 @@ import { buildOdt } from '../../src/lib/export/odt'; import { buildDocx } from '../../src/lib/export/docx'; import { importOdt } from '../../src/lib/import/odt'; import { importDocx } from '../../src/lib/import/docx'; -import { parseTabStops, formatTabStops } from '../../src/lib/editor/extensions/tabStops'; +import { parseTabStops, formatTabStops, nextStopCm } from '../../src/lib/editor/extensions/tabStops'; type N = any; @@ -39,6 +39,19 @@ describe('tab stops', () => { expect(parseTabStops(null)).toEqual([]); }); + it('advances to the next stop, else the next grid multiple', () => { + // The rule a run of tabs is walked with: LibreOffice carries the run onto the next + // line and restarts the grid there, which is what the break widget reproduces. + expect(nextStopCm(0, [], 1.25)).toBeCloseTo(1.25, 3); + expect(nextStopCm(1.25, [], 1.25)).toBeCloseTo(2.5, 3); + expect(nextStopCm(1.65, [], 1.25)).toBeCloseTo(2.5, 3); + // A custom stop right of the pen wins over the grid; past the last one the grid + // takes over again, on its own absolute multiples rather than from that stop. + expect(nextStopCm(1, [6, 12], 1.25)).toBeCloseTo(6, 3); + expect(nextStopCm(6, [6, 12], 1.25)).toBeCloseTo(12, 3); + expect(nextStopCm(12, [6, 12], 1.25)).toBeCloseTo(12.5, 3); + }); + it('round-trips through ODF', async () => { const bytes = await buildOdt(doc, margins, 'portrait'); const xml = strFromU8(unzipSync(bytes)['content.xml']);