open-agreements
Version:
Open-source legal template filling CLI and library
71 lines • 3.14 kB
JavaScript
/**
* Inline-run emitter.
*
* Shipped: text runs with full RunProps formatting, tab and break runs, and
* complete five-part complex fields. A FieldSpec compiles to
* begin → instruction text → separate → cached result → end so reading
* applications always display a value without recomputation prompts — the
* required `cachedResult` makes the no-recovery-dialog property
* unrepresentable-by-omission. `w:dirty` is never set (it triggers
* update-fields prompts in some readers).
*/
import { createWmlElement, createWmlTextElement } from '../../primitives/dom-helpers.js';
import { W } from '../../primitives/namespaces.js';
import { GenerationInternalError } from '../errors.js';
import { buildRunPropsElement } from './properties.js';
/** Instruction text per field, with the canonical surrounding spaces. */
const FIELD_INSTRUCTION_TEXT = {
PAGE: ' PAGE ',
NUMPAGES: ' NUMPAGES ',
};
function makeRun(doc, props, ctx, ...children) {
const run = createWmlElement(doc, W.r);
const rPr = buildRunPropsElement(doc, props, { themeColorValues: ctx?.themeColorValues });
if (rPr)
run.appendChild(rPr);
for (const child of children)
run.appendChild(child);
return run;
}
/**
* Five sibling runs per field: fldChar begin, preserved-space instruction
* text, fldChar separate, the cached result, fldChar end.
*
* @conformance ECMA-376 edition 5, Part 1 § 17.16.18
*/
function buildFieldRuns(doc, field, ctx) {
const instr = createWmlElement(doc, W.instrText);
instr.setAttribute('xml:space', 'preserve');
instr.appendChild(doc.createTextNode(FIELD_INSTRUCTION_TEXT[field.field]));
return [
makeRun(doc, field, ctx, createWmlElement(doc, W.fldChar, { 'w:fldCharType': 'begin' })),
makeRun(doc, field, ctx, instr),
makeRun(doc, field, ctx, createWmlElement(doc, W.fldChar, { 'w:fldCharType': 'separate' })),
makeRun(doc, field, ctx, createWmlTextElement(doc, field.cachedResult)),
makeRun(doc, field, ctx, createWmlElement(doc, W.fldChar, { 'w:fldCharType': 'end' })),
];
}
/** Build the w:r element(s) for one inline spec node. */
export function buildInlineRuns(doc, inline, ctx) {
switch (inline.kind) {
case 'text': {
const run = createWmlElement(doc, W.r);
const rPr = buildRunPropsElement(doc, inline, { themeColorValues: ctx?.themeColorValues });
if (rPr)
run.appendChild(rPr);
run.appendChild(createWmlTextElement(doc, inline.text));
return [run];
}
case 'field':
return buildFieldRuns(doc, inline, ctx);
case 'tab':
return [makeRun(doc, {}, ctx, createWmlElement(doc, W.tab))];
case 'break': {
const attrs = inline.breakType === 'page' ? { 'w:type': 'page' } : undefined;
return [makeRun(doc, {}, ctx, createWmlElement(doc, W.br, attrs))];
}
default:
throw new GenerationInternalError(`Inline kind '${inline.kind}' reached the run emitter without a shipped emitter`);
}
}
//# sourceMappingURL=run.js.map