Files
edentext/src/lib/import/CLAUDE.md
T
Steffen Becker aff3eaa812 fix: a named style's line spacing is the percentage the file declares
The style-registry path divided an ODF fo:line-height by 1.15 where the
block path, both DOCX paths and the export all treat it as the plain
percentage, so every paragraph whose spacing came from its style
rendered 15% too tight. Its suppression yardstick is the block's own
style too, so a 100% under a 115% style stays as direct formatting.
2026-08-09 20:43:34 +00:00

13 KiB

src/lib/import/

odt.ts + styleResolver.ts (ODF), docx.ts + docxStyles.ts (Word), imageFormats.ts (shared). The DOCX importer mirrors the ODF one section for section.

ODF import (odt.ts, styleResolver.ts)

The Open .odt button (App.svelte) parses an uploaded file with importOdt(bytes) and replaces the document via setContent (after a confirm when the current doc is non-empty), also adopting the file's page margins/orientation. It parses content.xml/styles.xml directly (fflate + DOMParser) rather than odf-kit's reader, which flattens cell blocks and drops row heights / list number formats.

  • StyleResolver flattens ODF style indirection: named + automatic styles from both XML files, style:parent-style-name chains rooted in style:default-style, font-face declarations (style:font-name → family), rel-column-width/column-width, min-row-height, list styles, and page geometry. fo:font-family and style:font-name shadow each other across chain levels (layerTextProps). A percentage fo:font-size ("130%" — how LibreOffice defines its heading styles) is resolved against the inherited size while walking the chain (resolvePercentSize); without it the file's size is dropped and our default silently replaces it.
  • LibreOffice's paragraph properties are not all inherited one by one. Its two vertical margins live in one item, so a style declaring only fo:margin-top (or only -bottom) takes the default style's value for the other, never the parent chain's (layerParaProps; probed — it is what makes a heading whose style sets only fo:margin-bottom sit flush). fo:line-height is stored as the ODF percentage itself (115% → 1.15, as both DOCX paths and the export use it) and suppressed against the block's own style, so a 100% under a 115% style stays as direct formatting.
  • The yardstick is the style the block can name. Only a body block carries a styleName, so a paragraph in a cell or a text box is measured against the default paragraph style instead of its own — otherwise everything its style provides is suppressed as "the style will supply it" and nothing ever does (a Word caption in a text box arrived without its italic or its colour).
  • Default suppression keeps round trips (editor → LibreOffice → editor) from accreting explicit attrs: values matching the editor's defaults (12pt body, HEADING_STYLE_OVERRIDES sizes/margins, 0 paragraph spacing, list margin 0, Times New Roman/Liberation Serif, #000000 text) are imported as null/no mark, with small tolerances for producer unit rounding (pt↔cm↔twips). This is why the editor's defaults must equal Word's/LibreOffice's (below) — an editor-only default is indistinguishable from a failed style resolution and silently lands in every imported document.
  • Mapping: text:h → heading (level clamped to MAX_HEADING_LEVEL), per-depth text:list-level-style-* defs decide bullet vs ordered and listStyleType (reverse lookup orderedTypeFromFormat), tables handle covered cells / number-columns-repeated / header rows / colspans / cell shading (StyleResolver.cellBackgroundColor → backgroundColor) / cell borders (StyleResolver.cellBorders + borderAttrFromOdf → the per-side border attrs) / table margins (tableMargins reads the table style's fo:margin-*, style:width/style:rel-width and table:align against Ctx.contentWidthCm — so a table narrower than the text width stays narrow instead of being stretched; DOCX does the same from w:tblInd + the w:tblGrid/w:tblW width), text:s/text:tab/text:line-break become spaces/\t/hardBreak, draw:frame/draw:image → an image node (convertFrame: bytes read from the zip's Pictures/ entry into a data-URI, svg:width/-height cm → px, svg:title → alt, draw:transform rotate → rotation; a non-as-char anchor or a graphic style's style:wrap → floating wrap mode via StyleResolver.graphicProps — an explicit as-char anchor is always inline: LibreOffice's named Graphics style carries a style:wrap that would otherwise float every inherited frame), text fields keep their stored value. Text boxes / shapes (convertDrawElement): draw:frame+draw:text-box → a textBox node (convertTextBoxFrame: height = fo:min-height else svg:height; fill/stroke read straight from graphicProps' draw:fill(-color)/draw:stroke/svg:stroke-*, values equal to the editor defaults suppressed, none → explicit null); draw:rect/draw:ellipse/draw:custom-shape with a rect/round-rectangle/ellipse preset → a textBox with the matching shapeKind (convertShape; other presets → "Unsupported shapes were removed"). A box is a block node but its frame sits inside a text:p, so converted boxes ride Ctx.pendingBlocks and convertBlocks flushes them after the anchor paragraph (dropping our own export's empty anchor); in cells/other boxes their blocks are unwrapped in place with a warning. The DOCX importer mirrors all of this (convertWpsShape for DrawingML wps:wsp — probed before the image a:blip path, convertPict for legacy VML; Word's mc:AlternateContent uses only the mc:Choice branch so the VML fallback can't double-import).
  • Image formats (import/imageFormats.ts, shared by both importers): <img> only renders a fixed set of formats, so imageDataUrl(bytes, path) resolves the mime by extension then magic-number (mislabelled/extensionless entries still work) and returns null for anything unrenderable — the importer then skips it with a specific "format the browser can't display" warning instead of a broken <img>. A frame's multiple <draw:image> alternatives (ODF) and a Word a:blip's svgBlip alternative are probed for the first displayable one, and <draw:a>-wrapped frames are unwrapped (the hyperlink dropped). Non-web formats we can decode client-side (currently TIFF) are converted to PNG up front by convertUnsupportedImages(bytes) — an async pass applyImport runs before the synchronous import, passing a path → PNG data-URI map (ConvertedImages) into importOdt/importDocx (default empty, so tests stay sync). The decoder (utif2) is a dynamic import() → its own lazy chunk, loaded only when a convertible image is actually present, so ordinary docs pay nothing. EMF goes through the same lazy pre-pass into an SVG picture (import/emf.ts, below). SVM/WMF still have no decoder (SVM is StarOffice-proprietary, WMF a different 16-bit record format) → skipped with the format warning; LibreOffice/WASM conversion was ruled out (no backend; WASM LO is ~300MB).
  • EMF (import/emf.ts): emfToSvg(bytes) replays the record stream into SVG — window/viewport plus world transform mapped per point, a DC stack (SAVEDC/RESTOREDC), pens/brushes/fonts (incl. the stock objects), the 16- and 32-bit poly records, path brackets, RECTANGLE/ELLIPSE, EXTTEXTOUT (its per-character advances become textLength, so labels keep their width) and STRETCHDIBITS (the DIB re-wrapped as a .bmp data-URI). Text is stored as raw code units, so a symbol font leaves lone surrogates behind — they must be stripped or encodeURIComponent throws and the whole picture is lost. Unknown records are skipped; a file that yields nothing returns null and keeps the placeholder.
  • Charts (import/chart.ts, DOCX): word/charts/chartN.xml is parsed and drawn as an SVG picture of the frame's own size — series values from the numCache the producer left, colours from the named theme accent (themeAccents), title/axis titles/gridlines, and the value axis' own c:scaling bounds where the file fixes them. Bar (incl. stacked and barDir="bar"), line, area, scatter and pie; anything else keeps the placeholder. Read-only — the editor has no chart object, so a re-export carries the picture, not the chart. ODF charts go through the same drawing (odfChartDataUrl, convertChartFrame): <chart:chart> in the draw:object's sub-document, series values read out of its own local-table by cell range, colours from the series' draw:fill-color, bounds from the y-axis style's chart:maximum/-minimum.
  • Content controls (inlineChildren, DOCX): a w:sdt inside a paragraph — Word wraps every citation and bibliography entry in one — is walked through to its w:sdtContent, or the runs inside it never reach the paragraph (the thesis fixture lost every [7]-style reference and broke its lines one page short).
  • Formulas (convertFormulaFrame): a <draw:frame> whose <draw:object> resolves to a sub-document with a math:math root (or holds one inline) → a formula node. Our own <annotation encoding="application/x-tex"> is preferred; LibreOffice strips it, so the MathML is parsed back to LaTeX instead. display comes from the paragraph (aloneInParagraph), not the object — LibreOffice writes display="block" on every formula it re-saves. DOCX: m:oMath/m:oMathPara sit beside the w:r runs in their own namespace, so convertInline probes them ahead of its namespaceURI !== W guard (that guard silently dropped every Word formula). See docs/architecture/formulas.md.
  • Bookmarks & cross-references: text:bookmark-start/-end (ODF) and w:bookmarkStart/End (DOCX) become a bookmark mark on the text they cover; the open ranges live in Ctx because Word writes them beside paragraphs as well as beside runs, and a range may close in a later paragraph. A point bookmark has no range to mark and is dropped, _GoBack with it. text:bookmark-ref and REF/PAGEREF fields (the fldChar machine and w:fldSimple alike, including a field Word left unresolved) become crossRef nodes carrying the producer's cached text. A w:hyperlink w:anchor with no r:id is an internal link → #name. See docs/architecture/formatting.md.
  • Graceful degradation (collected as warnings, surfaced once): footnotes/comments dropped, hyperlinks flattened to text, nested tables flattened to paragraphs, non-Pictures drawings dropped, unreadable pictures skipped (each with a warning). Page size is normalized to A4. Floating/wrapped images are imported as left/right/top-bottom wrap (free x/y positions collapse to the nearest side; see image.ts).

tests/roundtrip.test.ts (export→import) and tests/lo-roundtrip.test.ts (export→LibreOffice re-save→import, needs soffice) verify the round trip; run with npm test / npm run test:lo.

Header/footer import

  • Import: StyleResolver.masterPageHF() reads style:header/style:footer + the header/footer-style heights; pageGeometry() reconstructs the body margin (page margin + zone height + spacing) and edgeDistancesCm() returns the raw page margins as the zone distances. The header↔body spacing is only reserved when style:dynamic-spacing="false" — a true (LibreOffice's usual) means the gap collapses, so reserving it would shove the body down. convertHfZone → single-paragraph doc (extra paragraphs → hard breaks; a text-less zone that carries a background/border rule line is kept, box props merged with the bottom rule from the last paragraph); convertInline(…, hfFields=true) keeps text:page-number/-count as field nodes. A master page whose style:next-style-name points at another master governs one page only (the "different first page" idiom): its own zones become the first-page variants and the successor's the running ones — read as the running header instead, a title-page master repeats on every page of its section and its height pushes each block onto its own page. A zone's positioned (non-as-char) frame keeps its wrap and its svg:x/svg:y from the page corner: it is out of flow (a letterhead or full-page title background), so HeaderFooterLayer paints it per page behind the body and the zone's reach ignores it — inline it would reserve a page-tall line of body space. Text boxes there are still dropped with a warning. hfIsEmpty counts a rule-/shading-only paragraph as non-empty so it renders and exports.

Defaults on DOCX import

Table borders come from the table's own w:tblBorders, else its table style's along the w:basedOn chain (per side, nearest declaring style wins). A side nobody declares is not drawn: Word's Normal Table has no border, and the gridlines it shows on screen are not printed. ODF says the same for an undeclared fo:border, so both importers agree.

Body text with no resolved font falls back to the document's own theme minor font (docx.ts runMarks), not the editor default — Word's implicit body default. Headings don't (they keep the editor heading default); DOCX page margins default to Word's 2.54cm.