~james/core

core/web/src/lib/components/profile/ProfileActivityChart.svelte -rw-r--r-- 8.9 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
<script lang="ts">
	import type { Action } from "svelte/action";
	import type { Component } from "svelte";
	import type { SvelteHTMLElements } from "svelte/elements";
	import { SvelteDate } from "svelte/reactivity";
	import ArrowDownRight from "$icon/arrow-down-right";
	import ArrowUpRight from "$icon/arrow-up-right";
	import Minus from "$icon/minus";
	import BookPlus from "$icon/book-plus";
	import CircleDot from "$icon/circle-dot";
	import GitCommit from "$icon/git-commit-horizontal";
	import GitPullRequest from "$icon/git-pull-request";
	import EmptyState from "#lib/components/ui/EmptyState.svelte";
	import { formatCount, plural } from "#lib/format.ts";
	import {
		ACTIVITY_METRICS,
		layoutActivityChart,
		type ActivityMetric
	} from "#lib/components/profile/profileActivityChart.ts";
	import type {
		ProfileActivityData,
		ProfileActivityMonth
	} from "#lib/components/profile/types.ts";

	type Icon = Component<SvelteHTMLElements["svg"]>;

	let { activity }: { activity: ProfileActivityData } = $props();

	const emptyMonth = (monthsAgo: number): ProfileActivityMonth => ({
		monthsAgo,
		commits: 0,
		repos: [],
		issues: [],
		pulls: []
	});
	const months = $derived(
		Array.from({ length: 6 }, (_, index) => {
			const monthsAgo = 5 - index;
			return (
				activity.months.find((month) => month.monthsAgo === monthsAgo) ??
				emptyMonth(monthsAgo)
			);
		})
	);
	const monthName = (monthsAgo: number) => {
		const date = new SvelteDate();
		date.setUTCDate(1);
		date.setUTCMonth(date.getUTCMonth() - monthsAgo);
		return new Intl.DateTimeFormat("en", { month: "long", timeZone: "UTC" }).format(date);
	};
	const metrics: { key: ActivityMetric; label: string; singular: string; icon: Icon }[] = [
		{ key: "pulls", label: "pull requests", singular: "pull request", icon: GitPullRequest },
		{ key: "commits", label: "commits", singular: "commit", icon: GitCommit },
		{ key: "repos", label: "new repositories", singular: "new repository", icon: BookPlus },
		{ key: "issues", label: "issues", singular: "issue", icon: CircleDot }
	];
	const valueOf = (month: ProfileActivityMonth, key: ActivityMetric) =>
		key === "commits" ? month.commits : month[key].length;
	const nameOf = (value: number, metric: (typeof metrics)[number]) =>
		plural(value, metric.singular, metric.label);
	const values = $derived(
		Object.fromEntries(
			ACTIVITY_METRICS.map((metric) => [
				metric,
				months.map((month) => valueOf(month, metric))
			])
		) as Record<ActivityMetric, number[]>
	);

	let availableWidth = $state(982);
	let focused = $state<number | null>(null);
	let measured = $state(false);
	const layout = $derived(layoutActivityChart(values, availableWidth));
	const viewport: Action<HTMLDivElement> = (node) => {
		let followsCurrent = true;
		let frame = 0;
		const alignCurrent = () => {
			cancelAnimationFrame(frame);
			frame = requestAnimationFrame(() => {
				if (followsCurrent) node.scrollLeft = node.scrollWidth - node.clientWidth;
				findFocused();
			});
		};
		const findFocused = () => {
			const scrollable = node.scrollWidth - node.clientWidth;
			if (scrollable <= 1) {
				focused = null;
				return;
			}
			if (node.scrollLeft <= 1) {
				focused = 0;
				return;
			}
			const middle = node.scrollLeft + node.clientWidth / 2;
			const index = layout.columns.findIndex(
				(column) => middle >= column.left && middle < column.left + column.width
			);
			focused = index < 0 ? null : Math.min(index, layout.columns.length - 2);
		};
		const onScroll = () => {
			followsCurrent = node.scrollWidth - node.clientWidth - node.scrollLeft <= 1;
			findFocused();
		};
		const observer = new ResizeObserver(([entry]) => {
			availableWidth = Math.floor(entry.contentRect.width);
			measured = true;
			alignCurrent();
		});
		observer.observe(node);
		node.addEventListener("scroll", onScroll, { passive: true });
		alignCurrent();
		return {
			destroy() {
				cancelAnimationFrame(frame);
				observer.disconnect();
				node.removeEventListener("scroll", onScroll);
			}
		};
	};

	let pointerInside = $state(false);
	let shiftHeld = $state(false);
	let hoveredMetric = $state<ActivityMetric | null>(null);
	const trackPointer = (event: PointerEvent) => {
		pointerInside = true;
		shiftHeld = event.shiftKey;
	};
	const trackShift = (event: KeyboardEvent) => {
		shiftHeld = event.shiftKey;
	};
</script>

<svelte:window onkeydown={trackShift} onkeyup={trackShift} onblur={() => (shiftHeld = false)} />

<section class="space-y-xs">
	<h2 class="px-xs typography-paragraph-regular font-medium">Activity</h2>
	{#if activity.months.length === 0}
		<EmptyState message="This user does not have any activity yet." />
	{:else}
		<div
			use:viewport
			class="rounded-md border border-border-default {measured
				? 'overflow-x-auto'
				: 'overflow-hidden'}"
		>
			<div
				class="relative bg-background-default"
				style={`width:${layout.width}px;height:${layout.height}px`}
				role="presentation"
				onpointermove={trackPointer}
				onpointerleave={() => (pointerInside = false)}
			>
				<div
					class="absolute top-0 right-0 h-full bg-background-subtle"
					style={`width:${layout.columns.at(-1)!.width}px`}
				></div>
				<svg
					class="pointer-events-none absolute inset-0 size-full"
					viewBox={`0 0 ${layout.width} ${layout.height}`}
					fill="none"
					aria-hidden="true"
				>
					{#each metrics as metric (metric.key)}
						{#each layout.segments[metric.key] as segment, index (index)}
							<path
								d={segment.d}
								class="transition-[stroke-opacity] duration-200 ease-out {segment.rising
									? 'stroke-foreground-success'
									: 'stroke-foreground-subtle'}"
								stroke-width="1"
								stroke-opacity={hoveredMetric === null
									? 0.25
									: hoveredMetric === metric.key
										? 0.9
										: 0.08}
							/>
						{/each}
					{/each}
				</svg>

				{#each months as month, monthIndex (month.monthsAgo)}
					{@const column = layout.columns[monthIndex]}
					<div
						class="absolute top-0 h-full {column.divider
							? 'border-l border-border-default'
							: ''}"
						style={`left:${column.left}px;width:${column.width}px`}
					>
						<span
							class="absolute bottom-2 left-2 cursor-default rounded-md px-xs py-3xs typography-paragraph-regular {monthIndex ===
							5
								? 'border border-border-subtle bg-background-default text-foreground-default'
								: 'text-foreground-muted'}"
						>
							{monthName(month.monthsAgo)}
						</span>
					</div>

					{#each metrics as metric (metric.key)}
						{@const Icon = metric.icon}
						{@const point = layout.points[metric.key][monthIndex]}
						{@const previous =
							monthIndex > 0 ? layout.points[metric.key][monthIndex - 1] : null}
						{@const trend =
							point.value === (previous?.value ?? 0)
								? "flat"
								: point.value > (previous?.value ?? 0)
									? "up"
									: "down"}
						{@const current = monthIndex === 5}
						{@const revealed =
							current ||
							focused === monthIndex ||
							hoveredMetric === metric.key ||
							(pointerInside && shiftHeld)}
						<div
							class="absolute z-10 flex h-7 -translate-y-1/2 cursor-default items-center rounded-md px-2xs py-3xs typography-paragraph-regular transition-colors duration-150 ease-out hover:z-20 {current
								? 'bg-background-subtle text-foreground-default shadow-[0_0_var(--spacing-xs)_var(--spacing-2xs)_var(--color-background-subtle)]'
								: `bg-background-default shadow-[0_0_var(--spacing-xs)_var(--spacing-2xs)_var(--color-background-default)] select-none ${revealed ? 'text-foreground-default' : 'text-foreground-muted'}`}"
							style={`left:${point.x}px;top:${point.y}px`}
							data-metric={metric.key}
							data-month={monthIndex}
							role="presentation"
							onpointerenter={() => (hoveredMetric = metric.key)}
							onpointerleave={() => (hoveredMetric = null)}
						>
							<Icon class="size-3.5 shrink-0" aria-hidden="true" />
							<span
								class="grid transition-[grid-template-columns,opacity] duration-200 ease-out {revealed
									? 'grid-cols-[1fr] opacity-100'
									: 'grid-cols-[0fr] opacity-0'}"
							>
								<span class="min-w-0 overflow-hidden">
									<span class="flex items-center pl-xs whitespace-nowrap">
										{formatCount(point.value)}
										{#if current}
											<span class="whitespace-pre">
												{` ${nameOf(point.value, metric)}`}
											</span>
										{/if}
									</span>
								</span>
							</span>
							{#if trend === "flat"}
								<Minus class="ml-xs size-3 shrink-0" aria-hidden="true" />
							{:else if trend === "up"}
								<ArrowUpRight
									class="ml-xs size-3 shrink-0 transition-colors duration-150 ease-out {revealed
										? 'text-foreground-success'
										: ''}"
									aria-hidden="true"
								/>
							{:else}
								<ArrowDownRight class="ml-xs size-3 shrink-0" aria-hidden="true" />
							{/if}
						</div>
					{/each}
				{/each}
			</div>
		</div>
		{#if activity.truncated}
			<p class="px-xs typography-paragraph-small text-foreground-subtle">
				Some older activity is not shown.
			</p>
		{/if}
	{/if}
</section>