Skip to content
71 linesCodeBlameRaw
1import assert from "node:assert/strict";
2import { test } from "node:test";
3
4import type { FileDiff } from "@g1t/contracts";
5
6import { diffContent, htmlOfFile, withHtml } from "./diff.ts";
7import { highlightFile } from "./shiki.ts";
8
9const FILE: FileDiff = {
10 path: "src/lib.rs",
11 status: "modified",
12 additions: 2,
13 deletions: 1,
14 binary: false,
15 hunks: [
16 {
17 lines: [
18 { kind: "context", old: 1, new: 1, text: "fn main() {" },
19 { kind: "delete", old: 2, new: null, text: ' println!("old");' },
20 { kind: "add", old: null, new: 2, text: ' println!("new");' },
21 { kind: "add", old: null, new: 3, text: "" },
22 { kind: "context", old: 3, new: 4, text: "}" },
23 ],
24 },
25 { lines: [{ kind: "add", old: null, new: 10, text: "// end" }] },
26 ],
27};
28
29test("a highlighted file's HTML, kept apart and given back, is the same highlighted file", async () => {
30 const highlighted = await highlightFile(FILE);
31 assert.ok(highlighted);
32 const html = htmlOfFile(highlighted);
33 assert.equal(html.length, 2);
34 assert.ok(html[0]!.every((row) => row !== null));
35 // Through the data centre's cache it travels as JSON.
36 const kept = JSON.parse(JSON.stringify(html));
37 assert.deepEqual(withHtml(FILE, kept), highlighted);
38});
39
40test("lines without HTML stay without it", () => {
41 const html = [[null, "<b>x</b>", null, "", null], [null]];
42 const file = withHtml(FILE, html);
43 assert.equal("html" in file.hunks[0]!.lines[0]!, false);
44 assert.equal(file.hunks[0]!.lines[1]!.html, "<b>x</b>");
45 // An empty line's HTML is kept: it is not the same as none.
46 assert.equal(file.hunks[0]!.lines[3]!.html, "");
47 assert.equal("html" in file.hunks[1]!.lines[0]!, false);
48 // The diff given in is not changed.
49 assert.equal("html" in FILE.hunks[0]!.lines[1]!, false);
50});
51
52test("what a file's colours depend on: each line's side and text, not its numbers or path", () => {
53 const moved: FileDiff = {
54 ...FILE,
55 path: "other/lib.rs",
56 hunks: FILE.hunks.map((hunk) => ({ lines: hunk.lines.map((line) => ({ ...line, old: 99, new: 99 })) })),
57 };
58 assert.equal(diffContent(moved), diffContent(FILE));
59 const sideChanged: FileDiff = {
60 ...FILE,
61 hunks: [{ lines: FILE.hunks[0]!.lines.map((line, n) => (n === 0 ? { ...line, kind: "add" as const } : line)) }, FILE.hunks[1]!],
62 };
63 assert.notEqual(diffContent(sideChanged), diffContent(FILE));
64 // A line split differently is different content.
65 const one: FileDiff = { ...FILE, hunks: [{ lines: [{ kind: "add", old: null, new: 1, text: "a\nb" }] }] };
66 const two: FileDiff = {
67 ...FILE,
68 hunks: [{ lines: [{ kind: "add", old: null, new: 1, text: "a" }, { kind: "add", old: null, new: 2, text: "b" }] }],
69 };
70 assert.notEqual(diffContent(one), diffContent(two));
71});