diff --git a/docs/usage/patcher.md b/docs/usage/patcher.md index c182078592..9c29ec88c3 100644 --- a/docs/usage/patcher.md +++ b/docs/usage/patcher.md @@ -29,7 +29,7 @@ fs.writeFileSync("My Patched Document.docx", doc); Use `patchDetector({ data })` to find the placeholder keys in a template before calling `patchDocument`. It returns distinct keys without the `{{` and `}}` delimiters. This is useful when templates differ: an expensive patch, such as downloading images, only needs to be built when its placeholder is present. -This discovery workflow supports only `{{...}}` placeholders. `patchDetector` does not accept the custom `placeholderDelimiters` supported by `patchDocument`. +If the template's placeholders have other delimiters, such as `<>`, give `patchDetector` the same `placeholderDelimiters` as `patchDocument`, such as `{ start: "<<", end: ">>" }`. If the template's placeholders can have spaces inside their braces, such as `{{ name }}`, give both `patchDetector` and `patchDocument` `trimPlaceholders: true`. `patchDetector` then gives the key as `name`, and `patchDocument` patches the placeholder with the patch `name`. See [Spaces inside placeholders](usage/templates.md#spaces-inside-placeholders). @@ -57,7 +57,7 @@ const doc = await patchDocument({ outputType: "nodebuffer", data, patches: Objec fs.writeFileSync("My Patched Document.docx", doc); ``` -This example patches only keys with a registered builder; other placeholders remain in the document. If every placeholder must be resolved, validate the detected keys against your builders and report unsupported keys before patching. Detection discovers keys; it does not generate replacement content or call `patchDocument` for you. +This example patches only keys with a registered builder; other placeholders remain in the document. To find patches whose placeholder isn't in the template, which `patchDocument` leaves out without an error, see [A placeholder isn't replaced](usage/templates.md#a-placeholder-isnt-replaced). If every placeholder must be resolved, validate the detected keys against your builders and report unsupported keys before patching. Detection discovers keys; it does not generate replacement content or call `patchDocument` for you. ## Patches @@ -81,6 +81,8 @@ A paragraph in a patch can be a heading. Its style is added to a template that d The patcher also takes in a `keepOriginalStyles` boolean, which will preserve the styles of the patched text when set to true. +It also takes in `placeholderDelimiters`, for a template whose placeholders aren't in double curly braces, such as `{ start: "<<", end: ">>" }` for `<>`. + It also takes in a `trimPlaceholders` boolean, which patches a placeholder with spaces inside its delimiters, such as `{{ name }}`, as if it had none. See [Spaces inside placeholders](usage/templates.md#spaces-inside-placeholders). It also takes in `footnotes` and `endnotes`, for the notes that patches refer to with a `FootnoteReferenceRun` or an `EndnoteReferenceRun`. See [Footnotes and endnotes](usage/templates.md#footnotes-and-endnotes). diff --git a/docs/usage/templates.md b/docs/usage/templates.md index 5e7e360e49..d0e2d7ffa6 100644 --- a/docs/usage/templates.md +++ b/docs/usage/templates.md @@ -64,6 +64,65 @@ fs.writeFileSync("output.docx", doc); - Only the placeholders of the patches given lose their spaces. Other text that looks like a placeholder, such as `{{ not_patched }}`, is left as it is. - [`patchDetector`](usage/patcher.md#discover-placeholders-before-building-patches) takes `trimPlaceholders` too, and then gives the key of `{{ customer_name }}` as `customer_name`. +### Placeholders in links, content controls and tracked changes + +A placeholder is patched wherever it is in a paragraph's text: in a link's text, in a content control, in text typed with Track Changes on, or in a field's result. The patch's content goes where the placeholder was, so the text of a link stays linked, and a tracked insertion stays tracked: + +```ts live +import * as fs from "fs"; +import { Document, ExternalHyperlink, InsertedTextRun, Packer, Paragraph, patchDocument, PatchType, TextRun } from "docx"; + +// The template, made here as it would be in Word: a link whose text is a placeholder, and a placeholder typed with Track Changes on +const template = new Document({ + sections: [ + { + children: [ + new Paragraph({ + children: [ + new TextRun("Our website: "), + new ExternalHyperlink({ + link: "https://example.com", + children: [new TextRun({ text: "{{site}}", style: "Hyperlink" })], + }), + ], + }), + new Paragraph({ + children: [ + new InsertedTextRun({ + text: "Dear {{customer_name}},", + id: 1, + author: "Template author", + date: "2024-05-01T00:00:00Z", + }), + ], + }), + ], + }, + ], +}); + +const doc = await patchDocument({ + outputType: "nodebuffer", + data: await Packer.toBuffer(template), + patches: { + site: { type: PatchType.PARAGRAPH, children: [new TextRun("example.com")] }, + customer_name: { type: PatchType.PARAGRAPH, children: [new TextRun("John Smith")] }, + }, +}); + +fs.writeFileSync("output.docx", doc); +``` + +Where the content can't go in what holds the placeholder, it goes as close as it can, so Word opens the document: + +- **A link in a tracked insertion**: a tracked insertion can't hold a link, so the link goes between two parts of the insertion and isn't tracked, as when a link is added with Track Changes off. +- **A link in a link**: the patch's link takes the place of the template's link where the placeholder was, and the text around it keeps the template's link. +- **A plain text content control**: given anything but text, such as a link, a picture, a field or a symbol, it becomes a rich text content control, as Word won't open a plain text one holding it. +- **A content control showing its placeholder text**: if `{{name}}` is the control's placeholder text, the control shows the patch's content as its own, with the control's formatting rather than the grey of placeholder text. +- **A content control bound to custom XML or a document property**: the binding is removed, as Word fills a bound control in from its data when it opens the document, which would put the placeholder back. + +Deleted text, which Word shows struck through when Track Changes is on, isn't the document's text, so a placeholder in it isn't patched. + ## Basic Usage ```ts live @@ -776,6 +835,46 @@ const doc = await patchDocument({ fs.writeFileSync("invoice-output.docx", doc); ``` +## A placeholder isn't replaced + +`patchDocument` doesn't throw for a patch whose placeholder isn't in the template, as one set of patches can be given to templates that don't all have every placeholder. The placeholder is left as it is. To find such patches, compare their keys with the placeholders [`patchDetector`](usage/patcher.md#discover-placeholders-before-building-patches) finds, giving it the same `placeholderDelimiters` and `trimPlaceholders` as `patchDocument`: + +```ts live +import * as fs from "fs"; +import { Document, Packer, Paragraph, patchDetector, patchDocument, PatchType, TextRun } from "docx"; + +// The template, with one placeholder typed in single braces +const template = await Packer.toBuffer( + new Document({ + sections: [{ children: [new Paragraph("Dear {{customer_name}},"), new Paragraph("Your order: {order_number}")] }], + }), +); + +const patches = { + customer_name: { type: PatchType.PARAGRAPH, children: [new TextRun("John Smith")] }, + order_number: { type: PatchType.PARAGRAPH, children: [new TextRun("12345")] }, +}; + +// The patches whose placeholder isn't in the template. Here it's ["order_number"], as the template has {order_number} +const found = await patchDetector({ data: template }); +const notFound = Object.keys(patches).filter((key) => !found.includes(key)); +console.log("No placeholder for:", notFound); + +const doc = await patchDocument({ outputType: "nodebuffer", data: template, patches }); + +fs.writeFileSync("output.docx", doc); +``` + +A patch whose placeholder isn't found is usually one of these: + +- **The key has the delimiters**: the key of `{{customer_name}}` is `customer_name`, not `"{{customer_name}}"`, which is looked for as `{{{{customer_name}}}}`. +- **The key isn't spelled as the placeholder is**: keys match exactly, including upper and lower case. +- **The template has other delimiters**, such as `{name}`, `<>` or `[name]`: give `patchDocument` and `patchDetector` the template's delimiters, such as `placeholderDelimiters: { start: "<<", end: ">>" }`. +- **Spaces inside the delimiters**, such as `{{ name }}`: see [Spaces inside placeholders](#spaces-inside-placeholders). +- **The placeholder is only in a picture's or a chart's alt text**: only an [`ImagePatch`](#replacing-a-picture) or a `ChartDataPatch` patches it, and a text patch leaves it as it is. `patchDetector` finds placeholders in alt text too, so the check above doesn't list this patch. + +A placeholder in deleted text, which Word shows struck through when Track Changes is on, isn't patched or found, nor is one in a chart's own text, such as its title. + ## Tips - **Placeholder naming**: Use descriptive names like `customer_name` instead of `x1` diff --git a/src/patcher/from-docx.ts b/src/patcher/from-docx.ts index 7e3c8f5818..04722134b7 100644 --- a/src/patcher/from-docx.ts +++ b/src/patcher/from-docx.ts @@ -44,7 +44,7 @@ import { patchStyles } from "./styles"; import { patchTableRows } from "./table-rows"; import { readThemeColors } from "./theme-colors"; import { trimPlaceholders as trimPlaceholdersIn } from "./trim-placeholders"; -import { decodeUtf8, toJson } from "./util"; +import { checkPlaceholderDelimiters, decodeUtf8, toJson } from "./util"; import { removeShapeTypesIn } from "./vml-shape-types"; /** @@ -382,9 +382,7 @@ export const patchDocument = async (); - if (!placeholderDelimiters?.start.trim() || !placeholderDelimiters?.end.trim()) { - throw new Error("Both start and end delimiters must be non-empty strings."); - } + checkPlaceholderDelimiters(placeholderDelimiters); const { start, end } = placeholderDelimiters; for (const [key, patch] of Object.entries(patches)) { diff --git a/src/patcher/paragraph-split-inject.spec.ts b/src/patcher/paragraph-split-inject.spec.ts index 1ecd5f98e2..5481c42440 100644 --- a/src/patcher/paragraph-split-inject.spec.ts +++ b/src/patcher/paragraph-split-inject.spec.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from "vitest"; -import { findRunElementIndexWithToken, splitRunElement } from "./paragraph-split-inject"; +import { findRunElementPathWithToken, splitRunElement } from "./paragraph-split-inject"; describe("paragraph-split-inject", () => { - describe("findRunElementIndexWithToken", () => { - it("should find the index of a run element with a token", () => { - const output = findRunElementIndexWithToken( + describe("findRunElementPathWithToken", () => { + it("should find the path to a run element with a token", () => { + const output = findRunElementPathWithToken( { name: "w:p", type: "element", @@ -30,12 +30,12 @@ describe("paragraph-split-inject", () => { }, "hello", ); - expect(output).to.deep.equal(0); + expect(output).to.deep.equal([0]); }); it("should throw an exception when ran with empty elements", () => { expect(() => - findRunElementIndexWithToken( + findRunElementPathWithToken( { name: "w:p", type: "element", @@ -47,7 +47,7 @@ describe("paragraph-split-inject", () => { it("should throw an exception when ran with empty elements", () => { expect(() => - findRunElementIndexWithToken( + findRunElementPathWithToken( { name: "w:p", type: "element", @@ -65,7 +65,7 @@ describe("paragraph-split-inject", () => { it("should throw an exception when ran with empty elements", () => { expect(() => - findRunElementIndexWithToken( + findRunElementPathWithToken( { name: "w:p", type: "element", @@ -89,7 +89,7 @@ describe("paragraph-split-inject", () => { it("should continue if text run doesn't have text", () => { expect(() => - findRunElementIndexWithToken( + findRunElementPathWithToken( { name: "w:p", type: "element", @@ -113,7 +113,7 @@ describe("paragraph-split-inject", () => { it("should continue if text run doesn't have text", () => { expect(() => - findRunElementIndexWithToken( + findRunElementPathWithToken( { name: "w:p", type: "element", diff --git a/src/patcher/paragraph-split-inject.ts b/src/patcher/paragraph-split-inject.ts index be4f2dd162..9dd5785c53 100644 --- a/src/patcher/paragraph-split-inject.ts +++ b/src/patcher/paragraph-split-inject.ts @@ -6,6 +6,7 @@ import type { XmlElement as Element } from "@util/xml"; +import { renderParagraphNode } from "./run-renderer"; import { createTextElementContents, patchSpaceAttribute } from "./util"; export class TokenNotFoundError extends Error { @@ -16,42 +17,34 @@ export class TokenNotFoundError extends Error { } /** - * Finds the index of the run element containing a specific token. + * Finds the run element containing a specific token. * - * Searches through all run (w:r) elements in a paragraph to find which one - * contains the specified token text. This is used to locate where new content - * should be injected during replacement operations. + * Searches through all run (w:r) elements in a paragraph, including those in a link, + * content control or tracked insertion, to find which one contains the specified + * token text. This is used to locate where new content should be injected during + * replacement operations. * * @param paragraphElement - The paragraph element to search * @param token - The token text to find - * @returns The index of the run element containing the token + * @returns The position indices from the paragraph to the run element containing the token * @throws Error if the token is not found in any run * * @example * ```typescript - * const index = findRunElementIndexWithToken(paragraph, "ɵ"); - * // Returns the index of the run containing the split token + * const path = findRunElementPathWithToken(paragraph, "ɵ"); + * // Returns [0] for the paragraph's first run, or [2, 1] for the second run in a link that is its third element * ``` */ -export const findRunElementIndexWithToken = (paragraphElement: Element, token: string): number => { - for (let i = 0; i < (paragraphElement.elements ?? []).length; i++) { - const element = paragraphElement.elements![i]; - if (element.type === "element" && element.name === "w:r") { - const textElement = (element.elements ?? []).filter((e) => e.type === "element" && e.name === "w:t"); +export const findRunElementPathWithToken = (paragraphElement: Element, token: string): readonly number[] => { + const run = renderParagraphNode({ element: paragraphElement, index: 0, parent: undefined }).runs.find(({ parts }) => + parts.some(({ text }) => text.includes(token)), + ); - for (const text of textElement) { - if (!text.elements?.[0]) { - continue; - } - - if ((text.elements[0].text as string)?.includes(token)) { - return i; - } - } - } + if (!run) { + throw new TokenNotFoundError(token); } - throw new TokenNotFoundError(token); + return run.path; }; // cspell:words Helloɵworld diff --git a/src/patcher/paragraph-token-replacer.spec.ts b/src/patcher/paragraph-token-replacer.spec.ts index 4ad7d72dea..b3d92cc8a0 100644 --- a/src/patcher/paragraph-token-replacer.spec.ts +++ b/src/patcher/paragraph-token-replacer.spec.ts @@ -31,7 +31,7 @@ describe("paragraph-token-replacer", () => { runs: [ { end: 4, - index: 0, + path: [0], parts: [ { end: 4, @@ -123,9 +123,9 @@ describe("paragraph-token-replacer", () => { renderedParagraph: { text: "Hello {{name}} World", runs: [ - { text: "Hello ", parts: [{ text: "Hello ", index: 0, start: 0, end: 5 }], index: 1, start: 0, end: 5 }, - { text: "{{name}} ", parts: [{ text: "{{name}} ", index: 0, start: 6, end: 14 }], index: 2, start: 6, end: 14 }, - { text: "World", parts: [{ text: "World", index: 0, start: 15, end: 19 }], index: 3, start: 15, end: 19 }, + { text: "Hello ", parts: [{ text: "Hello ", index: 0, start: 0, end: 5 }], path: [1], start: 0, end: 5 }, + { text: "{{name}} ", parts: [{ text: "{{name}} ", index: 0, start: 6, end: 14 }], path: [2], start: 6, end: 14 }, + { text: "World", parts: [{ text: "World", index: 0, start: 15, end: 19 }], path: [3], start: 15, end: 19 }, ], index: 0, pathToParagraph: [0, 1, 0, 0], @@ -252,7 +252,7 @@ describe("paragraph-token-replacer", () => { runs: [ { end: 0, - index: 0, + path: [0], parts: [ { end: 0, @@ -266,7 +266,7 @@ describe("paragraph-token-replacer", () => { }, { end: 5, - index: 1, + path: [1], parts: [ { end: 5, @@ -332,9 +332,9 @@ describe("paragraph-token-replacer", () => { renderedParagraph: { text: "{{name}} world", runs: [ - { text: "{{na", parts: [{ text: "{{na", index: 0, start: 0, end: 3 }], index: 0, start: 0, end: 3 }, - { text: "me}}", parts: [{ text: "me}}", index: 0, start: 4, end: 7 }], index: 1, start: 4, end: 7 }, - { text: " world", parts: [{ text: " world", index: 0, start: 8, end: 13 }], index: 2, start: 8, end: 13 }, + { text: "{{na", parts: [{ text: "{{na", index: 0, start: 0, end: 3 }], path: [0], start: 0, end: 3 }, + { text: "me}}", parts: [{ text: "me}}", index: 0, start: 4, end: 7 }], path: [1], start: 4, end: 7 }, + { text: " world", parts: [{ text: " world", index: 0, start: 8, end: 13 }], path: [2], start: 8, end: 13 }, ], index: 0, pathToParagraph: [0], @@ -373,7 +373,7 @@ describe("paragraph-token-replacer", () => { { text: "Name:", index: 0, start: 0, end: 4 }, { text: "{{name}}", index: 2, start: 5, end: 12 }, ], - index: 0, + path: [0], start: 0, end: 12, }, @@ -400,7 +400,7 @@ describe("paragraph-token-replacer", () => { { text: "{{name}} {{name}}", parts: [{ text: "{{name}} {{name}}", index: 0, start: 0, end: 16 }], - index: 0, + path: [0], start: 0, end: 16, }, diff --git a/src/patcher/paragraph-token-replacer.ts b/src/patcher/paragraph-token-replacer.ts index 4d1e7ecbef..46cd87f398 100644 --- a/src/patcher/paragraph-token-replacer.ts +++ b/src/patcher/paragraph-token-replacer.ts @@ -6,7 +6,7 @@ import type { XmlElement as Element } from "@util/xml"; -import type { IRenderedParagraphNode } from "./run-renderer"; +import { type IRenderedParagraphNode, elementAtPath } from "./run-renderer"; import { createTextElementContents, patchSpaceAttribute } from "./util"; /** @@ -64,6 +64,7 @@ export const replaceTokenInParagraphElement = ({ let replaceMode: (typeof ReplaceMode)[keyof typeof ReplaceMode] = ReplaceMode.START; for (const run of renderedParagraph.runs) { + const runElement = elementAtPath(paragraphElement, run.path); for (const { text, index, start, end } of run.parts) { switch (replaceMode) { case ReplaceMode.START: @@ -80,7 +81,7 @@ export const replaceTokenInParagraphElement = ({ // Replace by position, as the same text can come earlier in the part const firstPart = text.substring(0, offsetStartIndex) + replacementText + text.substring(offsetEndIndex + 1); - patchTextElement(paragraphElement.elements![run.index].elements![index], firstPart); + patchTextElement(runElement.elements![index], firstPart); replaceMode = ReplaceMode.MIDDLE; continue; /* c8 ignore next 2 */ @@ -89,15 +90,15 @@ export const replaceTokenInParagraphElement = ({ case ReplaceMode.MIDDLE: if (endIndex <= end) { const lastPart = text.substring(endIndex - start + 1); - patchTextElement(paragraphElement.elements![run.index].elements![index], lastPart); - const currentElement = paragraphElement.elements![run.index].elements![index]; + patchTextElement(runElement.elements![index], lastPart); + const currentElement = runElement.elements![index]; // We need to add xml:space="preserve" to the last element to preserve the whitespace // Otherwise, the text will be merged with the next element // eslint-disable-next-line functional/immutable-data - paragraphElement.elements![run.index].elements![index] = patchSpaceAttribute(currentElement); + runElement.elements![index] = patchSpaceAttribute(currentElement); replaceMode = ReplaceMode.END; } else { - patchTextElement(paragraphElement.elements![run.index].elements![index], ""); + patchTextElement(runElement.elements![index], ""); } break; default: diff --git a/src/patcher/patch-detector.spec.ts b/src/patcher/patch-detector.spec.ts index 1caff22211..9a67b240e3 100644 --- a/src/patcher/patch-detector.spec.ts +++ b/src/patcher/patch-detector.spec.ts @@ -2,7 +2,7 @@ import { Readable } from "stream"; import { describe, expect, it, vi } from "vitest"; -import { Document, Packer, Paragraph, TextRun } from "../index"; +import { Document, ExternalHyperlink, InsertedTextRun, Packer, Paragraph, SimpleField, TextRun } from "../index"; import { type IPatch, patchDocument } from "./from-docx"; import { patchDetector } from "./patch-detector"; import { PatchType } from "./patch-type"; @@ -406,6 +406,63 @@ describe("patch-detector", () => { expect(await patchDetector({ data })).to.deep.equal([" name ", "name", " ", "first name ", "\tname"]); }); + describe("with placeholderDelimiters", () => { + it("should detect the placeholders patchDocument patches with the same delimiters", async () => { + const data = await Packer.toBuffer( + new Document({ sections: [{ children: [new Paragraph("Dear <>, {{not a placeholder}}")] }] }), + ); + const placeholderDelimiters = { start: "<<", end: ">>" }; + + const keys = await patchDetector({ data, placeholderDelimiters }); + const output = await patchDocument({ + outputType: "nodebuffer", + data, + patches: { name: { type: PatchType.PARAGRAPH, children: [new TextRun("Ada")] } }, + placeholderDelimiters, + }); + + expect(keys).toEqual(["name"]); + expect(textOf(unzip(output), "word/document.xml")).toMatch(/]*>Ada<\/w:t>/); + }); + + it("should look for delimiters with characters a regular expression gives a meaning to as they are", async () => { + const data = await Packer.toBuffer(new Document({ sections: [{ children: [new Paragraph("[[a]] $(b) ((c) .d.")] }] })); + + expect(await patchDetector({ data, placeholderDelimiters: { start: "[[", end: "]]" } })).toEqual(["a"]); + expect(await patchDetector({ data, placeholderDelimiters: { start: "$(", end: ")" } })).toEqual(["b"]); + expect(await patchDetector({ data, placeholderDelimiters: { start: ".", end: "." } })).toEqual(["d"]); + }); + + it("should not let a start delimiter before a placeholder hide it", async () => { + const data = await Packer.toBuffer( + new Document({ sections: [{ children: [new Paragraph("<>"), new Paragraph("a < b and ")] }] }), + ); + + expect(await patchDetector({ data, placeholderDelimiters: { start: "<<", end: ">>" } })).toEqual(["name"]); + expect(await patchDetector({ data, placeholderDelimiters: { start: "<", end: ">" } })).toEqual(["name", "city"]); + }); + + it("should give the keys without the spaces inside the delimiters, with trimPlaceholders", async () => { + const data = await Packer.toBuffer(new Document({ sections: [{ children: [new Paragraph("<< name >> <>")] }] })); + + expect(await patchDetector({ data, placeholderDelimiters: { start: "<<", end: ">>" }, trimPlaceholders: true })).toEqual([ + "name", + "city", + ]); + }); + + it("should throw for a delimiter that is empty or only spaces, as patchDocument does", async () => { + const data = await Packer.toBuffer(new Document({ sections: [{ children: [new Paragraph("<>")] }] })); + + await expect(patchDetector({ data, placeholderDelimiters: { start: "", end: ">>" } })).rejects.toThrow( + "Both start and end delimiters must be non-empty strings.", + ); + await expect(patchDetector({ data, placeholderDelimiters: { start: "<<", end: " " } })).rejects.toThrow( + "Both start and end delimiters must be non-empty strings.", + ); + }); + }); + it("should detect and patch placeholders in a template read from a stream", async () => { const data = await Packer.toBuffer(new Document({ sections: [{ children: [new Paragraph("Hello {{name}}")] }] })); // A stream such as fs.createReadStream gives a template in chunks, and can be read only once @@ -424,6 +481,43 @@ describe("patch-detector", () => { expect(xml).not.toContain("{{name}}"); }); + it("should detect and patch placeholders in a link, a tracked insertion and a field's result, not only in the paragraph", async () => { + const data = await Packer.toBuffer( + new Document({ + sections: [ + { + children: [ + new Paragraph({ + children: [new ExternalHyperlink({ link: "https://example.com", children: [new TextRun("{{site}}")] })], + }), + new Paragraph({ + children: [ + new InsertedTextRun({ text: "Dear {{name}},", id: 1, author: "Author", date: "2024-05-01T00:00:00Z" }), + ], + }), + new Paragraph({ children: [new SimpleField("FILENAME", "{{file}}")] }), + ], + }, + ], + }), + ); + const text = (value: string): IPatch => ({ type: PatchType.PARAGRAPH, children: [new TextRun(value)] }); + + const keys = await patchDetector({ data }); + const output = await patchDocument({ + outputType: "nodebuffer", + data, + patches: { site: text("Example"), name: text("Ada"), file: text("letter.docx") }, + }); + const xml = textOf(unzip(output), "word/document.xml")!; + + expect(keys).toEqual(["site", "name", "file"]); + expect(xml).not.toContain("{{"); + expect(xml).toMatch(/]*>((?:(?!<\/w:r>).)*<\/w:r>)*]*>Example<\/w:t>/); + expect(xml).toMatch(/]*>((?:(?!<\/w:r>).)*<\/w:r>)*]*>Ada<\/w:t>/); + expect(xml).toMatch(/]*>((?:(?!<\/w:r>).)*<\/w:r>)*]*>letter.docx<\/w:t>/); + }); + it("should read only the parts placeholders can be in, leaving a template's images uninflated", async () => { const template = zip({ "word/document.xml": MOCK_XML_2, diff --git a/src/patcher/patch-detector.ts b/src/patcher/patch-detector.ts index 4eac063c6c..23564cbf79 100644 --- a/src/patcher/patch-detector.ts +++ b/src/patcher/patch-detector.ts @@ -4,19 +4,22 @@ * @module */ import { altTextOf, findDrawings } from "./drawing-patch"; -import type { InputDataType } from "./from-docx"; +import type { InputDataType, PatchDocumentOptions } from "./from-docx"; import { loadZip } from "./load-zip"; import { traverse } from "./traverser"; -import { decodeUtf8, toJson } from "./util"; +import { checkPlaceholderDelimiters, decodeUtf8, toJson } from "./util"; /** * Options for patch detection. * * @property data - The document template to scan for placeholders + * @property placeholderDelimiters - Custom delimiter characters for placeholders, as given to `patchDocument` * @property trimPlaceholders - Whether to give the key of a placeholder with spaces inside its delimiters without them */ type PatchDetectorOptions = { readonly data: InputDataType; + /** Custom placeholder delimiters, the same as `patchDocument`'s (default: {{ and }}) */ + readonly placeholderDelimiters?: PatchDocumentOptions["placeholderDelimiters"]; /** * Give the key of a placeholder with spaces inside its delimiters without them, such as "name" for `{{ name }}`, as * `patchDocument`'s `trimPlaceholders` patches it (default: false) @@ -31,7 +34,7 @@ const isSearched = (path: string): boolean => path.startsWith("word/") && /\.(xm * Detects all placeholders present in a document template. * * Scans through all XML content in a .docx file to find placeholder text - * enclosed in delimiters (default: {{placeholder}}), and placeholders in the + * enclosed in delimiters (default: {{placeholder}}, or `placeholderDelimiters`), and placeholders in the * alt text of drawings, such as a chart for `docx/charts`' `ChartDataPatch`. * This is useful for discovering what patches a template expects before * performing replacement. @@ -44,6 +47,9 @@ const isSearched = (path: string): boolean => path.startsWith("word/") && /\.(xm * const placeholders = await patchDetector({ data: templateBuffer }); * // Returns: ["name", "date", "address"] if template contains {{name}}, {{date}}, {{address}} * + * // With the delimiters given to patchDocument, such as for <> + * const keys = await patchDetector({ data: templateBuffer, placeholderDelimiters: { start: "<<", end: ">>" } }); + * * // Use detected placeholders to create patches * const patches = {}; * placeholders.forEach(key => { @@ -54,7 +60,13 @@ const isSearched = (path: string): boolean => path.startsWith("word/") && /\.(xm * }); * ``` */ -export const patchDetector = async ({ data, trimPlaceholders = false }: PatchDetectorOptions): Promise => { +export const patchDetector = async ({ + data, + placeholderDelimiters = { start: "{{", end: "}}" }, + trimPlaceholders = false, +}: PatchDetectorOptions): Promise => { + checkPlaceholderDelimiters(placeholderDelimiters); + const pattern = placeholderPattern(placeholderDelimiters); // Only the parts placeholders can be in are inflated, not a template's images or embedded files const zipContent = await loadZip(data, isSearched); const patches = new Set(); @@ -63,7 +75,7 @@ export const patchDetector = async ({ data, trimPlaceholders = false }: PatchDet const json = toJson(decodeUtf8(value)); const texts = [...traverse(json).map((p) => p.text), ...findDrawings(json).flatMap(({ properties }) => altTextOf(properties))]; const keys = texts - .flatMap((text) => findPatchKeys(text)) + .flatMap((text) => text.match(pattern) ?? []) .map((patch) => (trimPlaceholders ? patch.trim() : patch)) // A placeholder of only spaces has no key .filter((patch) => patch !== ""); @@ -73,13 +85,16 @@ export const patchDetector = async ({ data, trimPlaceholders = false }: PatchDet return Array.from(patches); }; +// Characters a regular expression gives a meaning to, so delimiters such as [[ and ]] are looked for as they are +const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + /** - * Extracts placeholder keys from text using regex pattern. + * The pattern of the keys of placeholders: the text between the delimiters, without them. A key has no start delimiter + * in it, so a start delimiter before a placeholder, such as in `<>` or `a < b and `, doesn't + * hide it, and the search from a start delimiter with no end after it stops at the next start delimiter. * - * @param text - Text to search for placeholders - * @returns Array of placeholder keys (without delimiters) + * @param delimiters - The delimiters, such as `{{` and `}}` + * @returns A pattern that matches every key in a text */ -const findPatchKeys = (text: string): readonly string[] => { - const pattern = /(?<=\{\{).+?(?=\}\})/gs; - return text.match(pattern) ?? []; -}; +const placeholderPattern = ({ start, end }: { readonly start: string; readonly end: string }): RegExp => + new RegExp(`(?<=${escapeRegExp(start)})(?:(?!${escapeRegExp(start)}).)+?(?=${escapeRegExp(end)})`, "gs"); diff --git a/src/patcher/replacer.spec.ts b/src/patcher/replacer.spec.ts index 9e2058eee0..0be673c486 100644 --- a/src/patcher/replacer.spec.ts +++ b/src/patcher/replacer.spec.ts @@ -1268,6 +1268,188 @@ describe("replacer", () => { expect(namesOf(shapeRun.elements)).to.deep.equal(["w:rPr", "w:drawing"]); expect(runsIn(shapeRun).map((run) => namesOf(run.elements))).to.deep.equal([["w:t"]]); }); + + describe("with the placeholder in a link, a content control or a tracked change", () => { + const createElement = (name: string, attributes: Element["attributes"], ...elements: readonly Element[]): Element => ({ + type: "element", + name, + attributes, + elements: [...elements], + }); + const link = new ConcreteHyperlink([new TextRun("link")], "9"); + const contentControl = (properties: readonly Element[], ...content: readonly Element[]): Element => + createElement( + "w:sdt", + undefined, + createElement("w:sdtPr", undefined, ...properties), + createElement("w:sdtContent", undefined, ...content), + ); + const plainText = createElement("w:text", undefined); + + it("should replace the placeholder where it is, in the element holding its run", () => { + for (const name of ["w:hyperlink", "w:ins", "w:moveTo", "w:smartTag", "w:customXml", "w:fldSimple", "w:dir", "w:bdo"]) { + const holder = createElement(name, undefined, createRun(createText("A {{ph}} B"))); + const paragraph = createParagraph(holder); + + expect(replaceWith({ elements: [paragraph] }, [new TextRun("X")]).didFindOccurrence).to.equal(true); + + expect(textsOf({ elements: [paragraph] }), name).to.deep.equal(["A X B"]); + expect(namesOf(paragraph.elements), name).to.deep.equal([name]); + expect(namesOf(holder.elements), name).to.deep.equal(["w:r", "w:r", "w:r"]); + } + }); + + it("should replace the placeholder in a content control's content", () => { + const control = contentControl([], createRun(createText("{{ph}}"))); + const paragraph = createParagraph(control); + + replaceWith({ elements: [paragraph] }, [new TextRun("X")]); + + expect(textsOf({ elements: [paragraph] })).to.deep.equal(["X"]); + expect(namesOf(control.elements![1].elements)).to.deep.equal(["w:r", "w:r", "w:r"]); + }); + + it("should replace every occurrence, in the paragraph and in a link, but not one in the content it inserts", () => { + const paragraph = createParagraph( + createRun(createText("{{ph}} and ")), + createElement("w:hyperlink", undefined, createRun(createText("{{ph}}"))), + createElement("w:ins", undefined, createRun(createText(" and {{ph}}"))), + ); + + replaceWith({ elements: [paragraph] }, [new TextRun("[{{ph}}]")]); + + expect(textsOf({ elements: [paragraph] })).to.deep.equal(["[{{ph}}] and [{{ph}}] and [{{ph}}]"]); + }); + + it("should replace a placeholder that starts in the paragraph and ends in a tracked insertion, where it starts", () => { + const insertion = createElement("w:ins", { "w:id": "1" }, createRun(createText("h}} after"))); + const paragraph = createParagraph(createRun(createText("Before {{p")), insertion); + + replaceWith({ elements: [paragraph] }, [new TextRun("X")]); + + expect(textsOf({ elements: [paragraph] })).to.deep.equal(["Before X after"]); + expect(namesOf(paragraph.elements)).to.deep.equal(["w:r", "w:r", "w:r", "w:ins"]); + }); + + it("should take a link out of a tracked insertion, which can't hold it, giving the insertion after it an id nothing else has", () => { + const insertion = createElement( + "w:ins", + { "w:id": "1", "w:author": "A" }, + createRun(createText("Dear ")), + createRun(createText("{{ph}}, welcome")), + ); + const paragraph = createParagraph(insertion, createElement("w:bookmarkStart", { "w:id": "7", "w:name": "b" })); + + replaceWith({ elements: [paragraph] }, [link]); + + expect(textsOf({ elements: [paragraph] })).to.deep.equal(["Dear link, welcome"]); + expect(paragraph.elements!.map((e) => [e.name, e.attributes])).to.deep.equal([ + ["w:ins", { "w:id": "1", "w:author": "A" }], + ["w:hyperlink", { "w:history": "1", "r:id": "rId9" }], + ["w:ins", { "w:id": "8", "w:author": "A" }], + ["w:bookmarkStart", { "w:id": "7", "w:name": "b" }], + ]); + // The runs before the link stay together in the first part + expect(namesOf(paragraph.elements![0].elements)).to.deep.equal(["w:r", "w:r"]); + }); + + it("should take a link out of a link, so the patch's link takes the place of the template's there", () => { + const paragraph = createParagraph( + createElement("w:hyperlink", { "w:anchor": "top" }, createRun(createText("Go to {{ph}} now"))), + ); + + replaceWith({ elements: [paragraph] }, [link]); + + expect(textsOf({ elements: [paragraph] })).to.deep.equal(["Go to link now"]); + expect(paragraph.elements!.map((e) => e.attributes)).to.deep.equal([ + { "w:anchor": "top" }, + { "w:history": "1", "r:id": "rId9" }, + { "w:anchor": "top" }, + ]); + }); + + it("should take a link out of a tracked insertion in a link, and then out of the link", () => { + const paragraph = createParagraph( + createElement( + "w:hyperlink", + { "w:anchor": "top" }, + createElement("w:ins", { "w:id": "1" }, createRun(createText("{{ph}}"))), + ), + ); + + replaceWith({ elements: [paragraph] }, [link]); + + expect(paragraph.elements!.map((e) => [e.attributes, namesOf(e.elements)])).to.deep.equal([ + [{ "w:anchor": "top" }, ["w:ins"]], + [{ "w:history": "1", "r:id": "rId9" }, ["w:r"]], + [{ "w:anchor": "top" }, ["w:ins"]], + ]); + expect(paragraph.elements!.map((e) => e.elements![0].attributes?.["w:id"])).to.deep.equal(["1", undefined, "2"]); + }); + + it("should replace a placeholder in a content control without properties, as it needs none", () => { + const control = createElement( + "w:sdt", + undefined, + createElement("w:sdtContent", undefined, createRun(createText("{{ph}}"))), + ); + const paragraph = createParagraph(control); + + replaceWith({ elements: [paragraph] }, [link]); + + expect(textsOf({ elements: [paragraph] })).to.deep.equal(["link"]); + expect(namesOf(control.elements)).to.deep.equal(["w:sdtContent"]); + expect(namesOf(control.elements![0].elements)).to.deep.equal(["w:r", "w:hyperlink", "w:r"]); + }); + + it("should make a plain text content control a rich text one when a link is put in it, as Word won't open it otherwise", () => { + const control = contentControl([plainText], createRun(createText("{{ph}}"))); + + replaceWith({ elements: [createParagraph(control)] }, [link]); + + expect(namesOf(control.elements![0].elements)).to.deep.equal([]); + }); + + it("should keep a plain text content control when only text, tabs, breaks and bookmarks are put in it", () => { + const control = contentControl([plainText], createRun(createText("{{ph}}"))); + + replaceWith({ elements: [createParagraph(control)] }, [ + new TextRun({ text: "X", bold: true, break: 1 }), + new Bookmark({ id: "here", children: [new TextRun("\tY")] }), + ]); + + expect(namesOf(control.elements![0].elements)).to.deep.equal(["w:text"]); + }); + + it("should unbind a content control bound to custom XML, so Word doesn't fill the placeholder back in from it", () => { + const binding = createElement("w:dataBinding", { + "w:xpath": "/ns0:root[1]/ns0:name[1]", + "w:storeItemID": "{6E5A1C1B-2B7B-4C55-9E36-7B9C5B0F2A11}", + }); + const control = contentControl( + [createElement("w:id", { "w:val": "1" }), binding, plainText], + createRun(createText("{{ph}}")), + ); + + replaceWith({ elements: [createParagraph(control)] }, [new TextRun("X")]); + + expect(namesOf(control.elements![0].elements)).to.deep.equal(["w:id", "w:text"]); + }); + + it("should stop a content control showing its placeholder text, giving the content the control's run properties", () => { + const bold: Element = { type: "element", name: "w:rPr", elements: [{ type: "element", name: "w:b" }] }; + const control = contentControl( + [createElement("w:showingPlcHdr", undefined), bold, plainText], + createRun(italic, createText("Enter {{ph}}")), + ); + + replaceWith({ elements: [createParagraph(control)] }, [new TextRun("X")]); + + const runs = control.elements![1].elements!; + expect(namesOf(control.elements![0].elements)).to.deep.equal(["w:rPr", "w:text"]); + expect(runs.map((run) => namesOf(run.elements![0].elements))).to.deep.equal([["w:i"], ["w:b"], ["w:i"]]); + }); + }); }); }); }); diff --git a/src/patcher/replacer.ts b/src/patcher/replacer.ts index da9974f298..a296bdfd75 100644 --- a/src/patcher/replacer.ts +++ b/src/patcher/replacer.ts @@ -8,9 +8,9 @@ import type { IContext, XmlComponent } from "@file/xml-components"; import { type XmlElement as Element, stringifyXmlable } from "@util/xml"; import { type IPatch, PatchType } from "./from-docx"; -import { findRunElementIndexWithToken, splitRunElement } from "./paragraph-split-inject"; +import { findRunElementPathWithToken, splitRunElement } from "./paragraph-split-inject"; import { replaceTokenInParagraphElement } from "./paragraph-token-replacer"; -import { type IRenderedParagraphNode, renderParagraphNode } from "./run-renderer"; +import { type IRenderedParagraphNode, elementAtPath, renderParagraphNode } from "./run-renderer"; import { findLocationOfText } from "./traverser"; import { toJson } from "./util"; @@ -83,6 +83,13 @@ export const replacer = ({ // A document patch replaces the whole paragraph, so a match inside another match, such as in its text box, would be thrown away const paragraphsToPatch = patch.type === PatchType.DOCUMENT ? withoutNestedParagraphs(paragraphsInPatchOrder) : paragraphsInPatchOrder; + // A tracked change split around a link is given ids for its new pieces that nothing in the part has + let highestId: number | undefined; + const newTrackedChangeId = (): string => { + highestId = (highestId ?? highestIdIn(json)) + 1; + return String(highestId); + }; + for (const renderedParagraph of paragraphsToPatch) { switch (patch.type) { case PatchType.DOCUMENT: { @@ -103,20 +110,18 @@ export const replacer = ({ let fromIndex = 0; do { - const nextRunIndex = replaceOccurrenceInParagraph({ + // Look for the next occurrence after the inserted content, so a placeholder in the patch is never patched + fromIndex = replaceOccurrenceInParagraph({ paragraphElement, renderedParagraph: paragraph, patchText, fromIndex, children: formatChildren(patch, context, renumberIds), keepOriginalStyles, + newTrackedChangeId, }); paragraph = renderParagraphNode({ element: paragraphElement, index: renderedParagraph.index, parent: undefined }); - // Look for the next occurrence after the inserted content, so a placeholder in the patch is never patched - fromIndex = paragraph.runs - .filter((run) => run.index < nextRunIndex) - .reduce((length, run) => length + run.text.length, 0); } while (recursive && paragraph.text.includes(patchText, fromIndex)); break; } @@ -138,9 +143,11 @@ const formatChildren = (patch: IPatch, context: IContext, renumberIds: RenumberI ); /** - * Replaces the first occurrence of the placeholder from `fromIndex` on, splitting the run it starts in. + * Replaces the first occurrence of the placeholder from `fromIndex` on, splitting the run it starts in. The content goes + * where that run is, in the paragraph or in what holds the run in it, such as a link or a content control, unless that + * can't hold it. * - * @returns The index of the run after the inserted content + * @returns Where the text after the inserted content starts in the paragraph's text */ const replaceOccurrenceInParagraph = ({ paragraphElement, @@ -149,6 +156,7 @@ const replaceOccurrenceInParagraph = ({ fromIndex, children, keepOriginalStyles, + newTrackedChangeId, }: { readonly paragraphElement: Element; readonly renderedParagraph: IRenderedParagraphNode; @@ -156,7 +164,10 @@ const replaceOccurrenceInParagraph = ({ readonly fromIndex: number; readonly children: readonly Element[]; readonly keepOriginalStyles: boolean; + readonly newTrackedChangeId: () => string; }): number => { + const start = renderedParagraph.text.indexOf(patchText, fromIndex); + replaceTokenInParagraphElement({ paragraphElement, renderedParagraph, @@ -165,20 +176,126 @@ const replaceOccurrenceInParagraph = ({ fromIndex, }); - const index = findRunElementIndexWithToken(paragraphElement, SPLIT_TOKEN); + const runPath = findRunElementPathWithToken(paragraphElement, SPLIT_TOKEN); + const containerPath = runPath.slice(0, -1); + const container = elementAtPath(paragraphElement, containerPath); + const index = runPath[runPath.length - 1]; + // The content controls the placeholder is in, the innermost last + const contentControls = containerPath + .map((_, depth) => elementAtPath(paragraphElement, containerPath.slice(0, depth + 1))) + .filter((e) => e.name === "w:sdt"); + const controlShowingPlaceholder = [...contentControls].reverse().find(isShowingPlaceholder); - const runElementToBeReplaced = paragraphElement.elements![index]; + const runElementToBeReplaced = container.elements![index]; const { left, right } = splitRunElement(runElementToBeReplaced, SPLIT_TOKEN); const runProperties = runElementToBeReplaced.elements!.find((e) => e.type === "element" && e.name === "w:rPr"); + // A content control's placeholder text has a look of its own, such as Word's grey Placeholder Text, and what + // replaces it takes the control's run properties instead, as text typed in it does + const contentRunProperties = controlShowingPlaceholder ? runPropertiesOfContentControl(controlShowingPlaceholder) : runProperties; - const newRunElements = keepOriginalStyles && runProperties ? children.map((e) => withRunPropertiesOnRuns(e, runProperties)) : children; + const newRunElements = + keepOriginalStyles && contentRunProperties ? children.map((e) => withRunPropertiesOnRuns(e, contentRunProperties)) : children; // The text after the placeholder is the document's own, so it keeps its formatting either way const patchedRightElement = runProperties ? { ...right, elements: [runProperties, ...right.elements!] } : right; // eslint-disable-next-line functional/immutable-data - paragraphElement.elements!.splice(index, 1, left, ...newRunElements, patchedRightElement); + container.elements!.splice(index, 1, left, ...newRunElements, patchedRightElement); + contentControls.forEach((contentControl) => fillContentControl(contentControl, newRunElements)); + liftOutOfContainers(paragraphElement, containerPath, newTrackedChangeId); - return index + 1 + newRunElements.length; + return ( + start + renderParagraphNode({ element: { name: "w:p", elements: [...newRunElements] }, index: 0, parent: undefined }).text.length + ); +}; + +const propertiesOfContentControl = (contentControl: Element): Element | undefined => + contentControl.elements?.find((e) => e.name === "w:sdtPr"); + +const isShowingPlaceholder = (contentControl: Element): boolean => + !!propertiesOfContentControl(contentControl)?.elements?.some((e) => e.name === "w:showingPlcHdr"); + +const runPropertiesOfContentControl = (contentControl: Element): Element | undefined => + propertiesOfContentControl(contentControl)?.elements?.find((e) => e.name === "w:rPr"); + +// What Word opens in a plain text content control: runs of text, tabs and breaks, and bookmarks. A link, a picture, a +// field or a symbol in one makes Word find the document unreadable +const PLAIN_TEXT_RUN_CONTENT: ReadonlySet = new Set(["w:rPr", "w:t", "w:tab", "w:br"]); + +const isPlainText = (element: Element): boolean => + element.name === "w:bookmarkStart" || + element.name === "w:bookmarkEnd" || + (element.name === "w:r" && childElementsOf(element).every((e) => PLAIN_TEXT_RUN_CONTENT.has(e.name))); + +/** + * Makes a content control show the content a patch put in it as its own. It no longer shows its placeholder text, as + * when text is typed in it, and a plain text control given more than text, such as a link or a picture, becomes a rich + * text control, as Word won't open a plain text one with it. A control bound to custom XML or a document property is + * no longer bound, as Word fills a bound control in from its data when it opens the document, which would put the + * placeholder back. + */ +const fillContentControl = (contentControl: Element, insertedElements: readonly Element[]): void => { + const properties = propertiesOfContentControl(contentControl); + if (!properties?.elements) { + return; + } + + const isPlainTextControl = properties.elements.some((e) => e.name === "w:text"); + const needsRichText = isPlainTextControl && !insertedElements.every(isPlainText); + properties.elements = properties.elements.filter( + (e) => e.name !== "w:showingPlcHdr" && e.name !== "w:dataBinding" && !(needsRichText && e.name === "w:text"), + ); +}; + +// What a tracked insertion or move can't hold, though a paragraph can: a link, a field or a subdocument +const NOT_IN_TRACKED_CHANGES: ReadonlySet = new Set(["w:hyperlink", "w:fldSimple", "w:subDoc"]); + +/** + * The elements each container of runs can't hold. Word reads a link in a link as two links over the same text, so a + * patch's link in place of a placeholder in a link takes the place of that link there. + */ +const NOT_IN_CONTAINER: ReadonlyMap> = new Map([ + ["w:ins", NOT_IN_TRACKED_CHANGES], + ["w:moveTo", NOT_IN_TRACKED_CHANGES], + ["w:hyperlink", new Set(["w:hyperlink"])], +]); + +/** + * Splits each container of runs, from the placeholder's run up to the paragraph, around the content in it that it can't + * hold, such as a link a patch put in place of a placeholder typed with Track Changes on. That content then isn't + * tracked, as when Word inserts a link with Track Changes off, and the text before and after it still is. Each tracked + * change must have an id of its own, so the pieces after the first are given new ones. + */ +const liftOutOfContainers = (paragraphElement: Element, containerPath: readonly number[], newTrackedChangeId: () => string): void => { + for (let depth = containerPath.length; depth > 0; depth--) { + const parent = elementAtPath(paragraphElement, containerPath.slice(0, depth - 1)); + const index = containerPath[depth - 1]; + const container = parent.elements![index]; + const cantHold = NOT_IN_CONTAINER.get(container.name); + const isLifted = (element: Element): boolean => !!cantHold?.has(element.name); + + if (!container.elements?.some(isLifted)) { + continue; + } + + // Each stretch of what it can hold stays in a copy of it. A stretch starts at a lifted element and after one + const { elements } = container; + const starts = elements.flatMap((element, i) => (i === 0 || isLifted(element) || isLifted(elements[i - 1]) ? [i] : [])); + const stretches = starts.map((start, i) => elements.slice(start, starts[i + 1])); + const isTrackedChange = cantHold === NOT_IN_TRACKED_CHANGES; + let isFirstCopy = true; + const pieces = stretches.map((stretch) => { + if (isLifted(stretch[0])) { + return stretch[0]; + } + const attributes = + isTrackedChange && !isFirstCopy ? { ...container.attributes, "w:id": newTrackedChangeId() } : container.attributes; + isFirstCopy = false; + return { ...container, attributes, elements: [...stretch] }; + }); + + // eslint-disable-next-line functional/immutable-data + parent.elements!.splice(index, 1, ...pieces); + } }; /** @@ -289,6 +406,14 @@ const runPropertyRank = (element: Element): number => { const childElementsOf = (element: Element): readonly Element[] => element.elements ?? []; +/** + * The highest whole number id (w:id) of an element or anything in it. + */ +const highestIdIn = (element: Element): number => { + const id = Number(element.attributes?.["w:id"]); + return (element.elements ?? []).reduce((highest, child) => Math.max(highest, highestIdIn(child)), Number.isInteger(id) ? id : 0); +}; + const isInsideElementAtPath = (path: readonly number[], ancestorPath: readonly number[]): boolean => path.length > ancestorPath.length && ancestorPath.every((index, i) => path[i] === index); diff --git a/src/patcher/run-renderer.spec.ts b/src/patcher/run-renderer.spec.ts index de7dca5a9d..76722ed89a 100644 --- a/src/patcher/run-renderer.spec.ts +++ b/src/patcher/run-renderer.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from "vitest"; +import type { XmlElement as Element } from "@util/xml"; + import { renderParagraphNode } from "./run-renderer"; describe("run-renderer", () => { @@ -44,7 +46,7 @@ describe("run-renderer", () => { runs: [ { end: 4, - index: 0, + path: [0], parts: [ { end: 4, @@ -84,7 +86,7 @@ describe("run-renderer", () => { runs: [ { end: 0, - index: -1, + path: [0], parts: [], start: 0, text: "", @@ -124,7 +126,7 @@ describe("run-renderer", () => { runs: [ { end: -1, - index: 0, + path: [0], parts: [ { end: -1, @@ -167,11 +169,59 @@ describe("run-renderer", () => { { text: "Name:", index: 0, start: 0, end: 4 }, { text: "{{ph}}", index: 2, start: 5, end: 10 }, ], - index: 0, + path: [0], start: 0, end: 10, }, ]); }); + + describe("runs in other elements of the paragraph", () => { + const run = (text: string): Element => ({ name: "w:r", elements: [{ name: "w:t", elements: [{ type: "text", text }] }] }); + const element = (name: string, ...elements: readonly Element[]): Element => ({ name, elements: [...elements] }); + const render = (...elements: readonly Element[]) => + renderParagraphNode({ element: element("w:p", ...elements), index: 0, parent: undefined }); + + it("should read the runs in a link, a content control, a tracked insertion or move, a smart tag, custom XML, a field and text in a direction, in order", () => { + const output = render( + run("A"), + element("w:hyperlink", run("B")), + element("w:sdt", element("w:sdtPr", element("w:rPr")), element("w:sdtContent", run("C"))), + element("w:ins", run("D")), + element("w:moveTo", run("E")), + element("w:smartTag", element("w:smartTagPr"), run("F")), + element("w:customXml", run("G")), + element("w:fldSimple", run("H")), + element("w:dir", element("w:bdo", run("I"))), + ); + + expect(output.text).to.equal("ABCDEFGHI"); + expect(output.runs.map(({ path, start }) => ({ path, start }))).to.deep.equal([ + { path: [0], start: 0 }, + { path: [1, 0], start: 1 }, + { path: [2, 1, 0], start: 2 }, + { path: [3, 0], start: 3 }, + { path: [4, 0], start: 4 }, + { path: [5, 1], start: 5 }, + { path: [6, 0], start: 6 }, + { path: [7, 0], start: 7 }, + { path: [8, 0, 0], start: 8 }, + ]); + }); + + it("should read a link with nothing in it as no text", () => { + const output = render(run("A"), { name: "w:hyperlink" }, run("B")); + + expect(output.text).to.equal("AB"); + expect(output.runs.map(({ path }) => path)).to.deep.equal([[0], [2]]); + }); + + it("should leave out deleted and moved-away text, as it isn't the paragraph's", () => { + const output = render(run("A"), element("w:del", run("B")), element("w:moveFrom", run("C")), run("D")); + + expect(output.text).to.equal("AD"); + expect(output.runs.map(({ path }) => path)).to.deep.equal([[0], [3]]); + }); + }); }); }); diff --git a/src/patcher/run-renderer.ts b/src/patcher/run-renderer.ts index ec41b2f4a3..fe9d0f5440 100644 --- a/src/patcher/run-renderer.ts +++ b/src/patcher/run-renderer.ts @@ -48,22 +48,58 @@ type IParts = { * * @property text - Complete text content of the run * @property parts - Array of text fragments (w:t elements) within the run - * @property index - Position index of the run within the paragraph + * @property path - Position indices from the paragraph to the run, through the element holding it, such as a link * @property start - Starting character index in the paragraph * @property end - Ending character index in the paragraph */ export type IRenderedRunNode = { readonly text: string; readonly parts: readonly IParts[]; - readonly index: number; + readonly path: readonly number[]; } & StartAndEnd; +/** + * The elements in a paragraph that hold runs of its text, so a placeholder can be in a link, a content control, a + * tracked insertion, a smart tag or a field's result. A content control holds them in its w:sdtContent. Deleted text, in + * w:del or w:moveFrom, isn't the paragraph's text, and a run's own content, such as a text box, has paragraphs of its own. + */ +const RUN_CONTAINERS: ReadonlySet = new Set([ + "w:hyperlink", + "w:sdt", + "w:sdtContent", + "w:ins", + "w:moveTo", + "w:smartTag", + "w:customXml", + "w:fldSimple", + "w:dir", + "w:bdo", +]); + +/** + * The runs in an element of a paragraph, in the order they are read, with the indices from the paragraph to each. + */ +const runsIn = (element: Element, path: readonly number[]): readonly { readonly element: Element; readonly path: readonly number[] }[] => + (element.elements ?? []).flatMap((child, i) => { + if (child.name === "w:r") { + return [{ element: child, path: [...path, i] }]; + } + return RUN_CONTAINERS.has(child.name ?? "") ? runsIn(child, [...path, i]) : []; + }); + +/** + * The element at the end of a path of position indices from an element, such as a run from its paragraph. + */ +export const elementAtPath = (element: Element, path: readonly number[]): Element => + path.reduce((parent, index) => parent.elements![index], element); + /** * Renders a paragraph element into a structured representation with text content. * * Extracts all text content from a paragraph (w:p) element by processing its - * run (w:r) children. Calculates character positions for each text fragment - * to enable precise text replacement operations. + * runs (w:r), including those in a link, content control or tracked insertion. + * Calculates character positions for each text fragment to enable precise text + * replacement operations. * * @param node - The paragraph element wrapper to render * @returns Rendered paragraph with text content, runs, and position information @@ -92,16 +128,12 @@ export const renderParagraphNode = (node: ElementWrapper): IRenderedParagraphNod let currentRunStringLength = 0; - const runs = node.element.elements - .map((element, i) => ({ element, i })) - .filter(({ element }) => element.name === "w:r") - .map(({ element, i }) => { - const renderedRunNode = renderRunNode(element, i, currentRunStringLength); - currentRunStringLength += renderedRunNode.text.length; + const runs = runsIn(node.element, []).map(({ element, path }) => { + const renderedRunNode = renderRunNode(element, path, currentRunStringLength); + currentRunStringLength += renderedRunNode.text.length; - return renderedRunNode; - }) - .filter((e) => !!e); + return renderedRunNode; + }); const text = runs.reduce((acc, curr) => acc + curr.text, ""); @@ -113,12 +145,12 @@ export const renderParagraphNode = (node: ElementWrapper): IRenderedParagraphNod }; }; -const renderRunNode = (node: Element, index: number, currentRunStringIndex: number): IRenderedRunNode => { +const renderRunNode = (node: Element, path: readonly number[], currentRunStringIndex: number): IRenderedRunNode => { if (!node.elements) { return { text: "", parts: [], - index: -1, + path, start: currentRunStringIndex, end: currentRunStringIndex, }; @@ -147,7 +179,7 @@ const renderRunNode = (node: Element, index: number, currentRunStringIndex: numb return { text, parts, - index, + path, start: currentRunStringIndex, end: parts.length > 0 ? parts[parts.length - 1].end : currentRunStringIndex, }; diff --git a/src/patcher/traverser.spec.ts b/src/patcher/traverser.spec.ts index a2704e7b09..cfc6028923 100644 --- a/src/patcher/traverser.spec.ts +++ b/src/patcher/traverser.spec.ts @@ -639,7 +639,7 @@ describe("traverser", () => { runs: [ { end: 18, - index: 0, + path: [0], parts: [ { end: 18, @@ -667,7 +667,7 @@ describe("traverser", () => { { text: "What a {{bold}} text!", parts: [{ text: "What a {{bold}} text!", index: 1, start: 0, end: 20 }], - index: 0, + path: [0], start: 0, end: 20, }, @@ -688,7 +688,7 @@ describe("traverser", () => { { text: "What a {{bold}} text!", parts: [{ text: "What a {{bold}} text!", index: 1, start: 0, end: 20 }], - index: 0, + path: [0], start: 0, end: 20, }, @@ -709,15 +709,15 @@ describe("traverser", () => { { text: "This is a {{head", parts: [{ text: "This is a {{head", index: 0, start: 0, end: 15 }], - index: 1, + path: [1], start: 0, end: 15, }, - { text: "er", parts: [{ text: "er", index: 0, start: 16, end: 17 }], index: 2, start: 16, end: 17 }, + { text: "er", parts: [{ text: "er", index: 0, start: 16, end: 17 }], path: [2], start: 16, end: 17 }, { text: "_adjective}} don’t you think?", parts: [{ text: "_adjective}} don’t you think?", index: 0, start: 18, end: 46 }], - index: 3, + path: [3], start: 18, end: 46, }, diff --git a/src/patcher/util.ts b/src/patcher/util.ts index 16ad0819a9..a22b7f564a 100644 --- a/src/patcher/util.ts +++ b/src/patcher/util.ts @@ -112,3 +112,15 @@ export const getFirstLevelElements = (relationships: Element, id: string): Eleme parent.elements ??= []; return parent.elements; }; + +/** + * Checks the delimiters of a template's placeholders, which must be more than spaces. + * + * @param delimiters - The delimiters, such as `{{` and `}}` + * @throws Error if either delimiter is empty or only spaces + */ +export const checkPlaceholderDelimiters = (delimiters: { readonly start: string; readonly end: string } | undefined): void => { + if (!delimiters?.start.trim() || !delimiters?.end.trim()) { + throw new Error("Both start and end delimiters must be non-empty strings."); + } +};