feat: a freeform drawing keeps its own outline

A polygon, a polyline, a curve or a connector's elbow used to be dropped
with a warning; it now rides the box as an SVG path in the 0…100 box a
preset's points use, and the editor draws it. Read from all four dialects
the two products write (ODF points and svg:d, a non-primitive
enhanced-path, DrawingML custGeom, VML's reversed-case path), written
back as enhanced-path and custGeom — LibreOffice renders both exactly as
the editor draws them. An open outline is stroked, never filled.
This commit is contained in:
Steffen Becker committed 2026-08-15 12:09:12 +02:00
1 parent 889f11cffc
commit 503c9821d6
11 files changed
+483 -25

No files matched your search

+2 -1
View File
@@ -94,6 +94,7 @@
- Bookmarks and cross-references: name a selection, then insert a reference to it (its text, its number or its page); the reference follows the text it points at. Round-trips to ODF `text:bookmark-start`/`text:bookmark-ref` and Word's `Bookmark` + `REF`/`PAGEREF` fields
- Manual page break (Ctrl+Enter); round-trips to ODF `fo:break-before`
- Text boxes and basic shapes — rectangle, rounded rectangle, ellipse, triangles, diamond, pentagon, hexagon, five-point star, trapezoid, parallelogram and the four block arrows: editable block content, fill and border colors, border width, resize/rotate handles, text wrap (inline / left / right / top-bottom) like images; a shape gallery in the floating toolbar and in the ribbon's Shape tab. Each outline is one polygon in `utils/shapes.ts` that the editor draws as SVG and the ODF export scales into its `draw:enhanced-path`, so the shape on screen is the shape in the file; Word gets the preset's name and draws its own. Round-trips to ODF `draw:frame`/`draw:text-box` + `draw:custom-shape` and DOCX DrawingML `wps:wsp`/`wps:txbx` (imports Word's `mc:AlternateContent` and legacy VML text boxes too)
- A drawing no gallery covers — a freeform, a polygon, a polyline, a bezier curve, a connector's elbow — keeps its own outline instead of being dropped: the box holds the file's path in the same 0…100 box a preset's points use, and the editor draws it. Read from all four dialects the two products write (ODF `draw:points`, `svg:d` on a `draw:path` or `draw:connector`, a `non-primitive` enhanced-path, DrawingML `a:custGeom` and VML's own reversed-case `path`), written back as ODF's enhanced-path and Word's custGeom — LibreOffice renders both exactly as the editor draws them. An outline that never closes is stroked only, as a polyline is in both products
- A text box carries its content into Word intact: a list inside one is a real Word list with its own numbering definition (nesting, marker symbols and start values included) and a picture inside one is a real picture, its bytes and relationship minted beside the package's own. Both were flattened to literal `•`/`1.` markers and dropped, respectively
**Page & layout**
@@ -158,7 +159,7 @@ The gap against Word/LibreOffice, most valuable first. Reviewed 2026-08-14.
**Content an imported document loses**
- Charts are **drawn** from the file (`import/chart.ts`: DrawingML `chartN.xml` and ODF `chart:chart`), but as a picture, not a chart object — a re-export carries the drawing and the numbers behind it are no longer editable. The same holds for an **EMF** metafile (`import/emf.ts`): it is drawn, but as the SVG picture it was rebuilt into, and only from the record set a plot consists of — a hatched brush, a clipping region or a rotated bitmap is skipped. **WMF/SVM** metafiles and OLE objects still keep their box and a placeholder label, and export writes that back out: WMF is a different (16-bit) record format, SVM is StarOffice-proprietary, and an OLE object cannot be rendered without its application
- Connectors that attach to other shapes, and freeform curves — a connector is an anchoring model rather than a shape, and a freeform needs a drawing tool. Both still dropped on import with a warning
- A drawing tool: a freeform, a polygon or a connector **imports, draws and saves** (see below), but there is no way to author one here. A Word connector preset (`bentConnector3`) is also still dropped — Word resolves that geometry and writes no path for it
**Missing while writing**
- Hyphenation's zone and ladder count (`fo:hyphenation-ladder-count`, `w:hyphenationZone`) — CSS exposes neither
+23 -2
View File
@@ -60,5 +60,26 @@ double arrow.
an undeclared `draw:` prefix there makes the whole file unreadable.
- **DOCX** keeps the frame and flips it (`<a:xfrm flipV="1">`), the heads riding the
shape's `<a:ln>` as `a:headEnd`/`a:tailEnd`, and writes no `wps:txbx` at all.
- **Not covered**: connectors that attach to other shapes, and freeform curves. Both are
still dropped with a warning — a connector is an anchoring model, not a shape.
## Freeform outlines (`shapePath`)
A drawing this editor offers no tool to author — a polygon, a polyline, a bezier curve,
a connector's elbow — still has to survive being opened and saved. The box keeps the
file's own outline in `shapePath`, an SVG `d` in the same **0…100 box** a preset's
points live in (`utils/shapes.ts`), and its presence is what makes the box draw itself.
An outline that never closes is **stroked only**, whatever fill its style declares,
which is how both products draw a polyline.
- **Reading** takes four path dialects, all through `parseSvgPath`, which resolves the
relative commands both products write into absolute `M`/`L`/`C`/`Z`: ODF's
`draw:points` (polygon closed, polyline open), its `svg:d` (`draw:path`, and a
`draw:connector`, which carries the resolved elbow beside its endpoints), a
`non-primitive` `draw:enhanced-path`, DrawingML's `a:custGeom` path list, and VML's
`path` — whose cases are SVG's the other way round (`parseVmlPath`).
- A geometry whose commands are **modifier formulas** (`?f0`) or an arc is not an
outline we can draw, so the shape stays unsupported and is dropped with the warning,
as before. So is a Word connector preset (`bentConnector3`), which is a geometry
Word resolves and does not write down.
- **Writing** goes back out as the shape's own geometry: ODF a `non-primitive`
`<draw:enhanced-geometry>` in its 21600 viewBox (probed: LibreOffice writes that
straight back out unchanged), DOCX an `<a:custGeom>` path list in the shape's EMU
extent. Both render in LibreOffice exactly as the editor draws them.
+22 -5
View File
@@ -46,6 +46,7 @@ export interface TextBoxAttrs {
wrapAlign: string | null; // 'center'/'right' = set against the middle/far end
paddingCm: number; // inset ring around the text (ODF fo:padding)
shapeKind: ShapeKind;
shapePath: string | null; // a freeform's own outline, in the 0…100 box
flipV: boolean; // a line runs bottom-left → top-right instead
textVertical: boolean; // text runs top-to-bottom, right-to-left
fillColor: string | null;
@@ -81,6 +82,12 @@ function shapeRadius(kind: ShapeKind): string {
return kind === 'ellipse' ? '50%' : kind === 'roundRect' ? '8px' : '0';
}
// A box that paints its own outline — a preset polygon, a freeform, or a line, which
// is only its stroke. The box behind any of them stays bare.
function isDrawnShape(a: TextBoxAttrs): boolean {
return !!SHAPES[a.shapeKind]?.points || !!a.shapePath || isLineKind(a.shapeKind);
}
export const TextBox = Node.create({
name: 'textBox',
// Own group (not `block`): only the doc admits it, so it can't nest in table
@@ -154,6 +161,13 @@ export const TextBox = Node.create({
},
renderHTML: () => ({}),
},
// A drawing this editor cannot author (a polygon, a curve, a connector's elbow):
// the file's own outline, in the same 0…100 box a preset's points live in.
shapePath: {
default: null,
parseHTML: el => (el as HTMLElement).getAttribute('data-shape-path') || null,
renderHTML: () => ({}),
},
// Which diagonal of the frame a line runs along — the one flag Word's `flipV`
// and ODF's own endpoints both come down to.
flipV: {
@@ -200,8 +214,8 @@ export const TextBox = Node.create({
a.height ? `min-height:${a.height}px` : '',
// A polygon paints itself and a line is only its stroke, so the box behind
// either of them stays bare.
a.fillColor && !SHAPES[a.shapeKind]?.points && !isLineKind(a.shapeKind) ? `background:${a.fillColor}` : '',
a.strokeColor && !SHAPES[a.shapeKind]?.points && !isLineKind(a.shapeKind)
a.fillColor && !isDrawnShape(a) ? `background:${a.fillColor}` : '',
a.strokeColor && !isDrawnShape(a)
? `border:${a.strokeWidthPt * PX_PER_PT}px solid ${a.strokeColor}` : '',
a.shapeKind !== 'textbox' ? `border-radius:${shapeRadius(a.shapeKind)}` : '',
a.rotation ? `transform:rotate(${a.rotation}deg)` : '',
@@ -213,6 +227,7 @@ export const TextBox = Node.create({
...(a.rotation ? { 'data-rotation': String(a.rotation) } : {}),
...(a.wrap !== 'inline' ? { 'data-wrap': a.wrap } : {}),
...(a.shapeKind !== 'textbox' ? { 'data-shape': a.shapeKind } : {}),
...(a.shapePath ? { 'data-shape-path': a.shapePath } : {}),
...(a.flipV ? { 'data-flip-v': 'true' } : {}),
...(a.textVertical ? { 'data-text-vertical': 'true' } : {}),
...(a.fillColor ? { 'data-fill': a.fillColor } : {}),
@@ -365,7 +380,7 @@ class TextBoxView {
this.rotor.style.minHeight = a.height ? `${a.height}px` : '';
// A polygon shape paints its own fill and stroke, so the box behind it stays bare;
// a line has no box at all, only the two endpoints it is drawn between.
const poly = !!SHAPES[a.shapeKind]?.points;
const poly = !!SHAPES[a.shapeKind]?.points || !!a.shapePath;
const line = isLineKind(a.shapeKind);
// The outline covers the padding box, so the frame's own ring moves to the text
// where a polygon draws it — applyShapeInset adds it back in.
@@ -420,7 +435,7 @@ class TextBoxView {
// width under that distortion.
private applyOutline(): void {
const a = this.attrs();
const d = shapePath(a.shapeKind);
const d = shapePath(a.shapeKind, a.shapePath);
if (!d) {
this.outline?.parentElement?.remove();
this.outline = null;
@@ -437,7 +452,9 @@ class TextBoxView {
this.rotor.insertBefore(svg, this.rotor.firstChild);
}
this.outline.setAttribute('d', d);
this.outline.setAttribute('fill', a.fillColor ?? 'none');
// An outline that never closes is stroked only, whatever fill its style declares —
// which is how both products draw a polyline.
this.outline.setAttribute('fill', d.trimEnd().endsWith('Z') ? a.fillColor ?? 'none' : 'none');
this.outline.setAttribute('stroke', a.strokeColor ?? 'none');
this.outline.setAttribute('stroke-width', String(a.strokeWidthPt * PX_PER_PT));
}
+10 -3
View File
@@ -16,7 +16,7 @@ import type {
} from 'docx';
import { unzipSync, zipSync, strFromU8, strToU8 } from 'fflate';
import { TEXTBOX_PADDING_CM } from '../editor/extensions/textBox';
import { SHAPES, isShapeKind, type ShapeKind } from '../utils/shapes';
import { SHAPES, isShapeKind, drawingMlPath, type ShapeKind } from '../utils/shapes';
import { cellFormatCode, isCellFormat } from '../utils/cellFormat';
import { DEFAULT_MARGINS, type PageMargins } from '../storage/pageMargins';
import type { Orientation } from '../storage/pageOrientation';
@@ -690,6 +690,7 @@ type TextBoxDocx = {
offsetYCm: number | null;
distCm: number | null;
shapeKind: ShapeKind;
shapePath: string | null;
flipV: boolean;
textVertical: boolean;
fill: string | null;
@@ -710,6 +711,7 @@ function textBoxDocxDescriptor(node: TiptapNode): TextBoxDocx {
offsetYCm: typeof a.wrapOffsetY === 'number' ? a.wrapOffsetY : null,
distCm: typeof a.wrapDist === 'number' ? a.wrapDist : null,
shapeKind: isShapeKind(a.shapeKind) ? a.shapeKind : 'textbox',
shapePath: typeof a.shapePath === 'string' && a.shapePath ? a.shapePath : null,
flipV: a.flipV === true,
textVertical: a.textVertical === true,
fill: typeof a.fillColor === 'string' && a.fillColor ? a.fillColor : null,
@@ -930,7 +932,12 @@ function textBoxDrawingXml(box: TextBoxDocx, index: number, parts: TxbxParts): s
: '<a:ln><a:noFill/></a:ln>';
const inset = Math.round(TEXTBOX_PADDING_CM * EMU_PER_CM);
// Auto-grow only for plain text boxes, matching the ODT export.
const autofit = box.shapeKind === 'textbox' ? '<a:spAutoFit/>' : '';
const autofit = box.shapeKind === 'textbox' && !box.shapePath ? '<a:spAutoFit/>' : '';
// A freeform is its own outline: custGeom over the same 0…100 box, in the shape's
// own EMU extent so the path needs no second scale.
const geom = box.shapePath
? `<a:custGeom><a:avLst/><a:pathLst>${drawingMlPath(box.shapePath, cx, cy)}</a:pathLst></a:custGeom>`
: `<a:prstGeom prst="${SHAPES[box.shapeKind].prst}"><a:avLst/></a:prstGeom>`;
// Word draws the `line` preset down the frame's diagonal and flips it to reach the
// other one; a line carries no fill and no text body.
const flip = line && box.flipV ? ' flipV="1"' : '';
@@ -941,7 +948,7 @@ function textBoxDrawingXml(box: TextBoxDocx, index: number, parts: TxbxParts): s
`<wps:wsp xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">` +
`<wps:cNvSpPr txBox="1"/>` +
`<wps:spPr><a:xfrm${rot}${flip}><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm>` +
`<a:prstGeom prst="${SHAPES[box.shapeKind].prst}"><a:avLst/></a:prstGeom>${line ? '<a:noFill/>' : fill}${ln}</wps:spPr>` +
`${geom}${line ? '<a:noFill/>' : fill}${ln}</wps:spPr>` +
body +
`<wps:bodyPr rot="0" vert="${box.textVertical ? 'vert' : 'horz'}" wrap="square"` +
` lIns="${inset}" tIns="${inset}" rIns="${inset}" bIns="${inset}" anchor="t">${autofit}</wps:bodyPr>` +
+12 -4
View File
@@ -24,7 +24,7 @@ import { BORDER_SIDES, parseBorderAttr } from '../editor/extensions/tableCellBor
import { parseCellPadding, DEFAULT_CELL_PADDING, type CellPadding } from '../editor/extensions/tableCellPadding';
import { TEXTBOX_PADDING_CM } from '../editor/extensions/textBox';
import { numberLocale, parseCellNumber, toWriterFormula, type CellRef, type NumberLocale } from '../utils/tableFormula';
import { SHAPES, arrowHeadCm, isShapeKind, isLineKind, odfEnhancedGeometry, type ShapeKind } from '../utils/shapes';
import { SHAPES, arrowHeadCm, isShapeKind, isLineKind, odfEnhancedGeometry, odfEnhancedPath, type ShapeKind } from '../utils/shapes';
import { normalizeLeader, parseTabStops } from '../editor/extensions/tabStops';
import { charStyleProps, listMarkerFormat, type MarkerFormat } from '../editor/extensions/listMarker';
import { orderedTypeDef, effectiveOrderedDef, effectiveOrderedDefAt, childCycle, formatOrdinal, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
@@ -942,6 +942,7 @@ type TextBoxExport = {
wrapAlign: string | null;
paddingCm: number;
shapeKind: ShapeKind;
shapePath: string | null;
flipV: boolean;
textVertical: boolean;
fill: string | null;
@@ -968,6 +969,7 @@ function textBoxDescriptor(node: TiptapNode): TextBoxExport {
wrapAlign: a.wrapAlign === 'center' || a.wrapAlign === 'right' ? a.wrapAlign : null,
paddingCm: typeof a.paddingCm === 'number' ? round3(a.paddingCm) : TEXTBOX_PADDING_CM,
shapeKind: isShapeKind(a.shapeKind) ? a.shapeKind : 'textbox',
shapePath: typeof a.shapePath === 'string' && a.shapePath ? a.shapePath : null,
flipV: a.flipV === true,
textVertical: a.textVertical === true,
fill: typeof a.fillColor === 'string' && a.fillColor ? a.fillColor : null,
@@ -3880,7 +3882,7 @@ function textBoxGraphicStyle(box: TextBoxExport, index: number): string {
` style:vertical-pos="${box.wrapOffsetYCm != null ? 'from-top' : 'top'}" style:vertical-rel="paragraph"`;
// auto-grow only for plain text boxes; a custom-shape needs both explicitly
// false, or LibreOffice's shape autofit shrinks it to its text.
const grow = box.shapeKind === 'textbox'
const grow = box.shapeKind === 'textbox' && !box.shapePath
? ' draw:auto-grow-height="true"'
: ' draw:auto-grow-height="false" draw:auto-grow-width="false"';
// An arrow head is a named marker in ODF, defined once in styles.xml.
@@ -3936,7 +3938,7 @@ function textBoxXml(box: TextBoxExport, inner: string, index: number): string {
` svg:x1="0cm" svg:y1="${y1}cm" svg:x2="${box.widthCm}cm" svg:y2="${y2}cm"/>`
);
}
if (box.shapeKind === 'textbox') {
if (box.shapeKind === 'textbox' && !box.shapePath) {
// svg:height for consumers without auto-grow; fo:min-height is the real semantic
// (height = minimum, content grows the box) and wins on our own re-import.
return (
@@ -3944,9 +3946,15 @@ function textBoxXml(box: TextBoxExport, inner: string, index: number): string {
`<draw:text-box fo:min-height="${box.heightCm}cm">${inner}</draw:text-box></draw:frame>`
);
}
// A freeform is its own outline rather than a preset's: `non-primitive` plus the
// path, which is what LibreOffice writes back out unchanged (probed).
const geometry = box.shapePath
? `<draw:enhanced-geometry svg:viewBox="0 0 21600 21600" draw:type="non-primitive"`
+ ` draw:enhanced-path="${odfEnhancedPath(box.shapePath)}"/>`
: odfEnhancedGeometry(box.shapeKind) ?? '';
return (
`<draw:custom-shape draw:name="Shape${n}"${common} svg:height="${box.heightCm}cm"${transform}>` +
`${inner}${odfEnhancedGeometry(box.shapeKind) ?? ''}</draw:custom-shape>`
`${inner}${geometry}</draw:custom-shape>`
);
}
+1 -1
View File
@@ -20,7 +20,7 @@ The **Open .odt** button (`App.svelte`) parses an uploaded file with `importOdt(
- **A run is measured against the block's own size**, not the yardstick's: a list item whose style sets 11pt would otherwise drop every 12pt run as "the style supplies it" and render it at 11 (`convertParaLike`, `runDefaults`).
- **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 — its drawing root is the `w:drawing`'s **direct** `wp:inline`/`wp:anchor` child, since a box holding a picture nests a second drawing and a subtree search reads *its* root instead, dropping the box and the caption in it (`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).
- **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`), and `draw:polygon`/`polyline`/`path`/`connector` — or a preset no gallery covers but whose `draw:enhanced-path` is a plain outline — → a box carrying that outline as `shapePath` (`convertFreeform`, `docs/architecture/frames.md`; a geometry built from modifier formulas still reads as "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 — its drawing root is the `w:drawing`'s **direct** `wp:inline`/`wp:anchor` child, since a box holding a picture nests a second drawing and a subtree search reads *its* root instead, dropping the box and the caption in it (`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). A **CMYK** JPEG loses its ICC profile (`stripCmykIccProfile`): Chromium colour-manages through it, LibreOffice and Word convert naively, and the file's own colours are the ones every word processor shows (measured on the contract fixture's logo: blue (0,80,131) → (0,77,183) against LibreOffice's (0,32,183), black (57,53,54) → (11,11,18) against (0,0,0)).
- **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`.
+33 -7
View File
@@ -11,7 +11,7 @@ import { tableLookAttr } from '../styles/tableStyles';
import { formatOrdinal, orderedTypeFromFormat, orderedTypeAttrAt, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
import { bulletCharAttr, bulletCharFromDocx } from '../utils/bulletListTypes';
import { DATE_FORMATS, TIME_FORMATS, docxPicture, toDateValue } from '../utils/dateTime';
import { shapeFromPrst, isLineKind, lineKindFor } from '../utils/shapes';
import { shapeFromPrst, isLineKind, lineKindFor, parseSvgPath, parseVmlPath, fitPath } from '../utils/shapes';
import { imageDataUrl, placeholderImage, type ConvertedImages } from './imageFormats';
import { PX_PER_CM, cmToPx, type PageMargins } from '../storage/pageMargins';
import type { Orientation } from '../storage/pageOrientation';
@@ -1873,16 +1873,36 @@ function setShapeStyleAttrs(attrs: Record<string, unknown>, fill: string | null,
}
}
// A DrawingML <wps:wsp> (text box or preset shape) → a textBox node. A preset
// `utils/shapes.ts` can't draw (a connector, a freeform) is dropped with a warning. All property
// lookups are scoped to spPr so a nested image's fill/xfrm can't leak in.
// <a:custGeom> read as the shape's own outline, in the coordinate space its path
// declares. A segment no outline can hold (an arc) leaves the shape unsupported.
function custGeomPath(spPr: Element | null): string {
const path = nsChild(nsChild(nsChild(spPr, A, 'custGeom'), A, 'pathLst'), A, 'path');
const w = intAttr(path, '', 'w') ?? 0;
const h = intAttr(path, '', 'h') ?? 0;
if (!path || w <= 0 || h <= 0) return '';
const parts: string[] = [];
for (const seg of Array.from(path.children)) {
const pts = Array.from(seg.getElementsByTagNameNS(A, 'pt'))
.map((p) => `${p.getAttribute('x') ?? 0} ${p.getAttribute('y') ?? 0}`).join(' ');
const cmd = { moveTo: 'M', lnTo: 'L', cubicBezTo: 'C', quadBezTo: 'Q', close: 'Z' }[seg.localName];
if (!cmd) return '';
parts.push(`${cmd} ${pts}`);
}
return fitPath(parseSvgPath(parts.join(' ')), w, h);
}
// A DrawingML <wps:wsp> (text box, preset shape or freeform) → a textBox node. A preset
// `utils/shapes.ts` can't draw and has no path of its own (a connector) is dropped with a
// warning. All property lookups are scoped to spPr so a nested image's fill/xfrm can't leak in.
function convertWpsShape(wsp: Element, root: Element, isAnchor: boolean, ctx: Ctx): Node | null {
const spPr = nsChild(wsp, WPS, 'spPr');
const kind = shapeFromPrst(nsChild(spPr, A, 'prstGeom')?.getAttribute('prst') ?? 'rect');
const outline = custGeomPath(spPr);
const kind = outline ? 'textbox' : shapeFromPrst(nsChild(spPr, A, 'prstGeom')?.getAttribute('prst') ?? 'rect');
if (!kind) { ctx.warnings.add('Unsupported shapes were removed'); return null; }
const attrs: Record<string, unknown> = {};
if (kind !== 'textbox') attrs.shapeKind = kind;
if (outline) attrs.shapePath = outline;
const extent = root.getElementsByTagNameNS(WP, 'extent')[0];
const cx = intAttr(extent, '', 'cx');
const cy = intAttr(extent, '', 'cy');
@@ -1966,9 +1986,15 @@ function convertPict(pict: Element, ctx: Ctx): Node | null {
const textbox = shape.getElementsByTagNameNS(VML, 'textbox')[0] ?? null;
const txbxContent = nsChild(textbox, W, 'txbxContent');
if (!txbxContent) { ctx.warnings.add('Drawings were removed'); return null; }
// A freeform is a v:shape drawn by its own path over a declared coordinate space,
// and it holds no text box — LibreOffice's .docx filter writes one that way.
const coord = (shape.getAttribute('coordsize') ?? '').split(',').map(Number);
const outline = coord.length === 2 && coord[0] > 0 && coord[1] > 0 && shape.getAttribute('path')
? fitPath(parseVmlPath(shape.getAttribute('path') ?? ''), coord[0], coord[1]) : '';
if (!txbxContent && !outline) { ctx.warnings.add('Drawings were removed'); return null; }
const attrs: Record<string, unknown> = {};
if (outline) attrs.shapePath = outline;
// VML says vertical text in the box's own style, as `layout-flow:vertical`.
if (/layout-flow\s*:\s*vertical/.test(textbox?.getAttribute('style') ?? '')) attrs.textVertical = true;
const kind = shape.localName === 'oval' ? 'ellipse' : shape.localName === 'roundrect' ? 'roundRect' : 'textbox';
@@ -1985,7 +2011,7 @@ function convertPict(pict: Element, ctx: Ctx): Node | null {
const swm = /^([\d.]+)\s*(pt)?$/.exec(shape.getAttribute('strokeweight') ?? '');
setShapeStyleAttrs(attrs, fill, stroke, swm ? parseFloat(swm[1]) : null);
const blocks = convertBlocks(Array.from(txbxContent.children), ctx, 'cell');
const blocks = txbxContent ? convertBlocks(Array.from(txbxContent.children), ctx, 'cell') : [];
return { type: 'textBox', attrs, content: blocks.length ? blocks : [{ type: 'paragraph' }] };
}
+60 -1
View File
@@ -11,7 +11,9 @@ import { TABLE_REGIONS, tableLookAttr, type TableLook, type TableRegion } from '
import { orderedTypeFromFormat, orderedTypeAttrAt, childCycle, ROOT_ORDERED_CYCLE, type OrderedCycle } from '../utils/orderedListTypes';
import { bulletCharAttr, bulletCharFromOdf } from '../utils/bulletListTypes';
import { matchFormat, toDateValue, type Token } from '../utils/dateTime';
import { shapeFromOdfType, lineKindFor, type ShapeKind } from '../utils/shapes';
import {
shapeFromOdfType, lineKindFor, parseSvgPath, parseOdfPoints, fitPath, type ShapeKind,
} from '../utils/shapes';
import { imageDataUrl, placeholderImage, type ConvertedImages } from './imageFormats';
import { astToLatex } from '../math/latex';
import { parseMathml } from '../math/mathml';
@@ -501,11 +503,18 @@ function loadObjectDoc(href: string | null, ctx: Ctx): Document | null {
// can't draw (a connector, a freeform) is dropped with a warning.
function convertShape(el: Element, ctx: Ctx): Node | null {
let kind: ShapeKind | null = null;
let path = '';
if (el.localName === 'rect') kind = 'textbox';
else if (el.localName === 'ellipse') kind = 'ellipse';
else {
const geo = el.getElementsByTagNameNS(NS.draw, 'enhanced-geometry')[0];
kind = shapeFromOdfType(geo?.getAttributeNS(NS.draw, 'type'));
// A shape no preset covers still draws, as long as its own outline is one:
// LibreOffice writes a freeform as `non-primitive` plus the path itself.
if (!kind && geo) {
path = enhancedPathOutline(geo);
if (path) kind = 'textbox';
}
}
if (!kind) {
ctx.warnings.add('Unsupported shapes were removed');
@@ -513,6 +522,7 @@ function convertShape(el: Element, ctx: Ctx): Node | null {
}
const attrs: Record<string, unknown> = {};
if (kind !== 'textbox') attrs.shapeKind = kind;
if (path) attrs.shapePath = path;
const wCm = lengthToCm(el.getAttributeNS(NS.svg, 'width'));
const hCm = lengthToCm(el.getAttributeNS(NS.svg, 'height'));
if (wCm != null) attrs.width = framePx(cmToPx(wCm));
@@ -523,6 +533,50 @@ function convertShape(el: Element, ctx: Ctx): Node | null {
return { type: 'textBox', attrs, content: textBoxContent(Array.from(el.children), ctx) };
}
// A `<draw:enhanced-geometry>` no preset matches, read as its own outline: only the
// four commands a freeform is drawn with, so a shape with modifier formulas (`?f0`)
// or an arc segment stays unsupported rather than drawing wrong.
function enhancedPathOutline(geo: Element): string {
const raw = geo.getAttributeNS(NS.draw, 'enhanced-path') ?? '';
if (!raw || !/^[\sMLCZN\d.,+-]+$/.test(raw)) return '';
const vb = (geo.getAttributeNS(NS.svg, 'viewBox') ?? '').split(/\s+/).map(Number);
if (vb.length !== 4 || !(vb[2] > 0) || !(vb[3] > 0)) return '';
return fitPath(parseSvgPath(raw.replace(/N/g, '')), vb[2], vb[3], vb[0], vb[1]);
}
// draw:polygon / draw:polyline / draw:path / draw:connector → a box drawing the file's
// own outline. The frame is the shape's box, or — a connector declaring none — the one
// its two endpoints span.
function convertFreeform(el: Element, ctx: Ctx): Node | null {
const num = (ns: string, name: string) => lengthToCm(el.getAttributeNS(ns, name));
const vb = (el.getAttributeNS(NS.svg, 'viewBox') ?? '').split(/\s+/).map(Number);
const points = el.getAttributeNS(NS.draw, 'points');
const d = el.getAttributeNS(NS.svg, 'd');
const cmds = d ? parseSvgPath(d)
: points ? parseOdfPoints(points, el.localName === 'polygon')
: [];
let wCm = num(NS.svg, 'width');
let hCm = num(NS.svg, 'height');
if (wCm == null || hCm == null) {
const [x1, y1, x2, y2] = ['x1', 'y1', 'x2', 'y2'].map((a) => num(NS.svg, a) ?? 0);
wCm = Math.abs(x2 - x1);
hCm = Math.abs(y2 - y1);
}
const path = cmds.length && vb.length === 4 && vb[2] > 0 && vb[3] > 0
? fitPath(cmds, vb[2], vb[3], vb[0], vb[1]) : '';
if (!path || !wCm || !hCm) {
ctx.warnings.add('Unsupported shapes were removed');
return null;
}
const attrs: Record<string, unknown> = {
shapePath: path, width: framePx(cmToPx(wCm)), height: framePx(cmToPx(hCm)),
};
const gp = ctx.resolver.graphicProps(el.getAttributeNS(NS.draw, 'style-name'));
applyFrameRotationAndWrap(el, attrs, gp);
shapeStyleAttrs(gp, attrs, true);
return { type: 'textBox', attrs, content: [{ type: 'paragraph' }] };
}
// draw:line → a textBox of the matching line kind: the two endpoints become the frame
// they span, and which diagonal they run along. Which heads the graphic style declares
// is what decides plain line / arrow / double arrow.
@@ -574,6 +628,11 @@ function convertDrawElement(e: Element, ctx: Ctx): { inline?: Node; block?: Node
const shape = convertShape(e, ctx);
return shape ? { block: shape } : null;
}
if (e.localName === 'polygon' || e.localName === 'polyline' || e.localName === 'path'
|| e.localName === 'connector') {
const shape = convertFreeform(e, ctx);
return shape ? { block: shape } : null;
}
if (e.localName === 'a') {
// draw:a wraps a drawing in a hyperlink; the editor has no image link, so unwrap
// to the inner drawing (the link is dropped, like other flattened hyperlinks).
+123 -1
View File
@@ -193,7 +193,8 @@ export function linePaths(kind: ShapeKind, w: number, h: number, flip: boolean,
}
/** The outline as an SVG `d`, in the 0…100 box the node view's viewBox uses. */
export function shapePath(kind: ShapeKind): string | null {
export function shapePath(kind: ShapeKind, own?: string | null): string | null {
if (own) return own;
const pts = SHAPES[kind].points;
if (!pts) return null;
return `M ${pts.map(([x, y]) => `${r2(x)},${r2(y)}`).join(' L ')} Z`;
@@ -228,6 +229,127 @@ export function odfEnhancedGeometry(kind: ShapeKind): string | null {
return body === null ? null : `<draw:enhanced-geometry svg:viewBox="0 0 ${VB} ${VB}"${body}/>`;
}
// ---- freeform outlines -----------------------------------------------------
// A drawing this editor cannot author but must not drop: a polygon, a polyline, a
// bezier curve or a connector's elbow, kept as its own outline in the same 0…100 box
// a preset's points live in. An open path is stroked only, as both products draw one.
export type PathCmd =
| { c: 'M' | 'L'; p: number[] }
| { c: 'C'; p: number[] }
| { c: 'Z' };
/** The `<letter> <numbers…>` groups of a path, whatever dialect wrote it. */
function pathTokens(d: string): { cmd: string; n: number[] }[] {
const out: { cmd: string; n: number[] }[] = [];
for (const m of d.matchAll(/([A-Za-z])([^A-Za-z]*)/g)) {
const n = (m[2].match(/-?\d*\.?\d+(?:e[-+]?\d+)?/gi) ?? []).map(Number);
out.push({ cmd: m[1], n });
}
return out;
}
const PATH_ARITY: Record<string, number> = { M: 2, L: 2, T: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, A: 7, Z: 0 };
/**
* SVG path data as absolute M/L/C/Z. A quadratic is raised to a cubic and a smooth
* curve takes its own start as the first control point; an arc is joined by a line —
* none of the three is what either product writes for a freeform.
*/
export function parseSvgPath(d: string): PathCmd[] {
const out: PathCmd[] = [];
let x = 0, y = 0, sx = 0, sy = 0;
for (const { cmd, n } of pathTokens(d)) {
const rel = cmd === cmd.toLowerCase();
const k = cmd.toUpperCase();
const step = PATH_ARITY[k];
if (step === undefined) continue;
if (k === 'Z') { out.push({ c: 'Z' }); [x, y] = [sx, sy]; continue; }
// A repeated group continues the command, and the one after an M is an L.
for (let i = 0; i + step <= n.length; i += step) {
const a = n.slice(i, i + step);
const at = (dx: number, dy: number): [number, number] => rel ? [x + dx, y + dy] : [dx, dy];
if (k === 'M' || k === 'L' || k === 'T') {
const [px, py] = at(a[0], a[1]);
out.push({ c: k === 'M' && i === 0 ? 'M' : 'L', p: [px, py] });
if (k === 'M' && i === 0) [sx, sy] = [px, py];
[x, y] = [px, py];
} else if (k === 'H' || k === 'V') {
const [px, py] = k === 'H' ? [rel ? x + a[0] : a[0], y] : [x, rel ? y + a[0] : a[0]];
out.push({ c: 'L', p: [px, py] });
[x, y] = [px, py];
} else if (k === 'A') {
const [px, py] = at(a[5], a[6]);
out.push({ c: 'L', p: [px, py] });
[x, y] = [px, py];
} else {
const pts: number[] = [];
for (let j = 0; j + 1 < step; j += 2) pts.push(...at(a[j], a[j + 1]));
const [ex, ey] = [pts[pts.length - 2], pts[pts.length - 1]];
const p = k === 'C' ? pts
: k === 'S' ? [x, y, ...pts]
: [x + (2 / 3) * (pts[0] - x), y + (2 / 3) * (pts[1] - y),
ex + (2 / 3) * (pts[0] - ex), ey + (2 / 3) * (pts[1] - ey), ex, ey];
out.push({ c: 'C', p });
[x, y] = [ex, ey];
}
}
}
return out;
}
/**
* VML's path language, which is SVG's with the cases swapped: `m l c x` are the
* absolute commands and `t r v` their relative twins, `e` ends the path.
*/
export function parseVmlPath(d: string): PathCmd[] {
const svg = d.replace(/[a-z]/g, (c) => ({ m: 'M', l: 'L', c: 'C', x: 'Z', t: 'm', r: 'l', v: 'c', e: '', n: '', f: '', s: '' }[c] ?? ''));
return parseSvgPath(svg);
}
/** `draw:points="0,0 4001,1000"` — ODF's polygon and polyline outline. */
export function parseOdfPoints(points: string, closed: boolean): PathCmd[] {
const nums = (points.match(/-?[\d.]+/g) ?? []).map(Number);
const out: PathCmd[] = [];
for (let i = 0; i + 1 < nums.length; i += 2) out.push({ c: i ? 'L' : 'M', p: [nums[i], nums[i + 1]] });
if (closed && out.length) out.push({ c: 'Z' });
return out;
}
const r3 = (n: number) => Math.round(n * 1000) / 1000;
/** The outline mapped from its own viewBox into the 0…100 box the editor draws in. */
export function fitPath(cmds: PathCmd[], vbW: number, vbH: number, vbX = 0, vbY = 0): string {
if (!cmds.length || vbW <= 0 || vbH <= 0) return '';
const parts = cmds.map((c) => {
if (c.c === 'Z') return 'Z';
const nums = c.p.map((v, i) => r3(((v - (i % 2 ? vbY : vbX)) * 100) / (i % 2 ? vbH : vbW)));
return `${c.c} ${nums.join(' ')}`;
});
return parts.join(' ');
}
/** ODF's `draw:enhanced-path` for an outline the editor holds in its 0…100 box. */
export function odfEnhancedPath(path: string): string {
const body = parseSvgPath(path).map((c) => (c.c === 'Z' ? 'Z'
: `${c.c} ${c.p.map((v) => Math.round((v * VB) / 100)).join(' ')}`)).join(' ');
return `${body} N`;
}
/** DrawingML's `<a:path>` for the same outline, in a `w`×`h` coordinate space. */
export function drawingMlPath(path: string, w: number, h: number): string {
const pt = (x: number, y: number) => `<a:pt x="${Math.round((x * w) / 100)}" y="${Math.round((y * h) / 100)}"/>`;
const body = parseSvgPath(path).map((c) => {
if (c.c === 'Z') return '<a:close/>';
const pts = [];
for (let i = 0; i + 1 < c.p.length; i += 2) pts.push(pt(c.p[i], c.p[i + 1]));
return c.c === 'M' ? `<a:moveTo>${pts[0]}</a:moveTo>`
: c.c === 'L' ? `<a:lnTo>${pts[0]}</a:lnTo>`
: `<a:cubicBezTo>${pts.join('')}</a:cubicBezTo>`;
}).join('');
return `<a:path w="${w}" h="${h}">${body}</a:path>`;
}
// The three line kinds share their names, and the heads a file declares are what
// tells them apart (lineKindFor), so only the bare one is reachable by name.
const NAMED = (Object.keys(SHAPES) as ShapeKind[]).filter((k) => SHAPES[k].line !== 'end' && SHAPES[k].line !== 'both');
+134
View File
@@ -0,0 +1,134 @@
// A drawing the editor cannot author but must keep: a polygon, a polyline, a bezier
// curve and a connector's elbow. Each imports as a box drawing the file's own outline,
// and both exports write that outline back.
import { describe, it, expect } from 'vitest';
import { zipSync, strToU8, unzipSync, 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';
type N = any;
const NS = 'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"'
+ ' xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"'
+ ' xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"'
+ ' xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"'
+ ' xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"'
+ ' xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"';
function odt(body: string): Uint8Array {
const content = `<?xml version="1.0" encoding="UTF-8"?><office:document-content ${NS} office:version="1.3">`
+ '<office:automatic-styles><style:style style:name="gr1" style:family="graphic">'
+ '<style:graphic-properties draw:fill="solid" draw:fill-color="#FFD320" draw:stroke="solid"'
+ ' svg:stroke-color="#3465A4" style:wrap="none"/></style:style></office:automatic-styles>'
+ `<office:body><office:text>${body}</office:text></office:body></office:document-content>`;
return zipSync({
'mimetype': strToU8('application/vnd.oasis.opendocument.text'),
'content.xml': strToU8(content),
'styles.xml': strToU8(`<?xml version="1.0" encoding="UTF-8"?><office:document-styles ${NS} office:version="1.3"/>`),
});
}
const W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
const VML = 'urn:schemas-microsoft-com:vml';
const docx = (body: string): Uint8Array => zipSync({
'word/document.xml': strToU8(`<?xml version="1.0"?><w:document xmlns:w="${W}" xmlns:v="${VML}">`
+ `<w:body>${body}</w:body></w:document>`),
});
const shape = (r: N): N => ((r.content as N).content ?? []).find((n: N) => n.type === 'textBox');
const margins = { top: 2, bottom: 2, left: 2, right: 2 };
describe('a freeform drawing', () => {
it('reads a polygon as its own closed outline', () => {
const r = importOdt(odt('<text:p>x</text:p><text:p><draw:polygon draw:style-name="gr1"'
+ ' text:anchor-type="paragraph" svg:width="4cm" svg:height="3cm"'
+ ' svg:viewBox="0 0 4000 3000" draw:points="0,0 4000,1000 2000,3000"/></text:p>'));
expect(shape(r).attrs.shapePath).toBe('M 0 0 L 100 33.333 L 50 100 Z');
expect(shape(r).attrs.fillColor).toBe('#FFD320');
});
it('leaves a polyline open, so it is stroked and not filled', () => {
const r = importOdt(odt('<text:p><draw:polyline draw:style-name="gr1"'
+ ' text:anchor-type="paragraph" svg:width="4cm" svg:height="2cm"'
+ ' svg:viewBox="0 0 4000 2000" draw:points="0,0 1000,2000 4000,1000"/></text:p>'));
expect(shape(r).attrs.shapePath).toBe('M 0 0 L 25 100 L 100 50');
});
it('reads the relative bezier LibreOffice writes for a curve', () => {
const r = importOdt(odt('<text:p><draw:path draw:style-name="gr1" text:anchor-type="paragraph"'
+ ' svg:width="4cm" svg:height="3cm" svg:viewBox="0 0 4000 3000"'
+ ' svg:d="M0 0c1000 0 3000 3000 4000 1500l-4000 1500z"/></text:p>'));
expect(shape(r).attrs.shapePath).toBe('M 0 0 C 25 0 75 100 100 50 L 0 100 Z');
});
it("takes a connector's elbow, and the box its endpoints span", () => {
const r = importOdt(odt('<text:p><draw:connector draw:style-name="gr1" text:anchor-type="paragraph"'
+ ' draw:type="standard" svg:x1="1cm" svg:y1="0cm" svg:x2="6cm" svg:y2="2cm"'
+ ' svg:viewBox="0 0 5000 2000" svg:d="M1000 0h2500v2000h2500"/></text:p>'));
const a = shape(r).attrs;
expect(a.shapePath).toBe('M 20 0 L 70 0 L 70 100 L 120 100');
// 5cm × 2cm at 96dpi.
expect(a.width).toBe(189);
expect(a.height).toBe(75.59);
});
it('round-trips through ODF as a non-primitive custom shape', async () => {
const doc: N = {
type: 'doc',
content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'before' }] },
{
type: 'textBox',
attrs: { width: 200, height: 150, shapePath: 'M 0 0 C 25 0 75 100 100 50 L 0 100 Z' },
content: [{ type: 'paragraph' }],
},
],
};
const bytes = await buildOdt(doc, margins, 'portrait');
const xml = strFromU8(unzipSync(bytes)['content.xml']);
expect(xml).toContain('draw:type="non-primitive"');
expect(xml).toContain('draw:enhanced-path="M 0 0 C 5400 0 16200 21600 21600 10800 L 0 21600 Z N"');
expect(shape(importOdt(bytes)).attrs.shapePath).toBe('M 0 0 C 25 0 75 100 100 50 L 0 100 Z');
});
it('round-trips through DOCX as a custGeom', async () => {
const doc: N = {
type: 'doc',
content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'before' }] },
{
type: 'textBox',
attrs: { width: 200, height: 100, shapePath: 'M 0 0 L 100 50 L 0 100 Z' },
content: [{ type: 'paragraph' }],
},
],
};
const bytes = await buildDocx(doc, margins, 'portrait');
const xml = strFromU8(unzipSync(bytes)['word/document.xml']);
expect(xml).toContain('<a:custGeom><a:avLst/><a:pathLst><a:path');
expect(xml).toContain('<a:moveTo><a:pt x="0" y="0"/></a:moveTo>');
expect(shape(importDocx(bytes)).attrs.shapePath).toBe('M 0 0 L 100 50 L 0 100 Z');
});
it('reads the VML path LibreOffice writes into a .docx', () => {
const body = '<w:p><w:r><w:pict>'
+ '<v:shape id="s1" coordsize="4000,3000" fillcolor="#ffd320"'
+ ' style="position:absolute;width:113.35pt;height:85.05pt"'
+ ' path="m0,0l4000,1000l2000,3000l0,0e"><v:stroke color="#3465a4"/></v:shape>'
+ '</w:pict></w:r></w:p>';
const r = importDocx(docx(body));
expect(shape(r).attrs.shapePath).toBe('M 0 0 L 100 33.333 L 50 100 L 0 0');
expect(shape(r).attrs.fillColor).toBe('#FFD320');
});
it('still drops a shape whose geometry is a formula', () => {
const r = importOdt(odt('<text:p><draw:custom-shape draw:style-name="gr1" text:anchor-type="paragraph"'
+ ' svg:width="4cm" svg:height="3cm"><text:p/><draw:enhanced-geometry draw:type="mso-spt100"'
+ ' svg:viewBox="0 0 21600 21600" draw:enhanced-path="M 0 0 L ?f0 ?f1 Z N"/></draw:custom-shape></text:p>'));
expect(shape(r)).toBeUndefined();
expect(r.warnings.some((w: string) => /shapes/i.test(w))).toBe(true);
});
});
+63
View File
@@ -0,0 +1,63 @@
// A freeform outline crossing the four path dialects: SVG (ODF's draw:path), VML
// (LibreOffice's own .docx filter), ODF's point lists, and DrawingML's custGeom.
import { describe, it, expect } from 'vitest';
import {
parseSvgPath, parseVmlPath, parseOdfPoints, fitPath, odfEnhancedPath, drawingMlPath,
} from '../../src/lib/utils/shapes';
describe('path parsing', () => {
it('reads the relative commands LibreOffice writes', () => {
// The bezier a converted draw:path comes back as, in a 4001×3001 viewBox.
const cmds = parseSvgPath('M0 0c1000 0 3001 3001 4001 1501l-4001 1500z');
expect(cmds.map((c) => c.c)).toEqual(['M', 'C', 'L', 'Z']);
expect(cmds[1].c === 'C' && cmds[1].p).toEqual([1000, 0, 3001, 3001, 4001, 1501]);
expect(cmds[2].c === 'L' && cmds[2].p).toEqual([0, 3001]);
});
it('reads VML, whose cases are the other way round', () => {
const vml = parseVmlPath('m0,0l4001,1000l2001,3001l0,0e');
expect(vml.map((c) => c.c)).toEqual(['M', 'L', 'L', 'L']);
expect(vml[1].c === 'L' && vml[1].p).toEqual([4001, 1000]);
// `x` closes; `r` is the relative lineto.
expect(parseVmlPath('m0,0r100,100x').map((c) => c.c)).toEqual(['M', 'L', 'Z']);
expect(parseVmlPath('m0,0r100,100x')[1]).toEqual({ c: 'L', p: [100, 100] });
});
it('closes a polygon and leaves a polyline open', () => {
expect(parseOdfPoints('0,0 100,50 0,100', true).map((c) => c.c)).toEqual(['M', 'L', 'L', 'Z']);
expect(parseOdfPoints('0,0 100,50 0,100', false).map((c) => c.c)).toEqual(['M', 'L', 'L']);
});
it('raises a quadratic to a cubic and joins an arc', () => {
expect(parseSvgPath('M0 0Q 0 100 100 100')[1].c).toBe('C');
expect(parseSvgPath('M0 0A 50 50 0 0 1 100 100')[1]).toEqual({ c: 'L', p: [100, 100] });
});
it('takes an implicit repeat as the same command', () => {
expect(parseSvgPath('M0 0 10 10 20 20').map((c) => c.c)).toEqual(['M', 'L', 'L']);
});
});
describe('path emitting', () => {
const box = fitPath(parseOdfPoints('0,0 4000,1000 2000,3000', true), 4000, 3000);
it('fits an outline into the editor 0…100 box', () => {
expect(box).toBe('M 0 0 L 100 33.333 L 50 100 Z');
});
it('writes ODF enhanced-path in its own 21600 viewBox', () => {
expect(odfEnhancedPath(box)).toBe('M 0 0 L 21600 7200 L 10800 21600 Z N');
});
it('writes a DrawingML path list', () => {
expect(drawingMlPath(box, 1000, 600)).toBe(
'<a:path w="1000" h="600"><a:moveTo><a:pt x="0" y="0"/></a:moveTo>'
+ '<a:lnTo><a:pt x="1000" y="200"/></a:lnTo>'
+ '<a:lnTo><a:pt x="500" y="600"/></a:lnTo><a:close/></a:path>');
});
it('survives a full turn through both dialects', () => {
const again = fitPath(parseSvgPath(odfEnhancedPath(box).replace(' N', '')), 21600, 21600);
expect(again).toBe(box);
});
});