146 lines · 9.8 KBRaw
// A read-only view of one file, opened as a tab by files-tabs. Props: { file, on }.
// A file with uncommitted changes opens on its diff against HEAD, with a toggle to the whole file.
// Both follow the file while the tab is open. Long lines scroll sideways until Wrap is turned on (per tab).
import { View, div, image } from "gpui-kit";
import { v_flex, h_flex, Editor, EditorState, Scrollbar, v_virtual_list, TextView } from "gpui-base";
import { props, exec, readTextFile, watchFolder, theme, settings } from "herdr";
// Shown as a picture instead of text (local files only: image() can't reach another machine).
const IMAGE = new Set(["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "tif", "tiff"]);
const LANG = { ts: "js", tsx: "js", mts: "js", cts: "js", jsx: "js", mjs: "js", toml: "yaml", jsonc: "json", svelte: "html", vue: "html" };
// From the shipped changes mod: reads that write nothing under .git, tabs padded, diff lines numbered.
const READ = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "diff.autoRefreshIndex=false"];
const untab = (text) => text.replace(/[^\t]*\t/g, (s) => s.slice(0, -1).padEnd((s.length - 1) - (s.length - 1) % 4 + 4));
function diffRows(lines) {
let old = 0, next = 0;
return lines.map((line) => {
const match = /^@@ -(\d+)(?:,\d+)? \+(\d+)/.exec(line);
if (match) { old = +match[1]; next = +match[2]; return { kind: "@", text: line }; }
const kind = line[0];
if (kind === "-") return { kind, number: old++, text: untab(line.slice(1)) || " " };
if (kind === "+") return { kind, number: next++, text: untab(line.slice(1)) || " " };
if (kind === " ") { old++; return { kind, number: next++, text: untab(line.slice(1)) || " " }; }
return { kind: "", text: line };
});
}
export default class FileView extends View {
init(_props, cx) {
const { file, on } = props() ?? {};
this.rows = []; this.mode = "diff"; this.wrap = false;
if (!file) { this.error = "No file"; return; }
this.load(cx);
// Follows the file: a local one through a folder watch, another machine's every 10 seconds.
if (on) cx.timer.every(10000, cx => this.load(cx));
else {
const dir = file.replace(/[\\/][^\\/]*$/, "");
cx.spawn(async cx => { for (;;) { const paths = await watchFolder(dir); if (paths.includes(file) || paths.includes(dir)) this.load(cx); } });
// And the repo's .git, so a commit (a moved ref) or a reset clears the diff.
cx.spawn(async cx => {
const r = await exec("git", [...READ, "rev-parse", "--absolute-git-dir"], { cwd: dir }).catch(() => null);
if (r?.code !== 0) return;
const git = r.stdout.trim();
for (;;) {
const paths = await watchFolder(git);
if (paths.some(p => p === git || p.endsWith("/HEAD") || p.endsWith("/index") || p.endsWith("/packed-refs") || p.includes("/refs/"))) this.load(cx);
}
});
}
}
load(cx) {
const { file, on } = props();
const ext = file.split(".").pop().toLowerCase();
// Markdown and SVG also get a Preview: rendered Markdown, or the SVG as a picture.
this.preview = ext === "md" || ext === "markdown" || (ext === "svg" && !on);
if (IMAGE.has(ext) && on) { this.error = "Images on another machine can't be shown"; return; }
if (IMAGE.has(ext) || ext === "svg" && !on) {
// image() only reads inside the config folder, so show a copy kept there, named by its content
// (an edited image gets a new name and shows the new version). Copies over a day old are cleared.
cx.spawn(async cx => {
const r = await exec("sh", ["-c", 'd="${HERDR_APP_HOME:-$HOME/.config/herdr-app}/cache/file-view"; mkdir -p "$d" && find "$d" -type f -mtime +1 -delete; n="$(shasum < "$1" | cut -c1-16).$2"; cp "$1" "$d/$n" && echo "$n"', "sh", file, file.split(".").pop()]).catch(() => null);
if (r?.code === 0) { this.image = "cache/file-view/" + r.stdout.trim(); this.error = null; }
else this.error = "This file is no longer available";
cx.notify();
});
if (ext !== "svg") return;
}
cx.spawn(async cx => {
try {
const text = await readTextFile(file, { on });
this.error = null;
if (text === null) this.error = "This file is no longer available";
else if (text.includes("\0")) this.error = "Binary file · no text preview";
else {
const t = theme(), name = file.split(/[\\/]/).pop(), ext = name.includes(".") ? name.split(".").pop() : "txt";
const value = text.length > 400000 ? text.slice(0, 400000) + "\n… (file truncated)" : text;
if (this.code) { if (this.code.value() !== value) this.code.set_value(value); }
else {
this.editor = { language: LANG[ext] ?? ext, readonly: true, font_family: settings().font_family, font_size: 13,
syntax: { keyword: t.ansi5, string: t.ansi2, comment: t.dim, function: t.ansi4, type: t.ansi3, number: t.ansi1, constant: t.ansi6 } };
this.code = EditorState.new({ ...this.editor, value, soft_wrap: this.wrap });
}
const cwd = file.replace(/[\\/][^\\/]*$/, "");
const r = await exec("git", [...READ, "diff", "HEAD", "--no-ext-diff", "--no-textconv", "--no-color", "--", name], { cwd, on }).catch(() => null);
const all = r?.code === 0 ? r.stdout.replace(/\n$/, "").split("\n") : [], first = all.findIndex((l) => l.startsWith("@@"));
this.rows = first < 0 ? [] : diffRows(all.slice(first).slice(0, 1500).map(l => l.length > 4000 ? l.slice(0, 4000) + "… (line truncated)" : l));
this.add = this.rows.filter(r => r.kind === "+").length; this.del = this.rows.filter(r => r.kind === "-").length;
this.diffWidth = Math.max(300, ...this.rows.map(row => (row.text.length + 1) * 8 + 60));
}
} catch { this.error = "Cannot preview this file (binary, too large, or unreadable)"; }
finally { cx.notify(); }
});
}
diffRow({ kind, number, text }, t) {
if (kind === "@") return div().w_full().px(12).h(22).flex_none().truncate().bg(t.raised).text_color(t.dim).child(text);
return h_flex().w_full().when(this.wrap, e => e.min_h(22).items_start()).when(!this.wrap, e => e.h(22)).flex_none().gap(12).when(kind === "+", (e) => e.bg(t.ansi2 + "18")).when(kind === "-", (e) => e.bg(t.ansi1 + "18"))
.child(div().w(36).flex_none().text_right().text_color(t.dim).child(number === undefined ? "" : String(number)))
.child(div().w(10).flex_none().text_color(kind === "+" ? t.ansi2 : kind === "-" ? t.ansi1 : t.dim).child(kind === " " ? "" : kind))
.child(div().flex_1().min_w(0).when(this.wrap, e => e.whitespace_normal()).when(!this.wrap, e => e.truncate()).child(text));
}
toggle(id, label, on, t) {
return div().id(id).px(10).h(24).flex().items_center().rounded(6).cursor_pointer().text_size(12)
.bg(on ? t.selected : t.background).text_color(on ? t.foreground : t.muted).hover(s => s.bg(t.hover))
.on_click((_e, cx) => { this.mode = id; cx.notify(); }).child(label);
}
// The editor only takes soft_wrap when it's made, so turning Wrap on or off makes it again.
wrapToggle(t) {
return div().id("wrap").px(10).h(24).flex().items_center().rounded(6).cursor_pointer().text_size(12)
.bg(this.wrap ? t.selected : t.background).text_color(this.wrap ? t.foreground : t.muted).hover(s => s.bg(t.hover))
.on_click((_e, cx) => {
this.wrap = !this.wrap;
if (this.code) this.code = EditorState.new({ ...this.editor, value: this.code.value(), soft_wrap: this.wrap });
cx.notify();
}).child("Wrap");
}
render() {
const t = theme(), diff = this.mode === "diff" && this.rows.length > 0;
const preview = !diff && this.mode !== "file" && this.preview, picture = this.image && !this.code;
return v_flex().id("file-view").size_full().bg(t.background).text_color(t.foreground)
.child(h_flex().h(36).flex_none().px(10).gap(4).items_center().border_b(1).border_color(t.border)
.when(this.rows.length > 0, el => el.child(this.toggle("diff", "Changes", diff, t)))
.when(this.preview, el => el.child(this.toggle("preview", "Preview", preview, t)))
.when(this.rows.length > 0 || this.preview, el => el.child(this.toggle("file", this.preview ? "Raw" : "File", !diff && !preview, t)))
.child(div().flex_1())
.when(this.rows.length > 0, el => el.child(div().text_size(11).text_color(t.ansi2).child(`+${this.add}`)).child(div().text_size(11).text_color(t.ansi1).child(`−${this.del}`)))
.when(!preview && !picture, el => el.child(this.wrapToggle(t))))
.child(diff && this.wrap
// Wrapped rows vary in height, which the virtual list can't do; the diff is at most 1500 rows.
? v_flex().id("file-diff-wrap").flex_1().min_h(0).overflow_y_scrollbar().font_family(settings().font_family ?? "JetBrains Mono").text_size(13)
.children(this.rows.map(row => this.diffRow(row, t)))
: diff
? div().flex_1().min_h(0).relative().font_family(settings().font_family ?? "JetBrains Mono").text_size(13)
.child(div().id("file-diff-x").size_full().overflow_x_scrollbar()
.child(div().w_full().min_w(this.diffWidth).h_full().child(v_virtual_list("file-diff", this.rows.length, 22, (i) => String(i),
(range) => this.rows.slice(range.start, range.end).map((row) => this.diffRow(row, t))).size_full())))
.child(Scrollbar.vertical("file-diff").viewport_from_layout().absolute().inset_0())
: preview && this.code && !this.image ? div().id("file-md").flex_1().min_h(0).overflow_y_scrollbar().px(24).py(16).text_size(14)
.child(TextView.markdown("file-md-text", this.code.value()).selectable(true))
: (preview || picture) && this.image ? div().flex_1().min_h(0).p(16).flex().items_center().justify_center().child(image(this.image).size_full())
: this.code ? Editor.new(this.code).flex_1().min_h(0) : div().p(12).text_size(13).text_color(t.dim).child(this.error || "Loading file…"));
}
}