foldDiff

tcmts.share.foldDiff · #o6tev24d · term · runs anywhere

A change's lines as the rows a page sends (DiffRow): each change and two lines of context around it, the rest as gaps, each line once (its HTML, or its text made HTML); past most rows, the rest one gap. Done before the page goes to the browser, so a one-line edit to a long definition sends a few lines, not two copies of it.

import { esc } from "#codebase/tcmts/cli/pages";
import type { DiffRow, ReviewItem } from "#codebase/tcmts/share";

export function foldDiff(lines: ReviewItem["lines"], html?: string[], most = 400): DiffRow[] {
  let a = 0;
  let b = 0;
  const rows: DiffRow[] = [];
  let left = 0;
  const shown = (k: number) =>
    lines[k]![0] !== " " ||
    lines.length <= 12 ||
    lines.slice(Math.max(0, k - 2), k + 3).some(([o]) => o !== " ");
  for (let k = 0; k < lines.length; k++) {
    const [op, text] = lines[k]!;
    const row = { op, a: op === "+" ? undefined : ++a, b: op === "-" ? undefined : ++b };
    if (!shown(k)) {
      left++;
      continue;
    }
    if (left) rows.push({ gap: left });
    left = 0;
    if (rows.length >= most) {
      rows.push({ gap: lines.length - k, cut: true });
      return rows;
    }
    rows.push({ ...row, html: html?.[k] ?? esc(text) });
  }
  if (left) rows.push({ gap: left });
  return rows;
}

uses

used by