repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/diff-render/render.ts

Raw
File outline
import type { Theme } from "@mariozechner/pi-coding-agent";
import { renderDiff } from "@mariozechner/pi-coding-agent";
import type { Component } from "@mariozechner/pi-tui";
import { truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
import type { DiffRenderPayload } from "./model";

const MAX_RENDER_LINES = 240;

export class DiffRenderComponent implements Component {
  constructor(
    private readonly payload: DiffRenderPayload,
    private readonly theme: Theme,
    private readonly expanded: boolean,
  ) {}

  render(width: number): string[] {
    if (!this.expanded || this.payload.diff.length === 0) return [fitLine(this.summary(), width)];
    return capLines(renderDiff(this.payload.diff).split("\n")).map((line) => fitLine(line, width));
  }

  invalidate(): void {}

  private summary(): string {
    const s = this.payload.stats;
    const text = `${s.files} file${s.files === 1 ? "" : "s"}  +${s.additions} -${s.deletions}  ${s.hunks} hunk${s.hunks === 1 ? "" : "s"}`;
    return `${this.theme.fg("success", "Applied")} ${this.theme.fg("muted", text)}`;
  }
}

function capLines(lines: string[]): string[] {
  if (lines.length <= MAX_RENDER_LINES) return lines;
  return [...lines.slice(0, MAX_RENDER_LINES), `… ${lines.length - MAX_RENDER_LINES} more diff lines`];
}

function fitLine(line: string, width: number): string {
  const clipped = truncateToWidth(line, width, "…");
  return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
}