Files
RuneStone/src/lib/features/git/GitGraph.svelte
T
2026-11-16 04:21:21 -07:00

245 lines
13 KiB
Svelte

<script lang="ts">
import { onMount, tick, untrack } from "svelte";
import { t, tr } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import { gitApi } from "$lib/git/service";
import type { GitCommitDetails, GitCommitFile, GitGraph } from "$lib/git/contracts";
import { graphLayout } from "./model";
import DiffText from "./DiffText.svelte";
import type { GitState } from "./state.svelte";
let { git }: { git: GitState } = $props();
const rowHeight = 30;
const x = (lane: number) => 12 + lane * 18;
const y = (row: number) => rowHeight / 2 + row * rowHeight;
let history = $state.raw<GitGraph | null>(null);
let graphMessage = $state(tr("Loading history…"));
let graphError = $state(false);
let refreshing = $state(false);
let detail = $state.raw<GitCommitDetails | null>(null);
let detailMessage = $state(tr("Select a commit."));
let diff = $state<{ text: string; error: boolean } | null>(null);
let list: HTMLOListElement | undefined = $state();
let disposed = false, generation = 0, selection = 0, fileRequest = 0;
const layout = $derived(graphLayout(history));
function tooltip(node: HTMLElement, text: string) {
let current = text;
const dispose = attachTooltip(node, () => current);
return { update(value: string) { current = value; }, destroy: dispose };
}
async function refresh() {
const request = ++generation;
refreshing = true;
try {
const result = await gitApi.graph();
if (disposed || request !== generation) return;
history = result;
graphError = false;
graphMessage = result.commits.length ? "" : tr("No commits yet. Create a commit to start the graph.");
const kept = result.commits.some(commit => commit.id === git.history.selectedId) ? git.history.selectedId : result.commits[0]?.id ?? null;
if (kept) {
if (kept !== detail?.id || kept !== git.history.selectedId) void select(kept);
} else {
git.history.selectedId = null;
++selection; ++fileRequest;
detail = null; diff = null;
detailMessage = tr("No commit is selected.");
}
} catch (reason) {
if (disposed || request !== generation) return;
history = null;
graphError = true;
graphMessage = String(reason);
++selection; ++fileRequest;
detail = null; diff = null;
detailMessage = tr("Select Refresh to try again.");
} finally {
if (!disposed && request === generation) refreshing = false;
}
}
async function select(id: string) {
git.history.selectedId = id;
const request = ++selection;
++fileRequest;
detailMessage = tr("Loading commit…");
try {
const result = await gitApi.commitDetails(id);
if (disposed || request !== selection) return;
detail = result;
diff = null;
const file = result.files.find(item => item.path === git.history.file) ?? result.files[0];
if (file) void selectFile(file, result);
} catch (reason) {
if (disposed || request !== selection) return;
detail = null;
detailMessage = String(reason);
}
}
async function selectFile(file: GitCommitFile, commit: GitCommitDetails) {
git.history.file = file.path;
const request = ++fileRequest;
diff = { text: tr("Loading diff…"), error: false };
try {
const text = await gitApi.commitDiff(commit.id, file.path);
if (disposed || request !== fileRequest || git.history.selectedId !== commit.id) return;
diff = { text: text || tr("No text changes."), error: false };
} catch (reason) {
if (!disposed && request === fileRequest) diff = { text: String(reason), error: true };
}
}
async function keydown(event: KeyboardEvent) {
const commits = layout.nodes;
const index = commits.findIndex(commit => commit.id === git.history.selectedId);
const next = event.key === "ArrowDown" ? Math.min(commits.length - 1, index + 1)
: event.key === "ArrowUp" ? Math.max(0, index - 1)
: event.key === "Home" ? 0 : event.key === "End" ? commits.length - 1 : -1;
if (next < 0 || !commits[next]) return;
event.preventDefault();
void select(commits[next].id);
await tick();
list?.querySelector<HTMLButtonElement>(`[data-commit="${commits[next].id}"]`)?.focus();
}
// The graph reads the history again after a commit, push, or pull, and on window focus.
$effect(() => {
void git.historyVersion;
untrack(() => void refresh());
});
onMount(() => {
const focus = () => void refresh();
window.addEventListener("focus", focus);
return () => { disposed = true; ++generation; ++selection; ++fileRequest; window.removeEventListener("focus", focus); };
});
</script>
<section class="git-graph" aria-label={$t("Git history")}>
<div class="header">
<strong>{$t("Commit graph")}</strong>
<IconButton icon="refresh" label={$t("Refresh commit graph")} disabled={refreshing} onclick={() => void refresh()} />
</div>
<p class="hint">{$t("Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.")}</p>
<div class="body">
<div class="graph" aria-label={$t("Commit graph with branches, authors, and dates")}>
{#if graphMessage}
<p class:error={graphError}>{graphMessage}</p>
{:else}
<div class="canvas">
<svg width={layout.lanes * 18 + 12} height={layout.nodes.length * rowHeight} aria-hidden="true" class="lines">
{#each layout.edges as edge (`${edge.from}:${edge.to}`)}
{@const middle = y(edge.row) + rowHeight / 2}
<path class="edge" class:boundary={edge.outside} style:color={`var(--git-lane-${edge.color + 1})`}
d={`M ${x(edge.lane)} ${y(edge.row)} C ${x(edge.lane)} ${middle} ${x(edge.parentLane)} ${middle} ${x(edge.parentLane)} ${y(edge.row) + rowHeight} L ${x(edge.parentLane)} ${y(edge.endRow)}`} />
{/each}
{#each layout.nodes as commit (commit.id)}
<circle class="node" cx={x(commit.lane)} cy={y(commit.row)} r="4" style:color={`var(--git-lane-${commit.color + 1})`} />
{/each}
</svg>
<ol role="listbox" aria-label={$t("Commits")} bind:this={list} onkeydown={keydown}>
{#each layout.nodes as commit (commit.id)}
{@const selected = commit.id === git.history.selectedId}
<li>
<button type="button" role="option" data-commit={commit.id} aria-selected={selected}
tabindex={selected || (!git.history.selectedId && commit.row === 0) ? 0 : -1}
use:tooltip={`${commit.summary}\n${commit.author} · ${commit.date}\n${commit.id}`}
onclick={() => void select(commit.id)}>
<span class="description">
{#if commit.refs.length}<span class="refs">{commit.refs.join(" · ")}</span>{/if}
<span class="summary">{commit.summary}</span>
</span>
<span class="meta author">{commit.author}</span>
<span class="meta date">{commit.date}</span>
<span class="meta">{commit.id.slice(0, 7)}</span>
<span class="screen-reader">{commit.parents.length ? $t("Parents: {parents}", { parents: commit.parents.join(", ") }) : $t("Root commit")}</span>
</button>
</li>
{/each}
</ol>
</div>
{/if}
</div>
<section class="details" aria-label={$t("Commit details")}>
{#if detail}
<div class="detail-meta">
<strong>{detail.author}</strong>
<time>{detail.date}</time>
<code>{detail.id}</code>
{#if detail.parents.length > 1}<span class="dim">{$t("Changes against the first parent.")}</span>{/if}
</div>
<p class="message">{detail.message}</p>
<strong>{$t("Changed files: {count}", { count: detail.files.length })}</strong>
<div class="files" aria-label={$t("Changed files")}>
{#each detail.files as file (file.path)}
<button type="button" class="file" aria-pressed={file.path === git.history.file}
use:tooltip={file.originalPath ? `${file.originalPath} → ${file.path}` : file.path}
onclick={() => void selectFile(file, detail!)}>
<span>{file.path}</span><span class="dim">{file.status}</span>
</button>
{/each}
</div>
{#if diff}
<DiffText text={diff.text} error={diff.error} label={$t("Commit file diff")} />
{:else}
<p class="dim">{detail.files.length ? $t("Select a file to see its diff.") : $t("This commit contains no file changes.")}</p>
{/if}
{:else}
<p class="dim">{detailMessage}</p>
{/if}
</section>
</div>
</section>
<style>
.git-graph { container-type: inline-size; display: flex; flex-direction: column; gap: 6px; height: 100%; padding: 8px; box-sizing: border-box; overflow: hidden; font-size: 13px;
--git-lane-1: #007fff; --git-lane-2: #ca7000; --git-lane-3: #f000ff; --git-lane-4: #00a000; --git-lane-5: #aa00ff; --git-lane-6: #ff0033; }
.header, .hint { padding: 4px 6px; border-radius: var(--rs-control-radius); background: var(--rs-image-control-bg, var(--rs-bg)); }
.header { display: flex; align-items: center; gap: 6px; }
.header strong { flex: 1; }
.hint { margin: 0; font-size: 11px; color: var(--rs-text-dim); }
.body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 32%); flex: 1; min-height: 0; min-width: 0; }
.graph { min-height: 0; min-width: 0; padding: 4px; overflow: auto; background: var(--rs-image-editor-bg, var(--rs-bg)); }
.graph p { margin: 8px; color: var(--rs-text-dim); }
.graph p.error { color: var(--rs-error); }
.canvas { display: flex; align-items: flex-start; min-width: 0; }
.lines { flex: 0 0 auto; overflow: hidden; }
.edge { fill: none; stroke: currentColor; stroke-width: 2; }
.boundary { stroke-dasharray: 3 3; }
.node { fill: currentColor; stroke: currentColor; stroke-width: 2; }
ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; }
li { height: 30px; min-width: 0; }
ol button { display: grid; grid-template-columns: minmax(0, 1fr) 95px 78px 54px; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
ol button:hover { background: var(--rs-hover-bg); }
ol button[aria-selected="true"], .file[aria-pressed="true"] { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
ol button:focus-visible, .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.description { display: flex; align-items: center; gap: 5px; min-width: 0; }
.summary, .refs, .meta { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.summary { flex: 1; }
.refs { max-width: 45%; padding: 1px 4px; border-radius: var(--rs-control-radius); background: var(--rs-bg-active); color: var(--rs-accent); font-size: 11px; }
.meta, .dim { color: var(--rs-text-dim); font-size: 11px; }
.screen-reader { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.details { display: flex; flex-direction: column; gap: 8px; min-height: 0; min-width: 0; padding: 10px; overflow: auto; border-left: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-image-editor-bg, var(--rs-bg)); }
.details p { margin: 0; }
.detail-meta { display: flex; flex-direction: column; gap: 3px; overflow-wrap: anywhere; }
time { color: var(--rs-text-dim); }
code { font: 11px var(--rs-font-mono); overflow-wrap: anywhere; }
.message { white-space: pre-wrap; overflow-wrap: anywhere; }
.files { display: flex; flex-direction: column; flex-shrink: 0; max-height: 180px; overflow: auto; }
.file { display: flex; flex-shrink: 0; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 3px 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
.file:hover { background: var(--rs-hover-bg); }
.file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.details :global(.diff) { min-height: 140px; }
@container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } }
@container (max-width: 650px) {
.body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(140px, 45%) minmax(0, 1fr); }
.details { border-left: 0; border-top: 1px solid var(--rs-border); }
}
</style>