@createiq/htmldiff 1.0.5-beta.0 → 1.0.5-beta.2
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.
- package/dist/HtmlDiff.cjs +861 -5
- package/dist/HtmlDiff.cjs.map +1 -1
- package/dist/HtmlDiff.d.cts +16 -2
- package/dist/HtmlDiff.d.mts +16 -2
- package/dist/HtmlDiff.mjs +861 -5
- package/dist/HtmlDiff.mjs.map +1 -1
- package/package.json +1 -1
- package/src/HtmlDiff.ts +51 -5
- package/src/TableDiff.ts +1269 -0
- package/test/HtmlDiff.spec.ts +1 -1
- package/test/HtmlDiff.tables.spec.ts +1458 -0
- package/test/TableDiff.bench.ts +244 -0
package/dist/HtmlDiff.cjs
CHANGED
|
@@ -202,6 +202,830 @@ var Operation = class {
|
|
|
202
202
|
}
|
|
203
203
|
};
|
|
204
204
|
//#endregion
|
|
205
|
+
//#region src/TableDiff.ts
|
|
206
|
+
const PLACEHOLDER_PREFIX_BASE = "<!--HTMLDIFF_TABLE_";
|
|
207
|
+
const PLACEHOLDER_SUFFIX = "-->";
|
|
208
|
+
/**
|
|
209
|
+
* Hard cap on table dimensions handled by the structural-aware path.
|
|
210
|
+
* The row-LCS is O(rows²), the per-row cell-LCS is O(cells²), and each
|
|
211
|
+
* comparison string-equals row content (potentially many KB). Without a
|
|
212
|
+
* cap, a several-thousand-row table can pin a CPU for seconds. Tables
|
|
213
|
+
* larger than this fall through to the word-level diff, which scales
|
|
214
|
+
* linearly. Tuned to comfortably cover real-world ISDA schedules
|
|
215
|
+
* (which routinely have 1000+ rows).
|
|
216
|
+
*/
|
|
217
|
+
const MAX_TABLE_ROWS = 1500;
|
|
218
|
+
const MAX_TABLE_CELLS_PER_ROW = 200;
|
|
219
|
+
function makePlaceholderPrefix(oldHtml, newHtml) {
|
|
220
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
221
|
+
const prefix = `${PLACEHOLDER_PREFIX_BASE}${Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")}_`;
|
|
222
|
+
if (!oldHtml.includes(prefix) && !newHtml.includes(prefix)) return prefix;
|
|
223
|
+
}
|
|
224
|
+
return `${PLACEHOLDER_PREFIX_BASE}fallback_${Date.now()}_`;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Diffs every paired-by-position table in the inputs and replaces each
|
|
228
|
+
* source table with a placeholder, returning the modified inputs plus the
|
|
229
|
+
* placeholder→diff mapping. Returns null when there are no tables to
|
|
230
|
+
* preprocess or the table counts don't line up.
|
|
231
|
+
*/
|
|
232
|
+
function preprocessTables(oldHtml, newHtml, diffCell) {
|
|
233
|
+
const oldTables = findTopLevelTables(oldHtml);
|
|
234
|
+
const newTables = findTopLevelTables(newHtml);
|
|
235
|
+
if (oldTables.length === 0 && newTables.length === 0) return null;
|
|
236
|
+
if (oldTables.length !== newTables.length) return null;
|
|
237
|
+
for (let i = 0; i < oldTables.length; i++) if (exceedsSizeLimit(oldTables[i]) || exceedsSizeLimit(newTables[i])) return null;
|
|
238
|
+
const pairs = [];
|
|
239
|
+
for (let i = 0; i < oldTables.length; i++) pairs.push({
|
|
240
|
+
oldTable: oldTables[i],
|
|
241
|
+
newTable: newTables[i],
|
|
242
|
+
diffed: diffTable(oldHtml, newHtml, oldTables[i], newTables[i], diffCell)
|
|
243
|
+
});
|
|
244
|
+
let modifiedOld = oldHtml;
|
|
245
|
+
let modifiedNew = newHtml;
|
|
246
|
+
const placeholderPrefix = makePlaceholderPrefix(oldHtml, newHtml);
|
|
247
|
+
const placeholderToDiff = /* @__PURE__ */ new Map();
|
|
248
|
+
for (let i = pairs.length - 1; i >= 0; i--) {
|
|
249
|
+
const placeholder = `${placeholderPrefix}${i}${PLACEHOLDER_SUFFIX}`;
|
|
250
|
+
placeholderToDiff.set(placeholder, pairs[i].diffed);
|
|
251
|
+
modifiedOld = spliceString(modifiedOld, pairs[i].oldTable.tableStart, pairs[i].oldTable.tableEnd, placeholder);
|
|
252
|
+
modifiedNew = spliceString(modifiedNew, pairs[i].newTable.tableStart, pairs[i].newTable.tableEnd, placeholder);
|
|
253
|
+
}
|
|
254
|
+
return {
|
|
255
|
+
modifiedOld,
|
|
256
|
+
modifiedNew,
|
|
257
|
+
placeholderToDiff
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
function restoreTablePlaceholders(diffOutput, placeholderToDiff) {
|
|
261
|
+
let result = diffOutput;
|
|
262
|
+
for (const [placeholder, html] of placeholderToDiff) result = result.split(placeholder).join(html);
|
|
263
|
+
return result;
|
|
264
|
+
}
|
|
265
|
+
function spliceString(s, start, end, replacement) {
|
|
266
|
+
return s.slice(0, start) + replacement + s.slice(end);
|
|
267
|
+
}
|
|
268
|
+
function exceedsSizeLimit(table) {
|
|
269
|
+
if (table.rows.length > MAX_TABLE_ROWS) return true;
|
|
270
|
+
for (const row of table.rows) if (row.cells.length > MAX_TABLE_CELLS_PER_ROW) return true;
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
function diffTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
|
|
274
|
+
if (sameDimensions(oldTable, newTable)) return diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell);
|
|
275
|
+
if (oldTable.rows.length === newTable.rows.length) return diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell);
|
|
276
|
+
return diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell);
|
|
277
|
+
}
|
|
278
|
+
function diffSameRowCountTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
|
|
279
|
+
const out = [];
|
|
280
|
+
let cursor = newTable.tableStart;
|
|
281
|
+
let r = 0;
|
|
282
|
+
while (r < newTable.rows.length) {
|
|
283
|
+
const merge = detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r);
|
|
284
|
+
if (merge) {
|
|
285
|
+
out.push(newHtml.slice(cursor, newTable.rows[r].rowStart));
|
|
286
|
+
out.push(merge.diff);
|
|
287
|
+
cursor = newTable.rows[r + merge.span - 1].rowEnd;
|
|
288
|
+
r += merge.span;
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const split = detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r);
|
|
292
|
+
if (split) {
|
|
293
|
+
out.push(newHtml.slice(cursor, newTable.rows[r].rowStart));
|
|
294
|
+
out.push(split.diff);
|
|
295
|
+
cursor = newTable.rows[r + split.span - 1].rowEnd;
|
|
296
|
+
r += split.span;
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
const newRow = newTable.rows[r];
|
|
300
|
+
out.push(newHtml.slice(cursor, newRow.rowStart));
|
|
301
|
+
out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[r], newRow, diffCell));
|
|
302
|
+
cursor = newRow.rowEnd;
|
|
303
|
+
r++;
|
|
304
|
+
}
|
|
305
|
+
out.push(newHtml.slice(cursor, newTable.tableEnd));
|
|
306
|
+
return out.join("");
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Detects a vertical merge starting at row `r`: new row R has a single
|
|
310
|
+
* cell with rowspan=K (and any colspan ≥ 1), with rows R+1..R+K-1 empty
|
|
311
|
+
* in new. Old rows R..R+K-1 must have a logical column width equal to
|
|
312
|
+
* the new cell's colspan and contain no rowspan'd cells of their own.
|
|
313
|
+
* This handles both single-column merges (old rows are 1-cell, new cell
|
|
314
|
+
* rowspan=K) and rectangular merges (e.g. 2×2 merge into a single
|
|
315
|
+
* colspan=2 rowspan=2 cell). Output: emit the merged cell with
|
|
316
|
+
* `class='mod rowspan'` and the empty trailing rows unchanged.
|
|
317
|
+
*/
|
|
318
|
+
function detectVerticalMerge(oldHtml, newHtml, oldTable, newTable, r) {
|
|
319
|
+
const newRow = newTable.rows[r];
|
|
320
|
+
if (newRow.cells.length !== 1) return null;
|
|
321
|
+
const cell = newRow.cells[0];
|
|
322
|
+
const span = getRowspan(newHtml, cell);
|
|
323
|
+
if (span <= 1) return null;
|
|
324
|
+
if (r + span > newTable.rows.length) return null;
|
|
325
|
+
const colspan = getColspan(newHtml, cell);
|
|
326
|
+
for (let k = 1; k < span; k++) if (newTable.rows[r + k].cells.length !== 0) return null;
|
|
327
|
+
for (let k = 0; k < span; k++) {
|
|
328
|
+
const oldRow = oldTable.rows[r + k];
|
|
329
|
+
if (!oldRow) return null;
|
|
330
|
+
if (sumColspans(oldHtml, oldRow.cells) !== colspan) return null;
|
|
331
|
+
for (const c of oldRow.cells) if (getRowspan(oldHtml, c) !== 1) return null;
|
|
332
|
+
}
|
|
333
|
+
const out = [];
|
|
334
|
+
out.push(rowHeaderSlice(newHtml, newRow));
|
|
335
|
+
out.push(emitSpanChangedCell(newHtml, cell, "rowspan"));
|
|
336
|
+
out.push("</tr>");
|
|
337
|
+
for (let k = 1; k < span; k++) out.push(emitEmptyRow(newHtml, newTable.rows[r + k]));
|
|
338
|
+
return {
|
|
339
|
+
diff: out.join(""),
|
|
340
|
+
span
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Detects a vertical split starting at row `r`: old row R has a single
|
|
345
|
+
* cell with rowspan=K, old rows R+1..R+K-1 are empty. New rows R..R+K-1
|
|
346
|
+
* each have a single cell. Output: emit each new row with the new cell
|
|
347
|
+
* tagged `class='mod rowspan'`.
|
|
348
|
+
*/
|
|
349
|
+
function detectVerticalSplit(oldHtml, newHtml, oldTable, newTable, r) {
|
|
350
|
+
const oldRow = oldTable.rows[r];
|
|
351
|
+
if (oldRow.cells.length !== 1) return null;
|
|
352
|
+
const oldCell = oldRow.cells[0];
|
|
353
|
+
const span = getRowspan(oldHtml, oldCell);
|
|
354
|
+
if (span <= 1) return null;
|
|
355
|
+
if (r + span > oldTable.rows.length) return null;
|
|
356
|
+
const colspan = getColspan(oldHtml, oldCell);
|
|
357
|
+
for (let k = 1; k < span; k++) if (oldTable.rows[r + k].cells.length !== 0) return null;
|
|
358
|
+
for (let k = 0; k < span; k++) {
|
|
359
|
+
const newRow = newTable.rows[r + k];
|
|
360
|
+
if (!newRow) return null;
|
|
361
|
+
if (sumColspans(newHtml, newRow.cells) !== colspan) return null;
|
|
362
|
+
for (const c of newRow.cells) if (getRowspan(newHtml, c) !== 1) return null;
|
|
363
|
+
}
|
|
364
|
+
const out = [];
|
|
365
|
+
for (let k = 0; k < span; k++) {
|
|
366
|
+
const newRow = newTable.rows[r + k];
|
|
367
|
+
out.push(rowHeaderSlice(newHtml, newRow));
|
|
368
|
+
for (const c of newRow.cells) out.push(emitSpanChangedCell(newHtml, c, "rowspan"));
|
|
369
|
+
out.push("</tr>");
|
|
370
|
+
}
|
|
371
|
+
return {
|
|
372
|
+
diff: out.join(""),
|
|
373
|
+
span
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function emitEmptyRow(html, row) {
|
|
377
|
+
return html.slice(row.rowStart, row.rowEnd);
|
|
378
|
+
}
|
|
379
|
+
function sameDimensions(a, b) {
|
|
380
|
+
if (a.rows.length !== b.rows.length) return false;
|
|
381
|
+
for (let i = 0; i < a.rows.length; i++) if (a.rows[i].cells.length !== b.rows[i].cells.length) return false;
|
|
382
|
+
return true;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Same-dimension path: walk the new table verbatim and substitute each
|
|
386
|
+
* cell content range with the cell-level diff. The surrounding
|
|
387
|
+
* `<thead>`/`<tbody>`/whitespace passes through untouched.
|
|
388
|
+
*/
|
|
389
|
+
function diffPositionalTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
|
|
390
|
+
const out = [];
|
|
391
|
+
let cursor = newTable.tableStart;
|
|
392
|
+
for (let r = 0; r < newTable.rows.length; r++) {
|
|
393
|
+
const oldRow = oldTable.rows[r];
|
|
394
|
+
const newRow = newTable.rows[r];
|
|
395
|
+
for (let c = 0; c < newRow.cells.length; c++) {
|
|
396
|
+
const oldCell = oldRow.cells[c];
|
|
397
|
+
const newCell = newRow.cells[c];
|
|
398
|
+
out.push(newHtml.slice(cursor, newCell.contentStart));
|
|
399
|
+
out.push(diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd)));
|
|
400
|
+
cursor = newCell.contentEnd;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
out.push(newHtml.slice(cursor, newTable.tableEnd));
|
|
404
|
+
return out.join("");
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Mismatched-dimensions path: row-level LCS to identify added/deleted rows,
|
|
408
|
+
* then per preserved row a cell-level LCS to identify added/deleted cells.
|
|
409
|
+
* Reconstructs the table from scratch — there's no "single new structure"
|
|
410
|
+
* to walk verbatim, since we're stitching together kept rows from both
|
|
411
|
+
* sides.
|
|
412
|
+
*/
|
|
413
|
+
function diffStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, diffCell) {
|
|
414
|
+
const alignment = pairSimilarUnmatchedRows(lcsAlign(oldTable.rows.map((row) => rowKey(oldHtml, row)), newTable.rows.map((row) => rowKey(newHtml, row))), oldTable, newTable, oldHtml, newHtml);
|
|
415
|
+
if (newTable.rows.length === 0) return rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment, diffCell);
|
|
416
|
+
const out = [];
|
|
417
|
+
out.push(newHtml.slice(newTable.tableStart, newTable.rows[0].rowStart));
|
|
418
|
+
let cursor = newTable.rows[0].rowStart;
|
|
419
|
+
for (const align of alignment) if (align.newIdx !== null) {
|
|
420
|
+
const newRow = newTable.rows[align.newIdx];
|
|
421
|
+
out.push(newHtml.slice(cursor, newRow.rowStart));
|
|
422
|
+
if (align.oldIdx !== null) out.push(diffPreservedRow(oldHtml, newHtml, oldTable.rows[align.oldIdx], newRow, diffCell));
|
|
423
|
+
else out.push(emitFullRow(newHtml, newRow, "ins", diffCell));
|
|
424
|
+
cursor = newRow.rowEnd;
|
|
425
|
+
} else if (align.oldIdx !== null) out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], "del", diffCell));
|
|
426
|
+
out.push(newHtml.slice(cursor, newTable.tableEnd));
|
|
427
|
+
return out.join("");
|
|
428
|
+
}
|
|
429
|
+
function rebuildStructurallyAlignedTable(oldHtml, newHtml, oldTable, newTable, alignment, diffCell) {
|
|
430
|
+
const out = [];
|
|
431
|
+
out.push(headerSlice(newHtml, newTable, oldHtml, oldTable));
|
|
432
|
+
for (const align of alignment) if (align.oldIdx !== null) out.push(emitFullRow(oldHtml, oldTable.rows[align.oldIdx], "del", diffCell));
|
|
433
|
+
else if (align.newIdx !== null) out.push(emitFullRow(newHtml, newTable.rows[align.newIdx], "ins", diffCell));
|
|
434
|
+
out.push("</table>");
|
|
435
|
+
return out.join("");
|
|
436
|
+
}
|
|
437
|
+
function headerSlice(newHtml, newTable, oldHtml, oldTable) {
|
|
438
|
+
const newFirstRow = newTable.rows[0]?.rowStart ?? newTable.tableEnd - 8;
|
|
439
|
+
if (newFirstRow > newTable.tableStart) return newHtml.slice(newTable.tableStart, newFirstRow);
|
|
440
|
+
const oldFirstRow = oldTable.rows[0]?.rowStart ?? oldTable.tableEnd - 8;
|
|
441
|
+
return oldHtml.slice(oldTable.tableStart, oldFirstRow);
|
|
442
|
+
}
|
|
443
|
+
function rowKey(html, row) {
|
|
444
|
+
return html.slice(row.rowStart, row.rowEnd).replace(/\s+/g, " ").trim();
|
|
445
|
+
}
|
|
446
|
+
function diffPreservedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
|
|
447
|
+
if (oldRow.cells.length === newRow.cells.length) return diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell);
|
|
448
|
+
const colspanAligned = diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell);
|
|
449
|
+
if (colspanAligned !== null) return colspanAligned;
|
|
450
|
+
return diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Try to align cells by logical column position (sum of colspans). When
|
|
454
|
+
* one side has a colspan'd cell that absorbs multiple cells on the other
|
|
455
|
+
* side, emit the new structure with `class='mod colspan'` on the
|
|
456
|
+
* merged/split cells. Returns null if the rows don't align cleanly —
|
|
457
|
+
* caller falls back to a generic cell-LCS.
|
|
458
|
+
*/
|
|
459
|
+
function diffColspanChangedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
|
|
460
|
+
if (sumColspans(oldHtml, oldRow.cells) !== sumColspans(newHtml, newRow.cells)) return null;
|
|
461
|
+
const out = [];
|
|
462
|
+
out.push(rowHeaderSlice(newHtml, newRow));
|
|
463
|
+
let oi = 0;
|
|
464
|
+
let ni = 0;
|
|
465
|
+
while (oi < oldRow.cells.length && ni < newRow.cells.length) {
|
|
466
|
+
const oCell = oldRow.cells[oi];
|
|
467
|
+
const nCell = newRow.cells[ni];
|
|
468
|
+
const oSpan = getColspan(oldHtml, oCell);
|
|
469
|
+
const nSpan = getColspan(newHtml, nCell);
|
|
470
|
+
if (oSpan === nSpan) {
|
|
471
|
+
out.push(emitDiffedCell(oldHtml, newHtml, oCell, nCell, diffCell));
|
|
472
|
+
oi++;
|
|
473
|
+
ni++;
|
|
474
|
+
} else if (nSpan > oSpan) {
|
|
475
|
+
let totalOldSpan = 0;
|
|
476
|
+
let oj = oi;
|
|
477
|
+
while (oj < oldRow.cells.length && totalOldSpan < nSpan) {
|
|
478
|
+
totalOldSpan += getColspan(oldHtml, oldRow.cells[oj]);
|
|
479
|
+
oj++;
|
|
480
|
+
}
|
|
481
|
+
if (totalOldSpan !== nSpan) return null;
|
|
482
|
+
out.push(emitSpanChangedCell(newHtml, nCell, "colspan"));
|
|
483
|
+
oi = oj;
|
|
484
|
+
ni++;
|
|
485
|
+
} else {
|
|
486
|
+
let totalNewSpan = 0;
|
|
487
|
+
let nj = ni;
|
|
488
|
+
while (nj < newRow.cells.length && totalNewSpan < oSpan) {
|
|
489
|
+
totalNewSpan += getColspan(newHtml, newRow.cells[nj]);
|
|
490
|
+
nj++;
|
|
491
|
+
}
|
|
492
|
+
if (totalNewSpan !== oSpan) return null;
|
|
493
|
+
for (let k = ni; k < nj; k++) out.push(emitSpanChangedCell(newHtml, newRow.cells[k], "colspan"));
|
|
494
|
+
oi++;
|
|
495
|
+
ni = nj;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (oi !== oldRow.cells.length || ni !== newRow.cells.length) return null;
|
|
499
|
+
out.push("</tr>");
|
|
500
|
+
return out.join("");
|
|
501
|
+
}
|
|
502
|
+
function sumColspans(html, cells) {
|
|
503
|
+
let total = 0;
|
|
504
|
+
for (const cell of cells) total += getColspan(html, cell);
|
|
505
|
+
return total;
|
|
506
|
+
}
|
|
507
|
+
function getColspan(html, cell) {
|
|
508
|
+
return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), "colspan");
|
|
509
|
+
}
|
|
510
|
+
function getRowspan(html, cell) {
|
|
511
|
+
return parseSpanAttribute(html.slice(cell.cellStart, cell.contentStart), "rowspan");
|
|
512
|
+
}
|
|
513
|
+
function parseSpanAttribute(openingTag, name) {
|
|
514
|
+
const m = (name === "colspan" ? /\bcolspan\s*=\s*["']?(\d+)["']?/i : /\browspan\s*=\s*["']?(\d+)["']?/i).exec(openingTag);
|
|
515
|
+
if (!m) return 1;
|
|
516
|
+
const value = Number.parseInt(m[1], 10);
|
|
517
|
+
return Number.isFinite(value) && value > 0 ? value : 1;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Emits a cell that's the merged/split product of a structural change,
|
|
521
|
+
* tagged with `class='mod colspan'` or `class='mod rowspan'`. Content is
|
|
522
|
+
* carried through unmodified — Word doesn't track these changes, and
|
|
523
|
+
* inserting del/ins around content that didn't really change would be
|
|
524
|
+
* misleading.
|
|
525
|
+
*/
|
|
526
|
+
function emitSpanChangedCell(html, cell, kind) {
|
|
527
|
+
const tdOpening = parseOpeningTagAt(html, cell.cellStart);
|
|
528
|
+
if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd);
|
|
529
|
+
return injectClass(html.slice(cell.cellStart, tdOpening.end), `mod ${kind}`) + html.slice(cell.contentStart, cell.cellEnd);
|
|
530
|
+
}
|
|
531
|
+
function diffPositionalRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
|
|
532
|
+
const out = [];
|
|
533
|
+
const trHeader = rowHeaderSlice(newHtml, newRow);
|
|
534
|
+
out.push(trHeader);
|
|
535
|
+
let cursor = newRow.cells[0]?.cellStart ?? newRow.rowEnd;
|
|
536
|
+
for (let c = 0; c < newRow.cells.length; c++) {
|
|
537
|
+
const oldCell = oldRow.cells[c];
|
|
538
|
+
const newCell = newRow.cells[c];
|
|
539
|
+
out.push(newHtml.slice(cursor, newCell.contentStart));
|
|
540
|
+
out.push(diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd)));
|
|
541
|
+
cursor = newCell.contentEnd;
|
|
542
|
+
}
|
|
543
|
+
out.push(newHtml.slice(cursor, newRow.rowEnd));
|
|
544
|
+
return out.join("");
|
|
545
|
+
}
|
|
546
|
+
function diffStructurallyAlignedRow(oldHtml, newHtml, oldRow, newRow, diffCell) {
|
|
547
|
+
const alignment = pairSimilarUnmatchedCells(lcsAlign(oldRow.cells.map((cell) => cellKey(oldHtml, cell)), newRow.cells.map((cell) => cellKey(newHtml, cell))), oldRow, newRow, oldHtml, newHtml);
|
|
548
|
+
const out = [];
|
|
549
|
+
out.push(rowHeaderSlice(newHtml, newRow));
|
|
550
|
+
for (const align of alignment) if (align.oldIdx !== null && align.newIdx !== null) {
|
|
551
|
+
const oldCell = oldRow.cells[align.oldIdx];
|
|
552
|
+
const newCell = newRow.cells[align.newIdx];
|
|
553
|
+
out.push(emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell));
|
|
554
|
+
} else if (align.newIdx !== null) out.push(emitFullCell(newHtml, newRow.cells[align.newIdx], "ins", diffCell));
|
|
555
|
+
else if (align.oldIdx !== null) out.push(emitFullCell(oldHtml, oldRow.cells[align.oldIdx], "del", diffCell));
|
|
556
|
+
out.push("</tr>");
|
|
557
|
+
return out.join("");
|
|
558
|
+
}
|
|
559
|
+
function cellKey(html, cell) {
|
|
560
|
+
return html.slice(cell.contentStart, cell.contentEnd).replace(/\s+/g, " ").trim();
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Emits a row with all cells either inserted (kind='ins') or deleted
|
|
564
|
+
* (kind='del'). Adds `class='diffins'`/`'diffdel'` to the `<tr>` and to
|
|
565
|
+
* each `<td>`, with an `<ins>`/`<del>` wrapper around any cell content
|
|
566
|
+
* (empty cells get the class but no wrapper).
|
|
567
|
+
*/
|
|
568
|
+
function emitFullRow(html, row, kind, diffCell) {
|
|
569
|
+
const cls = kind === "ins" ? "diffins" : "diffdel";
|
|
570
|
+
const trOpening = parseOpeningTagAt(html, row.rowStart);
|
|
571
|
+
if (!trOpening) return html.slice(row.rowStart, row.rowEnd);
|
|
572
|
+
const out = [injectClass(html.slice(row.rowStart, trOpening.end), cls)];
|
|
573
|
+
let cursor = trOpening.end;
|
|
574
|
+
for (const cell of row.cells) {
|
|
575
|
+
out.push(html.slice(cursor, cell.cellStart));
|
|
576
|
+
out.push(emitFullCell(html, cell, kind, diffCell));
|
|
577
|
+
cursor = cell.cellEnd;
|
|
578
|
+
}
|
|
579
|
+
out.push(html.slice(cursor, row.rowEnd));
|
|
580
|
+
return out.join("");
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Emits a fully-inserted or fully-deleted cell. Inner text runs are wrapped
|
|
584
|
+
* with `<ins>`/`<del>` while formatting tags pass through unchanged, so
|
|
585
|
+
* `<strong>B</strong>` renders as `<strong><ins>B</ins></strong>` —
|
|
586
|
+
* matching htmldiff's general convention without the doubled-`<ins>` that
|
|
587
|
+
* the full recursive diff would produce for newly-inserted formatting.
|
|
588
|
+
* Empty cells get the class on the `<td>` but no inner wrapping.
|
|
589
|
+
*/
|
|
590
|
+
function emitFullCell(html, cell, kind, _diffCell) {
|
|
591
|
+
const cls = kind === "ins" ? "diffins" : "diffdel";
|
|
592
|
+
const tdOpening = parseOpeningTagAt(html, cell.cellStart);
|
|
593
|
+
if (!tdOpening) return html.slice(cell.cellStart, cell.cellEnd);
|
|
594
|
+
const tdOpenTag = injectClass(html.slice(cell.cellStart, tdOpening.end), cls);
|
|
595
|
+
const content = html.slice(cell.contentStart, cell.contentEnd);
|
|
596
|
+
const wrapped = content.trim().length === 0 ? content : wrapInlineTextRuns(content, kind);
|
|
597
|
+
const closing = html.slice(cell.contentEnd, cell.cellEnd);
|
|
598
|
+
return tdOpenTag + wrapped + closing;
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Wraps every non-whitespace text run in the given content with an
|
|
602
|
+
* `<ins>`/`<del>` tag, leaving HTML tags untouched. This produces output
|
|
603
|
+
* like `<strong><ins>X</ins></strong>` for fully-inserted formatted
|
|
604
|
+
* content — the same shape the rest of htmldiff emits for content
|
|
605
|
+
* insertions inside existing formatting.
|
|
606
|
+
*/
|
|
607
|
+
function wrapInlineTextRuns(content, kind) {
|
|
608
|
+
const tag = kind === "ins" ? "ins" : "del";
|
|
609
|
+
const cls = kind === "ins" ? "diffins" : "diffdel";
|
|
610
|
+
const out = [];
|
|
611
|
+
let i = 0;
|
|
612
|
+
while (i < content.length) {
|
|
613
|
+
if (content[i] === "<") {
|
|
614
|
+
const tagEnd = parseOpeningTagAt(content, i);
|
|
615
|
+
if (!tagEnd) {
|
|
616
|
+
out.push(content.slice(i));
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
out.push(content.slice(i, tagEnd.end));
|
|
620
|
+
i = tagEnd.end;
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
let j = i;
|
|
624
|
+
while (j < content.length && content[j] !== "<") j++;
|
|
625
|
+
const text = content.slice(i, j);
|
|
626
|
+
if (text.trim().length > 0) out.push(`<${tag} class='${cls}'>${text}</${tag}>`);
|
|
627
|
+
else out.push(text);
|
|
628
|
+
i = j;
|
|
629
|
+
}
|
|
630
|
+
return out.join("");
|
|
631
|
+
}
|
|
632
|
+
function emitDiffedCell(oldHtml, newHtml, oldCell, newCell, diffCell) {
|
|
633
|
+
const tdOpening = parseOpeningTagAt(newHtml, newCell.cellStart);
|
|
634
|
+
if (!tdOpening) return newHtml.slice(newCell.cellStart, newCell.cellEnd);
|
|
635
|
+
const tdOpenTag = newHtml.slice(newCell.cellStart, tdOpening.end);
|
|
636
|
+
const content = diffCell(oldHtml.slice(oldCell.contentStart, oldCell.contentEnd), newHtml.slice(newCell.contentStart, newCell.contentEnd));
|
|
637
|
+
const closing = newHtml.slice(newCell.contentEnd, newCell.cellEnd);
|
|
638
|
+
return tdOpenTag + content + closing;
|
|
639
|
+
}
|
|
640
|
+
function rowHeaderSlice(html, row) {
|
|
641
|
+
const opening = parseOpeningTagAt(html, row.rowStart);
|
|
642
|
+
if (!opening) return "";
|
|
643
|
+
if (row.cells.length === 0) return html.slice(row.rowStart, opening.end);
|
|
644
|
+
return html.slice(row.rowStart, row.cells[0].cellStart);
|
|
645
|
+
}
|
|
646
|
+
/** Character-level similarity threshold above which we treat two rows as "the same row, edited". */
|
|
647
|
+
const ROW_FUZZY_THRESHOLD = .5;
|
|
648
|
+
/**
|
|
649
|
+
* Threshold for "this cell is a content-edit of that cell." Tuned the same
|
|
650
|
+
* as ROW_FUZZY_THRESHOLD; cells in legal docs that share most of their
|
|
651
|
+
* content typically ARE the same logical cell with a body edit, so 0.5
|
|
652
|
+
* works for both granularities in practice.
|
|
653
|
+
*/
|
|
654
|
+
const CELL_FUZZY_THRESHOLD = .5;
|
|
655
|
+
/**
|
|
656
|
+
* After exact LCS, scan the alignment for runs of "old deleted, then new
|
|
657
|
+
* inserted" (or vice versa) and pair entries whose content is similar
|
|
658
|
+
* enough to be treated as an edit rather than a delete+insert. This keeps
|
|
659
|
+
* row-level edits (a typo fix, a single word change) from being shown as
|
|
660
|
+
* an entire row vanishing and a new one appearing — matching what users
|
|
661
|
+
* expect from a typical track-changes view.
|
|
662
|
+
*/
|
|
663
|
+
function pairSimilarUnmatchedRows(alignment, oldTable, newTable, oldHtml, newHtml) {
|
|
664
|
+
return pairSimilarUnmatched(alignment, ROW_FUZZY_THRESHOLD, (oldIdx, newIdx) => rowSimilarity(oldTable.rows[oldIdx], newTable.rows[newIdx], oldHtml, newHtml));
|
|
665
|
+
}
|
|
666
|
+
function pairSimilarUnmatchedCells(alignment, oldRow, newRow, oldHtml, newHtml) {
|
|
667
|
+
return pairSimilarUnmatched(alignment, CELL_FUZZY_THRESHOLD, (oldIdx, newIdx) => cellSimilarity(oldRow.cells[oldIdx], newRow.cells[newIdx], oldHtml, newHtml));
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Identify pairings inside each unmatched-only run, then build the output
|
|
671
|
+
* alignment by walking the original and substituting paired entries at
|
|
672
|
+
* the *ins position* (not the del position). This keeps the result
|
|
673
|
+
* monotonic in newIdx — critical because the cursor-based emission
|
|
674
|
+
* downstream walks new's html in order. Emitting at the del position
|
|
675
|
+
* would be fine when del<ins in the alignment array (the typical case),
|
|
676
|
+
* but can violate monotonicity when there are mixed unpaired entries in
|
|
677
|
+
* between (column-add + row-add together, content-edit + column-add,
|
|
678
|
+
* etc.).
|
|
679
|
+
*
|
|
680
|
+
* Generic over what's being paired — works for both rows (by full row
|
|
681
|
+
* content similarity) and cells (by per-cell content similarity).
|
|
682
|
+
*/
|
|
683
|
+
function pairSimilarUnmatched(alignment, threshold, similarity) {
|
|
684
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
685
|
+
let i = 0;
|
|
686
|
+
while (i < alignment.length) {
|
|
687
|
+
if (alignment[i].oldIdx !== null && alignment[i].newIdx !== null) {
|
|
688
|
+
i++;
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
const runStart = i;
|
|
692
|
+
while (i < alignment.length && alignment[i].oldIdx === null !== (alignment[i].newIdx === null)) i++;
|
|
693
|
+
const runEnd = i;
|
|
694
|
+
const delIndices = [];
|
|
695
|
+
const insIndices = [];
|
|
696
|
+
for (let k = runStart; k < runEnd; k++) if (alignment[k].oldIdx !== null) delIndices.push(k);
|
|
697
|
+
else insIndices.push(k);
|
|
698
|
+
const usedIns = /* @__PURE__ */ new Set();
|
|
699
|
+
for (const di of delIndices) {
|
|
700
|
+
let bestIi = -1;
|
|
701
|
+
let bestSim = threshold;
|
|
702
|
+
for (const ii of insIndices) {
|
|
703
|
+
if (usedIns.has(ii)) continue;
|
|
704
|
+
const sim = similarity(alignment[di].oldIdx, alignment[ii].newIdx);
|
|
705
|
+
if (sim > bestSim) {
|
|
706
|
+
bestSim = sim;
|
|
707
|
+
bestIi = ii;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (bestIi >= 0) {
|
|
711
|
+
pairs.set(di, bestIi);
|
|
712
|
+
usedIns.add(bestIi);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
const insToDel = /* @__PURE__ */ new Map();
|
|
717
|
+
for (const [delAi, insAi] of pairs) insToDel.set(insAi, delAi);
|
|
718
|
+
const pairedDels = new Set(pairs.keys());
|
|
719
|
+
const result = [];
|
|
720
|
+
for (let k = 0; k < alignment.length; k++) {
|
|
721
|
+
if (pairedDels.has(k)) continue;
|
|
722
|
+
if (insToDel.has(k)) {
|
|
723
|
+
const delAi = insToDel.get(k);
|
|
724
|
+
result.push({
|
|
725
|
+
oldIdx: alignment[delAi].oldIdx,
|
|
726
|
+
newIdx: alignment[k].newIdx
|
|
727
|
+
});
|
|
728
|
+
} else result.push(alignment[k]);
|
|
729
|
+
}
|
|
730
|
+
return result;
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Character-level similarity using shared prefix + suffix as a fraction
|
|
734
|
+
* of the longer string. Catches "single edit somewhere in a long row"
|
|
735
|
+
* (which token-Jaccard misses on short rows) while still correctly
|
|
736
|
+
* rejecting rows with no positional overlap. HTML tags are stripped to
|
|
737
|
+
* keep the comparison content-focused.
|
|
738
|
+
*/
|
|
739
|
+
function rowSimilarity(oldRow, newRow, oldHtml, newHtml) {
|
|
740
|
+
const a = rowText(oldHtml, oldRow);
|
|
741
|
+
const b = rowText(newHtml, newRow);
|
|
742
|
+
if (a === b) return 1;
|
|
743
|
+
if (a.length === 0 || b.length === 0) return 0;
|
|
744
|
+
let prefix = 0;
|
|
745
|
+
const minLen = Math.min(a.length, b.length);
|
|
746
|
+
while (prefix < minLen && a[prefix] === b[prefix]) prefix++;
|
|
747
|
+
let suffix = 0;
|
|
748
|
+
while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
|
|
749
|
+
return (prefix + suffix) / Math.max(a.length, b.length);
|
|
750
|
+
}
|
|
751
|
+
function rowText(html, row) {
|
|
752
|
+
const parts = [];
|
|
753
|
+
for (const cell of row.cells) parts.push(html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, " "));
|
|
754
|
+
return parts.join(" ").replace(/\s+/g, " ").trim().toLowerCase();
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Character-level prefix+suffix similarity for a single cell's text
|
|
758
|
+
* content. Same metric as rowSimilarity, scoped to one cell so we can
|
|
759
|
+
* fuzzy-pair unmatched cells (e.g. a cell with a content edit alongside
|
|
760
|
+
* a column add in the same row).
|
|
761
|
+
*/
|
|
762
|
+
function cellSimilarity(oldCell, newCell, oldHtml, newHtml) {
|
|
763
|
+
const a = cellText(oldHtml, oldCell);
|
|
764
|
+
const b = cellText(newHtml, newCell);
|
|
765
|
+
if (a === b) return 1;
|
|
766
|
+
if (a.length === 0 || b.length === 0) return 0;
|
|
767
|
+
let prefix = 0;
|
|
768
|
+
const minLen = Math.min(a.length, b.length);
|
|
769
|
+
while (prefix < minLen && a[prefix] === b[prefix]) prefix++;
|
|
770
|
+
let suffix = 0;
|
|
771
|
+
while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
|
|
772
|
+
return (prefix + suffix) / Math.max(a.length, b.length);
|
|
773
|
+
}
|
|
774
|
+
function cellText(html, cell) {
|
|
775
|
+
return html.slice(cell.contentStart, cell.contentEnd).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Standard LCS alignment: walks both sequences and emits a list of pairs
|
|
779
|
+
* where `(oldIdx, newIdx)` are both set for matching positions, and one
|
|
780
|
+
* side is null for an unmatched entry on the other side. Equality uses
|
|
781
|
+
* strict ===.
|
|
782
|
+
*/
|
|
783
|
+
function lcsAlign(oldKeys, newKeys) {
|
|
784
|
+
const m = oldKeys.length;
|
|
785
|
+
const n = newKeys.length;
|
|
786
|
+
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
|
787
|
+
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) if (oldKeys[i - 1] === newKeys[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
|
|
788
|
+
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
|
789
|
+
const result = [];
|
|
790
|
+
let i = m;
|
|
791
|
+
let j = n;
|
|
792
|
+
while (i > 0 || j > 0) if (i > 0 && j > 0 && oldKeys[i - 1] === newKeys[j - 1]) {
|
|
793
|
+
result.unshift({
|
|
794
|
+
oldIdx: i - 1,
|
|
795
|
+
newIdx: j - 1
|
|
796
|
+
});
|
|
797
|
+
i--;
|
|
798
|
+
j--;
|
|
799
|
+
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
|
|
800
|
+
result.unshift({
|
|
801
|
+
oldIdx: null,
|
|
802
|
+
newIdx: j - 1
|
|
803
|
+
});
|
|
804
|
+
j--;
|
|
805
|
+
} else {
|
|
806
|
+
result.unshift({
|
|
807
|
+
oldIdx: i - 1,
|
|
808
|
+
newIdx: null
|
|
809
|
+
});
|
|
810
|
+
i--;
|
|
811
|
+
}
|
|
812
|
+
return result;
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Returns the opening tag string with the given class injected. Existing
|
|
816
|
+
* `class` attributes are preserved and the new class appended.
|
|
817
|
+
*/
|
|
818
|
+
/**
|
|
819
|
+
* Returns the opening tag with the given class injected. Locates the real
|
|
820
|
+
* `class` attribute via attribute-aware walking (NOT a flat regex — that
|
|
821
|
+
* would mis-match inside a foreign attribute value like
|
|
822
|
+
* `title="see class='x'"`). When the class already partially overlaps with
|
|
823
|
+
* `cls` — e.g. existing `class="mod"` and we're injecting `mod colspan` —
|
|
824
|
+
* only the missing tokens get appended, so we never end up with
|
|
825
|
+
* `class="mod mod colspan"`.
|
|
826
|
+
*/
|
|
827
|
+
function injectClass(openingTag, cls) {
|
|
828
|
+
const clsTokens = cls.split(/\s+/).filter(Boolean);
|
|
829
|
+
if (clsTokens.length === 0) return openingTag;
|
|
830
|
+
const classAttr = findClassAttribute(openingTag);
|
|
831
|
+
if (classAttr) {
|
|
832
|
+
const existingTokens = classAttr.value.split(/\s+/).filter(Boolean);
|
|
833
|
+
const missing = clsTokens.filter((t) => !existingTokens.includes(t));
|
|
834
|
+
if (missing.length === 0) return openingTag;
|
|
835
|
+
const updatedValue = existingTokens.length === 0 ? missing.join(" ") : `${existingTokens.join(" ")} ${missing.join(" ")}`;
|
|
836
|
+
return openingTag.slice(0, classAttr.valueStart) + updatedValue + openingTag.slice(classAttr.valueEnd);
|
|
837
|
+
}
|
|
838
|
+
const insertAt = openingTag.endsWith("/>") ? openingTag.length - 2 : openingTag.length - 1;
|
|
839
|
+
return `${openingTag.slice(0, insertAt).replace(/\s*$/, "")} class='${cls}'${openingTag.slice(insertAt)}`;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Walks the opening tag's attributes (respecting quoted values) to find
|
|
843
|
+
* the actual `class` attribute. Returns the value range (start/end of the
|
|
844
|
+
* value content, *excluding* the surrounding quotes) and the value, or
|
|
845
|
+
* null if no `class` attribute is present.
|
|
846
|
+
*/
|
|
847
|
+
function findClassAttribute(openingTag) {
|
|
848
|
+
let i = 1;
|
|
849
|
+
while (i < openingTag.length && /[A-Za-z0-9_:-]/.test(openingTag[i])) i++;
|
|
850
|
+
while (i < openingTag.length) {
|
|
851
|
+
while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
|
|
852
|
+
if (i >= openingTag.length) break;
|
|
853
|
+
if (openingTag[i] === ">" || openingTag[i] === "/") break;
|
|
854
|
+
const nameStart = i;
|
|
855
|
+
while (i < openingTag.length && !/[\s=>/]/.test(openingTag[i])) i++;
|
|
856
|
+
const name = openingTag.slice(nameStart, i);
|
|
857
|
+
while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
|
|
858
|
+
if (openingTag[i] !== "=") continue;
|
|
859
|
+
i++;
|
|
860
|
+
while (i < openingTag.length && /\s/.test(openingTag[i])) i++;
|
|
861
|
+
let valueStart;
|
|
862
|
+
let valueEnd;
|
|
863
|
+
if (openingTag[i] === "\"" || openingTag[i] === "'") {
|
|
864
|
+
const quote = openingTag[i];
|
|
865
|
+
i++;
|
|
866
|
+
valueStart = i;
|
|
867
|
+
while (i < openingTag.length && openingTag[i] !== quote) i++;
|
|
868
|
+
valueEnd = i;
|
|
869
|
+
if (i < openingTag.length) i++;
|
|
870
|
+
} else {
|
|
871
|
+
valueStart = i;
|
|
872
|
+
while (i < openingTag.length && !/[\s>/]/.test(openingTag[i])) i++;
|
|
873
|
+
valueEnd = i;
|
|
874
|
+
}
|
|
875
|
+
if (name.toLowerCase() === "class") return {
|
|
876
|
+
valueStart,
|
|
877
|
+
valueEnd,
|
|
878
|
+
value: openingTag.slice(valueStart, valueEnd)
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
return null;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Walks html and returns ranges for every top-level `<table>...</table>`
|
|
885
|
+
* block. Nested tables aren't extracted as separate top-level entries —
|
|
886
|
+
* they're captured inside the parent's content range and handled when the
|
|
887
|
+
* cell-level diff recurses through them.
|
|
888
|
+
*/
|
|
889
|
+
function findTopLevelTables(html) {
|
|
890
|
+
const tables = [];
|
|
891
|
+
let i = 0;
|
|
892
|
+
while (i < html.length) if (matchesTagAt(html, i, "table")) {
|
|
893
|
+
const opening = parseOpeningTagAt(html, i);
|
|
894
|
+
if (!opening) {
|
|
895
|
+
i++;
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
const tableContentStart = opening.end;
|
|
899
|
+
const tableEnd = findMatchingClosingTag(html, tableContentStart, "table");
|
|
900
|
+
if (tableEnd === -1) {
|
|
901
|
+
i = opening.end;
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
const rows = findTopLevelRows(html, tableContentStart, tableEnd - 8);
|
|
905
|
+
tables.push({
|
|
906
|
+
tableStart: i,
|
|
907
|
+
tableEnd,
|
|
908
|
+
rows
|
|
909
|
+
});
|
|
910
|
+
i = tableEnd;
|
|
911
|
+
} else i++;
|
|
912
|
+
return tables;
|
|
913
|
+
}
|
|
914
|
+
function findTopLevelRows(html, start, end) {
|
|
915
|
+
const rows = [];
|
|
916
|
+
let i = start;
|
|
917
|
+
while (i < end) if (matchesTagAt(html, i, "tr")) {
|
|
918
|
+
const opening = parseOpeningTagAt(html, i);
|
|
919
|
+
if (!opening) {
|
|
920
|
+
i++;
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const rowContentStart = opening.end;
|
|
924
|
+
const rowEnd = findMatchingClosingTag(html, rowContentStart, "tr", end);
|
|
925
|
+
if (rowEnd === -1) {
|
|
926
|
+
i = opening.end;
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
const cells = findTopLevelCells(html, rowContentStart, rowEnd - 5);
|
|
930
|
+
rows.push({
|
|
931
|
+
rowStart: i,
|
|
932
|
+
rowEnd,
|
|
933
|
+
cells
|
|
934
|
+
});
|
|
935
|
+
i = rowEnd;
|
|
936
|
+
} else if (matchesClosingTagAt(html, i, "table")) break;
|
|
937
|
+
else i++;
|
|
938
|
+
return rows;
|
|
939
|
+
}
|
|
940
|
+
function findTopLevelCells(html, start, end) {
|
|
941
|
+
const cells = [];
|
|
942
|
+
let i = start;
|
|
943
|
+
while (i < end) if (matchesTagAt(html, i, "td") || matchesTagAt(html, i, "th")) {
|
|
944
|
+
const tagName = matchesTagAt(html, i, "td") ? "td" : "th";
|
|
945
|
+
const opening = parseOpeningTagAt(html, i);
|
|
946
|
+
if (!opening) {
|
|
947
|
+
i++;
|
|
948
|
+
continue;
|
|
949
|
+
}
|
|
950
|
+
const contentStart = opening.end;
|
|
951
|
+
const cellEnd = findMatchingClosingTag(html, contentStart, tagName, end);
|
|
952
|
+
if (cellEnd === -1) {
|
|
953
|
+
i = opening.end;
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
const contentEnd = cellEnd - `</${tagName}>`.length;
|
|
957
|
+
cells.push({
|
|
958
|
+
cellStart: i,
|
|
959
|
+
cellEnd,
|
|
960
|
+
contentStart,
|
|
961
|
+
contentEnd
|
|
962
|
+
});
|
|
963
|
+
i = cellEnd;
|
|
964
|
+
} else if (matchesClosingTagAt(html, i, "tr")) break;
|
|
965
|
+
else i++;
|
|
966
|
+
return cells;
|
|
967
|
+
}
|
|
968
|
+
function matchesTagAt(html, i, tagName) {
|
|
969
|
+
if (html[i] !== "<") return false;
|
|
970
|
+
if (html.slice(i + 1, i + 1 + tagName.length).toLowerCase() !== tagName) return false;
|
|
971
|
+
const after = html[i + 1 + tagName.length];
|
|
972
|
+
return after === ">" || after === " " || after === " " || after === "\n" || after === "\r" || after === "/";
|
|
973
|
+
}
|
|
974
|
+
function matchesClosingTagAt(html, i, tagName) {
|
|
975
|
+
if (html[i] !== "<" || html[i + 1] !== "/") return false;
|
|
976
|
+
if (html.slice(i + 2, i + 2 + tagName.length).toLowerCase() !== tagName) return false;
|
|
977
|
+
const after = html[i + 2 + tagName.length];
|
|
978
|
+
return after === ">" || after === " " || after === " " || after === "\n" || after === "\r";
|
|
979
|
+
}
|
|
980
|
+
function parseOpeningTagAt(html, i) {
|
|
981
|
+
if (html.startsWith("<!--", i)) {
|
|
982
|
+
const close = html.indexOf("-->", i + 4);
|
|
983
|
+
return close === -1 ? null : { end: close + 3 };
|
|
984
|
+
}
|
|
985
|
+
if (html.startsWith("<![CDATA[", i)) {
|
|
986
|
+
const close = html.indexOf("]]>", i + 9);
|
|
987
|
+
return close === -1 ? null : { end: close + 3 };
|
|
988
|
+
}
|
|
989
|
+
if (html.startsWith("<?", i)) {
|
|
990
|
+
const close = html.indexOf("?>", i + 2);
|
|
991
|
+
return close === -1 ? null : { end: close + 2 };
|
|
992
|
+
}
|
|
993
|
+
let j = i + 1;
|
|
994
|
+
let quote = null;
|
|
995
|
+
while (j < html.length) {
|
|
996
|
+
const ch = html[j];
|
|
997
|
+
if (quote) {
|
|
998
|
+
if (ch === quote) quote = null;
|
|
999
|
+
} else if (ch === "\"" || ch === "'") quote = ch;
|
|
1000
|
+
else if (ch === ">") return { end: j + 1 };
|
|
1001
|
+
j++;
|
|
1002
|
+
}
|
|
1003
|
+
return null;
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Returns the index just past the matching `</tagName>`, accounting for
|
|
1007
|
+
* nested tags of the same name. Returns -1 if no match before `limit`.
|
|
1008
|
+
*/
|
|
1009
|
+
function findMatchingClosingTag(html, from, tagName, limit = html.length) {
|
|
1010
|
+
let depth = 1;
|
|
1011
|
+
let i = from;
|
|
1012
|
+
while (i < limit) if (matchesTagAt(html, i, tagName)) {
|
|
1013
|
+
const opening = parseOpeningTagAt(html, i);
|
|
1014
|
+
if (!opening) {
|
|
1015
|
+
i++;
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
if (!html.slice(i, opening.end).endsWith("/>")) depth++;
|
|
1019
|
+
i = opening.end;
|
|
1020
|
+
} else if (matchesClosingTagAt(html, i, tagName)) {
|
|
1021
|
+
depth--;
|
|
1022
|
+
const closingEnd = parseOpeningTagAt(html, i)?.end ?? i + `</${tagName}>`.length;
|
|
1023
|
+
if (depth === 0) return closingEnd;
|
|
1024
|
+
i = closingEnd;
|
|
1025
|
+
} else i++;
|
|
1026
|
+
return -1;
|
|
1027
|
+
}
|
|
1028
|
+
//#endregion
|
|
205
1029
|
//#region src/WordSplitter.ts
|
|
206
1030
|
var WordSplitter = class WordSplitter {
|
|
207
1031
|
text;
|
|
@@ -447,9 +1271,20 @@ var HtmlDiff = class HtmlDiff {
|
|
|
447
1271
|
"s",
|
|
448
1272
|
"span"
|
|
449
1273
|
]);
|
|
1274
|
+
/**
|
|
1275
|
+
* Hard cap on nested `HtmlDiff.execute` calls (table preprocessing
|
|
1276
|
+
* recurses through `diffCell` for cell content). Each level allocates
|
|
1277
|
+
* fresh DP matrices and word arrays; without a guard a maliciously
|
|
1278
|
+
* nested table-in-cell-in-table-in-cell input could blow stack and
|
|
1279
|
+
* memory. Set high enough to comfortably handle real legal documents
|
|
1280
|
+
* (tables nested 2-3 deep at most), low enough to short-circuit
|
|
1281
|
+
* pathological input.
|
|
1282
|
+
*/
|
|
1283
|
+
static MaxTablePreprocessDepth = 8;
|
|
450
1284
|
content = [];
|
|
451
1285
|
newText;
|
|
452
1286
|
oldText;
|
|
1287
|
+
tablePreprocessDepth;
|
|
453
1288
|
specialTagDiffStack = [];
|
|
454
1289
|
newWords = [];
|
|
455
1290
|
oldWords = [];
|
|
@@ -512,13 +1347,17 @@ var HtmlDiff = class HtmlDiff {
|
|
|
512
1347
|
* Initializes a new instance of the class.
|
|
513
1348
|
* @param oldText The old text.
|
|
514
1349
|
* @param newText The new text.
|
|
1350
|
+
* @param tablePreprocessDepth Internal: nested-call depth for table
|
|
1351
|
+
* preprocessing. Callers should leave at default (0); the recursive
|
|
1352
|
+
* `diffCell` callback in TableDiff bumps it.
|
|
515
1353
|
*/
|
|
516
|
-
constructor(oldText, newText) {
|
|
1354
|
+
constructor(oldText, newText, tablePreprocessDepth = 0) {
|
|
517
1355
|
this.oldText = oldText;
|
|
518
1356
|
this.newText = newText;
|
|
1357
|
+
this.tablePreprocessDepth = tablePreprocessDepth;
|
|
519
1358
|
}
|
|
520
|
-
static execute(oldText, newText) {
|
|
521
|
-
return new HtmlDiff(oldText, newText).build();
|
|
1359
|
+
static execute(oldText, newText, tablePreprocessDepth = 0) {
|
|
1360
|
+
return new HtmlDiff(oldText, newText, tablePreprocessDepth).build();
|
|
522
1361
|
}
|
|
523
1362
|
/**
|
|
524
1363
|
* Builds the HTML diff output
|
|
@@ -526,6 +1365,22 @@ var HtmlDiff = class HtmlDiff {
|
|
|
526
1365
|
*/
|
|
527
1366
|
build() {
|
|
528
1367
|
if (this.oldText === this.newText) return this.newText;
|
|
1368
|
+
const blockExpressions = this.blockExpressions;
|
|
1369
|
+
const repeatingWordsAccuracy = this.repeatingWordsAccuracy;
|
|
1370
|
+
const orphanMatchThreshold = this.orphanMatchThreshold;
|
|
1371
|
+
const ignoreWhitespaceDifferences = this.ignoreWhitespaceDifferences;
|
|
1372
|
+
const tablePreprocess = this.tablePreprocessDepth >= HtmlDiff.MaxTablePreprocessDepth ? null : preprocessTables(this.oldText, this.newText, (oldCell, newCell) => {
|
|
1373
|
+
const inner = new HtmlDiff(oldCell, newCell, this.tablePreprocessDepth + 1);
|
|
1374
|
+
for (const expr of blockExpressions) inner.addBlockExpression(expr);
|
|
1375
|
+
inner.repeatingWordsAccuracy = repeatingWordsAccuracy;
|
|
1376
|
+
inner.orphanMatchThreshold = orphanMatchThreshold;
|
|
1377
|
+
inner.ignoreWhitespaceDifferences = ignoreWhitespaceDifferences;
|
|
1378
|
+
return inner.build();
|
|
1379
|
+
});
|
|
1380
|
+
if (tablePreprocess) {
|
|
1381
|
+
this.oldText = tablePreprocess.modifiedOld;
|
|
1382
|
+
this.newText = tablePreprocess.modifiedNew;
|
|
1383
|
+
}
|
|
529
1384
|
this.splitInputsToWords();
|
|
530
1385
|
this.buildContentProjections();
|
|
531
1386
|
const wordsForDiffOld = this.oldContentWords ?? this.oldWords;
|
|
@@ -533,7 +1388,8 @@ var HtmlDiff = class HtmlDiff {
|
|
|
533
1388
|
this.matchGranularity = Math.min(HtmlDiff.MatchGranularityMaximum, Math.min(wordsForDiffOld.length, wordsForDiffNew.length));
|
|
534
1389
|
const operations = this.operations();
|
|
535
1390
|
for (const op of operations) this.performOperation(op);
|
|
536
|
-
|
|
1391
|
+
const result = this.content.join("");
|
|
1392
|
+
return tablePreprocess ? restoreTablePlaceholders(result, tablePreprocess.placeholderToDiff) : result;
|
|
537
1393
|
}
|
|
538
1394
|
/**
|
|
539
1395
|
* Uses {@link expression} to group text together so that any change detected within the group is treated as a single block
|
|
@@ -760,7 +1616,7 @@ var HtmlDiff = class HtmlDiff {
|
|
|
760
1616
|
if (words.slice(0, indexLastTagInFirstTagBlock + 1).some((w) => !HtmlDiff.SpecialCaseClosingTagsSet.has(w.toLowerCase()))) tagIndexToCompare = 0;
|
|
761
1617
|
}
|
|
762
1618
|
const openingAndClosingTagsMatch = !!openingTag && Utils_default.getTagName(openingTag) === Utils_default.getTagName(words[tagIndexToCompare]);
|
|
763
|
-
if (
|
|
1619
|
+
if (openingTag && openingAndClosingTagsMatch) {
|
|
764
1620
|
specialCaseTagInjection = "</ins>";
|
|
765
1621
|
specialCaseTagInjectionIsBefore = true;
|
|
766
1622
|
} else if (openingTag) this.specialTagDiffStack.push(openingTag);
|