| 1 | import type { Comparison, DiffLine, FileDiff } from "@g1t/contracts"; |
| 2 | |
| 3 | /** A diff line, with its text as highlighted HTML when the language is known. */ |
| 4 | export type HighlightedLine = DiffLine & { html?: string }; |
| 5 | export type HighlightedFile = Omit<FileDiff, "hunks"> & { hunks: { lines: HighlightedLine[] }[] }; |
| 6 | export type HighlightedComparison = Omit<Comparison, "files"> & { files: HighlightedFile[] }; |
| 7 | |
| 8 | /** Each hunk's lines' HTML, null for a line without any: what a highlighted file adds to its diff. */ |
| 9 | export type FileHtml = (string | null)[][]; |
| 10 | |
| 11 | /** The HTML `highlighted` gives its lines, to keep apart from the diff it came from. */ |
| 12 | export function htmlOfFile(highlighted: HighlightedFile): FileHtml { |
| 13 | return highlighted.hunks.map((hunk) => hunk.lines.map((line) => line.html ?? null)); |
| 14 | } |
| 15 | |
| 16 | /** `file` with `html` given back to its lines: the same as the highlighted file it was taken from. */ |
| 17 | export function withHtml(file: FileDiff, html: FileHtml): HighlightedFile { |
| 18 | return { |
| 19 | ...file, |
| 20 | hunks: file.hunks.map((hunk, h) => ({ |
| 21 | lines: hunk.lines.map((line, n): HighlightedLine => { |
| 22 | const row = html[h]?.[n]; |
| 23 | return row == null ? { ...line } : { ...line, html: row }; |
| 24 | }), |
| 25 | })), |
| 26 | }; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * What a file's highlighting depends on besides its language: each line's |
| 31 | * side and text, hunk by hunk. Line numbers and the path do not change the |
| 32 | * colours, so they are left out. |
| 33 | */ |
| 34 | export function diffContent(file: FileDiff): string { |
| 35 | return JSON.stringify(file.hunks.map((hunk) => hunk.lines.map((line) => [line.kind, line.text]))); |
| 36 | } |