diff --git a/docs/architecture/frames.md b/docs/architecture/frames.md
index 466e4f3..be5c5e8 100644
--- a/docs/architecture/frames.md
+++ b/docs/architecture/frames.md
@@ -4,7 +4,7 @@ Covers `src/lib/editor/extensions/image.ts` and `textBox.ts` — node views, res
handles, wrap modes, frame offsets — and their ODF/DOCX legs.
- **`image.ts`** (`Image`) — inline, as-character image atom (Word's "in line with text"). Attrs: `src` (data-URI), `alt`, `width`/`height` (**unscaled doc px @96dpi**, like `rowHeight`, and **fractional** — rounding a page-wide picture to whole px costs 0.3mm of height; `framePx` snaps back to a whole one within 0.05px, which is where our own export's 0.001cm quantization lands, so the round trip stays exact), `rotation` (CW degrees). The node view nests an `` in a rotated "rotor" inside an axis-aligned wrapper that reserves the rotated bounding box (so text reflows around it). The rotor's transform makes it a stacking context, so a selected `.image-node` is given a `z-index` above the header/footer layer to keep handles that poke into a margin grabbable. It has eight zoom-aware resize handles — corners aspect-locked, edges single-axis (width- or height-only) — plus a rotation-arrow grip, and shows a live "Width … × Height …" (cm) badge while resizing; resize deltas are un-rotated onto the image's own axes so handles track the pointer at any angle (drag math mirrors `tableRowResize.ts`; width cap = the cell or page-text-column, height cap = the page text height). `setImage` command inserts it; the toolbar button (ToolbarExpanded), drag-drop and paste (Editor.svelte) read the file via `FileReader` → data-URI and clamp the initial size to the page text box. **Text wrap:** the `wrap` attr (`'inline'|'left'|'right'|'topBottom'|'through'`) makes the image a *floating* frame — `ImageToolbar.svelte` (a per-image floating toolbar wired in `Editor.svelte` like `TableToolbar`) sets the mode; `left`/`right` float the wrapper at its anchor paragraph (text flows on the open side via CSS `float`), `topBottom` is a **full-width `float`** (text only above/below), and `through` — Word's in-front-of / behind-text (`wp:wrapNone` + `behindDoc`), ODF's `style:wrap="run-through"` — leaves the flow entirely: `position: absolute` with no offsets keeps the static position it was anchored at, so it reserves neither width nor height, and `inFront` picks the side of the text it lands on. Read as a side float instead it reserved a near-column-wide picture's whole height, which cost the image fixture a page and ~50 reports. A text box in that mode always sits behind the text — the mode has no toolbar entry yet, so only a file can carry it in. All modes use `float` deliberately: an in-flow `display:block` on an inline-atom node view splits the paragraph's inline content into anonymous block boxes, which desyncs ProseMirror's inline view descriptor and makes it drop the following page-break spacer widget; a float is out-of-flow and avoids that. Dragging an **inline** image runs ProseMirror's native node move (the `dropCursor` plugin shows the caret). Dragging a **floating** image runs a custom drag (`ImageView.startReposition`) that **live re-anchors** the node to the text position under the cursor, so the float and text reflow in real time as you drag; it's rAF-throttled and only moves when the cursor's line changes (a float can't move within a line), and stays a single undo step (first move records history, later moves are `addToHistory:false` and get rebased on undo). A paragraph that contains an image paginates **atomically** (`pageBreaks.ts` — pushed whole to the next page, spacer placed before it) so a page break never splits the paragraph next to the image's float (where ProseMirror drops the spacer widget). **Wrap distance:** `wrapDist` is the gap the file keeps beside a float, in cm (Word's `distL`/`distR`, ODF's `fo:margin-left`/`-right` on the graphic style) — only the side the text flows on, since the other one is the frame's own offset. A frame that declares none reserves **nothing**, beside it or above/below it: probed, LibreOffice wraps flush against it, and a gap of our own put every figure in a text box 3mm too tall and broke a line a word early. `setImageWrap` gives a frame the file never floated the 0.32cm a word processor's own wrap command writes. **Vertical alignment (as-char):** `vAlign` carries ODF's `style:vertical-pos`/`-rel` pair for an inline frame — `null` (LibreOffice's `top`/`baseline` and Word's only mode) stands the frame on the text baseline, `middle`/`below` centre it on the baseline or hang it below, and `text-top`/`text-middle`/`text-bottom` measure against the character area instead (CSS `vertical-align: text-top`/`text-bottom`; nothing in CSS centres on that area, so `text-middle` uses 0.36em for half of ascent − descent, which Liberation Serif/Sans, Times and Arial share). `from-top` becomes `vAlign: 'offset'` and puts the frame's top `wrapOffsetY` cm below the baseline whatever the relation says — all probed against LibreOffice, whose formula images use `middle`/`text` and `from-top` almost exclusively. A line an as-char frame has to itself — nothing beside it but whitespace — is as tall as the frame or the block's line height, whichever is more, with **no text descent below it** (probed); `image.ts` gives such a frame an `image-line` class, since CSS cannot ask whether a line holds real text. Hard breaks are the only line boundaries the model shows, so the run between two of them is what gets tested — which covers the frame-break-caption idiom LibreOffice's own guides are full of; a frame alone on a *soft-wrapped* line is invisible from there. A frame that shares its line with text keeps the baseline and the descent. **Frame offsets:** `wrapOffset` is the frame's left edge in the text column (Word's `positionH` posOffset, ODF `svg:x`), rendered as the float's near/far margin against the live column vars — an indented anchor paragraph can't skew it — and shared with `textBox.ts` through `frameMargins`. A `topBottom` float spans the column, so its own x moves the *rotor* inside the wrapper instead. `wrapOffsetY` (`positionV`, `svg:y`) is the frame's top below the anchor paragraph's, drawn for `topBottom` only — no text sits beside such a frame, where a side float's top margin would push away lines Word keeps. Chromium places **every** line after a full-width float below it, even the ones the float's top margin leaves room for, so a frame set below the paragraph top is sunk behind that paragraph's text at import (`sinkOffsetFrames`, both importers) and `ImageView.sinkToOffset` measures what the lines above it already cover, adding only the rest. The **block after the anchor paragraph clears the band** (an `editor.css` `:has` rule): a float only pushes lines that intersect it, so a short block (a heading) would slot into the clearance gap a prior side float opens above the band — both word processors start it below; a page-break spacer and the block holding a band-sharing partner frame are exempt. Two `topBottom` frames set against **opposite ends** of nearby paragraphs (`wrapAlign`, from Word's `positionH` align / ODF `style:horizontal-pos`) share one band and float to their own sides instead: `pairAlignedFrames` (import/odt.ts, both importers) keeps the attr only for such a pair — a lone one reserves the whole band, which is what the wrap means — and scales a pair up to 15% wider than the column down to it, since Word lets the two overlap in the middle and two floats cannot. A frame Word puts *inside* running text still lands after it: browsers can't wrap text around a freely-positioned box (CSS Exclusions are unimplemented). Inline images stay as-char. Works inside table cells. Not available while editing a header/footer (the HF schema has no image node). Images live as data-URIs in the autosaved JSON; `autosave.ts` warns once if that exceeds the localStorage quota.
-- **`textBox.ts`** (`TextBox`) — block-level text box / basic shape with editable block content (`content: '(paragraph|heading|bulletList|orderedList)+'`, `isolating`). Attrs: `width`/`height` (px @96dpi; height renders as **min-height** — content grows the box), `rotation` (CW deg), `wrap` (image's `WrapMode`; `inline` renders in-flow, floats via CSS `float` like `ImageView.applyWrap` — an in-flow box also `clear`s, since a block box is laid *over* a float rather than beside it, and both word processors put it on the next free line), `shapeKind` (see the shape table below), `fillColor`/`strokeColor` (`null` = transparent/no border), `strokeWidthPt`. Padding is the fixed `TEXTBOX_PADDING_CM` (0.15cm). The node has its **own group** (`group: 'textBox'`) so only the document admits it (`extensions.ts` widens Document to `'(block | textBox)+'`) — never in table cells, lists, header/footer, or other boxes; imports found there are flattened with a warning. `TextBoxView` mirrors `ImageView` (wrapper reserving the rotated bbox → rotor carrying fill/stroke/rotation → `contentDOM`); the rotor is out of flow and auto-grows, so a ResizeObserver refits the wrapper. **Click model (Word-like):** `stopEvent`/`isFrameHit` claim mouse events on a ~6px frame ring (rotation-/zoom-aware) → NodeSelection + handles (the shared `image-*` handle classes/CSS); clicks further inside pass to ProseMirror (caret). The box is browser-`draggable` only while node-selected, so PM's native block drag moves it without hijacking text selection. Commands: `insertTextBox()` (after the current top-level block, cursor inside), `setTextBoxAttrs()` (NodeSelection *or* cursor inside; helper `findTextBox`). `TextBoxToolbar.svelte` (wired in `Editor.svelte` like the image toolbar, also shown while the caret is inside a box) sets wrap/shape/fill/stroke and `textVertical` — the box's text running **top-to-bottom, right-to-left** (`writing-mode: vertical-rl` on the content area, which is all the browser needs). It round-trips as the style's own writing mode in ODF — a plain box is a Writer text frame (its `TbxFr` style chains to `Frame`; see `src/lib/export/CLAUDE.md`) and takes it in the graphic properties, a drawing *shape* only in its style's paragraph properties (both probed) — and Word's `w:bodyPr vert`; ODF's bottom-to-top and Word's `vert270` read as the same one direction the browser lays out. `trailingNode.ts` appends a paragraph after a trailing box; `pageBreaks.ts` paginates `.textbox-node` atomically. **Spacing:** a box lifted out of an anchor paragraph that held nothing else stands in for it, so it takes that paragraph's resolved `fo:margin-top`/`-bottom` as `spaceBefore`/`spaceAfter` (`ParagraphSpacing` covers `textBox` for that). Space above is padding — it adds to the block above rather than collapsing against it — which means the node is `content-box` and the rotor, centred in the padding box, gets half of it back.
+- **`textBox.ts`** (`TextBox`) — block-level text box / basic shape with editable block content (`content: '(paragraph|heading|bulletList|orderedList)+'`, `isolating`). Attrs: `width`/`height` (px @96dpi; height renders as **min-height** — content grows the box), `rotation` (CW deg), `wrap` (image's `WrapMode`; `inline` renders in-flow, floats via CSS `float` like `ImageView.applyWrap` — an in-flow box also `clear`s, since a block box is laid *over* a float rather than beside it, and both word processors put it on the next free line), `shapeKind` (see the shape table below), `fillColor`/`strokeColor` (`null` = transparent/no border), `strokeWidthPt`. Padding is the fixed `TEXTBOX_PADDING_CM` (0.15cm). The node has its **own group** (`group: 'textBox'`) so only the document admits it (`extensions.ts` widens Document to `'(block | textBox)+'`) — never in table cells, lists, header/footer, or other boxes; imports found there are flattened with a warning. `TextBoxView` mirrors `ImageView` (wrapper reserving the rotated bbox → rotor carrying fill/stroke/rotation → `contentDOM`); the rotor is out of flow and auto-grows, so a ResizeObserver refits the wrapper. **Click model (Word-like):** `stopEvent`/`isFrameHit` claim mouse events on a ~6px frame ring (rotation-/zoom-aware) → NodeSelection + handles (the shared `image-*` handle classes/CSS); clicks further inside pass to ProseMirror (caret). The box is browser-`draggable` only while node-selected, so PM's native block drag moves it without hijacking text selection. Commands: `insertTextBox()` (after the current top-level block, cursor inside), `setTextBoxAttrs()` (NodeSelection *or* cursor inside; helper `findTextBox`). `TextBoxToolbar.svelte` (wired in `Editor.svelte` like the image toolbar, also shown while the caret is inside a box) sets wrap/shape/fill/stroke, `wrapAlign` and `textVertical` — the box's text running **top-to-bottom, right-to-left** (`writing-mode: vertical-rl` on the content area, which is all the browser needs). It round-trips as the style's own writing mode in ODF — a plain box is a Writer text frame (its `TbxFr` style chains to `Frame`; see `src/lib/export/CLAUDE.md`) and takes it in the graphic properties, a drawing *shape* only in its style's paragraph properties (both probed) — and Word's `w:bodyPr vert`; ODF's bottom-to-top and Word's `vert270` read as the same one direction the browser lays out. `trailingNode.ts` appends a paragraph after a trailing box; `pageBreaks.ts` paginates `.textbox-node` atomically. **Where it sits across the column:** the two modes that leave the box in flow (`inline`, `topBottom`) take `wrapAlign` — `null`/`center`/`right`, drawn as the wrapper's auto margins, and the toolbar drops any `wrapOffset` when one is picked. A side wrap names the side itself, so the buttons hide there. **Spacing:** a box lifted out of an anchor paragraph that held nothing else stands in for it, so it takes that paragraph's resolved `fo:margin-top`/`-bottom` as `spaceBefore`/`spaceAfter` (`ParagraphSpacing` covers `textBox` for that). Space above is padding — it adds to the block above rather than collapsing against it — which means the node is `content-box` and the rotor, centred in the padding box, gets half of it back.
## Clicking a float
diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte
index 899cfa0..1b368b8 100644
--- a/src/lib/components/Editor.svelte
+++ b/src/lib/components/Editor.svelte
@@ -674,9 +674,9 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
// just above it. Hidden while the image toolbar shows (an image inside a box).
let textBoxUi = $state<{
visible: boolean; top: number; left: number;
- wrap: WrapMode; shapeKind: ShapeKind; fillColor: string | null;
+ wrap: WrapMode; wrapAlign: string | null; shapeKind: ShapeKind; fillColor: string | null;
strokeColor: string | null; strokeWidthPt: number; textVertical: boolean;
- }>({ visible: false, top: 0, left: 0, wrap: 'inline', shapeKind: 'textbox', fillColor: '#FFFFFF', strokeColor: '#000000', strokeWidthPt: 1, textVertical: false });
+ }>({ visible: false, top: 0, left: 0, wrap: 'inline', wrapAlign: null, shapeKind: 'textbox', fillColor: '#FFFFFF', strokeColor: '#000000', strokeWidthPt: 1, textVertical: false });
function recomputeTextBoxUi() {
const ed = editor;
@@ -701,6 +701,7 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
top: anchorTop - cRect.top + container!.scrollTop,
left: r.left - cRect.left + container!.scrollLeft,
wrap: (a.wrap as WrapMode) || 'inline',
+ wrapAlign: (a.wrapAlign as string | null) ?? null,
shapeKind: (a.shapeKind as ShapeKind) || 'textbox',
fillColor: (a.fillColor as string | null) ?? null,
strokeColor: (a.strokeColor as string | null) ?? null,
@@ -1561,6 +1562,7 @@ import { EMPTY_PAGE_DECOR, type PageDecor } from '../storage/pageDecor';
top={textBoxUi.top}
left={textBoxUi.left}
wrap={textBoxUi.wrap}
+ wrapAlign={textBoxUi.wrapAlign}
shapeKind={textBoxUi.shapeKind}
fillColor={textBoxUi.fillColor}
strokeColor={textBoxUi.strokeColor}
diff --git a/src/lib/components/TextBoxToolbar.svelte b/src/lib/components/TextBoxToolbar.svelte
index ab11abe..488b3bf 100644
--- a/src/lib/components/TextBoxToolbar.svelte
+++ b/src/lib/components/TextBoxToolbar.svelte
@@ -11,6 +11,7 @@
top,
left,
wrap,
+ wrapAlign,
shapeKind,
fillColor,
strokeColor,
@@ -21,6 +22,7 @@
top: number;
left: number;
wrap: WrapMode;
+ wrapAlign: string | null;
shapeKind: ShapeKind;
fillColor: string | null;
strokeColor: string | null;
@@ -43,6 +45,21 @@
: t().textBox.wrapTopBottom;
}
+ // Where the box sits across the column. A side wrap has no such choice — the wrap
+ // names the side — so the buttons show for the two modes that leave the box in flow.
+ const alignModes = ['left', 'center', 'right'] as const;
+ const alignable = $derived(wrap === 'inline' || wrap === 'topBottom');
+ function alignTitle(a: (typeof alignModes)[number]): string {
+ return a === 'left' ? t().textBox.alignLeft
+ : a === 'center' ? t().textBox.alignCenter
+ : t().textBox.alignRight;
+ }
+ // An imported box placed by coordinate keeps that x over any alignment, so picking
+ // one drops it.
+ function setAlign(a: (typeof alignModes)[number]) {
+ set({ wrapAlign: a === 'left' ? null : a, wrapOffset: null });
+ }
+
const strokeWidths = [0.5, 1, 2.25];
@@ -100,6 +117,27 @@
{/each}
+ {#if alignable}
+
+
+ {#each alignModes as a}
+
+ {/each}
+ {/if}
+
`/`` in content.xml.
- **Images** (`replaceImages`/`applyImages`): odf-kit's native image path rounds dimensions to whole cm and doesn't reach our cell path, so images bypass it. `replaceImages` (a pre-pass) swaps each `image` node for an `IMG`-sentinel text run and collects the bytes (decoded data-URI) + cm geometry (px→cm via `round3`); the sentinel rides every odf-kit path including table cells. `applyImages` (after `applyCellBlocks`) rewrites each sentinel to a ``, adds the binary `Pictures/` entries to the zip, and appends a `` per picture to `META-INF/manifest.xml`. Integer px ⇄ round3-cm ⇄ px is sub-pixel exact, so size is unchanged. A rotated image also gets a `draw:transform="rotate() translate(...)"` (ODF rotate is CCW radians, ours CW degrees; the translate re-centres it on the unrotated box). A **floating** image (`wrap !== 'inline'`) instead uses `text:anchor-type="paragraph"` + a minted `` carrying `style:wrap` + `style:horizontal-pos` (image-left → `wrap="right" horizontal-pos="left"`; topBottom → `wrap="none" horizontal-pos="center"`; through → `wrap="run-through"` + `style:run-through`) injected into content.xml automatic-styles.
- **Tables:** column widths come from the editor's per-column weights (`tableColumnWidthsCm`, summing exactly to the text width, with `table:align="margins"`). **Table margins:** a table's `marginLeft`/`marginRight` shrink that width and are written by `applyTableMargins` into the table's automatic style (`style:width` + `fo:margin-left`/`-right`; odf-kit names table styles `Table1`, `Table2`, … in document order, matching the descriptor list `exportTable` fills). odf-kit serializes each cell to a single `` of runs; `exportTable` emits all of a cell's content into that paragraph separated by a `SEG` sentinel and records a `CellBlock[]` descriptor, then `applyCellBlocks` splits on `SEG` and rebuilds real ``/``/`` (incl. nested lists) with minted automatic paragraph styles. **Merged cells:** `exportTable` passes each cell's `colspan`/`rowspan` as odf-kit `CellOptions.colSpan`/`rowSpan`; odf-kit emits `table:number-columns/rows-spanned` and auto-generates the `` placeholders (which never match the `applyCellBlocks` cell regex, so `cellBlocks` stays one-per-real-cell aligned). Import already reads spans/covered cells in `convertTable`. **Cell shading:** a cell's `backgroundColor` attr is passed as `CellOptions.backgroundColor` (normalized), which odf-kit mints into the cell style as `fo:background-color`. **Cell borders:** the per-side border attrs (tableCellBorders.ts) are passed as `CellOptions.borderTop/Right/Bottom/Left` (`'none'` or `'pt solid #RRGGBB'`) overriding the table-level default border per side.
-- **Text boxes / shapes** (`replaceTextBoxes`/`applyTextBoxes`): a top-level `textBox` is **hoisted** — `replaceTextBoxes` (after `replacePageBreaks`, before the inline passes) swaps it for `TBX`-sentinel marker paragraphs (`S{i}`…`E{i}`, U+E008) bracketing its child blocks at top level, so every existing pass (custom attrs, list styles, inline sentinels, images) serializes them unchanged and document-order-indexed passes stay aligned. `applyTextBoxes` (after `applyImages`) wraps each serialized S…E region into `` (plain box; `svg:height` also emitted for non-auto-grow consumers) or `` + preset `` (`utils/shapes.ts`; see `docs/architecture/frames.md`) inside a fresh anchor paragraph, minting a `TbxFr{n}` graphic style (fill/stroke/padding + the image wrap props; `draw:auto-grow-height="true"` for boxes, both auto-grows explicitly **false** for shapes or LibreOffice's autofit shrinks them to their text). A plain box's style chains to **`style:parent-style-name="Frame"`** — that parent is what makes LibreOffice read it as a Writer text *frame*; without it it is a drawing object whose text loses lists, nested images and borders (probed on a re-save). Frames take `fo:background-color` (written beside `draw:fill`) and `fo:border` — `draw:stroke` is ignored there — and vertical text as `style:writing-mode` in the graphic properties; a *shape* instead needs `` (both probed). `rewriteStylesXml` declares a minimal `Frame` base style (zeroed margins/padding/border, or the built-in leaks 2mm margins and a hairline). An **inline box's `wrapAlign`** rides its anchor paragraph's `fo:text-align` (`TbxP{n}`) — an as-char frame has no horizontal-pos, the paragraph centres it, which the import reads back.
+- **Text boxes / shapes** (`replaceTextBoxes`/`applyTextBoxes`): a top-level `textBox` is **hoisted** — `replaceTextBoxes` (after `replacePageBreaks`, before the inline passes) swaps it for `TBX`-sentinel marker paragraphs (`S{i}`…`E{i}`, U+E008) bracketing its child blocks at top level, so every existing pass (custom attrs, list styles, inline sentinels, images) serializes them unchanged and document-order-indexed passes stay aligned. `applyTextBoxes` (after `applyImages`) wraps each serialized S…E region into `` (plain box; `svg:height` also emitted for non-auto-grow consumers) or `` + preset `` (`utils/shapes.ts`; see `docs/architecture/frames.md`) inside a fresh anchor paragraph, minting a `TbxFr{n}` graphic style (fill/stroke/padding + the image wrap props; `draw:auto-grow-height="true"` for boxes, both auto-grows explicitly **false** for shapes or LibreOffice's autofit shrinks them to their text). A plain box's style chains to **`style:parent-style-name="Frame"`** — that parent is what makes LibreOffice read it as a Writer text *frame*; without it it is a drawing object whose text loses lists, nested images and borders (probed on a re-save). Frames take `fo:background-color` (written beside `draw:fill`) and `fo:border` — `draw:stroke` is ignored there — and vertical text as `style:writing-mode` in the graphic properties; a *shape* instead needs `` (both probed). `rewriteStylesXml` declares a minimal `Frame` base style (zeroed margins/padding/border, or the built-in leaks 2mm margins and a hairline). An **inline box's `wrapAlign`** rides its anchor paragraph's `fo:text-align` (`TbxP{n}`) — an as-char frame has no horizontal-pos, the paragraph centres it, which the import reads back. In DOCX it is the same pair: `applyTextBoxesDocx` rebuilds the marker paragraph, so an as-char box's alignment goes in as its `w:jc` and a band-wrapped one's as the anchor's `wp:align`.
- **A text box's own parts, DOCX** (`applyTextBoxesDocx`): the `docx` package can't emit a DrawingML shape, so the box XML is a hand-built string — and its content needs parts the package never hears about. The pass holds the whole unzipped package, so it mints them itself: a picture becomes `word/media/tbx{n}.{ext}` plus a `Relationship` above the package's highest `rId` (Content_Types already declares the raster defaults), a list an ``/`` pair above its highest id, appended **before** the first `` because every abstract definition has to precede them. The numbering ids only exist once the packed file is in hand, so the paragraphs carry a `TXBX_NUM` sentinel that the same pass substitutes.
- **Templates** (`template.ts`): a `.ott`/`.dotx` is the built document with one label changed — ODF's package media type (in `mimetype` **and** in the manifest, the mimetype entry staying first and stored) and OOXML's content type for `/word/document.xml`. `saveAsTemplate` offers both in one picker, so the bytes are only built once the extension is known.
- **Formulas** (`replaceFormulas`/`applyFormulas`): an `MTH`-sentinel run becomes an as-char `` plus a `Formula{n}/content.xml` sub-document (MathML root) and its two manifest entries. **No `svg:width`/`svg:height`** — a sized frame makes LibreOffice scale the object instead of typesetting it. DOCX emits `` (or `` when displayed) from the same post-pack pass as the text boxes. See `docs/architecture/formulas.md`.
diff --git a/src/lib/export/docx.ts b/src/lib/export/docx.ts
index f487650..327c039 100644
--- a/src/lib/export/docx.ts
+++ b/src/lib/export/docx.ts
@@ -851,6 +851,7 @@ type TextBoxDocx = {
offsetCm: number | null;
offsetYCm: number | null;
distCm: number | null;
+ alignH: string | null;
shapeKind: ShapeKind;
shapePath: string | null;
flipV: boolean;
@@ -872,6 +873,7 @@ function textBoxDocxDescriptor(node: TiptapNode): TextBoxDocx {
offsetCm: typeof a.wrapOffset === 'number' ? a.wrapOffset : null,
offsetYCm: typeof a.wrapOffsetY === 'number' ? a.wrapOffsetY : null,
distCm: typeof a.wrapDist === 'number' ? a.wrapDist : null,
+ alignH: a.wrapAlign === 'center' || a.wrapAlign === 'right' || a.wrapAlign === 'left' ? a.wrapAlign : null,
shapeKind: isShapeKind(a.shapeKind) ? a.shapeKind : 'textbox',
shapePath: typeof a.shapePath === 'string' && a.shapePath ? a.shapePath : null,
flipV: a.flipV === true,
@@ -1257,7 +1259,9 @@ function textBoxDrawingXml(box: TextBoxDocx, index: number, parts: TxbxParts): s
const wrapEl = box.wrap === 'through' ? ''
: box.wrap === 'topBottom' ? ''
: ``;
- const align = box.wrap === 'right' ? 'right' : 'left';
+ // A side wrap names the side itself; only a band-wrapped box has a place to choose.
+ const align = box.wrap === 'right' ? 'right'
+ : box.wrap === 'topBottom' ? box.alignH ?? 'left' : 'left';
const emu = (cm: number) => Math.round(cm * 360000);
// The x rides topBottom too: it moves the frame within its full-width band.
const posH = box.offsetCm != null
@@ -1301,7 +1305,12 @@ function applyTextBoxesDocx(bytes: Uint8Array, boxes: TextBoxDocx[]): Uint8Array
new RegExp(`]*?>(?:(?!)[\\s\\S])*?${TBX}(\\d+)${TBX}(?:(?!)[\\s\\S])*?`, 'g'),
(_m, idx: string) => {
const box = boxes[Number(idx)];
- return box ? `${textBoxDrawingXml(box, Number(idx), parts)}` : '';
+ if (!box) return '';
+ // The marker paragraph is rebuilt, so an as-char box's alignment — which is the
+ // paragraph's, a frame in the line having none of its own — is written here.
+ const pPr = box.wrap === 'inline' && box.alignH
+ ? `` : '';
+ return `${pPr}${textBoxDrawingXml(box, Number(idx), parts)}`;
},
);
diff --git a/src/lib/i18n/locales/de.ts b/src/lib/i18n/locales/de.ts
index 1724c6c..d366124 100644
--- a/src/lib/i18n/locales/de.ts
+++ b/src/lib/i18n/locales/de.ts
@@ -318,6 +318,9 @@ const de: Messages = {
wrapLeft: 'Textumbruch — Feld links',
wrapRight: 'Textumbruch — Feld rechts',
wrapTopBottom: 'Oben und unten',
+ alignLeft: 'Linksbündig in der Spalte',
+ alignCenter: 'Zentriert in der Spalte',
+ alignRight: 'Rechtsbündig in der Spalte',
shape: 'Form',
chooseShape: 'Form auswählen',
shapes: {
diff --git a/src/lib/i18n/locales/en.ts b/src/lib/i18n/locales/en.ts
index 29d94a0..b1ad250 100644
--- a/src/lib/i18n/locales/en.ts
+++ b/src/lib/i18n/locales/en.ts
@@ -324,6 +324,9 @@ const en = {
wrapLeft: 'Wrap text — box left',
wrapRight: 'Wrap text — box right',
wrapTopBottom: 'Top and bottom',
+ alignLeft: 'Align left in the column',
+ alignCenter: 'Centre in the column',
+ alignRight: 'Align right in the column',
shape: 'Shape',
chooseShape: 'Choose a shape',
shapes: {
diff --git a/src/lib/import/docx.ts b/src/lib/import/docx.ts
index 4dc984e..98f08a8 100644
--- a/src/lib/import/docx.ts
+++ b/src/lib/import/docx.ts
@@ -528,6 +528,14 @@ function convertBlocks(children: Element[], ctx: Ctx, kind: BlockKind, boldByDef
if (anchor && !(pending.length && anchorIsEmpty)) out.push(anchor);
if (!pending.length) return;
if (kind === 'body') {
+ // A box lifted out of its anchor paragraph keeps the alignment that paragraph gave
+ // it: an as-char frame is set against the middle of the column by the paragraph it
+ // sits in, not by anything of its own.
+ const align = anchor?.attrs?.textAlign;
+ if (align === 'center' || align === 'right')
+ for (const b of pending)
+ if (b.type === 'textBox' && b.attrs && b.attrs.wrapOffset == null && !b.attrs.wrapAlign)
+ b.attrs.wrapAlign = align;
out.push(...pending);
} else {
ctx.warnings.add('Text boxes nested in table cells or other text boxes were flattened');
@@ -2117,6 +2125,12 @@ function convertWpsShape(wsp: Element, root: Element, isAnchor: boolean, ctx: Ct
if (offsetCm != null) attrs.wrapOffset = offsetCm;
if (offsetYCm != null) attrs.wrapOffsetY = offsetYCm;
if (distCm != null) attrs.wrapDist = distCm;
+ // Where the box sits across its band. A box is a block, so it takes the middle and
+ // the far end that an image reads as one half of a side-by-side pair.
+ const align = root.getElementsByTagNameNS(WP, 'positionH')[0]
+ ?.getElementsByTagNameNS(WP, 'align')[0]?.textContent?.trim();
+ if (wrap === 'topBottom' && offsetCm == null && (align === 'center' || align === 'right'))
+ attrs.wrapAlign = align;
}
const fillClr = nsChild(nsChild(spPr, A, 'solidFill'), A, 'srgbClr')?.getAttribute('val');
diff --git a/tests/roundtrip.test.ts b/tests/roundtrip.test.ts
index fd30430..0e3eb5c 100644
--- a/tests/roundtrip.test.ts
+++ b/tests/roundtrip.test.ts
@@ -2739,3 +2739,28 @@ describe('Leg 32: fold marks (ODT + DOCX)', () => {
check('off imports off', importDocx(plain).foldMarks === false);
});
});
+
+describe('Leg 33: where a box sits across the column (ODT + DOCX)', () => {
+ const box = (wrap: string, wrapAlign: string | null): N =>
+ TBX({ width: 200, height: 90, wrap, ...(wrapAlign ? { wrapAlign } : {}) }, P(null, T('Kasten')));
+ const doc = (wrap: string, wrapAlign: string | null): N =>
+ ({ type: 'doc', content: [P(null, T('above')), box(wrap, wrapAlign), P(null, T('below'))] });
+ const alignOf = (res: N): unknown =>
+ (res.content.content ?? []).find((n: N) => n.type === 'textBox')?.attrs?.wrapAlign ?? null;
+
+ for (const [wrap, align] of [['inline', 'center'], ['inline', 'right'], ['topBottom', 'center'], ['topBottom', 'right'], ['topBottom', null]] as const) {
+ it(`ODT: ${wrap} ${align ?? 'left'} comes back`, async () => {
+ const bytes = await buildOdt(doc(wrap, align), margins);
+ check('the alignment survives', alignOf(importOdt(bytes)) === align, alignOf(importOdt(bytes)));
+ });
+
+ it(`DOCX: ${wrap} ${align ?? 'left'} comes back`, async () => {
+ const bytes = await buildDocx(doc(wrap, align), margins);
+ const xml = strFromU8(unzipSync(bytes)['word/document.xml']);
+ if (wrap === 'topBottom') {
+ check('the band position is written', xml.includes(`${align ?? 'left'}`), //.exec(xml)?.[0]);
+ }
+ check('the alignment survives', alignOf(importDocx(bytes)) === align, alignOf(importDocx(bytes)));
+ });
+ }
+});