@ansonlai/docx-redline-js 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,12 +9,13 @@ import {
9
9
  } from './paragraph-targeting.js';
10
10
  import { parseListItem, stripListMarker } from '../pipeline/list-markers.js';
11
11
 
12
- function getFirstDescendantByLocalName(node, localName) {
13
- if (!node || typeof node.getElementsByTagNameNS !== 'function') return null;
14
- const namespaced = node.getElementsByTagNameNS(WORD_MAIN_NS, localName);
15
- if (namespaced.length > 0) return namespaced[0];
16
- const anyNs = node.getElementsByTagNameNS('*', localName);
17
- return anyNs.length > 0 ? anyNs[0] : null;
12
+ /** Direct element child by local name; never crosses w:pPrChange / w:rPrChange boundaries. */
13
+ function getDirectChildByLocalName(node, localName) {
14
+ if (!node) return null;
15
+ for (const child of Array.from(node.childNodes || [])) {
16
+ if (child?.nodeType === 1 && child.localName === localName) return child;
17
+ }
18
+ return null;
18
19
  }
19
20
 
20
21
  function readValAttribute(element) {
@@ -178,17 +179,18 @@ function buildListEntriesForInsertion(parsedItems, normalizedTargetText, anchorL
178
179
  export function getParagraphListInfo(paragraph) {
179
180
  if (!paragraph) return null;
180
181
 
181
- const pPr = getFirstDescendantByLocalName(paragraph, 'pPr');
182
+ // Current properties only: direct w:pPr/w:numPr, never historical w:pPrChange/w:pPr.
183
+ const pPr = getDirectChildByLocalName(paragraph, 'pPr');
182
184
  if (!pPr) return null;
183
- const numPr = getFirstDescendantByLocalName(pPr, 'numPr');
185
+ const numPr = getDirectChildByLocalName(pPr, 'numPr');
184
186
  if (!numPr) return null;
185
- const numIdEl = getFirstDescendantByLocalName(numPr, 'numId');
187
+ const numIdEl = getDirectChildByLocalName(numPr, 'numId');
186
188
  if (!numIdEl) return null;
187
189
 
188
190
  const numId = readValAttribute(numIdEl);
189
191
  if (!numId || numId === '0') return null;
190
192
 
191
- const ilvlEl = getFirstDescendantByLocalName(numPr, 'ilvl');
193
+ const ilvlEl = getDirectChildByLocalName(numPr, 'ilvl');
192
194
  const ilvlRaw = readValAttribute(ilvlEl);
193
195
  const ilvl = Number.parseInt(ilvlRaw || '0', 10);
194
196
 
@@ -1,4 +1,4 @@
1
- // @ansonlai/docx-redline-js v0.8.2 — https://github.com/AnsonLai/docx-redline-js
1
+ // @ansonlai/docx-redline-js v0.8.3 — https://github.com/AnsonLai/docx-redline-js
2
2
  var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -3973,7 +3973,37 @@ async function executeListGeneration(options) {
3973
3973
  }];
3974
3974
  }
3975
3975
  }
3976
- if (generateRedlines && deletionRuns.length > 0) {
3976
+ const sourceParagraphCount = (originalRunModel || []).filter((run) => run.kind === RunKind.PARAGRAPH_START).length;
3977
+ if (generateRedlines && sourceParagraphCount > 0 && (sourceParagraphCount > 1 || deletionRuns.length === 0)) {
3978
+ let segment = null;
3979
+ const flushSegment = () => {
3980
+ if (!segment) return;
3981
+ results.push(serializeToOoxml(segment, null, [], {
3982
+ author,
3983
+ generateRedlines,
3984
+ revisionIdAllocator
3985
+ }));
3986
+ segment = null;
3987
+ };
3988
+ for (const run of originalRunModel) {
3989
+ if (run.kind === RunKind.PARAGRAPH_START) {
3990
+ flushSegment();
3991
+ segment = [{
3992
+ ...run,
3993
+ pPrElement: null,
3994
+ pPrXml: addParagraphMarkRevision(
3995
+ run.pPrElement || run.pPrXml || null,
3996
+ "del",
3997
+ author,
3998
+ revisionIdAllocator
3999
+ )
4000
+ }];
4001
+ } else if (segment && (run.kind === "text" || run.kind === "run")) {
4002
+ segment.push({ ...run, kind: "deletion", author });
4003
+ }
4004
+ }
4005
+ flushSegment();
4006
+ } else if (generateRedlines && deletionRuns.length > 0) {
3977
4007
  const deletedPPr = addParagraphMarkRevision(sourcePPr, "del", author, revisionIdAllocator);
3978
4008
  const deletedParagraph = serializeToOoxml(deletionRuns, deletedPPr, [], {
3979
4009
  author,
@@ -10171,12 +10201,12 @@ function validateParagraphBoundaryMutation(targetParagraph, modifiedText, option
10171
10201
  }
10172
10202
 
10173
10203
  // core/list-targeting.js
10174
- function getFirstDescendantByLocalName(node, localName2) {
10175
- if (!node || typeof node.getElementsByTagNameNS !== "function") return null;
10176
- const namespaced = node.getElementsByTagNameNS(WORD_MAIN_NS, localName2);
10177
- if (namespaced.length > 0) return namespaced[0];
10178
- const anyNs = node.getElementsByTagNameNS("*", localName2);
10179
- return anyNs.length > 0 ? anyNs[0] : null;
10204
+ function getDirectChildByLocalName(node, localName2) {
10205
+ if (!node) return null;
10206
+ for (const child of Array.from(node.childNodes || [])) {
10207
+ if (child?.nodeType === 1 && child.localName === localName2) return child;
10208
+ }
10209
+ return null;
10180
10210
  }
10181
10211
  function readValAttribute(element) {
10182
10212
  if (!element) return null;
@@ -10293,15 +10323,15 @@ function buildListEntriesForInsertion(parsedItems, normalizedTargetText, anchorL
10293
10323
  }
10294
10324
  function getParagraphListInfo(paragraph) {
10295
10325
  if (!paragraph) return null;
10296
- const pPr = getFirstDescendantByLocalName(paragraph, "pPr");
10326
+ const pPr = getDirectChildByLocalName(paragraph, "pPr");
10297
10327
  if (!pPr) return null;
10298
- const numPr = getFirstDescendantByLocalName(pPr, "numPr");
10328
+ const numPr = getDirectChildByLocalName(pPr, "numPr");
10299
10329
  if (!numPr) return null;
10300
- const numIdEl = getFirstDescendantByLocalName(numPr, "numId");
10330
+ const numIdEl = getDirectChildByLocalName(numPr, "numId");
10301
10331
  if (!numIdEl) return null;
10302
10332
  const numId = readValAttribute(numIdEl);
10303
10333
  if (!numId || numId === "0") return null;
10304
- const ilvlEl = getFirstDescendantByLocalName(numPr, "ilvl");
10334
+ const ilvlEl = getDirectChildByLocalName(numPr, "ilvl");
10305
10335
  const ilvlRaw = readValAttribute(ilvlEl);
10306
10336
  const ilvl = Number.parseInt(ilvlRaw || "0", 10);
10307
10337
  return {
@@ -10711,8 +10741,13 @@ function enforceListBindingOnParagraphNodes(nodes, options = {}) {
10711
10741
  }
10712
10742
  return updated;
10713
10743
  }
10744
+ function parseOxmlFragment(oxml) {
10745
+ const text2 = String(oxml || "");
10746
+ const declared = /xmlns:w\s*=/.test(text2);
10747
+ return parseOoxmlSafe(declared ? text2 : `<w:root xmlns:w="${NS_W}">${text2}</w:root>`, "application/xml").doc;
10748
+ }
10714
10749
  function getFirstParagraphFromOxml(oxml) {
10715
- const doc = parseOoxmlSafe(oxml, "application/xml").doc;
10750
+ const doc = parseOxmlFragment(oxml);
10716
10751
  if (!doc) return null;
10717
10752
  const parseError = getXmlParseError(doc);
10718
10753
  if (parseError) return null;
@@ -10739,17 +10774,17 @@ function setElementVal(element, value) {
10739
10774
  element.setAttribute("w:val", String(value));
10740
10775
  }
10741
10776
  function extractFirstParagraphNumIdFromOxml(oxml) {
10742
- const doc = parseOoxmlSafe(oxml, "application/xml").doc;
10777
+ const doc = parseOxmlFragment(oxml);
10743
10778
  if (!doc) return null;
10744
10779
  const parseError = getXmlParseError(doc);
10745
10780
  if (parseError) return null;
10746
10781
  const paragraphs = getDocumentParagraphNodes(doc);
10747
- const firstParagraph = paragraphs[0] || null;
10748
- if (!firstParagraph) return null;
10749
- const numIdNodes = Array.from(firstParagraph.getElementsByTagNameNS("*", "numId"));
10750
- for (const numIdNode of numIdNodes) {
10751
- const numId = getElementId(numIdNode, ["w:val", "val"]);
10752
- if (numId != null) return String(numId);
10782
+ for (const paragraph of paragraphs) {
10783
+ const numIdNodes = Array.from(paragraph.getElementsByTagNameNS("*", "numId"));
10784
+ for (const numIdNode of numIdNodes) {
10785
+ const numId = getElementId(numIdNode, ["w:val", "val"]);
10786
+ if (numId != null) return String(numId);
10787
+ }
10753
10788
  }
10754
10789
  return null;
10755
10790
  }
@@ -11245,6 +11280,8 @@ function createDynamicNumberingIdState(numberingXml, options = {}) {
11245
11280
  const baseNumId = Math.max(minId, maxUsedNumId + 1);
11246
11281
  const baseAbstractNumId = Math.max(minId, maxUsedAbstractNumId + 1);
11247
11282
  return {
11283
+ // Kept so list edits can recognise which existing definition a source list uses and continue it.
11284
+ sourceNumberingXml: String(numberingXml || ""),
11248
11285
  nextNumId: nextAvailableId(baseNumId, usedNumIds, maxPreferred),
11249
11286
  nextAbstractNumId: nextAvailableId(baseAbstractNumId, usedAbstractNumIds, maxPreferred),
11250
11287
  usedNumIds,
@@ -11385,6 +11422,82 @@ function buildExplicitDecimalMultilevelNumberingXml(numId, abstractNumId, startA
11385
11422
  </w:num>
11386
11423
  </w:numbering>`.trim();
11387
11424
  }
11425
+ function isTrackedDeletedParagraph(node) {
11426
+ if (!node || node.nodeType !== 1 || node.localName !== "p") return false;
11427
+ const pPr = Array.from(node.childNodes || []).find((child) => isDirectWordChild(child, "pPr"));
11428
+ const rPr = pPr && Array.from(pPr.childNodes || []).find((child) => isDirectWordChild(child, "rPr"));
11429
+ return !!rPr && Array.from(rPr.childNodes || []).some((child) => isDirectWordChild(child, "del"));
11430
+ }
11431
+ function paragraphNumIdNodes(node) {
11432
+ return Array.from(node?.getElementsByTagNameNS?.("*", "numId") || []).filter((numIdNode) => numIdNode.parentNode?.localName === "numPr");
11433
+ }
11434
+ function levelFormats(abstractNum) {
11435
+ const formats = /* @__PURE__ */ new Map();
11436
+ for (const lvl of Array.from(abstractNum?.getElementsByTagNameNS?.("*", "lvl") || [])) {
11437
+ const ilvl = getElementId2(lvl, ["w:ilvl", "ilvl"]);
11438
+ const fmt = Array.from(lvl.getElementsByTagNameNS("*", "numFmt"))[0]?.getAttribute("w:val") || null;
11439
+ if (ilvl != null && fmt) formats.set(ilvl, fmt);
11440
+ }
11441
+ return formats;
11442
+ }
11443
+ function normalizeListFormat(format) {
11444
+ return format === "bullet" || format === "circle" || format === "square" ? "bullet" : format;
11445
+ }
11446
+ function abstractNumForNumId(numberingDoc, numId) {
11447
+ const num = Array.from(numberingDoc.getElementsByTagNameNS("*", "num")).find((candidate) => getElementId2(candidate, ["w:numId", "numId"]) === numId);
11448
+ const abstractId = num && getElementId2(Array.from(num.getElementsByTagNameNS("*", "abstractNumId"))[0], ["w:val", "val"]);
11449
+ if (abstractId == null) return null;
11450
+ return Array.from(numberingDoc.getElementsByTagNameNS("*", "abstractNum")).find((candidate) => getElementId2(candidate, ["w:abstractNumId", "abstractNumId"]) === abstractId) || null;
11451
+ }
11452
+ function reuseSourceListNumbering(numberingXml, replacementNodes, sourceParagraphs, numberingIdState) {
11453
+ const sourceXml = numberingIdState?.sourceNumberingXml;
11454
+ if (!numberingXml || !String(sourceXml || "").trim() || !Array.isArray(replacementNodes)) return null;
11455
+ const sourceNumIds = /* @__PURE__ */ new Set();
11456
+ for (const paragraph of sourceParagraphs || []) {
11457
+ for (const numIdNode of paragraphNumIdNodes(paragraph)) {
11458
+ const id = getElementId2(numIdNode, ["w:val", "val"]);
11459
+ if (id != null && id !== 0) sourceNumIds.add(id);
11460
+ }
11461
+ }
11462
+ if (sourceNumIds.size !== 1) return null;
11463
+ const [sourceNumId] = sourceNumIds;
11464
+ const sourceDoc = parseOoxml(sourceXml);
11465
+ const payloadDoc = parseOoxml(numberingXml);
11466
+ if (hasXmlParseError(sourceDoc) || hasXmlParseError(payloadDoc)) return null;
11467
+ const sourceAbstract = abstractNumForNumId(sourceDoc, sourceNumId);
11468
+ if (!sourceAbstract) return null;
11469
+ const sourceFormats = levelFormats(sourceAbstract);
11470
+ const newParagraphNumIds = [];
11471
+ for (const node of replacementNodes) {
11472
+ if (isTrackedDeletedParagraph(node)) continue;
11473
+ for (const numIdNode of paragraphNumIdNodes(node)) {
11474
+ const ilvlNode = Array.from(numIdNode.parentNode.childNodes || []).find((child) => child.localName === "ilvl");
11475
+ newParagraphNumIds.push({
11476
+ numId: getElementId2(numIdNode, ["w:val", "val"]),
11477
+ ilvl: ilvlNode ? getElementId2(ilvlNode, ["w:val", "val"]) ?? 0 : 0
11478
+ });
11479
+ }
11480
+ }
11481
+ if (newParagraphNumIds.length === 0) return null;
11482
+ const payloadFormats = /* @__PURE__ */ new Map();
11483
+ for (const { numId, ilvl } of newParagraphNumIds) {
11484
+ if (numId == null) return null;
11485
+ if (!payloadFormats.has(numId)) {
11486
+ const abstract = abstractNumForNumId(payloadDoc, numId);
11487
+ if (!abstract) return null;
11488
+ payloadFormats.set(numId, levelFormats(abstract));
11489
+ }
11490
+ const generated = payloadFormats.get(numId).get(ilvl);
11491
+ const existing = sourceFormats.get(ilvl);
11492
+ if (!generated || !existing || normalizeListFormat(generated) !== normalizeListFormat(existing)) return null;
11493
+ }
11494
+ const clonedNodes = replacementNodes.map((node) => node?.cloneNode ? node.cloneNode(true) : node);
11495
+ for (const node of clonedNodes) {
11496
+ if (isTrackedDeletedParagraph(node)) continue;
11497
+ for (const numIdNode of paragraphNumIdNodes(node)) setElementVal2(numIdNode, sourceNumId);
11498
+ }
11499
+ return { numId: sourceNumId, replacementNodes: clonedNodes };
11500
+ }
11388
11501
  function remapNumberingPayloadForDocument(numberingXml, replacementNodes, numberingIdState) {
11389
11502
  const numberingDoc = parseOoxml(numberingXml);
11390
11503
  if (hasXmlParseError(numberingDoc)) {
@@ -11422,6 +11535,7 @@ function remapNumberingPayloadForDocument(numberingXml, replacementNodes, number
11422
11535
  }
11423
11536
  const clonedNodes = Array.isArray(replacementNodes) ? replacementNodes.map((node) => node?.cloneNode ? node.cloneNode(true) : node) : [];
11424
11537
  for (const node of clonedNodes) {
11538
+ if (isTrackedDeletedParagraph(node)) continue;
11425
11539
  const numIdNodes = Array.from(node?.getElementsByTagNameNS?.("*", "numId") || []);
11426
11540
  for (const numIdNode of numIdNodes) {
11427
11541
  const oldNumRef = getElementId2(numIdNode, ["w:val", "val"]);
@@ -12242,6 +12356,8 @@ function areRevisionTokensEqual(a, b) {
12242
12356
  var attr2 = (node, name) => node?.getAttribute?.(`w:${name}`) || node?.getAttribute?.(name) || "";
12243
12357
  var descendants = (node, name) => Array.from(node?.getElementsByTagNameNS?.(NS_W, name) || []);
12244
12358
  var first = (node, name) => descendants(node, name)[0] || null;
12359
+ var directChild2 = (node, name) => Array.from(node?.childNodes || []).find((child) => child?.nodeType === 1 && child.localName === name && (!child.namespaceURI || child.namespaceURI === NS_W)) || null;
12360
+ var currentPPr = (paragraph) => directChild2(paragraph, "pPr");
12245
12361
  function hasAncestor(node, localName2) {
12246
12362
  let cursor = node?.parentNode;
12247
12363
  while (cursor) {
@@ -12257,11 +12373,11 @@ function parseXml2(xml, partName, required = false) {
12257
12373
  return { doc: parsed.doc, warnings: parsed.warnings || [] };
12258
12374
  }
12259
12375
  function paragraphListProperties(paragraph) {
12260
- const numPr = first(first(paragraph, "pPr"), "numPr");
12376
+ const numPr = directChild2(currentPPr(paragraph), "numPr");
12261
12377
  if (!numPr) return null;
12262
- const numId = attr2(first(numPr, "numId"), "val");
12378
+ const numId = attr2(directChild2(numPr, "numId"), "val");
12263
12379
  if (!numId || numId === "0") return null;
12264
- return { numId, level: Number.parseInt(attr2(first(numPr, "ilvl"), "val") || "0", 10) || 0 };
12380
+ return { numId, level: Number.parseInt(attr2(directChild2(numPr, "ilvl"), "val") || "0", 10) || 0 };
12265
12381
  }
12266
12382
  function parseNumbering(numberingDoc) {
12267
12383
  const abstracts = /* @__PURE__ */ new Map();
@@ -12346,11 +12462,11 @@ function createNumberingResolver(numberingDoc) {
12346
12462
  };
12347
12463
  }
12348
12464
  function headingLevel(paragraph) {
12349
- const pPr = first(paragraph, "pPr");
12350
- const style = attr2(first(pPr, "pStyle"), "val");
12465
+ const pPr = currentPPr(paragraph);
12466
+ const style = attr2(directChild2(pPr, "pStyle"), "val");
12351
12467
  const match = style.match(/^heading\s*([1-9])$/i);
12352
12468
  if (match) return Math.min(Number(match[1]), 6);
12353
- const outline = Number.parseInt(attr2(first(pPr, "outlineLvl"), "val"), 10);
12469
+ const outline = Number.parseInt(attr2(directChild2(pPr, "outlineLvl"), "val"), 10);
12354
12470
  return Number.isInteger(outline) ? Math.min(outline + 1, 6) : null;
12355
12471
  }
12356
12472
  function structuralContext(paragraph, text2) {
@@ -12529,7 +12645,7 @@ function inspectDocumentParts(parts, options = {}) {
12529
12645
  const ids = [...new Set([...descendants(paragraph, "commentRangeStart"), ...descendants(paragraph, "commentReference")].map((node) => attr2(node, "id")).filter(Boolean))];
12530
12646
  const authors = revisionAuthors(paragraph);
12531
12647
  const list = resolveNumbering(paragraphListProperties(paragraph));
12532
- const styleId = attr2(first(first(paragraph, "pPr"), "pStyle"), "val") || null;
12648
+ const styleId = attr2(directChild2(currentPPr(paragraph), "pStyle"), "val") || null;
12533
12649
  const structure = structuralContext(paragraph, text2);
12534
12650
  const index = zeroIndex + 1;
12535
12651
  const provision = list?.label && list.format !== "bullet" ? list.label : null;
@@ -17930,7 +18046,9 @@ async function applyToParagraphByExactText(documentXml, targetText, modifiedText
17930
18046
  paragraphText,
17931
18047
  generateRedlines ? createRevisionMetadata(author, xmlDoc) : null,
17932
18048
  author,
17933
- { generateRedlines }
18049
+ // A wholly inserted paragraph must track its own paragraph mark; otherwise Word's
18050
+ // Reject All removes the text but leaves an empty paragraph behind.
18051
+ { generateRedlines, trackParagraphMark: true }
17934
18052
  );
17935
18053
  const imported = xmlDoc.importNode(plainParagraph, true);
17936
18054
  ensureParagraphIdsOnImportedNode(imported, operationSession);
@@ -18061,6 +18179,14 @@ async function applyToParagraphByExactText(documentXml, targetText, modifiedText
18061
18179
  const extracted = extractReplacementNodes(result.oxml);
18062
18180
  let replacementNodes = removeListPackagingSentinel(extracted.replacementNodes, result.warnings);
18063
18181
  let numberingXml = extracted.numberingXml;
18182
+ if (numberingXml && runtimeContext?.numberingIdState && !useTableScope) {
18183
+ const sourceParagraphs = useListScope ? listScopeEdit.paragraphs : explicitRangeParagraphs || [targetParagraph];
18184
+ const continued = reuseSourceListNumbering(numberingXml, replacementNodes, sourceParagraphs, runtimeContext.numberingIdState);
18185
+ if (continued) {
18186
+ replacementNodes = continued.replacementNodes;
18187
+ numberingXml = null;
18188
+ }
18189
+ }
18064
18190
  if (numberingXml && runtimeContext?.numberingIdState) {
18065
18191
  const normalizedNumbering = remapNumberingPayloadForDocument(numberingXml, replacementNodes, runtimeContext.numberingIdState);
18066
18192
  replacementNodes = normalizedNumbering.replacementNodes;