forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

chart-heatmap.tsx265 lines, 10.6 KiBHistoryRawDownload
1import { For, Show, createMemo, onCleanup, type Component } from "solid-js";
2import { cn } from "@/lib/cn";
3import { usePreferences, useT } from "@/stores/preferences-context";
4import { EmptyInline } from "@/components/ui/empty-inline";
5
6/** One dated observation. Several entries may share a day — they are summed. */
7export type HeatmapEntry = {
8 /** Epoch millis. Bucketed into a local-time calendar day. */
9 at: number;
10 /** Amount contributed by this entry (minutes, records, …). */
11 value: number;
12};
13
14export type ChartHeatmapProps = {
15 title?: string;
16 subtitle?: string;
17 entries: HeatmapEntry[];
18 /** Calendar weeks to render, ending with the week containing `endsAt`. */
19 weeks?: number;
20 /** Right-hand edge of the range; defaults to now. */
21 endsAt?: number;
22 /** Cell tooltip / screen-reader text for a day that has data. */
23 dayLabel: (value: number, dayStart: number) => string;
24 /** Cell text for an empty day. */
25 emptyDayLabel: (dayStart: number) => string;
26 /** Summary line under the grid, e.g. "312 dk odak · son 26 hafta". */
27 footer?: string;
28 class?: string;
29};
30
31const DEFAULT_WEEKS = 26;
32/** Columns a month label needs clear of the next one. */
33const MONTH_LABEL_SPAN = 3;
34
35/** Local midnight for the day containing `ms` — DST-safe, unlike `ms - ms % DAY_MS`. */
36function startOfDay(ms: number): number {
37 const d = new Date(ms);
38 d.setHours(0, 0, 0, 0);
39 return d.getTime();
40}
41
42/** Local midnight of the Monday on or before `ms`. */
43function startOfWeek(ms: number): number {
44 const d = new Date(startOfDay(ms));
45 // getDay(): 0 = Sunday. Shift so Monday is column-row 0.
46 d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
47 return d.getTime();
48}
49
50/**
51 * GitHub-contribution-style calendar. Columns are weeks (oldest → newest),
52 * rows are Monday → Sunday. Intensity is bucketed against the busiest day in
53 * range, so the scale is always relative to real data rather than a guess.
54 */
55export const ChartHeatmap: Component<ChartHeatmapProps> = (props) => {
56 const t = useT();
57 const { locale } = usePreferences();
58
59 const weeks = () => props.weeks ?? DEFAULT_WEEKS;
60
61 // Totals per local day, keyed by that day's midnight timestamp.
62 const totals = createMemo(() => {
63 const map = new Map<number, number>();
64 for (const entry of props.entries) {
65 if (!Number.isFinite(entry.at) || entry.value <= 0) continue;
66 const day = startOfDay(entry.at);
67 map.set(day, (map.get(day) ?? 0) + entry.value);
68 }
69 return map;
70 });
71
72 const firstWeekStart = createMemo(() => {
73 const lastWeek = startOfWeek(props.endsAt ?? Date.now());
74 const d = new Date(lastWeek);
75 d.setDate(d.getDate() - (weeks() - 1) * 7);
76 return d.getTime();
77 });
78
79 // Columns of 7 local-midnight timestamps. Built by date arithmetic rather
80 // than fixed DAY_MS steps so a DST shift can't slide the grid by an hour.
81 const columns = createMemo(() => {
82 const start = firstWeekStart();
83 return Array.from({ length: weeks() }, (_, week) =>
84 Array.from({ length: 7 }, (_, day) => {
85 const d = new Date(start);
86 d.setDate(d.getDate() + week * 7 + day);
87 return d.getTime();
88 }),
89 );
90 });
91
92 const maxValue = createMemo(() => Math.max(0, ...totals().values()));
93 const todayStart = createMemo(() => startOfDay(props.endsAt ?? Date.now()));
94
95 /** 0 = no data, 1..4 = quartiles of the busiest day. */
96 const levelOf = (value: number) => {
97 if (value <= 0) return 0;
98 const peak = maxValue();
99 if (peak <= 0) return 0;
100 return Math.min(4, Math.ceil((value / peak) * 4));
101 };
102
103 const levelClasses = [
104 "bg-muted/60 dark:bg-muted/30",
105 "bg-primary/25",
106 "bg-primary/45",
107 "bg-primary/70",
108 "bg-primary",
109 ];
110
111 const monthFormat = createMemo(
112 () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { month: "short" }),
113 );
114 const weekdayFormat = createMemo(
115 () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { weekday: "short" }),
116 );
117
118 // A month label sits above the first column whose Monday opens a new month.
119 // A label runs wider than its column, so one whose next label starts within
120 // MONTH_LABEL_SPAN columns is dropped — otherwise the range's opening month
121 // and the next one print over each other ("MaNis").
122 const monthLabels = createMemo(() => {
123 const labels = columns().map((week, index) => {
124 const monday = new Date(week[0]);
125 if (index > 0) {
126 const previous = new Date(columns()[index - 1][0]);
127 if (previous.getMonth() === monday.getMonth()) return "";
128 }
129 return monthFormat().format(monday);
130 });
131 let next = Number.POSITIVE_INFINITY;
132 for (let index = labels.length - 1; index >= 0; index -= 1) {
133 if (!labels[index]) continue;
134 if (next - index < MONTH_LABEL_SPAN) labels[index] = "";
135 else next = index;
136 }
137 return labels;
138 });
139
140 // Monday / Wednesday / Friday only — the full seven would not fit the gutter.
141 const weekdayLabels = createMemo(() => {
142 const week = columns()[0] ?? [];
143 return week.map((day, index) => (index % 2 === 0 && index < 6 ? weekdayFormat().format(day) : ""));
144 });
145
146 const hasData = createMemo(() => maxValue() > 0);
147
148 return (
149 <div class={cn("flex flex-col gap-4 rounded-xl border border-border-line bg-surface-base p-4", props.class)}>
150 <Show when={props.title}>
151 <div class="border-b border-border-hairline pb-3">
152 <h3 class="text-sm font-semibold tracking-tight text-foreground">{props.title}</h3>
153 <Show when={props.subtitle}>
154 <p class="mt-0.5 text-xs text-muted-foreground">{props.subtitle}</p>
155 </Show>
156 </div>
157 </Show>
158
159 <Show
160 when={hasData()}
161 fallback={
162 <EmptyInline illustration="charts" title={t("dashboard.chartEmpty")} hint={t("dashboard.chartEmptyHint")} />
163 }
164 >
165 {/* One grid for labels and cells together: a weekday gutter column plus
166 an equal fraction per week, so the calendar always spans the card's
167 full width and every label stays on its own row. Below the min-width
168 it scrolls instead of shrinking cells past legibility. */}
169 {/* `px-1` keeps today's focus ring off the scroll container's clip
170 edge, which otherwise shaves the last column's cells in half. */}
171 {/* Where it scrolls (a phone), it opens on the newest weeks — the
172 right edge — rather than on the oldest. */}
173 <div class="overflow-x-auto px-1 pb-1">
174 <div
175 ref={(grid) => {
176 // Re-pinned on every resize while the page settles (under
177 // Suspense the node is built detached, and the card widens as
178 // the layout fills in), until the user scrolls it themselves.
179 if (typeof ResizeObserver === "undefined") return;
180 let pinned = true;
181 const release = () => {
182 pinned = false;
183 };
184 const observer = new ResizeObserver(() => {
185 const scroller = grid.parentElement;
186 if (pinned && scroller) scroller.scrollLeft = scroller.scrollWidth;
187 });
188 observer.observe(grid);
189 // The grid holds its min-width while the card around it shrinks,
190 // so the scroller's own size matters as much.
191 queueMicrotask(() => grid.parentElement && observer.observe(grid.parentElement));
192 for (const type of ["pointerdown", "wheel", "keydown"]) grid.addEventListener(type, release, { passive: true });
193 onCleanup(() => observer.disconnect());
194 }}
195 class="grid min-w-[460px] gap-1"
196 style={{ "grid-template-columns": `auto repeat(${weeks()}, minmax(0, 1fr))` }}
197 >
198 <span aria-hidden="true" />
199 <For each={monthLabels()}>
200 {(label) => (
201 <span class="whitespace-nowrap text-[11px] leading-none text-muted-foreground">{label}</span>
202 )}
203 </For>
204
205 <For each={weekdayLabels()}>
206 {(weekdayLabel, dayIndex) => (
207 <>
208 <span class="pr-1 text-right text-[11px] leading-none text-muted-foreground">
209 {weekdayLabel}
210 </span>
211 <For each={columns()}>
212 {(week) => {
213 const day = week[dayIndex()];
214 const value = () => totals().get(day) ?? 0;
215 // Days after today are outside the observable range —
216 // drawn as an empty slot so the last week keeps its shape.
217 const future = () => day > todayStart();
218 const label = () =>
219 value() > 0 ? props.dayLabel(value(), day) : props.emptyDayLabel(day);
220 return (
221 <Show
222 when={!future()}
223 fallback={
224 // Days after today simply do not exist yet. They hold
225 // the last column's shape but stay invisible — an
226 // outlined placeholder reads as a half-drawn cell.
227 <span aria-hidden="true" class="aspect-square w-full" />
228 }
229 >
230 <span
231 class={cn(
232 "aspect-square w-full rounded-[3px] transition-colors",
233 levelClasses[levelOf(value())],
234 day === todayStart() && "ring-1 ring-ring",
235 )}
236 title={label()}
237 aria-label={label()}
238 role="img"
239 />
240 </Show>
241 );
242 }}
243 </For>
244 </>
245 )}
246 </For>
247 </div>
248 </div>
249
250 <div class="flex flex-wrap items-center justify-between gap-2 border-t border-border-hairline pt-3">
251 <Show when={props.footer}>
252 <p class="text-[11px] text-muted-foreground">{props.footer}</p>
253 </Show>
254 <div class="ml-auto flex items-center gap-1.5">
255 <span class="text-[11px] text-muted-foreground">{t("dashboard.heatmapLess")}</span>
256 <For each={levelClasses}>
257 {(levelClass) => <span class={cn("h-3 w-3 rounded-[3px]", levelClass)} />}
258 </For>
259 <span class="text-[11px] text-muted-foreground">{t("dashboard.heatmapMore")}</span>
260 </div>
261 </div>
262 </Show>
263 </div>
264 );
265};