mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
* fix: patch placeholders in links, content controls and tracked changes patchDocument and patchDetector only read runs that are direct children of a paragraph, so a placeholder in a link, a content control, text typed with Track Changes on, a smart tag or a field's result was left as it was, with no error. Runs in those elements are now read and patched where they are. Where the content can't go in what holds the placeholder, it goes where Word can open it: a link is taken out of a tracked insertion (whose piece after it gets an id of its own) or a link, a plain text content control given more than text becomes a rich text one, and a content control showing its placeholder text stops showing it. Addresses #2679 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test: cover every branch of patching runs in links and content controls CI's coverage fell below 100%: an empty link, a content control without properties, and runs that stay together when a tracked insertion is split weren't tested. The name fallbacks in the replacer's lookups could never be reached, so the lookups take an element's name as it is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * feat: find placeholders with custom delimiters with patchDetector, and say why a placeholder isn't replaced patchDetector takes placeholderDelimiters, as patchDocument does, so it finds the same placeholders. Before, it only knew {{ and }}, and found nothing in a template with <<name>>. templates.md has a section on a placeholder that isn't replaced: how to find the patches whose placeholder isn't in the template with patchDetector, as patchDocument leaves them out without an error, and the usual reasons, such as a key written with its braces. Addresses #2679 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix: unbind a content control a patch fills, so Word doesn't put the placeholder back Word fills a control bound to custom XML or a document property (w:dataBinding) in from its data when it opens a document. A patched placeholder in one came back: Word for Mac showed {{name}} from the XML, though the control held the patch's text. The binding is now removed from a control a patch's content goes in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * perf: split a tracked change around a link in linear time The stretches were built by copying the stretch so far for each element, so a tracked insertion of n runs took n² steps to split. Each stretch is now sliced from where it starts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * docs: list a placeholder only in alt text among the reasons a patch isn't applied patchDetector finds placeholders in pictures' and charts' alt text, so comparing its keys with the patches' doesn't show a text patch for one, which leaves it as it is. It's now one of the listed reasons, saying so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * fix: don't let a start delimiter before a placeholder hide it from patchDetector A key ran from the first start delimiter to the next end delimiter, so in "<<unfinished <<name>>" patchDetector found "unfinished <<name", not "name", which patchDocument patches. With one-character delimiters such as < and >, any "<" in the text did this. A key now has no start delimiter in it. The search from a start delimiter with no end after it also stops at the next one, rather than going on to the end of the paragraph each time: 120,000 characters of unmatched "<" took 1.4 s, and now take no time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c * test: check the link a patch puts in a content control without properties The test only checked the control's text and its one child, so content that lost the link would have passed it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
101 lines
4.5 KiB
TypeScript
101 lines
4.5 KiB
TypeScript
/**
|
|
* Patch detector for discovering placeholders in document templates.
|
|
*
|
|
* @module
|
|
*/
|
|
import { altTextOf, findDrawings } from "./drawing-patch";
|
|
import type { InputDataType, PatchDocumentOptions } from "./from-docx";
|
|
import { loadZip } from "./load-zip";
|
|
import { traverse } from "./traverser";
|
|
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)
|
|
*/
|
|
readonly trimPlaceholders?: boolean;
|
|
};
|
|
|
|
// The parts placeholders are looked for in: those in word/ that are XML, other than their relationships
|
|
const isSearched = (path: string): boolean => path.startsWith("word/") && /\.(xml|rels)$/.test(path) && !path.endsWith(".xml.rels");
|
|
|
|
/**
|
|
* 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}}, 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.
|
|
*
|
|
* @param options - Patch detector configuration
|
|
* @returns Array of placeholder keys found in the document
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* 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 <<name>>
|
|
* const keys = await patchDetector({ data: templateBuffer, placeholderDelimiters: { start: "<<", end: ">>" } });
|
|
*
|
|
* // Use detected placeholders to create patches
|
|
* const patches = {};
|
|
* placeholders.forEach(key => {
|
|
* patches[key] = {
|
|
* type: PatchType.PARAGRAPH,
|
|
* children: [new TextRun(getUserData(key))],
|
|
* };
|
|
* });
|
|
* ```
|
|
*/
|
|
export const patchDetector = async ({
|
|
data,
|
|
placeholderDelimiters = { start: "{{", end: "}}" },
|
|
trimPlaceholders = false,
|
|
}: PatchDetectorOptions): Promise<readonly string[]> => {
|
|
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<string>();
|
|
|
|
for (const [, value] of zipContent) {
|
|
const json = toJson(decodeUtf8(value));
|
|
const texts = [...traverse(json).map((p) => p.text), ...findDrawings(json).flatMap(({ properties }) => altTextOf(properties))];
|
|
const keys = texts
|
|
.flatMap((text) => text.match(pattern) ?? [])
|
|
.map((patch) => (trimPlaceholders ? patch.trim() : patch))
|
|
// A placeholder of only spaces has no key
|
|
.filter((patch) => patch !== "");
|
|
// eslint-disable-next-line functional/immutable-data
|
|
keys.forEach((patch) => patches.add(patch));
|
|
}
|
|
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, "\\$&");
|
|
|
|
/**
|
|
* 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 `<<unfinished <<name>>` or `a < b and <name>`, doesn't
|
|
* hide it, and the search from a start delimiter with no end after it stops at the next start delimiter.
|
|
*
|
|
* @param delimiters - The delimiters, such as `{{` and `}}`
|
|
* @returns A pattern that matches every key in a text
|
|
*/
|
|
const placeholderPattern = ({ start, end }: { readonly start: string; readonly end: string }): RegExp =>
|
|
new RegExp(`(?<=${escapeRegExp(start)})(?:(?!${escapeRegExp(start)}).)+?(?=${escapeRegExp(end)})`, "gs");
|