open-agreements
Version:
Open-source legal template filling CLI and library
467 lines • 18.8 kB
JavaScript
/**
* reject_changes — reject all tracked changes in a OOXML document body.
*
* Produces the document as it was before tracked changes were made by:
* - Removing w:ins elements AND their content (insertions undone)
* - Unwrapping w:del elements and converting w:delText → w:t (deletions restored)
* - Unwrapping w:moveFrom (keep at original position), removing w:moveTo and content
* - Restoring original properties from *PrChange records
* - Preserving cross-paragraph bookmark boundaries when resolving inserted paragraph marks
* - Stripping paragraph-level revision markers, merging a paragraph whose
* mark was a tracked insertion into the following paragraph
* - Stripping rsidDel attributes
*
* Operates on the W3C DOM (`@xmldom/xmldom`).
*/
import { OOXML } from './namespaces.js';
const W_NS = OOXML.W_NS;
// ── DOM helpers (internal) ──────────────────────────────────────────
function isW(node, localName) {
return (node.nodeType === 1 &&
node.namespaceURI === W_NS &&
node.localName === localName);
}
function getDepth(node) {
let depth = 0;
let cur = node.parentNode;
while (cur) {
depth++;
cur = cur.parentNode;
}
return depth;
}
function collectByLocalName(container, localName) {
return Array.from(container.getElementsByTagNameNS(W_NS, localName));
}
function removeAllByLocalName(container, localName) {
const elements = collectByLocalName(container, localName);
let count = 0;
for (const el of elements) {
if (el.parentNode) {
el.parentNode.removeChild(el);
count++;
}
}
return count;
}
function unwrapAllByLocalName(container, localName) {
const elements = collectByLocalName(container, localName);
// Sort deepest-first to handle nested wrappers correctly
elements.sort((a, b) => getDepth(b) - getDepth(a));
let count = 0;
for (const el of elements) {
const parent = el.parentNode;
if (!parent)
continue;
while (el.firstChild) {
parent.insertBefore(el.firstChild, el);
}
parent.removeChild(el);
count++;
}
return count;
}
/**
* Check if a paragraph has a paragraph-level revision marker.
* Pattern: w:p > w:pPr > w:rPr > w:ins (or w:del)
*/
function paragraphHasParaMarker(p, markerLocalName) {
for (let i = 0; i < p.childNodes.length; i++) {
const child = p.childNodes[i];
if (!isW(child, 'pPr'))
continue;
for (let j = 0; j < child.childNodes.length; j++) {
const pPrChild = child.childNodes[j];
if (!isW(pPrChild, 'rPr'))
continue;
for (let k = 0; k < pPrChild.childNodes.length; k++) {
const rPrChild = pPrChild.childNodes[k];
if (isW(rPrChild, markerLocalName))
return true;
}
}
}
return false;
}
// Property change element local names (all 6 types)
const PR_CHANGE_LOCALS = [
'rPrChange', 'pPrChange', 'sectPrChange',
'tblPrChange', 'trPrChange', 'tcPrChange',
];
// Marker-ish elements that may sit between two paragraphs at block level
// without ending the search for a merge target: the full EG_RangeMarkupElements
// schema group (wml.xsd), plus permStart/permEnd range markers and proofErr
// proofing anchors.
const RANGE_MARKUP_BLOCK_SIBLING_LOCALS = new Set([
'bookmarkStart', 'bookmarkEnd',
'commentRangeStart', 'commentRangeEnd',
'moveFromRangeStart', 'moveFromRangeEnd',
'moveToRangeStart', 'moveToRangeEnd',
'customXmlInsRangeStart', 'customXmlInsRangeEnd',
'customXmlDelRangeStart', 'customXmlDelRangeEnd',
'customXmlMoveFromRangeStart', 'customXmlMoveFromRangeEnd',
'customXmlMoveToRangeStart', 'customXmlMoveToRangeEnd',
'permStart', 'permEnd',
'proofErr',
]);
/**
* Find the next sibling paragraph a paragraph-mark revision can merge into,
* skipping block-level range/annotation markers. Returns null when the next
* block is not a paragraph (table, sdt, sectPr, end of parent).
*/
function findFollowingSiblingParagraph(p) {
let sibling = p.nextSibling;
while (sibling) {
if (sibling.nodeType === 1) {
if (isW(sibling, 'p'))
return sibling;
const el = sibling;
if (el.namespaceURI === W_NS && RANGE_MARKUP_BLOCK_SIBLING_LOCALS.has(el.localName ?? '')) {
sibling = sibling.nextSibling;
continue;
}
return null;
}
sibling = sibling.nextSibling;
}
return null;
}
/** True iff the paragraph still holds content beyond w:pPr and bare annotation markers. */
function paragraphHasContent(p) {
for (let i = 0; i < p.childNodes.length; i++) {
const child = p.childNodes[i];
if (child.nodeType !== 1)
continue;
if (isW(child, 'pPr'))
continue;
const el = child;
if (el.namespaceURI === W_NS && RANGE_MARKUP_BLOCK_SIBLING_LOCALS.has(el.localName ?? ''))
continue;
return true;
}
return false;
}
/**
* True iff removing an emptied mark-revised paragraph keeps its parent
* structurally valid for Word: the parent must retain at least one block
* element, must not end on a w:tbl (a trailing table needs a following
* paragraph), and two tables must not become adjacent (Word merges
* back-to-back tables). w:sectPr is ignored — a trailing body sectPr is not a
* block element.
*/
function canSafelyRemoveEmptyParagraph(p) {
const blockSibling = (start, dir) => {
let sibling = start;
while (sibling) {
if (sibling.nodeType === 1) {
const el = sibling;
if ((el.namespaceURI === W_NS && RANGE_MARKUP_BLOCK_SIBLING_LOCALS.has(el.localName ?? '')) ||
isW(el, 'sectPr')) {
sibling = sibling[dir];
continue;
}
return el;
}
sibling = sibling[dir];
}
return null;
};
const prev = blockSibling(p.previousSibling, 'previousSibling');
const next = blockSibling(p.nextSibling, 'nextSibling');
if (!prev && !next)
return false;
if (prev && isW(prev, 'tbl') && !next)
return false;
if (prev && next && isW(prev, 'tbl') && isW(next, 'tbl'))
return false;
return true;
}
/**
* Resolve a paragraph whose paragraph MARK revision was applied (inserted mark
* rejected): the inserted paragraph break disappears, so the paragraph's
* surviving content merges into the FOLLOWING paragraph. The surviving
* (following) paragraph keeps its own w:pPr — formatting follows the surviving
* paragraph mark — and the merged-away paragraph's w:pPr is dropped.
*
* The revision targets only the mark, never the paragraph's contents, so the
* contents must not be dropped wholesale (they disappear only via their own
* run-level w:ins wrappers). When no following sibling paragraph exists (last
* block, or the next block is a table), there is no break to remove into:
* content-bearing paragraphs are kept, and emptied ones are removed only where
* removal keeps the parent structurally valid (canSafelyRemoveEmptyParagraph).
*
* @conformance ECMA-376 edition 5, Part 1 § 17.13.5.20
* @see https://github.com/UseJunior/safe-docx/issues/431
*/
function resolveParagraphMarkRevision(p) {
const parent = p.parentNode;
if (!parent)
return;
const target = findFollowingSiblingParagraph(p);
if (!target) {
if (!paragraphHasContent(p) && canSafelyRemoveEmptyParagraph(p)) {
parent.removeChild(p);
}
return;
}
// Insertion point: before the target's first non-pPr child (the merged
// content precedes the target's own content in document order).
let ref = null;
for (let i = 0; i < target.childNodes.length; i++) {
const c = target.childNodes[i];
if (c.nodeType === 1 && isW(c, 'pPr'))
continue;
ref = c;
break;
}
const toMove = [];
for (let i = 0; i < p.childNodes.length; i++) {
const c = p.childNodes[i];
if (c.nodeType === 1 && isW(c, 'pPr'))
continue;
toMove.push(c);
}
for (const c of toMove) {
target.insertBefore(c, ref);
}
parent.removeChild(p);
}
/**
* Relocate orphaned bookmarks from a paragraph being removed to an
* adjacent kept paragraph. This preserves cross-paragraph bookmark boundaries.
*/
function relocateBookmarks(p, paragraphsToRemove) {
const parent = p.parentNode;
if (!parent)
return;
// Find an adjacent kept paragraph (prefer next, fallback to previous)
let target = null;
let sibling = p.nextSibling;
while (sibling) {
if (sibling.nodeType === 1 && isW(sibling, 'p') && !paragraphsToRemove.has(sibling)) {
target = sibling;
break;
}
sibling = sibling.nextSibling;
}
if (!target) {
sibling = p.previousSibling;
while (sibling) {
if (sibling.nodeType === 1 && isW(sibling, 'p') && !paragraphsToRemove.has(sibling)) {
target = sibling;
break;
}
sibling = sibling.previousSibling;
}
}
if (!target)
return;
// Move bookmarkStart/bookmarkEnd elements that are direct children of the
// paragraph — but only when the paragraph will NOT merge into a following
// paragraph. The Phase-G merge carries direct children in document order;
// pre-relocating them here would reorder bookmark boundaries relative to the
// surviving untracked content. Without a merge target the paragraph may be
// removed outright, so the markers must be rescued.
const toMove = [];
if (!findFollowingSiblingParagraph(p)) {
for (let i = 0; i < p.childNodes.length; i++) {
const child = p.childNodes[i];
if (child.nodeType !== 1)
continue;
const el = child;
if (isW(el, 'bookmarkStart') || isW(el, 'bookmarkEnd')) {
toMove.push(el);
}
}
}
// Also check sibling bookmarks (sibling-style: <bookmarkStart/><p/><bookmarkEnd/>)
let prev = p.previousSibling;
while (prev) {
if (prev.nodeType === 1) {
const el = prev;
if (isW(el, 'bookmarkStart') || isW(el, 'bookmarkEnd')) {
toMove.push(el);
prev = prev.previousSibling;
continue;
}
break;
}
prev = prev.previousSibling;
}
let next = p.nextSibling;
while (next) {
if (next.nodeType === 1) {
const el = next;
if (isW(el, 'bookmarkStart') || isW(el, 'bookmarkEnd')) {
toMove.push(el);
next = next.nextSibling;
continue;
}
break;
}
next = next.nextSibling;
}
for (const bm of toMove) {
// Insert at the beginning of the target paragraph (after pPr if present)
const firstNonPPr = Array.from(target.childNodes).find((n) => !(n.nodeType === 1 && isW(n, 'pPr')));
if (bm.parentNode)
bm.parentNode.removeChild(bm);
target.insertBefore(bm, firstNonPPr ?? null);
}
}
// ── Public API ──────────────────────────────────────────────────────
/**
* Reject all tracked changes in the document body or story root, restoring
* the document to its pre-edit state.
*
* Mutates the Document in place (same convention as acceptChanges).
*/
export function rejectChanges(doc) {
const root = doc.getElementsByTagNameNS(W_NS, 'body').item(0) ?? doc.documentElement;
if (!root) {
return { insertionsRemoved: 0, deletionsRestored: 0, movesReverted: 0, propertyChangesReverted: 0 };
}
// Phase A — Identify paragraphs whose MARK is a tracked insertion
const markInsertedParagraphs = new Set();
const allParagraphs = collectByLocalName(root, 'p');
for (const p of allParagraphs) {
// A paragraph-mark insertion (w:p > w:pPr > w:rPr > w:ins) means the
// paragraph BREAK was inserted — rejecting it merges the paragraph into the
// following one (resolveParagraphMarkRevision); the contents disappear only
// via their own run-level w:ins wrappers.
// We deliberately do NOT touch a paragraph based on content ("all runs inside
// w:ins/w:moveTo"): a run-level insertion under an untracked mark means text was
// inserted into a pre-existing paragraph, which Word/LibreOffice keep (empty) on
// reject. safe-docx's inserted paragraphs always carry the mark now, so the
// mark-based rule suffices and is Word-faithful. (Mirrors rejectAllChanges.)
if (paragraphHasParaMarker(p, 'ins')) {
markInsertedParagraphs.add(p);
}
}
// Phase B — Preserve cross-paragraph bookmark boundaries. Direct-child
// bookmarks of a paragraph that will merge ride the Phase-G merge in
// document order; relocateBookmarks rescues the rest (direct children of a
// paragraph with no merge target, which may be removed outright, plus
// adjacent sibling-style markers).
for (const p of markInsertedParagraphs) {
relocateBookmarks(p, markInsertedParagraphs);
}
// Phase C — Remove insertions and move destinations
const insertionsRemoved = removeAllByLocalName(root, 'ins');
const moveToRemoved = removeAllByLocalName(root, 'moveTo');
removeAllByLocalName(root, 'moveToRangeStart');
removeAllByLocalName(root, 'moveToRangeEnd');
removeAllByLocalName(root, 'moveFromRangeStart');
removeAllByLocalName(root, 'moveFromRangeEnd');
// Phase D — Unwrap deletions and convert w:delText → w:t
const deletionsRestored = unwrapAllByLocalName(root, 'del');
// Rename all w:delText elements to w:t so getParagraphText() sees them
const delTexts = collectByLocalName(root, 'delText');
for (const dt of delTexts) {
const parent = dt.parentNode;
if (!parent)
continue;
const t = doc.createElementNS(W_NS, 'w:t');
// Copy text content
if (dt.textContent) {
t.appendChild(doc.createTextNode(dt.textContent));
}
// Copy xml:space attribute if present
const xmlSpace = dt.getAttributeNS('http://www.w3.org/XML/1998/namespace', 'space')
?? dt.getAttribute('xml:space');
if (xmlSpace) {
t.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', xmlSpace);
}
parent.replaceChild(t, dt);
}
// Phase E — Unwrap move sources (keep content at original position)
const moveFromUnwrapped = unwrapAllByLocalName(root, 'moveFrom');
// Phase F — Restore original properties from *PrChange records
let propertyChangesReverted = 0;
for (const localName of PR_CHANGE_LOCALS) {
const changes = collectByLocalName(root, localName);
// Sort deepest-first
changes.sort((a, b) => getDepth(b) - getDepth(a));
for (const change of changes) {
const parentProp = change.parentNode;
if (!parentProp)
continue;
const grandParent = parentProp.parentNode;
if (!grandParent)
continue;
// The *PrChange element contains the original properties.
// Extract the original property element (e.g. rPr inside rPrChange).
// The expected mapping:
// rPrChange → child rPr = original run properties
// pPrChange → child pPr = original paragraph properties
// etc.
const expectedChildLocal = localName.replace('Change', '');
let originalProps = null;
for (let i = 0; i < change.childNodes.length; i++) {
const child = change.childNodes[i];
if (child.nodeType === 1 && isW(child, expectedChildLocal)) {
originalProps = child;
break;
}
}
if (originalProps) {
// Replace the current property element with the original
const restored = originalProps.cloneNode(true);
grandParent.replaceChild(restored, parentProp);
}
else {
// Original props were empty — remove the parent property element entirely
grandParent.removeChild(parentProp);
}
propertyChangesReverted++;
}
}
// Phase G — Cleanup
// Strip paragraph-level revision markers from w:pPr/w:rPr
for (const p of collectByLocalName(root, 'p')) {
for (let i = 0; i < p.childNodes.length; i++) {
const child = p.childNodes[i];
if (!isW(child, 'pPr'))
continue;
for (let j = 0; j < child.childNodes.length; j++) {
const pPrChild = child.childNodes[j];
if (!isW(pPrChild, 'rPr'))
continue;
const toRemove = [];
for (let k = 0; k < pPrChild.childNodes.length; k++) {
const rPrChild = pPrChild.childNodes[k];
if (isW(rPrChild, 'ins') || isW(rPrChild, 'del')) {
toRemove.push(rPrChild);
}
}
for (const el of toRemove) {
pPrChild.removeChild(el);
}
}
}
}
// Resolve paragraphs collected in Phase A: merge each into its following
// paragraph (document order, so consecutive mark-inserted paragraphs cascade
// forward into the first surviving one).
for (const p of markInsertedParagraphs) {
resolveParagraphMarkRevision(p);
}
// Strip w:rsidDel attributes on remaining elements
const allElements = root.getElementsByTagNameNS(W_NS, '*');
for (let i = 0; i < allElements.length; i++) {
const el = allElements[i];
if (el.hasAttributeNS(W_NS, 'rsidDel')) {
el.removeAttributeNS(W_NS, 'rsidDel');
}
if (el.hasAttribute('w:rsidDel')) {
el.removeAttribute('w:rsidDel');
}
}
return {
insertionsRemoved,
deletionsRestored,
movesReverted: moveFromUnwrapped + moveToRemoved,
propertyChangesReverted,
};
}
//# sourceMappingURL=reject_changes.js.map