diff --git a/.claude/skills/weak-agent-test/scenarios/invoice/criteria.md b/.claude/skills/weak-agent-test/scenarios/invoice/criteria.md index 40c4b4d..03d7664 100644 --- a/.claude/skills/weak-agent-test/scenarios/invoice/criteria.md +++ b/.claude/skills/weak-agent-test/scenarios/invoice/criteria.md @@ -36,6 +36,7 @@ The agent never sees this file. It is the ground-truth definition of "correct" f ### Logo replaced - The top-left image is the new mark sourced from `assets/logo.svg`. - The document still contains **exactly two** embedded images (new logo + footer payment mark). +- The new logo is **not distorted**: its displayed box (`size=` in the `docx:image` read hint) has the same aspect ratio as `assets/logo.svg` (square, 256×256), give or take rounding. - Verify via `docx images list FILE`: two entries, and the logo entry's dimensions / source match `assets/logo.svg`. - Footer payment mark is preserved: the footer image relationship is still present and unreferenced relationships were not dropped. diff --git a/REFERENCE.md b/REFERENCE.md index 263489d..082613e 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -293,7 +293,7 @@ docx footers clear FILE … docx images add FILE (--after | --before) LOCATOR --image SRC [--alt T] [--width LENGTH] [--height LENGTH] [--caption "..."] # bare = inches; 5cm, 300px, … (see "Lengths and units") docx images add FILE (--at-start | --at-end) --image SRC [options] # SRC = path, data: URI, or http(s) URL docx images extract FILE --to DIR [--at imgN] # --to = output directory; --at picks one image -docx images replace FILE --at imgN --with ./new.png +docx images replace FILE --at imgN --with ./new.png [--width LENGTH | --height LENGTH | --keep-size] # keeps the displayed width, height follows the new aspect (fit to the text area); crop dropped; ack names the size docx images delete FILE --at imgN docx hyperlinks add FILE --at pN:S-E --url URL diff --git a/src/cli/images/add.ts b/src/cli/images/add.ts index d204c0b..37e9804 100644 --- a/src/cli/images/add.ts +++ b/src/cli/images/add.ts @@ -162,17 +162,27 @@ async function parseImageFlags(values: RawValues): Promise< const caption = decodeInlineEscapes(values.caption as string | undefined); if (caption !== undefined) out.caption = caption; + const size = await parseImageSize(values); + if (typeof size === "number") return size; + return { ...out, ...size }; +} + +/** `--width`/`--height` through the shared length grammar (`IMAGE_LENGTH`), + * as inches. Shared with `images replace`, so both verbs size identically. */ +export async function parseImageSize( + values: RawValues, +): Promise<{ widthInches?: number; heightInches?: number } | number> { + const size: { widthInches?: number; heightInches?: number } = {}; for (const flag of ["width", "height"] as const) { const raw = values[flag] as string | undefined; if (raw === undefined) continue; const twips = parseLength(raw, flag, IMAGE_LENGTH); if (typeof twips !== "number") return fail("USAGE", twips.error, twips.hint); - out[flag === "width" ? "widthInches" : "heightInches"] = + size[flag === "width" ? "widthInches" : "heightInches"] = twips / TWIPS_PER_INCH; } - - return out; + return size; } /** Image sizes: bare inches (the long-standing meaning), positive, and `px` at diff --git a/src/cli/images/replace.ts b/src/cli/images/replace.ts index 0b841ce..187251e 100644 --- a/src/cli/images/replace.ts +++ b/src/cli/images/replace.ts @@ -1,12 +1,19 @@ +import { getPageContentHeightEmu, getPageContentWidthEmu } from "@core"; import { findContainingParagraph } from "@core/comments"; import { + applyReplacementExtent, + fitReplacementExtent, + type ImageSource, ImageSourceError, Images, imageFormatForExtension, loadImageSource, + type ReplacementSizing, SUPPORTED_IMAGE_FORMATS, } from "@core/image"; import { addAuditComment } from "../audit-comment"; +import type { RawValues } from "../insert/index"; +import { formatImageSize } from "../read/annotations"; import { EXIT, fail, @@ -18,8 +25,9 @@ import { tryParseArgs, writeStdout, } from "../respond"; +import { parseImageSize } from "./add"; -const HELP = `docx images replace — swap an image's bytes +const HELP = `docx images replace — swap an image's picture, refitting its frame Usage: docx images replace FILE --at imgN --with PATH [options] @@ -27,12 +35,23 @@ Usage: Examples: docx images replace doc.docx --at img2 --with ./new-photo.png docx images replace doc.docx --at img0 --with ./diagram.jpg + docx images replace doc.docx --at img0 --with ./logo.png --width 1.5in Required: --at imgN image id to replace (e.g. img0) --with PATH New image file (format keyed off the file extension: png/jpg/gif/webp/bmp/tiff/svg/emf/wmf/ico) +Sizing (default: keep the displayed WIDTH, recompute the height from the new +image's aspect ratio, scaled down to fit the text area if needed — the new +picture is never stretched into the old one's box): + --width LENGTH Display width: bare inches (2) or in/cm/mm/pt/px/tw. + Alone, the height follows the new image's aspect ratio. + --height LENGTH Display height, same units. Alone, the width follows. + Both given: honored as-is. + --keep-size Keep the old box exactly (only when the new image has the + same shape) + Optional: --author NAME Author for the audit comment when track-changes is on (default: $DOCX_AUTHOR) @@ -42,15 +61,20 @@ Optional: -h, --help Show this help The replacement may use a different format from the original — the embedded -part is renamed and re-registered automatically. +part is renamed and re-registered automatically. Any crop on the old picture +is dropped (it was cut for the old image). Every place that shows the same +picture (a shared media part) is refitted, each from its own width. A format +whose pixel size isn't read (emf/wmf/webp/bmp/tiff/ico) keeps the old box — +the confirmation says so; pass --width and --height to size it. Image swaps can't be recorded as tracked changes, so when track-changes is on an audit comment is anchored to each place the swapped image appears. Output: - Prints a one-line confirmation on success (exit 0) — replace mints no new - id (the image keeps its imgN). --verbose prints {ok:true, operation, path, - imageId, partName, mimeType, bytes}. Errors print {code, error, hint?} with + Prints a one-line confirmation naming the new size on success (exit 0), + e.g. "images.replace img0 (1x4in)" — replace mints no new id (the image + keeps its imgN). --verbose prints {ok:true, operation, path, imageId, size, + partName, mimeType, bytes}. Errors print {code, error, hint?} with a nonzero exit. Discover ids with \`docx images list FILE\`. `; @@ -60,6 +84,9 @@ export async function run(args: string[]): Promise { { at: { type: "string" }, with: { type: "string" }, + width: { type: "string" }, + height: { type: "string" }, + "keep-size": { type: "boolean" }, author: { type: "string" }, ...SAVE_FLAGS, }, @@ -83,6 +110,9 @@ export async function run(args: string[]): Promise { const sourcePath = parsed.values.with as string | undefined; if (!sourcePath) return fail("USAGE", "Missing --with PATH", HELP); + const sizing = await parseSizing(parsed.values); + if (typeof sizing === "number") return sizing; + const sourceFile = Bun.file(sourcePath); if (!(await sourceFile.exists())) { return fail("FILE_NOT_FOUND", `Replacement file not found: ${sourcePath}`); @@ -104,6 +134,22 @@ export async function run(args: string[]): Promise { const newMimeType = format.mimeType; const newExtension = format.extension; + // Route the replacement through the shared resolver (same as `docx images add`) + // so it gets the same safety: SVG sanitization (scripts/handlers/animation + // stripped), HEIC→JPEG transcode, and the SSRF guard on remote srcs. We keep + // the extension/MIME resolved above for part naming; the bytes and pixel + // dimensions come back. + let source: ImageSource; + try { + source = await loadImageSource(sourcePath); + } catch (error) { + if (error instanceof ImageSourceError) { + return fail("IMAGE_SOURCE", error.message); + } + throw error; + } + const bytes = source.bytes; + const document = await openOrFail(path); if (typeof document === "number") return document; @@ -112,6 +158,44 @@ export async function run(args: string[]): Promise { return fail("IMAGE_NOT_FOUND", `Image not found: ${targetId}`); } + // The bytes are shared by every drawing on this relationship, so every one + // of them is refitted (each from its own displayed width). Plan all fits + // BEFORE any mutation, so a sizing error writes nothing. + const occurrences = new Images(document).list(); + const textArea = { + widthEmu: getPageContentWidthEmu(document), + heightEmu: getPageContentHeightEmu(document), + }; + const fits = []; + for (const [index, occurrence] of occurrences.entries()) { + if (occurrence.relationshipId !== reference.relationshipId) continue; + const drawing = occurrence.run.findChild("w:drawing"); + if (!drawing) continue; + const extent = fitReplacementExtent(drawing, source, sizing, textArea); + if (!extent) { + return fail( + "USAGE", + `Can't keep the aspect ratio: no pixel size could be read from .${sourceExtension}`, + "Pass both --width and --height to size it explicitly.", + ); + } + fits.push({ id: `img${index}`, occurrence, drawing, extent }); + } + const targetFit = fits.find((fit) => fit.id === targetId); + if (!targetFit) { + return fail( + "IMAGE_NOT_FOUND", + `Image reference is stale (no drawing for ${targetId})`, + ); + } + const size = formatImageSize( + targetFit.extent.widthEmu, + targetFit.extent.heightEmu, + ); + const sizeNote = targetFit.extent.sizeKnown + ? undefined + : `kept ${size}: size unknown for .${sourceExtension} — pass --width and --height if it's a different shape`; + const originalPartName = reference.partName; const newPartName = renameExtension(originalPartName, newExtension); const outputPath = parsed.values.output as string | undefined; @@ -122,6 +206,7 @@ export async function run(args: string[]): Promise { dryRun: true, path, imageId: targetId, + size, from: { partName: originalPartName, mimeType: reference.contentType }, to: { partName: newPartName, mimeType: newMimeType }, ...(outputPath ? { output: outputPath } : {}), @@ -129,19 +214,8 @@ export async function run(args: string[]): Promise { return EXIT.OK; } - // Route the replacement through the shared resolver (same as `docx images add`) - // so it gets the same safety: SVG sanitization (scripts/handlers/animation - // stripped), HEIC→JPEG transcode, and the SSRF guard on remote srcs. We keep - // the extension/MIME resolved above for part naming; only the bytes come back. - let bytes: Uint8Array; - try { - bytes = (await loadImageSource(sourcePath)).bytes; - } catch (error) { - if (error instanceof ImageSourceError) { - return fail("IMAGE_SOURCE", error.message); - } - throw error; - } + for (const fit of fits) applyReplacementExtent(fit.drawing, fit.extent); + const originalMimeType = reference.contentType; if (newPartName === originalPartName) { @@ -171,12 +245,9 @@ export async function run(args: string[]): Promise { if (document.isTrackChangesEnabled()) { const authorFlag = parsed.values.author as string | undefined; - const message = `image replaced: ${originalPartName} (${originalMimeType}) → ${newPartName} (${newMimeType}, ${bytes.length} bytes)`; - const drawingRuns = new Images(document) - .list() - .filter((hit) => hit.relationshipId === reference.relationshipId) - .map((hit) => hit.run); - for (const drawingRun of drawingRuns) { + const message = `image replaced: ${originalPartName} (${originalMimeType}) → ${newPartName} (${newMimeType}, ${bytes.length} bytes), now ${size}`; + for (const { occurrence } of fits) { + const drawingRun = occurrence.run; const paragraph = findContainingParagraph( document.documentTree, drawingRun, @@ -193,18 +264,41 @@ export async function run(args: string[]): Promise { await document.save(outputPath); - await respondAck({ - ok: true, - operation: "images.replace", - path: outputPath ?? path, - imageId: targetId, - partName: newPartName, - mimeType: newMimeType, - bytes: bytes.length, - }); + await respondAck( + { + ok: true, + operation: "images.replace", + path: outputPath ?? path, + imageId: targetId, + size, + ...(sizeNote ? { note: sizeNote } : {}), + partName: newPartName, + mimeType: newMimeType, + bytes: bytes.length, + }, + sizeNote && `↳ ${sizeNote}`, + ); return EXIT.OK; } +/** `--width`/`--height` (shared grammar with `images add`) or `--keep-size`, + * which can't be combined — it would silently win over an explicit size. */ +async function parseSizing( + values: RawValues, +): Promise { + const size = await parseImageSize(values); + if (typeof size === "number") return size; + if (!values["keep-size"]) return size; + if (size.widthInches !== undefined || size.heightInches !== undefined) { + return fail( + "USAGE", + "--keep-size can't be combined with --width/--height", + "Use --keep-size to keep the old box, or --width/--height to set a new one.", + ); + } + return { keepSize: true }; +} + function renameExtension(partName: string, newExtension: string): string { const dotIndex = partName.lastIndexOf("."); const slashIndex = partName.lastIndexOf("/"); diff --git a/src/cli/read/annotations.ts b/src/cli/read/annotations.ts index 68e7bdd..bb5b56d 100644 --- a/src/cli/read/annotations.ts +++ b/src/cli/read/annotations.ts @@ -126,6 +126,12 @@ export function deviatingCellMargins( /** Format an EMU count (914400 per inch) as inches, trimming trailing zeros. * Image extents (``) are in EMU; `read --ast` carries the raw EMU. */ +/** `WxHin` — the display-size form the `docx:image` hint and the + * `images replace` ack share, so an agent sees the same string in both. */ +export function formatImageSize(widthEmu: number, heightEmu: number): string { + return `${emuToInches(widthEmu)}x${emuToInches(heightEmu)}in`; +} + export function emuToInches(emu: number): string { return `${Number.parseFloat((emu / 914400).toFixed(2))}`; } diff --git a/src/cli/read/markdown.ts b/src/cli/read/markdown.ts index d2c1456..48df25f 100644 --- a/src/cli/read/markdown.ts +++ b/src/cli/read/markdown.ts @@ -43,8 +43,8 @@ import { } from "@core/track-changes/revision-visibility"; import { deviatingCellMargins, - emuToInches, formatCellMargins, + formatImageSize, formatNote, htmlAttr, type NotePair, @@ -780,10 +780,7 @@ function contentWidthEmu(geometry: SectionBreak | undefined): number { function formatImageNote(run: ImageRun, contentEmu: number): string { const pairs: NotePair[] = []; if (run.widthEmu && run.heightEmu) { - pairs.push([ - "size", - `${emuToInches(run.widthEmu)}x${emuToInches(run.heightEmu)}in`, - ]); + pairs.push(["size", formatImageSize(run.widthEmu, run.heightEmu)]); } if (run.floating) pairs.push(["float", "yes"]); if (run.wrap) pairs.push(["wrap", run.wrap]); diff --git a/src/cli/respond.ts b/src/cli/respond.ts index a08f7a7..69bec92 100644 --- a/src/cli/respond.ts +++ b/src/cli/respond.ts @@ -202,7 +202,10 @@ function ackTarget(ack: Record): string | null { const to = str(ack.to); return `${ack.hyperlinkId}${to ? ` → ${to}` : ""}`; } - if (str(ack.imageId)) return str(ack.imageId); + if (str(ack.imageId)) { + const size = str(ack.size); + return size ? `${ack.imageId} (${size})` : str(ack.imageId); + } if (str(ack.table)) { const position = num(ack.position); return position !== null ? `${ack.table} (${position})` : str(ack.table); diff --git a/src/core/image/CLAUDE.md b/src/core/image/CLAUDE.md index 500b113..ad9a6e3 100644 --- a/src/core/image/CLAUDE.md +++ b/src/core/image/CLAUDE.md @@ -1,11 +1,15 @@ # src/core/image — image emit, source resolution, formats -Three files reachable via the `@core/image` barrel ([index.ts](index.ts)): [formats.ts](formats.ts) (mime↔extension table), [source.ts](source.ts) (resolve an input reference to bytes), [drawing.tsx](drawing.tsx) (the `Images` lens + the `` emitter). A fourth file, [svg-sanitize.ts](svg-sanitize.ts), is internal to `source.ts` and not surfaced through the barrel. +Four files reachable via the `@core/image` barrel ([index.ts](index.ts)): [formats.ts](formats.ts) (mime↔extension table), [source.ts](source.ts) (resolve an input reference to bytes), [drawing.tsx](drawing.tsx) (the `Images` lens + the `` emitter), [refit.ts](refit.ts) (resize an existing drawing's frame for replacement bytes). A fifth file, [svg-sanitize.ts](svg-sanitize.ts), is internal to `source.ts` and not surfaced through the barrel. ## Emit + package ops `loadImageSource(src)` in [source.ts](source.ts) resolves a path / `data:` URI / `http(s)` URL to `{bytes, extension, mimeType, pixelWidth?, pixelHeight?}` (header-parsed dims for png/jpeg/gif; other formats need explicit sizing). `computeExtentEmu` turns pixels + optional inch overrides into the `` EMU pair. The `Images` lens in [drawing.tsx](drawing.tsx) carries `new Images(document).list()` (finds drawing runs in `imgN` order — shared by `images replace`/`delete`) and `new Images(document).add(source)` (writes `word/media/imageN.ext`, mints the `image` relationship, registers the content-type ``). `` is the pure emitter for the inline `` run. +## Replace refits the frame + +[refit.ts](refit.ts) sizes an EXISTING drawing for new bytes (`images replace`) so a differently-shaped picture is never stretched into the old box (issue #46). `fitReplacementExtent` is pure: keep the displayed width, recompute the height from the new pixel aspect, then scale down (aspect kept) to fit the text area; `--width`/`--height` go through `computeExtentEmu` exactly like `add`; `--keep-size` keeps the box; a format with no parsed pixel size keeps the box and reports `sizeKnown: false` (the CLI says so in the ack). `applyReplacementExtent` mutates in place: `` AND `pic:spPr/a:xfrm/a:ext` (they must agree), drops `` (a crop in the OLD image's coordinates), and resets a tight/through `` to the full frame (polygon coordinates are a fixed 21600 space, so the rectangle needs no scaling). The bytes are per-relationship, so the CLI refits EVERY drawing on that rId — each from its own width — and plans all fits before mutating. + The `a:`/`pic:` namespaces are declared inline on `a:graphic`/`pic:pic` (matching Word) so the subtree validates regardless of the document root's declarations — `docx create`'s template declares `w/r/m/mc/wp/...` but **not** `a`/`pic`. Drawing object ids (`wp:docPr`/`pic:cNvPr` @id) must be unique per document, so `nextDrawingId` scans existing ids. `r:embed` is an *attribute*, so there's no `r` element namespace in `jsx/index.ts`. An image run inside `` surfaces `ImageRun.trackedChange` (populated in the `w:drawing` branch of `readRun` in `ast/read.ts`), same as a text run. ## One format table, keyed by extension diff --git a/src/core/image/index.ts b/src/core/image/index.ts index 57767b3..684e743 100644 --- a/src/core/image/index.ts +++ b/src/core/image/index.ts @@ -9,6 +9,11 @@ export { imageFormatForExtension, SUPPORTED_IMAGE_FORMATS, } from "./formats"; +export { + applyReplacementExtent, + fitReplacementExtent, + type ReplacementSizing, +} from "./refit"; export { computeExtentEmu, type ImageSource, diff --git a/src/core/image/refit.ts b/src/core/image/refit.ts new file mode 100644 index 0000000..bdcef76 --- /dev/null +++ b/src/core/image/refit.ts @@ -0,0 +1,156 @@ +import { XmlNode } from "../parser"; +import { computeExtentEmu, type ImageSource } from "./source"; + +/** Size the frame of one existing drawing for a REPLACEMENT image, so the new + * picture is never stretched into the old picture's box (issue #46). Pure — + * reads the drawing's current ``, mutates nothing. + * + * - `keepSize`: the old box, verbatim (the caller asserts same shape). + * - `--width`/`--height`: `computeExtentEmu`, exactly as `images add` sizes + * (one axis keeps the new aspect ratio, both are honored as given). + * - default: keep the DISPLAYED width, recompute the height from the new + * image's pixel aspect ratio, then scale down (aspect kept) to fit the text + * area — so a replace can't introduce `overflow="yes"`, and a tall picture + * swapped into a wide banner can't grow taller than the page. + * - new image has no parsed pixel size (emf/wmf/webp/…): keep the old box and + * report `sizeKnown: false` so the caller can say so instead of silently + * distorting. + * + * Returns null when a single-axis override needs an aspect ratio the new image + * doesn't expose — the caller asks for both `--width` and `--height`. */ +export function fitReplacementExtent( + drawing: XmlNode, + source: Pick, + sizing: ReplacementSizing, + textArea: { widthEmu: number; heightEmu: number }, +): ReplacementExtent | null { + const current = currentExtent(drawing); + if (sizing.keepSize) return { ...current, sizeKnown: true }; + + if (sizing.widthInches !== undefined || sizing.heightInches !== undefined) { + const extent = computeExtentEmu(source, sizing, textArea.widthEmu); + return extent ? { ...extent, sizeKnown: true } : null; + } + + const { pixelWidth, pixelHeight } = source; + if (!pixelWidth || !pixelHeight) return { ...current, sizeKnown: false }; + // A frame with no readable width falls back to the native size, like `add`. + const extent = + current.widthEmu > 0 + ? { + widthEmu: current.widthEmu, + heightEmu: Math.round((current.widthEmu * pixelHeight) / pixelWidth), + } + : computeExtentEmu(source, {}); + if (!extent) return null; + return { ...fitWithin(extent, textArea), sizeKnown: true }; +} + +/** Scale an extent down (never up), aspect kept, until it fits `bounds`. A + * non-positive bound is treated as unknown and doesn't constrain. */ +function fitWithin( + extent: { widthEmu: number; heightEmu: number }, + bounds: { widthEmu: number; heightEmu: number }, +): { widthEmu: number; heightEmu: number } { + const ratio = (limit: number, size: number) => + limit > 0 && size > limit ? limit / size : 1; + const scale = Math.min( + ratio(bounds.widthEmu, extent.widthEmu), + ratio(bounds.heightEmu, extent.heightEmu), + ); + if (scale === 1) return extent; + return { + widthEmu: Math.round(extent.widthEmu * scale), + heightEmu: Math.round(extent.heightEmu * scale), + }; +} + +/** Apply a replacement frame to a drawing IN PLACE: both extents (`` + * on the inline/anchor and `` in `pic:spPr/a:xfrm`, which must agree), + * drop any `` crop (it's in the OLD image's coordinates and would + * mis-crop the new one), and reset a floating image's tight/through + * `` to the full frame (it traced the OLD picture's outline). */ +export function applyReplacementExtent( + drawing: XmlNode, + extent: { widthEmu: number; heightEmu: number }, +): void { + const frame = drawingFrame(drawing); + if (!frame) return; + const cx = String(extent.widthEmu); + const cy = String(extent.heightEmu); + + const frameExtent = frame.findChild("wp:extent"); + frameExtent?.setAttribute("cx", cx); + frameExtent?.setAttribute("cy", cy); + + const shapeExtent = frame + .findDescendant("pic:spPr") + ?.findChild("a:xfrm") + ?.findChild("a:ext"); + shapeExtent?.setAttribute("cx", cx); + shapeExtent?.setAttribute("cy", cy); + + const blipFill = frame.findDescendant("pic:blipFill"); + if (blipFill) { + blipFill.children = blipFill.children.filter( + (child) => child.tag !== "a:srcRect", + ); + } + + for (const wrapTag of ["wp:wrapTight", "wp:wrapThrough"]) { + const polygon = frame.findChild(wrapTag)?.findChild("wp:wrapPolygon"); + if (polygon) polygon.children = fullFramePolygon(); + } +} + +/** The `` / `` child of a `` — the element + * that carries the displayed size. */ +function drawingFrame(drawing: XmlNode): XmlNode | undefined { + return drawing.children.find( + (child) => child.tag === "wp:inline" || child.tag === "wp:anchor", + ); +} + +function currentExtent(drawing: XmlNode): { + widthEmu: number; + heightEmu: number; +} { + const extent = drawingFrame(drawing)?.findChild("wp:extent"); + const widthEmu = Number(extent?.getAttribute("cx") ?? "0"); + const heightEmu = Number(extent?.getAttribute("cy") ?? "0"); + return { + widthEmu: Number.isFinite(widthEmu) ? widthEmu : 0, + heightEmu: Number.isFinite(heightEmu) ? heightEmu : 0, + }; +} + +/** A wrap polygon around the whole frame. Wrap-polygon coordinates are in a + * fixed 21600×21600 space relative to the extent, so this rectangle stays + * correct whatever size the frame becomes. */ +function fullFramePolygon(): XmlNode[] { + const point = (tag: string, x: number, y: number) => + XmlNode.element(tag, { x: String(x), y: String(y) }); + return [ + point("wp:start", 0, 0), + point("wp:lineTo", 0, WRAP_POLYGON_SPAN), + point("wp:lineTo", WRAP_POLYGON_SPAN, WRAP_POLYGON_SPAN), + point("wp:lineTo", WRAP_POLYGON_SPAN, 0), + point("wp:lineTo", 0, 0), + ]; +} + +const WRAP_POLYGON_SPAN = 21600; + +export type ReplacementSizing = { + widthInches?: number; + heightInches?: number; + keepSize?: boolean; +}; + +type ReplacementExtent = { + widthEmu: number; + heightEmu: number; + /** False when the new image's pixel size is unknown and the old box was + * kept as-is (it may not match the new image's shape). */ + sizeKnown: boolean; +}; diff --git a/src/core/index.ts b/src/core/index.ts index 46d8b4b..1e744ea 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -133,6 +133,7 @@ export { } from "./render"; export { applyPageGeometry, + getPageContentHeightEmu, getPageContentWidthEmu, inheritGoverningSection, isSectionType, diff --git a/src/core/sections.tsx b/src/core/sections.tsx index fe5c86a..d2cfd40 100644 --- a/src/core/sections.tsx +++ b/src/core/sections.tsx @@ -7,32 +7,56 @@ import type { TrackedMeta } from "./track-changes"; const EMU_PER_TWIP = 635; /** US Letter (12240 twip) with 1″ (1440 twip) margins → 6.5″ content width. */ const DEFAULT_CONTENT_WIDTH_EMU = (12240 - 1440 - 1440) * EMU_PER_TWIP; +/** US Letter (15840 twip) with 1″ margins → 9″ content height. */ +const DEFAULT_CONTENT_HEIGHT_EMU = (15840 - 1440 - 1440) * EMU_PER_TWIP; /** Page content width in EMU (page width − left/right margins), read from the * document's trailing `` (``/``, in twips). Falls * back to US-Letter-with-1″-margins when section properties are absent or * malformed. Used to clamp inserted images so they don't spill into margins. */ export function getPageContentWidthEmu(document: Document): number { + return pageContentSpanEmu( + document, + ["w:w", "w:left", "w:right"], + DEFAULT_CONTENT_WIDTH_EMU, + ); +} + +/** Page content height in EMU (page height − top/bottom margins), the vertical + * twin of `getPageContentWidthEmu`. A negative top/bottom margin (content may + * not overlap the header) still bounds the text area by its magnitude. Used to + * keep a replaced image from growing taller than the page. */ +export function getPageContentHeightEmu(document: Document): number { + return pageContentSpanEmu( + document, + ["w:h", "w:top", "w:bottom"], + DEFAULT_CONTENT_HEIGHT_EMU, + ); +} + +function pageContentSpanEmu( + document: Document, + [sizeAttribute, startMargin, endMargin]: [string, string, string], + fallbackEmu: number, +): number { const root = XmlNode.findRoot(document.documentTree, "w:document"); const body = root?.findChild("w:body"); const sectPr = body?.children .filter((child) => child.tag === "w:sectPr") .pop(); - const width = Number(sectPr?.findChild("w:pgSz")?.getAttribute("w:w")); + const size = Number(sectPr?.findChild("w:pgSz")?.getAttribute(sizeAttribute)); const pgMar = sectPr?.findChild("w:pgMar"); - const left = Number(pgMar?.getAttribute("w:left")); - const right = Number(pgMar?.getAttribute("w:right")); + const start = Math.abs(Number(pgMar?.getAttribute(startMargin))); + const end = Math.abs(Number(pgMar?.getAttribute(endMargin))); if ( - !Number.isFinite(width) || - !Number.isFinite(left) || - !Number.isFinite(right) + !Number.isFinite(size) || + !Number.isFinite(start) || + !Number.isFinite(end) ) { - return DEFAULT_CONTENT_WIDTH_EMU; + return fallbackEmu; } - const contentTwips = width - left - right; - return contentTwips > 0 - ? contentTwips * EMU_PER_TWIP - : DEFAULT_CONTENT_WIDTH_EMU; + const contentTwips = size - start - end; + return contentTwips > 0 ? contentTwips * EMU_PER_TWIP : fallbackEmu; } export type SectionProperties = { diff --git a/tests/cli/images.test.ts b/tests/cli/images.test.ts index e84b8cd..b1692f3 100644 --- a/tests/cli/images.test.ts +++ b/tests/cli/images.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { Document, XmlNode } from "@core"; import { Pkg } from "@core/ast/document/package"; -import { runCli, tempWorkspace } from "./harness"; +import { runCli, spawnCli, tempWorkspace } from "./harness"; import { readMarkdown, trackedKinds } from "./helpers"; const FIXTURES = join(import.meta.dir, "..", "fixtures"); @@ -1159,3 +1159,207 @@ describe("docx images add — size units", () => { expect(height.result.exitCode).toBe(2); }); }); + +// Issue #46: replace used to keep the old , stretching the new +// picture into the old picture's box. The frame is now refitted. +describe("docx images replace — refits the frame to the new picture", () => { + const TALL_PATH = join(ASSETS, "tall.png"); // 48×144, 1:3 + + async function docWithWideImage(label: string, width = "2"): Promise { + const docPath = await newDoc(label); + await runCli( + "images", + "add", + docPath, + "--after", + "p0", + "--image", + PNG_PATH, + "--width", + width, + ); + return docPath; + } + + async function replace(docPath: string, ...flags: string[]) { + // spawnCli: the default text confirmation (runCli injects --verbose). + const result = await spawnCli( + "images", + "replace", + docPath, + "--at", + "img0", + ...flags, + ); + return { ...result, stdout: result.stdout.trim() }; + } + + async function sizeHint(docPath: string): Promise { + const markdown = await readMarkdown(docPath); + return markdown.match(/docx:image img0 size="([^"]+)in"/)?.[1]; + } + + test("keeps the displayed width and recomputes the height (wide → tall)", async () => { + const docPath = await docWithWideImage("refit-default"); + expect(await sizeHint(docPath)).toBe("2x1.33"); + + const result = await replace(docPath, "--with", TALL_PATH); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe("images.replace img0 (2x6in)"); + expect(await sizeHint(docPath)).toBe("2x6"); + + // and the shape's agree. + const xml = await (await Pkg.open(docPath)).readText("word/document.xml"); + const cx = 2 * EMU_PER_INCH; + const cy = 6 * EMU_PER_INCH; + expect(xml).toContain(``); + expect(xml).toContain(``); + }); + + test("never grows past the text area", async () => { + // 4in wide at 1:3 would be 12in tall on a 9in-tall text area. + const tallDoc = await docWithWideImage("refit-clamp-height", "4"); + await replace(tallDoc, "--with", TALL_PATH); + expect(await sizeHint(tallDoc)).toBe("3x9"); + + // An already-overflowing 8in image is brought inside the 6.5in column. + const wideDoc = await docWithWideImage("refit-clamp-width", "8"); + await replace(wideDoc, "--with", JPG_PATH); + expect(await sizeHint(wideDoc)).toBe("6.5x4.33"); + expect(await readMarkdown(wideDoc)).not.toContain('overflow="yes"'); + }); + + test("--width or --height alone keeps the new aspect; both are honored", async () => { + const docPath = await docWithWideImage("refit-explicit"); + expect( + (await replace(docPath, "--with", TALL_PATH, "--width", "1in")).stdout, + ).toBe("images.replace img0 (1x3in)"); + expect( + (await replace(docPath, "--with", TALL_PATH, "--height", "1.5")).stdout, + ).toBe("images.replace img0 (0.5x1.5in)"); + expect( + ( + await replace( + docPath, + "--with", + TALL_PATH, + "--width", + "2", + "--height", + "1", + ) + ).stdout, + ).toBe("images.replace img0 (2x1in)"); + }); + + test("--keep-size keeps the old box; it can't be combined with --width", async () => { + const docPath = await docWithWideImage("refit-keep"); + expect( + (await replace(docPath, "--with", JPG_PATH, "--keep-size")).stdout, + ).toBe("images.replace img0 (2x1.33in)"); + const conflict = await replace( + docPath, + "--with", + TALL_PATH, + "--keep-size", + "--width", + "1", + ); + expect(conflict.exitCode).toBe(2); + expect(await sizeHint(docPath)).toBe("2x1.33"); + }); + + test("a format with no parsed pixel size keeps the box and says so", async () => { + const docPath = await docWithWideImage("refit-emf"); + const emfPath = join(tempWorkspace("refit-emf-src"), "logo.emf"); + await Bun.write(emfPath, new Uint8Array([1, 0, 0, 0, 0x6c, 0, 0, 0])); + + const kept = await replace(docPath, "--with", emfPath); + expect(kept.exitCode).toBe(0); + expect(kept.stdout).toContain("images.replace img0 (2x1.33in)"); + expect(kept.stdout).toContain("size unknown for .emf"); + + // One axis needs an aspect ratio the emf doesn't expose: refuse, write nothing. + const before = await Bun.file(docPath).bytes(); + const oneAxis = await replace(docPath, "--with", emfPath, "--width", "1"); + expect(oneAxis.exitCode).toBe(2); + expect(await Bun.file(docPath).bytes()).toEqual(before); + + const both = await replace( + docPath, + "--with", + emfPath, + "--width", + "1", + "--height", + "2", + ); + expect(both.stdout).toBe("images.replace img0 (1x2in)"); + }); + + test("a cropped floating image loses its crop and takes the new aspect", async () => { + const docPath = join(tempWorkspace("refit-anchor"), "doc.docx"); + await Bun.write(docPath, Bun.file(join(FIXTURES, "large-mixed.docx"))); + const imageId = "img10"; // with an crop + const drawingXml = async (): Promise => { + const document = await Document.open(docPath); + const ordinal = Number(imageId.slice(3)); + const { Images } = await import("@core/image"); + const run = new Images(document).list()[ordinal]?.run; + return run ? XmlNode.serialize([run]) : ""; + }; + const before = await drawingXml(); + expect(before).toContain(" { + const docPath = await docWithWideImage("refit-shared"); + // Duplicate the drawing run (same rId) into p0 at a different width. + const document = await Document.open(docPath); + const { Images } = await import("@core/image"); + const [hit] = new Images(document).list(); + if (!hit) throw new Error("no image"); + const [copy] = XmlNode.parse( + XmlNode.serialize([hit.run]).replaceAll( + String(2 * EMU_PER_INCH), + String(EMU_PER_INCH), + ), + ); + const firstParagraph = XmlNode.findRoot( + document.documentTree, + "w:document", + )?.findDescendant("w:p"); + if (!copy || !firstParagraph) throw new Error("setup failed"); + firstParagraph.children.push(copy); + await document.save(); + + const result = await replace(docPath, "--with", TALL_PATH); + expect(result.exitCode).toBe(0); + const markdown = await readMarkdown(docPath); + expect(markdown).toMatch(/docx:image img0 size="1x3in"/); + expect(markdown).toMatch(/docx:image img1 size="2x6in"/); + // img0 is the 1in copy in p0 (document order); the ack names it. + expect(result.stdout).toBe("images.replace img0 (1x3in)"); + }); +}); diff --git a/tests/core/image-refit.test.ts b/tests/core/image-refit.test.ts new file mode 100644 index 0000000..cc8aa95 --- /dev/null +++ b/tests/core/image-refit.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, test } from "bun:test"; +import { XmlNode } from "@core"; +import { applyReplacementExtent, fitReplacementExtent } from "@core/image"; + +const EMU_PER_INCH = 914400; +const LETTER_TEXT_AREA = { + widthEmu: 6.5 * EMU_PER_INCH, + heightEmu: 9 * EMU_PER_INCH, +}; + +function drawing(frame: string): XmlNode { + const [node] = XmlNode.parse(`${frame}`); + if (!node) throw new Error("parse failed"); + return node; +} + +const WIDE_INLINE = ``; + +describe("fitReplacementExtent", () => { + const tall = { pixelWidth: 100, pixelHeight: 400 }; + + test("default keeps the displayed width and recomputes the height", () => { + const fit = fitReplacementExtent( + drawing( + WIDE_INLINE.replaceAll( + String(4 * EMU_PER_INCH), + String(2 * EMU_PER_INCH), + ), + ), + tall, + {}, + LETTER_TEXT_AREA, + ); + expect(fit).toEqual({ + widthEmu: 2 * EMU_PER_INCH, + heightEmu: 8 * EMU_PER_INCH, + sizeKnown: true, + }); + }); + + test("default scales down (aspect kept) to fit the text area", () => { + // 4in wide at 1:4 would be 16in tall — fit to the 9in text height. + const fit = fitReplacementExtent( + drawing(WIDE_INLINE), + tall, + {}, + LETTER_TEXT_AREA, + ); + expect(fit?.heightEmu).toBe(9 * EMU_PER_INCH); + expect(fit?.widthEmu).toBe(2.25 * EMU_PER_INCH); + }); + + test("unknown pixel size keeps the old box and says so", () => { + const fit = fitReplacementExtent( + drawing(WIDE_INLINE), + {}, + {}, + LETTER_TEXT_AREA, + ); + expect(fit).toEqual({ + widthEmu: 4 * EMU_PER_INCH, + heightEmu: EMU_PER_INCH, + sizeKnown: false, + }); + }); + + test("one explicit axis needs an aspect ratio", () => { + expect( + fitReplacementExtent( + drawing(WIDE_INLINE), + {}, + { widthInches: 1 }, + LETTER_TEXT_AREA, + ), + ).toBeNull(); + expect( + fitReplacementExtent( + drawing(WIDE_INLINE), + {}, + { widthInches: 1, heightInches: 2 }, + LETTER_TEXT_AREA, + ), + ).toEqual({ + widthEmu: EMU_PER_INCH, + heightEmu: 2 * EMU_PER_INCH, + sizeKnown: true, + }); + }); +}); + +describe("applyReplacementExtent", () => { + test("updates both extents and drops the crop", () => { + const node = drawing(WIDE_INLINE); + applyReplacementExtent(node, { widthEmu: 100, heightEmu: 400 }); + const xml = XmlNode.serialize([node]); + expect(xml).toContain(''); + expect(xml).toContain(''); + expect(xml).not.toContain("a:srcRect"); + expect(xml).toContain(""); + }); + + test("resets a floating image's wrap polygon to the full frame", () => { + const node = drawing( + ``, + ); + applyReplacementExtent(node, { widthEmu: 20, heightEmu: 40 }); + const xml = XmlNode.serialize([node]); + expect(xml).toContain(''); + expect(xml).toContain( + '', + ); + }); +}); diff --git a/tests/fixtures/assets/tall.png b/tests/fixtures/assets/tall.png new file mode 100644 index 0000000..18c64fc Binary files /dev/null and b/tests/fixtures/assets/tall.png differ diff --git a/tests/fixtures/images.docx b/tests/fixtures/images.docx index 6a78d09..d7382cc 100644 Binary files a/tests/fixtures/images.docx and b/tests/fixtures/images.docx differ diff --git a/tests/fixtures/setup/images.ts b/tests/fixtures/setup/images.ts index f4125ad..0bcdc69 100644 --- a/tests/fixtures/setup/images.ts +++ b/tests/fixtures/setup/images.ts @@ -17,6 +17,9 @@ process.env.DOCX_CLI_NOW ??= "2026-05-22T00:00:00Z"; * 4. PNG sized with unit suffixes (`--width 4cm`, then `--height 96px` on a * fifth copy) — the shared length grammar, which used to read `4cm` as * 4 INCHES. + * 5. A wide PNG swapped for a TALL one via `docx images replace` — the frame + * keeps its displayed width and the height follows the new aspect ratio + * (it used to keep the old box, squashing the new picture: issue #46). * The page itself is A4 with 2cm margins via `create --size 210x297mm * --margins 2cm` (WxH with a unit suffix — inches-only before). * @@ -37,6 +40,7 @@ async function cli(...args: string[]): Promise { mkdirSync(dirname(out), { recursive: true }); const pngPath = resolve(assets, "sample.png"); +const tallPngPath = resolve(assets, "tall.png"); // 48×144, a 1:3 portrait const jpgBytes = await Bun.file(resolve(assets, "sample.jpg")).bytes(); const jpgDataUri = `data:image/jpeg;base64,${Buffer.from(jpgBytes).toString("base64")}`; @@ -121,5 +125,28 @@ await cli( "96px", ); +await cli( + "insert", + out, + "--after", + "p9", + "--text", + "Wide PNG replaced by a tall PNG (width kept, height follows)", +); +await cli( + "images", + "add", + out, + "--after", + "p10", + "--image", + pngPath, + "--alt", + "Replaced PNG", + "--width", + "1in", +); +await cli("images", "replace", out, "--at", "img5", "--with", tallPngPath); + const bytes = (await Bun.file(out).bytes()).length; console.log(`Wrote ${out} (${bytes} bytes)`);