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.
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.
StyleResolverflattens ODF style indirection: named + automatic styles from both XML files,style:parent-style-namechains rooted instyle:default-style, font-face declarations (style:font-name→ family),rel-column-width/column-width,min-row-height, list styles, and page geometry.fo:font-familyandstyle:font-nameshadow each other across chain levels (layerTextProps). A percentagefo: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 onlyfo:margin-bottomsit flush).fo:line-heightis 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_OVERRIDESsizes/margins, 0 paragraph spacing, list margin 0, Times New Roman/Liberation Serif,#000000text) are imported asnull/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 toMAX_HEADING_LEVEL), per-depthtext:list-level-style-*defs decide bullet vs ordered andlistStyleType(reverse lookuporderedTypeFromFormat), 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 (tableMarginsreads the table style'sfo:margin-*,style:width/style:rel-widthandtable:alignagainstCtx.contentWidthCm— so a table narrower than the text width stays narrow instead of being stretched; DOCX does the same fromw:tblInd+ thew:tblGrid/w:tblWwidth),text:s/text:tab/text:line-breakbecome spaces/\t/hardBreak,draw:frame/draw:image→ animagenode (convertFrame: bytes read from the zip'sPictures/entry into a data-URI,svg:width/-heightcm → px,svg:title→alt,draw:transformrotate →rotation; a non-as-charanchor or a graphic style'sstyle:wrap→ floatingwrapmode viaStyleResolver.graphicProps— an explicitas-charanchor is always inline: LibreOffice's named Graphics style carries astyle:wrapthat would otherwise float every inherited frame), text fields keep their stored value. Text boxes / shapes (convertDrawElement):draw:frame+draw:text-box→ atextBoxnode (convertTextBoxFrame: height =fo:min-heightelsesvg:height; fill/stroke read straight fromgraphicProps'draw:fill(-color)/draw:stroke/svg:stroke-*, values equal to the editor defaults suppressed, none → explicitnull);draw:rect/draw:ellipse/draw:custom-shapewith a rect/round-rectangle/ellipse preset → atextBoxwith the matchingshapeKind(convertShape; other presets → "Unsupported shapes were removed"). A box is a block node but its frame sits inside atext:p, so converted boxes rideCtx.pendingBlocksandconvertBlocksflushes 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 (convertWpsShapefor DrawingMLwps:wsp— probed before the imagea:blippath,convertPictfor legacy VML; Word'smc:AlternateContentuses only themc:Choicebranch 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, soimageDataUrl(bytes, path)resolves the mime by extension then magic-number (mislabelled/extensionless entries still work) and returnsnullfor 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 Worda:blip'ssvgBlipalternative 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 byconvertUnsupportedImages(bytes)— an async passapplyImportruns before the synchronous import, passing apath → PNG data-URImap (ConvertedImages) intoimportOdt/importDocx(default empty, so tests stay sync). The decoder (utif2) is a dynamicimport()→ 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 becometextLength, so labels keep their width) andSTRETCHDIBITS(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 orencodeURIComponentthrows 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.xmlis parsed and drawn as an SVG picture of the frame's own size — series values from thenumCachethe producer left, colours from the named theme accent (themeAccents), title/axis titles/gridlines, and the value axis' ownc:scalingbounds where the file fixes them. Bar (incl. stacked andbarDir="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 thedraw:object's sub-document, series values read out of its ownlocal-tableby cell range, colours from the series'draw:fill-color, bounds from the y-axis style'schart:maximum/-minimum. - Content controls (
inlineChildren, DOCX): aw:sdtinside a paragraph — Word wraps every citation and bibliography entry in one — is walked through to itsw: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 amath:mathroot (or holds one inline) → aformulanode. Our own<annotation encoding="application/x-tex">is preferred; LibreOffice strips it, so the MathML is parsed back to LaTeX instead.displaycomes from the paragraph (aloneInParagraph), not the object — LibreOffice writesdisplay="block"on every formula it re-saves. DOCX:m:oMath/m:oMathParasit beside thew:rruns in their own namespace, soconvertInlineprobes them ahead of itsnamespaceURI !== Wguard (that guard silently dropped every Word formula). Seedocs/architecture/formulas.md. - Bookmarks & cross-references:
text:bookmark-start/-end(ODF) andw:bookmarkStart/End(DOCX) become abookmarkmark on the text they cover; the open ranges live inCtxbecause 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,_GoBackwith it.text:bookmark-refandREF/PAGEREFfields (thefldCharmachine andw:fldSimplealike, including a field Word left unresolved) becomecrossRefnodes carrying the producer's cached text. Aw:hyperlink w:anchorwith nor:idis an internal link →#name. Seedocs/architecture/formatting.md. - Graceful degradation (collected as
warnings, surfaced once): footnotes/comments dropped, hyperlinks flattened to text, nested tables flattened to paragraphs, non-Picturesdrawings 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; seeimage.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()readsstyle:header/style:footer+ the header/footer-style heights;pageGeometry()reconstructs the body margin (page margin + zone height + spacing) andedgeDistancesCm()returns the raw page margins as the zone distances. The header↔body spacing is only reserved whenstyle:dynamic-spacing="false"— atrue(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)keepstext:page-number/-countas field nodes. A master page whosestyle:next-style-namepoints 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 itssvg:x/svg:yfrom the page corner: it is out of flow (a letterhead or full-page title background), soHeaderFooterLayerpaints 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.hfIsEmptycounts 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.