import { For, Show, createMemo, onCleanup, type Component } from "solid-js"; import { cn } from "@/lib/cn"; import { usePreferences, useT } from "@/stores/preferences-context"; import { EmptyInline } from "@/components/ui/empty-inline"; /** One dated observation. Several entries may share a day — they are summed. */ export type HeatmapEntry = { /** Epoch millis. Bucketed into a local-time calendar day. */ at: number; /** Amount contributed by this entry (minutes, records, …). */ value: number; }; export type ChartHeatmapProps = { title?: string; subtitle?: string; entries: HeatmapEntry[]; /** Calendar weeks to render, ending with the week containing `endsAt`. */ weeks?: number; /** Right-hand edge of the range; defaults to now. */ endsAt?: number; /** Cell tooltip / screen-reader text for a day that has data. */ dayLabel: (value: number, dayStart: number) => string; /** Cell text for an empty day. */ emptyDayLabel: (dayStart: number) => string; /** Summary line under the grid, e.g. "312 dk odak · son 26 hafta". */ footer?: string; class?: string; }; const DEFAULT_WEEKS = 26; /** Columns a month label needs clear of the next one. */ const MONTH_LABEL_SPAN = 3; /** Local midnight for the day containing `ms` — DST-safe, unlike `ms - ms % DAY_MS`. */ function startOfDay(ms: number): number { const d = new Date(ms); d.setHours(0, 0, 0, 0); return d.getTime(); } /** Local midnight of the Monday on or before `ms`. */ function startOfWeek(ms: number): number { const d = new Date(startOfDay(ms)); // getDay(): 0 = Sunday. Shift so Monday is column-row 0. d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); return d.getTime(); } /** * GitHub-contribution-style calendar. Columns are weeks (oldest → newest), * rows are Monday → Sunday. Intensity is bucketed against the busiest day in * range, so the scale is always relative to real data rather than a guess. */ export const ChartHeatmap: Component = (props) => { const t = useT(); const { locale } = usePreferences(); const weeks = () => props.weeks ?? DEFAULT_WEEKS; // Totals per local day, keyed by that day's midnight timestamp. const totals = createMemo(() => { const map = new Map(); for (const entry of props.entries) { if (!Number.isFinite(entry.at) || entry.value <= 0) continue; const day = startOfDay(entry.at); map.set(day, (map.get(day) ?? 0) + entry.value); } return map; }); const firstWeekStart = createMemo(() => { const lastWeek = startOfWeek(props.endsAt ?? Date.now()); const d = new Date(lastWeek); d.setDate(d.getDate() - (weeks() - 1) * 7); return d.getTime(); }); // Columns of 7 local-midnight timestamps. Built by date arithmetic rather // than fixed DAY_MS steps so a DST shift can't slide the grid by an hour. const columns = createMemo(() => { const start = firstWeekStart(); return Array.from({ length: weeks() }, (_, week) => Array.from({ length: 7 }, (_, day) => { const d = new Date(start); d.setDate(d.getDate() + week * 7 + day); return d.getTime(); }), ); }); const maxValue = createMemo(() => Math.max(0, ...totals().values())); const todayStart = createMemo(() => startOfDay(props.endsAt ?? Date.now())); /** 0 = no data, 1..4 = quartiles of the busiest day. */ const levelOf = (value: number) => { if (value <= 0) return 0; const peak = maxValue(); if (peak <= 0) return 0; return Math.min(4, Math.ceil((value / peak) * 4)); }; const levelClasses = [ "bg-muted/60 dark:bg-muted/30", "bg-primary/25", "bg-primary/45", "bg-primary/70", "bg-primary", ]; const monthFormat = createMemo( () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { month: "short" }), ); const weekdayFormat = createMemo( () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { weekday: "short" }), ); // A month label sits above the first column whose Monday opens a new month. // A label runs wider than its column, so one whose next label starts within // MONTH_LABEL_SPAN columns is dropped — otherwise the range's opening month // and the next one print over each other ("MaNis"). const monthLabels = createMemo(() => { const labels = columns().map((week, index) => { const monday = new Date(week[0]); if (index > 0) { const previous = new Date(columns()[index - 1][0]); if (previous.getMonth() === monday.getMonth()) return ""; } return monthFormat().format(monday); }); let next = Number.POSITIVE_INFINITY; for (let index = labels.length - 1; index >= 0; index -= 1) { if (!labels[index]) continue; if (next - index < MONTH_LABEL_SPAN) labels[index] = ""; else next = index; } return labels; }); // Monday / Wednesday / Friday only — the full seven would not fit the gutter. const weekdayLabels = createMemo(() => { const week = columns()[0] ?? []; return week.map((day, index) => (index % 2 === 0 && index < 6 ? weekdayFormat().format(day) : "")); }); const hasData = createMemo(() => maxValue() > 0); return (

{props.title}

{props.subtitle}

} > {/* One grid for labels and cells together: a weekday gutter column plus an equal fraction per week, so the calendar always spans the card's full width and every label stays on its own row. Below the min-width it scrolls instead of shrinking cells past legibility. */} {/* `px-1` keeps today's focus ring off the scroll container's clip edge, which otherwise shaves the last column's cells in half. */} {/* Where it scrolls (a phone), it opens on the newest weeks — the right edge — rather than on the oldest. */}
{ // Re-pinned on every resize while the page settles (under // Suspense the node is built detached, and the card widens as // the layout fills in), until the user scrolls it themselves. if (typeof ResizeObserver === "undefined") return; let pinned = true; const release = () => { pinned = false; }; const observer = new ResizeObserver(() => { const scroller = grid.parentElement; if (pinned && scroller) scroller.scrollLeft = scroller.scrollWidth; }); observer.observe(grid); // The grid holds its min-width while the card around it shrinks, // so the scroller's own size matters as much. queueMicrotask(() => grid.parentElement && observer.observe(grid.parentElement)); for (const type of ["pointerdown", "wheel", "keydown"]) grid.addEventListener(type, release, { passive: true }); onCleanup(() => observer.disconnect()); }} class="grid min-w-[460px] gap-1" style={{ "grid-template-columns": `auto repeat(${weeks()}, minmax(0, 1fr))` }} >

{props.footer}

{t("dashboard.heatmapLess")} {(levelClass) => } {t("dashboard.heatmapMore")}
); };