Move commit day grouping into lib

Today/Yesterday labels and grouping by day had date edge cases that
nothing tested.
This commit is contained in:
Rūdolfs Ošiņš
2026-10-01 18:20:24 +02:00
parent f267d3d16f
commit a15a20393c
3 changed files with 193 additions and 82 deletions
+82
View File
@@ -0,0 +1,82 @@
import type { Commit } from "@bindings/repo/Commit";
export type CommitGroup = {
key: string;
label: string;
commits: Commit[];
};
export type CommitRow =
| { type: "header"; key: string; label: string }
| { type: "commit"; commit: Commit; first: boolean; last: boolean };
/// The local calendar day of a timestamp in milliseconds, as `YYYY-MM-DD`.
export function dayKey(timestamp: number): string {
const date = new Date(timestamp);
const month = `${date.getMonth() + 1}`.padStart(2, "0");
const day = `${date.getDate()}`.padStart(2, "0");
return `${date.getFullYear()}-${month}-${day}`;
}
/// "Today", "Yesterday", or the full date.
export function dayLabel(timestamp: number, now = Date.now()): string {
const today = new Date(now);
const yesterday = new Date(
today.getFullYear(),
today.getMonth(),
today.getDate() - 1,
);
if (dayKey(timestamp) === dayKey(today.getTime())) {
return "Today";
}
if (dayKey(timestamp) === dayKey(yesterday.getTime())) {
return "Yesterday";
}
return new Intl.DateTimeFormat("en", {
weekday: "long",
month: "long",
day: "numeric",
year: "numeric",
}).format(new Date(timestamp));
}
/// Commits grouped by the day they were committed, in order of each day's first
/// commit.
export function groupCommitsByDay(
commits: Commit[],
now = Date.now(),
): CommitGroup[] {
const groups = new Map<string, CommitGroup>();
for (const commit of commits) {
const timestamp = commit.committer.time * 1000;
const key = dayKey(timestamp);
const group = groups.get(key);
if (group) {
group.commits.push(commit);
} else {
groups.set(key, {
key,
label: dayLabel(timestamp, now),
commits: [commit],
});
}
}
return [...groups.values()];
}
/// The groups as one stream of rows, so the list can be virtualized. `first`
/// and `last` mark a group's boundaries so its commits form a bordered card.
export function commitRowsOf(groups: CommitGroup[]): CommitRow[] {
return groups.flatMap(group => [
{ type: "header" as const, key: group.key, label: group.label },
...group.commits.map((commit, i) => ({
type: "commit" as const,
commit,
first: i === 0,
last: i === group.commits.length - 1,
})),
]);
}
+2 -82
View File
@@ -6,6 +6,7 @@
import { COMMITS_PAGE_SIZE } from "@app/views/repo/router";
import fuzzysort from "fuzzysort";
import { commitRowsOf, groupCommitsByDay } from "@app/lib/commitGroups";
import { invoke } from "@app/lib/invoke";
import { createPaginatedList } from "@app/lib/paginatedList.svelte";
import * as router from "@app/lib/router";
@@ -41,12 +42,6 @@
revision,
});
type CommitGroup = {
key: string;
label: string;
commits: Commit[];
};
function listKey(): string {
return `repo.commits:${repo.rid}:${peer ?? ""}:${revision ?? ""}`;
}
@@ -79,38 +74,6 @@
return () => clearTimeout(timer);
});
function dayKey(timestamp: number) {
const date = new Date(timestamp);
const month = `${date.getMonth() + 1}`.padStart(2, "0");
const day = `${date.getDate()}`.padStart(2, "0");
return `${date.getFullYear()}-${month}-${day}`;
}
function dayLabel(timestamp: number) {
const date = new Date(timestamp);
const today = new Date();
const yesterday = new Date(
today.getFullYear(),
today.getMonth(),
today.getDate() - 1,
);
if (dayKey(date.getTime()) === dayKey(today.getTime())) {
return "Today";
}
if (dayKey(date.getTime()) === dayKey(yesterday.getTime())) {
return "Yesterday";
}
return new Intl.DateTimeFormat("en", {
weekday: "long",
month: "long",
day: "numeric",
year: "numeric",
}).format(date);
}
const searchableCommits = $derived(
list.items.map(c => ({
commit: c,
@@ -130,50 +93,7 @@
const filteredCommits = $derived(searchResults.map(r => r.obj.commit));
const groupedCommits = $derived.by<CommitGroup[]>(() => {
const groups: Record<string, CommitGroup> = {};
for (const commit of filteredCommits) {
const timestamp = commit.committer.time * 1000;
const key = dayKey(timestamp);
const current = groups[key];
if (current) {
current.commits.push(commit);
} else {
groups[key] = {
key,
label: dayLabel(timestamp),
commits: [commit],
};
}
}
return Object.values(groups);
});
type CommitRow =
| { type: "header"; key: string; label: string }
| { type: "commit"; commit: Commit; first: boolean; last: boolean };
// Flatten the day groups into a single row stream so the list can be
// virtualized; the row snippet renders headers and commits differently.
// `first`/`last` mark a group's boundaries so its commits form a bordered card.
const commitRows = $derived.by<CommitRow[]>(() => {
const rows: CommitRow[] = [];
for (const group of groupedCommits) {
rows.push({ type: "header", key: group.key, label: group.label });
group.commits.forEach((commit, i) => {
rows.push({
type: "commit",
commit,
first: i === 0,
last: i === group.commits.length - 1,
});
});
}
return rows;
});
const commitRows = $derived(commitRowsOf(groupCommitsByDay(filteredCommits)));
</script>
<style>
+109
View File
@@ -0,0 +1,109 @@
import type { Commit } from "@bindings/repo/Commit";
import { describe, expect, test } from "vitest";
import {
commitRowsOf,
dayKey,
dayLabel,
groupCommitsByDay,
} from "@app/lib/commitGroups";
// The unit tests run with TZ=UTC.
const now = Date.UTC(2026, 8, 30, 12);
const hour = 3600 * 1000;
function commit(id: string, at: number): Commit {
const person = { name: "Alice", email: "a@x", time: at / 1000 };
return {
id,
author: person,
committer: person,
summary: id,
message: id,
parents: [],
} as unknown as Commit;
}
test("dayKey is the calendar day", () => {
expect(dayKey(Date.UTC(2026, 0, 5, 23, 59))).toBe("2026-01-05");
expect(dayKey(Date.UTC(2026, 0, 6, 0, 0))).toBe("2026-01-06");
});
describe("dayLabel", () => {
test.each([
[now, "Today"],
[Date.UTC(2026, 8, 30, 0, 0), "Today"],
[Date.UTC(2026, 8, 29, 23, 59), "Yesterday"],
[Date.UTC(2026, 8, 29, 0, 0), "Yesterday"],
[Date.UTC(2026, 8, 28, 23, 59), "Monday, September 28, 2026"],
])("labels %j as %j", (timestamp, expected) => {
expect(dayLabel(timestamp, now)).toBe(expected);
});
test("defaults to the current time", () => {
expect(dayLabel(Date.now())).toBe("Today");
});
test("handles yesterday across a month boundary", () => {
expect(dayLabel(Date.UTC(2026, 8, 30, 10), Date.UTC(2026, 9, 1, 10))).toBe(
"Yesterday",
);
});
});
describe("grouping", () => {
const commits = [
commit("a", now),
commit("b", now - 2 * hour),
commit("c", now - 24 * hour),
commit("d", now - 1000 * hour),
];
test("groups commits by day in order", () => {
expect(
groupCommitsByDay(commits, now).map(g => [
g.label,
...g.commits.map(c => c.id),
]),
).toEqual([
["Today", "a", "b"],
["Yesterday", "c"],
["Wednesday, August 19, 2026", "d"],
]);
});
test("merges a day's commits even when they aren't adjacent", () => {
expect(
groupCommitsByDay(
[
commit("a", now),
commit("c", now - 24 * hour),
commit("b", now - hour),
],
now,
).map(g => g.commits.map(c => c.id)),
).toEqual([["a", "b"], ["c"]]);
});
test("groups by commit date, not author date", () => {
const rebased = {
...commit("r", now),
author: { name: "Alice", email: "a@x", time: (now - 1000 * hour) / 1000 },
};
expect(groupCommitsByDay([rebased], now)[0].label).toBe("Today");
});
test("flattens groups into header and commit rows", () => {
const rows = commitRowsOf(groupCommitsByDay(commits.slice(0, 3), now));
expect(
rows.map(row =>
row.type === "header"
? `# ${row.label}`
: `${row.commit.id}${row.first ? " first" : ""}${row.last ? " last" : ""}`,
),
).toEqual(["# Today", "a first", "b last", "# Yesterday", "c first last"]);
});
});