{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"commit-graph","type":"registry:component","title":"Commit Graph","description":"A contribution heatmap paged by two-week sprints, drillable to the day.","dependencies":["framer-motion","@phosphor-icons/react"],"files":[{"path":"components/ui/CommitGraph.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type FormEvent, type ReactNode } from \"react\";\nimport { motion, useReducedMotion } from \"framer-motion\";\nimport {\n GitCommitIcon as PhGitCommit,\n CircleNotchIcon as PhCircleNotch,\n FlameIcon as PhFlame,\n ArrowCounterClockwiseIcon as PhReset,\n ArrowLeftIcon as PhArrowLeft,\n CaretLeftIcon as PhCaretLeft,\n CaretRightIcon as PhCaretRight,\n PlusIcon as PhPlus,\n PencilSimpleIcon as PhPencil,\n} from \"@phosphor-icons/react\";\n\n// A sprint is a start and an end date, on any weekday. Sprints never overlap,\n// but they may leave days between them (a holiday week, a hardening week), and\n// those days belong to no sprint. The newest sprint runs to the later of its\n// end and today: a team that forgets to start the next one still sees today's\n// commits land somewhere.\nconst PLANNED_DAYS = 14;\n// The longest sprint the date fields accept.\nconst MAX_SPRINT_DAYS = 56;\n// A year of history, five sprints on screen at a time.\nconst SEEDED_SPRINTS = 26;\nconst VISIBLE_SPRINTS = 5;\n// How far ahead a sprint can be scheduled when it is created early.\nconst MAX_LEAD_DAYS = 28;\nconst DAY_MS = 86_400_000;\nconst DAYS = 7;\nconst WEEKDAYS = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nconst COMMITS_KEY = \"ui-commit-graph:commits\";\nconst SPRINTS_KEY = \"ui-commit-graph:sprints\";\nconst THEME_KEY = \"ui-commit-graph:theme\";\n// The server cannot know what day it is for the viewer, so the first paint\n// renders against a fixed date and the client swaps in the real one during\n// hydration (see useToday).\nconst SERVER_TODAY = \"2026-09-29\";\n\ntype ThemeId = \"emerald\" | \"blue\" | \"violet\" | \"amber\" | \"rose\";\n\ninterface Theme {\n label: string;\n swatch: string;\n light: [string, string, string, string];\n dark: [string, string, string, string];\n}\n\nconst THEMES: Record = {\n emerald: { label: \"Emerald\", swatch: \"#16A34A\", light: [\"#BBF7D0\", \"#4ADE80\", \"#16A34A\", \"#166534\"], dark: [\"#14532D\", \"#15803D\", \"#22C55E\", \"#86EFAC\"] },\n blue: { label: \"Blue\", swatch: \"#2563EB\", light: [\"#BFDBFE\", \"#60A5FA\", \"#2563EB\", \"#1E3A8A\"], dark: [\"#1E3A8A\", \"#1D4ED8\", \"#3B82F6\", \"#93C5FD\"] },\n violet: { label: \"Violet\", swatch: \"#7C3AED\", light: [\"#DDD6FE\", \"#A78BFA\", \"#7C3AED\", \"#4C1D95\"], dark: [\"#4C1D95\", \"#6D28D9\", \"#8B5CF6\", \"#C4B5FD\"] },\n amber: { label: \"Amber\", swatch: \"#D97706\", light: [\"#FDE68A\", \"#FBBF24\", \"#D97706\", \"#92400E\"], dark: [\"#78350F\", \"#B45309\", \"#F59E0B\", \"#FCD34D\"] },\n rose: { label: \"Rose\", swatch: \"#DB2777\", light: [\"#FBCFE8\", \"#F472B6\", \"#DB2777\", \"#831843\"], dark: [\"#831843\", \"#BE185D\", \"#EC4899\", \"#F9A8D4\"] },\n};\n\nconst THEME_IDS = Object.keys(THEMES) as ThemeId[];\n\n// Dates are handled as whole UTC day numbers (days since 1970-01-01). Adding a\n// day is adding one, and no daylight-saving change can make a day 23 hours long.\nfunction dayNumber(iso: string): number {\n const [y, m, d] = iso.split(\"-\").map(Number);\n return Math.round(Date.UTC(y, m - 1, d) / DAY_MS);\n}\n\nfunction isoFromDay(day: number): string {\n return new Date(day * DAY_MS).toISOString().slice(0, 10);\n}\n\nfunction weekdayOf(day: number): number {\n return new Date(day * DAY_MS).getUTCDay();\n}\n\n// Month names by hand rather than toLocaleDateString: the server and the\n// browser can disagree on locale, and text that differs between them is a\n// hydration error.\nfunction shortDate(day: number): string {\n const d = new Date(day * DAY_MS);\n return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;\n}\n\nfunction longDate(day: number): string {\n return `${WEEKDAYS[weekdayOf(day)].slice(0, 3)}, ${shortDate(day)}`;\n}\n\nfunction relativeDay(day: number, today: number): string {\n const diff = day - today;\n if (diff === 0) return \"today\";\n if (diff === -1) return \"yesterday\";\n if (diff === 1) return \"tomorrow\";\n return diff < 0 ? `${-diff} days ago` : `in ${diff} days`;\n}\n\n// Pure function of the calendar date, not of when the page is viewed: Sep 24\n// has the same count today and next month. Weekends run at a third, so the\n// weekday axis carries a real signal.\nfunction seededCount(day: number): number {\n const x = Math.sin((day + 11) * 12.9898 + 78.233) * 43758.5453;\n const frac = x - Math.floor(x);\n let count = 0;\n if (frac > 0.94) count = 8 + (Math.floor(frac * 37) % 6);\n else if (frac > 0.78) count = 4 + (Math.floor(frac * 23) % 4);\n else if (frac > 0.35) count = 1 + (Math.floor(frac * 17) % 3);\n return weekdayOf(day) % 6 === 0 ? Math.floor(count / 3) : count;\n}\n\n// Integer hash (Math.imul, exact in every engine), deliberately not the\n// sin-based seededCount above. A bucketed level survives a 1-ULP difference\n// between two engines' Math.sin; a message index or a SHA does not, and text\n// that differs between the server and the client is a hydration error.\nfunction hash32(seed: number): number {\n let h = Math.imul(seed ^ 0x9e3779b9, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return h >>> 0;\n}\n\ninterface SprintRange {\n start: number;\n end: number;\n}\n\n// The demo's history: 26 back-to-back sprints of 12 to 16 days, the newest\n// started five days ago. Uneven lengths put every sprint on a different\n// weekday, which is what real teams get once a holiday or a slipped planning\n// meeting has moved the start once or twice.\nfunction seededRanges(today: number): SprintRange[] {\n const starts = [today - 5];\n for (let i = 1; i < SEEDED_SPRINTS; i++) {\n starts.unshift(starts[0] - (12 + (hash32(i * 131 + 17) % 5)));\n }\n return starts.map((start, i) => ({ start, end: i < starts.length - 1 ? starts[i + 1] - 1 : start + PLANNED_DAYS - 1 }));\n}\n\n// A real deploy reads these from the git log (or the host's API). They are\n// generated here for the same reason the counts are: the site is a static\n// export, so the demo has to carry its own history.\nconst SUBJECTS = [\n \"fix: guard the tick generator against an empty range\",\n \"feat: add orientation to the chart frame\",\n \"refactor: pull the tooltip anchor out of the crosshair\",\n \"fix: stop the axis rounding away a fifth of the plot\",\n \"chore: bump framer-motion to 11.3.2\",\n \"test: cover the quantile legend ticks\",\n \"perf: batch the dot layer into one path\",\n \"fix: round projected coords so SSR and the client agree\",\n \"docs: note why the preview files are generated\",\n \"feat: keyboard roving across the heat map cells\",\n \"fix: dark ramp was two steps too light at level 3\",\n \"refactor: hoist the shared spline into the frame\",\n \"chore: regenerate the preview chunks\",\n \"fix: legend toggle left the y domain in dead space\",\n \"feat: sticky first column on the data table\",\n \"style: align the tick labels to the baseline\",\n \"fix: reset the day filter when the sprint changes\",\n \"test: snapshot the empty state\",\n \"perf: memoize the grid so hover stops re-rendering it\",\n \"fix: focus ring vanished at the light end of the ramp\",\n \"feat: copy button on the code block\",\n \"refactor: drop the wrapper div around every cell\",\n \"chore: pin the node version in CI\",\n \"fix: tooltip clipped inside the scroll container\",\n \"docs: rewrite the install steps for bun\",\n \"feat: reduced-motion path for the reveal\",\n \"fix: aria-label read the count without the day\",\n \"revert: put the old easing back on the drawer\",\n \"chore: delete the unused ramp helper\",\n \"fix: off-by-one in the week boundary\",\n];\n\ninterface Commit {\n sha: string;\n time: string;\n subject: string;\n}\n\n// Every stride is coprime with SUBJECTS.length, so walking the pool by one of\n// them visits every subject before repeating: a day never lands the same commit\n// message twice, which is what gives a hashed message away as fake.\nconst STRIDES = [7, 11, 13, 17, 19, 23];\n\nfunction commitsFor(day: number, count: number): Commit[] {\n const base = hash32(day * 31 + 7) % SUBJECTS.length;\n const stride = STRIDES[hash32(day * 17 + 5) % STRIDES.length];\n return Array.from({ length: count }, (_, i) => {\n const h = hash32(day * 97 + i * 7919 + 3);\n return { h, minutes: 8 * 60 + (h % 660) };\n })\n .sort((a, b) => a.minutes - b.minutes)\n .map(({ h, minutes }, i) => ({\n sha: h.toString(16).padStart(8, \"0\").slice(0, 7),\n time: `${String(Math.floor(minutes / 60)).padStart(2, \"0\")}:${String(minutes % 60).padStart(2, \"0\")}`,\n subject: SUBJECTS[(base + i * stride) % SUBJECTS.length],\n }));\n}\n\nfunction levelFor(count: number): 0 | 1 | 2 | 3 | 4 {\n if (count <= 0) return 0;\n if (count <= 2) return 1;\n if (count <= 5) return 2;\n if (count <= 9) return 3;\n return 4;\n}\n\ninterface Day {\n day: number;\n count: number;\n upcoming: boolean;\n}\n\ninterface Sprint {\n start: number;\n end: number;\n days: Day[];\n status: \"done\" | \"current\" | \"planned\";\n overBy: number;\n total: number;\n activeDays: number;\n elapsedDays: number;\n best: number;\n}\n\n// Where the newest sprint actually ends: its own end, or today if it has run\n// past that with nothing started after it.\nfunction effectiveEnd(range: SprintRange, isNewest: boolean, today: number): number {\n return isNewest && range.start <= today ? Math.max(range.end, today) : range.end;\n}\n\nfunction buildSprints(ranges: SprintRange[], today: number, extra: Record): Sprint[] {\n return ranges.map((range, i) => {\n const { start } = range;\n const isNewest = i === ranges.length - 1;\n const end = effectiveEnd(range, isNewest, today);\n const days: Day[] = [];\n for (let day = start; day <= end; day++) {\n const upcoming = day > today;\n days.push({ day, upcoming, count: upcoming ? 0 : seededCount(day) + (extra[isoFromDay(day)] ?? 0) });\n }\n const elapsed = days.filter((d) => !d.upcoming);\n return {\n start,\n end,\n days,\n status: start > today ? \"planned\" : end < today ? \"done\" : \"current\",\n overBy: end - range.end,\n total: elapsed.reduce((sum, d) => sum + d.count, 0),\n activeDays: elapsed.filter((d) => d.count > 0).length,\n elapsedDays: elapsed.length,\n best: elapsed.reduce((max, d) => Math.max(max, d.count), 0),\n };\n });\n}\n\n// The overview lays each sprint on the calendar, GitHub-style: rows are Sunday\n// to Saturday, so a sprint that starts on a Wednesday opens three cells down\n// its first column. Nulls pad the partial weeks at either end.\nfunction calendarColumns(days: Day[]): (Day | null)[][] {\n const cells: (Day | null)[] = [...Array(weekdayOf(days[0].day)).fill(null), ...days];\n while (cells.length % DAYS) cells.push(null);\n return Array.from({ length: cells.length / DAYS }, (_, c) => cells.slice(c * DAYS, (c + 1) * DAYS));\n}\n\n// The detail view counts from the sprint's own first day instead, so a\n// Wednesday sprint reads Wed to Tue across the top and two full rows down.\nfunction sprintRows(days: Day[]): (Day | null)[][] {\n return Array.from({ length: Math.ceil(days.length / DAYS) }, (_, r) => {\n const row: (Day | null)[] = days.slice(r * DAYS, (r + 1) * DAYS);\n while (row.length < DAYS) row.push(null);\n return row;\n });\n}\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nfunction parseDate(value: unknown): number | null {\n return typeof value === \"string\" && ISO_DATE.test(value) ? dayNumber(value) : null;\n}\n\n// Stored as [{ start, end }] in ISO dates. Anything overlapping the sprint\n// before it is dropped rather than guessed at, so a hand-edited value can\n// never produce two sprints claiming the same day.\nfunction parseRanges(raw: string | null): SprintRange[] | null {\n if (!raw) return null;\n try {\n const list: unknown = JSON.parse(raw);\n if (!Array.isArray(list)) return null;\n const ranges = list\n .map((item: unknown) => {\n const { start, end } = (item ?? {}) as { start?: unknown; end?: unknown };\n const s = parseDate(start);\n const e = parseDate(end);\n return s !== null && e !== null && e >= s ? { start: s, end: e } : null;\n })\n .filter((r): r is SprintRange => r !== null)\n .sort((a, b) => a.start - b.start)\n .filter((r, i, all) => i === 0 || r.start > all[i - 1].end);\n return ranges.length > 0 ? ranges : null;\n } catch {\n return null;\n }\n}\n\nfunction parseCommits(raw: string | null): Record {\n if (!raw) return {};\n try {\n const map: unknown = JSON.parse(raw);\n return map && typeof map === \"object\" && !Array.isArray(map) ? (map as Record) : {};\n } catch {\n return {};\n }\n}\n\nconst subscribeNever = () => () => {};\n\n// Read through useSyncExternalStore rather than seeding useState from\n// localStorage in an effect: the server snapshot is what both the server and\n// the first client paint render, so there's nothing for hydration to disagree\n// about, and no cascading setState-in-effect render. Raw strings, not parsed\n// values, so the snapshot compares equal between reads.\nfunction readKey(key: string): string | null {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\nfunction getSprintsSnapshot() {\n return readKey(SPRINTS_KEY);\n}\nfunction getCommitsSnapshot() {\n return readKey(COMMITS_KEY);\n}\nfunction getNullSnapshot() {\n return null;\n}\n\nfunction getThemeSnapshot(): ThemeId {\n const stored = readKey(THEME_KEY) as ThemeId | null;\n return stored && stored in THEMES ? stored : \"emerald\";\n}\nfunction getThemeServerSnapshot(): ThemeId {\n return \"emerald\";\n}\n\n// The viewer's local calendar date, not the UTC one: a commit at 9pm in\n// California belongs to that evening, not to tomorrow.\nfunction getTodaySnapshot(): string {\n const d = new Date();\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}-${String(d.getDate()).padStart(2, \"0\")}`;\n}\nfunction getTodayServerSnapshot(): string {\n return SERVER_TODAY;\n}\n\nfunction writeKey(key: string, value: string | null) {\n try {\n if (value === null) localStorage.removeItem(key);\n else localStorage.setItem(key, value);\n } catch {\n // no-op\n }\n}\n\nfunction GitCommitIcon() {\n return ;\n}\n\nfunction SpinnerIcon() {\n return ;\n}\n\nfunction FlameIcon() {\n return ;\n}\n\nfunction ResetIcon() {\n return ;\n}\n\nfunction BackIcon() {\n return ;\n}\n\nfunction OlderIcon() {\n return ;\n}\n\nfunction NewerIcon() {\n return ;\n}\n\nfunction PlusIcon() {\n return ;\n}\n\nfunction PencilIcon() {\n return ;\n}\n\nconst FOCUS =\n \"focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-600 dark:focus-visible:outline-emerald-400\";\n\nconst INPUT =\n \"h-8 w-full min-w-0 rounded-md border border-stone-300 bg-stone-100 px-3 text-sm tabular-nums text-stone-900 outline-none focus:border-emerald-600 focus:ring-2 focus:ring-emerald-600/25 dark:border-stone-700 dark:bg-stone-950 dark:text-stone-100 dark:[color-scheme:dark] dark:focus:border-emerald-400 dark:focus:ring-emerald-400/25\";\n\nconst EYEBROW = \"text-[11px] font-medium uppercase tracking-[0.08em] text-stone-500 dark:text-stone-500\";\n\ninterface DraftError {\n field: \"start\" | \"end\";\n message: string;\n}\n\ninterface Bounds {\n min: number | null;\n max: number;\n}\n\ninterface SprintDatesFormProps {\n title: string;\n start: string;\n end: string;\n startBounds: Bounds;\n endBounds: Bounds;\n today: number;\n error: DraftError | null;\n hint: ReactNode;\n submitLabel: string;\n onStartChange: (value: string) => void;\n onEndChange: (value: string) => void;\n onSubmit: () => void;\n onCancel: () => void;\n}\n\n// One form for both jobs, creating a sprint and changing an existing sprint's\n// dates. A new sprint defaults to starting today because most sprints are\n// created the day they start; the fields are there for the ones that are not.\nfunction SprintDatesForm({\n title,\n start,\n end,\n startBounds,\n endBounds,\n today,\n error,\n hint,\n submitLabel,\n onStartChange,\n onEndChange,\n onSubmit,\n onCancel,\n}: SprintDatesFormProps) {\n const shouldReduceMotion = useReducedMotion();\n const startRef = useRef(null);\n const id = useId();\n const hintId = `${id}-hint`;\n const todayIso = isoFromDay(today);\n const canPickToday = start !== todayIso && today <= startBounds.max && (startBounds.min === null || today >= startBounds.min);\n\n useEffect(() => {\n startRef.current?.focus({ preventScroll: true });\n }, []);\n\n const submit = (event: FormEvent) => {\n event.preventDefault();\n if (!error) onSubmit();\n };\n\n return (\n \n

{title}

\n
\n
\n
\n \n {canPickToday && (\n onStartChange(todayIso)}\n className={`rounded text-[11px] font-medium text-emerald-700 hover:underline dark:text-emerald-400 ${FOCUS}`}\n >\n Today\n \n )}\n
\n onStartChange(event.target.value)}\n aria-invalid={error?.field === \"start\" ? true : undefined}\n aria-describedby={hintId}\n className={`mt-1 ${INPUT}`}\n />\n
\n
\n
\n \n
\n onEndChange(event.target.value)}\n aria-invalid={error?.field === \"end\" ? true : undefined}\n aria-describedby={hintId}\n className={`mt-1 ${INPUT}`}\n />\n
\n
\n

\n {error?.message ?? hint}\n

\n
\n \n Cancel\n \n \n {submitLabel}\n \n
\n \n );\n}\n\ntype Draft = { mode: \"create\" } | { mode: \"edit\"; index: number };\n\nexport function CommitGraph() {\n const shouldReduceMotion = useReducedMotion();\n const todayIso = useSyncExternalStore(subscribeNever, getTodaySnapshot, getTodayServerSnapshot);\n const persistedSprints = useSyncExternalStore(subscribeNever, getSprintsSnapshot, getNullSnapshot);\n const persistedCommits = useSyncExternalStore(subscribeNever, getCommitsSnapshot, getNullSnapshot);\n const persistedTheme = useSyncExternalStore(subscribeNever, getThemeSnapshot, getThemeServerSnapshot);\n // undefined means \"no change this session, use what storage holds\"; null\n // means \"cleared\", which is different from never having been set.\n const [sprintsOverride, setSprintsOverride] = useState(undefined);\n const [commitsOverride, setCommitsOverride] = useState(undefined);\n const [themeOverride, setThemeOverride] = useState(null);\n const [committing, setCommitting] = useState(false);\n const [justCommitted, setJustCommitted] = useState(false);\n const [selected, setSelected] = useState(null);\n const [selectedDay, setSelectedDay] = useState(null);\n // Counted back from the newest page rather than forward from the oldest, so\n // adding a sprint keeps you on the newest page instead of one behind it.\n const [pagesBack, setPagesBack] = useState(0);\n const [pageDir, setPageDir] = useState(0);\n const [draft, setDraft] = useState(null);\n const [draftStart, setDraftStart] = useState(\"\");\n const [draftEnd, setDraftEnd] = useState(\"\");\n // A new sprint's end follows its start at the planned length until the end\n // is picked by hand; after that the two move independently.\n const [endTouched, setEndTouched] = useState(false);\n const [announcement, setAnnouncement] = useState(\"\");\n const sprintRefs = useRef<(HTMLButtonElement | null)[]>([]);\n const backRef = useRef(null);\n const draftTriggerRef = useRef(null);\n const returnFocusTo = useRef(null);\n const focusAfterCreate = useRef(null);\n const wasSelected = useRef(null);\n\n const today = dayNumber(todayIso);\n const sprintsRaw = sprintsOverride === undefined ? persistedSprints : sprintsOverride;\n const commitsRaw = commitsOverride === undefined ? persistedCommits : commitsOverride;\n const theme = themeOverride ?? persistedTheme;\n\n const customRanges = useMemo(() => parseRanges(sprintsRaw), [sprintsRaw]);\n const ranges = useMemo(() => customRanges ?? seededRanges(today), [customRanges, today]);\n const extra = useMemo(() => parseCommits(commitsRaw), [commitsRaw]);\n const sprints = useMemo(() => buildSprints(ranges, today, extra), [ranges, today, extra]);\n const sprintColumns = useMemo(() => sprints.map((sprint) => calendarColumns(sprint.days)), [sprints]);\n\n const currentIndex = sprints.findIndex((sprint) => sprint.status === \"current\");\n const current = currentIndex === -1 ? null : sprints[currentIndex];\n const lastIndex = sprints.length - 1;\n\n const maxStart = Math.max(0, sprints.length - VISIBLE_SPRINTS);\n const windowStart = Math.min(Math.max(maxStart - pagesBack, 0), maxStart);\n const windowEnd = Math.min(windowStart + VISIBLE_SPRINTS, sprints.length);\n const visibleSprints = sprints.slice(windowStart, windowEnd);\n // The window's own total, not the year's: the headline should count what is\n // actually on screen.\n const windowTotal = visibleSprints.reduce((sum, sprint) => sum + sprint.total, 0);\n const atOldest = windowStart === 0;\n const atNewest = windowStart >= maxStart;\n\n const streak = useMemo(() => {\n let count = 0;\n for (let day = today; day >= ranges[0].start; day--) {\n if (seededCount(day) + (extra[isoFromDay(day)] ?? 0) > 0) count++;\n else break;\n }\n return count;\n }, [today, ranges, extra]);\n\n const detail = selected === null ? null : (sprints[selected] ?? null);\n const isCurrentSprint = selected !== null && selected === currentIndex;\n const delta =\n selected === null || selected === 0 || detail?.status === \"planned\" ? null : sprints[selected].total - sprints[selected - 1].total;\n\n const sprintLog = useMemo(\n () => (detail === null ? [] : detail.days.map((d) => ({ ...d, commits: commitsFor(d.day, d.count) }))),\n [detail],\n );\n\n const visibleDays = selectedDay === null ? sprintLog.filter((d) => d.count > 0) : sprintLog.filter((d) => d.day === selectedDay);\n\n // Focus follows the view, in both directions: into the sprint it lands on the\n // way back out, and on return it lands on the sprint you came from rather\n // than at the top of the card.\n useEffect(() => {\n const was = wasSelected.current;\n wasSelected.current = selected;\n if (selected !== null && was === null) {\n backRef.current?.focus({ preventScroll: true });\n } else if (selected !== null && document.activeElement === document.body) {\n // Stepping onto the first or last sprint disables the chevron that was\n // pressed, and a disabled button drops focus to the page.\n backRef.current?.focus({ preventScroll: true });\n } else if (selected === null && was !== null && returnFocusTo.current !== null) {\n sprintRefs.current[returnFocusTo.current]?.focus({ preventScroll: true });\n returnFocusTo.current = null;\n }\n }, [selected]);\n\n // A new sprint's block only exists after the render that adds it.\n useEffect(() => {\n if (focusAfterCreate.current === null) return;\n sprintRefs.current[focusAfterCreate.current]?.focus({ preventScroll: true });\n focusAfterCreate.current = null;\n }, [sprints]);\n\n const moveWindowTo = (start: number) => setPagesBack(maxStart - Math.min(Math.max(start, 0), maxStart));\n\n // Stepping to a sprint also drags the overview window along, so coming back\n // out lands on the sprint you were reading rather than where you started.\n const openSprint = (si: number) => {\n const target = Math.min(Math.max(si, 0), lastIndex);\n returnFocusTo.current = target;\n setSelected(target);\n setSelectedDay(null);\n setDraft(null);\n moveWindowTo(Math.min(Math.max(windowStart, target - VISIBLE_SPRINTS + 1), target));\n };\n\n const page = (direction: -1 | 1) => {\n setPageDir(direction);\n moveWindowTo(windowStart + direction * VISIBLE_SPRINTS);\n };\n\n const closeDetail = () => {\n setSelected(null);\n setSelectedDay(null);\n setDraft(null);\n };\n\n const activeTheme = THEMES[theme];\n const ramp = (level: 0 | 1 | 2 | 3 | 4, isDark: boolean) => (level === 0 ? null : (isDark ? activeTheme.dark : activeTheme.light)[level - 1]);\n\n const changeTheme = (id: ThemeId) => {\n setThemeOverride(id);\n writeKey(THEME_KEY, id);\n };\n\n const saveRanges = (next: SprintRange[]) => {\n const raw = JSON.stringify(next.map((r) => ({ start: isoFromDay(r.start), end: isoFromDay(r.end) })));\n writeKey(SPRINTS_KEY, raw);\n setSprintsOverride(raw);\n };\n\n const handleCommit = () => {\n if (committing) return;\n setCommitting(true);\n // A real deploy of this component would POST to /api/commits and read the\n // updated count back; this demo simulates that round trip's latency and\n // persists the result the same place a server response would end up\n // caching to, so the count survives a reload without a real backend.\n // Keyed by date, so tomorrow's commits land on tomorrow.\n const latency = 420 + Math.round(Math.random() * 260);\n window.setTimeout(() => {\n const raw = JSON.stringify({ ...extra, [todayIso]: (extra[todayIso] ?? 0) + 1 });\n writeKey(COMMITS_KEY, raw);\n setCommitsOverride(raw);\n setCommitting(false);\n setJustCommitted(true);\n window.setTimeout(() => setJustCommitted(false), 500);\n }, latency);\n };\n\n const handleReset = () => {\n writeKey(COMMITS_KEY, null);\n writeKey(SPRINTS_KEY, null);\n setCommitsOverride(null);\n setSprintsOverride(null);\n closeDetail();\n setPagesBack(0);\n setAnnouncement(\"Sprints and commits reset to the sample history.\");\n };\n\n const draftStartDay = ISO_DATE.test(draftStart) ? dayNumber(draftStart) : null;\n const draftEndDay = ISO_DATE.test(draftEnd) ? dayNumber(draftEnd) : null;\n const newest = ranges[lastIndex];\n\n // Where each field may land. A new sprint has to start after the newest one\n // starts (otherwise it would swallow it whole) and at most four weeks out.\n // An existing sprint keeps clear of its neighbours: nothing else moves when\n // its dates change, so it can never take days that belong to another sprint.\n const draftLimits = (() => {\n if (draft === null) return null;\n const anchor = draftStartDay ?? (draft.mode === \"create\" ? today : ranges[draft.index].start);\n const endMax = (next: SprintRange | undefined) => (next ? Math.min(next.start - 1, anchor + MAX_SPRINT_DAYS - 1) : anchor + MAX_SPRINT_DAYS - 1);\n if (draft.mode === \"create\") {\n return {\n start: { min: newest.start + 1, max: today + MAX_LEAD_DAYS },\n end: { min: draftStartDay, max: endMax(undefined) },\n };\n }\n const i = draft.index;\n const prev = ranges[i - 1];\n const next = ranges[i + 1];\n return {\n start: { min: prev ? prev.end + 1 : null, max: next ? next.start - 1 : today + MAX_LEAD_DAYS },\n end: { min: draftStartDay, max: endMax(next) },\n };\n })();\n\n // Creating a sprint closes the newest one the day before it starts. If the\n // new one starts later than that, the newest keeps its own end (or today, if\n // it had already run past it) and the days between belong to no sprint.\n const newestEndAfterCreate = (start: number) => {\n const runsTo = effectiveEnd(newest, true, today);\n return start <= runsTo + 1 ? start - 1 : runsTo;\n };\n\n const draftError = ((): DraftError | null => {\n if (draft === null || draftLimits === null) return null;\n if (draftStartDay === null) return { field: \"start\", message: \"Pick a date for the sprint to start.\" };\n if (draftEndDay === null) return { field: \"end\", message: \"Pick a date for the sprint to end.\" };\n const { start, end } = draftLimits;\n const i = draft.mode === \"create\" ? lastIndex + 1 : draft.index;\n if (start.min !== null && draftStartDay < start.min) {\n return draft.mode === \"create\"\n ? { field: \"start\", message: `Has to be after Sprint ${i} starts on ${longDate(start.min - 1)}.` }\n : { field: \"start\", message: `Sprint ${i} ends ${longDate(start.min - 1)}, so this one can start ${shortDate(start.min)} at the earliest.` };\n }\n if (draftStartDay > start.max) {\n return draft.mode === \"edit\" && draft.index < lastIndex\n ? { field: \"start\", message: `Sprint ${i + 2} starts ${longDate(start.max + 1)}, so this one has to start before it.` }\n : { field: \"start\", message: `Sprints can be scheduled up to four weeks ahead, ${longDate(start.max)} at the latest.` };\n }\n if (draftEndDay < draftStartDay) return { field: \"end\", message: \"The end date is before the start date.\" };\n const next = draft.mode === \"edit\" ? ranges[draft.index + 1] : undefined;\n if (next && draftEndDay >= next.start) {\n return { field: \"end\", message: `Sprint ${i + 2} starts ${longDate(next.start)}, so this one has to end by ${shortDate(next.start - 1)}.` };\n }\n if (draftEndDay > end.max) {\n return { field: \"end\", message: `Sprints run eight weeks at most, so ${longDate(end.max)} at the latest.` };\n }\n return null;\n })();\n\n const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n\n // The consequence line. Dates decide more than this sprint's own length: a\n // new sprint closes the one before it, and any sprint can leave days that\n // belong to no sprint. The form says so before anything is saved.\n const draftHint = (() => {\n if (draft === null || draftStartDay === null || draftEndDay === null || draftEndDay < draftStartDay) return null;\n const parts = [`${plural(draftEndDay - draftStartDay + 1, \"day\")}, starting ${relativeDay(draftStartDay, today)}.`];\n if (draft.mode === \"create\") {\n const closesOn = newestEndAfterCreate(draftStartDay);\n if (closesOn !== newest.end) {\n const length = closesOn - newest.start + 1;\n parts.push(\n closesOn < today\n ? `Sprint ${lastIndex + 1} closes ${shortDate(closesOn)} after ${plural(length, \"day\")}.`\n : `Sprint ${lastIndex + 1} now ends ${shortDate(closesOn)}, ${plural(length, \"day\")} in all.`,\n );\n }\n const gap = draftStartDay - closesOn - 1;\n if (gap > 0) parts.push(`The ${plural(gap, \"day\")} between them belong to no sprint.`);\n } else {\n const i = draft.index;\n const prev = ranges[i - 1];\n const next = ranges[i + 1];\n const gapBefore = prev ? draftStartDay - prev.end - 1 : 0;\n const gapAfter = next ? next.start - draftEndDay - 1 : 0;\n if (gapBefore > 0) parts.push(`Leaves ${plural(gapBefore, \"day\")} after Sprint ${i} in no sprint.`);\n if (gapAfter > 0) parts.push(`Leaves ${plural(gapAfter, \"day\")} before Sprint ${i + 2} in no sprint.`);\n if (!next && draftStartDay <= today && draftEndDay < today) {\n parts.push(\"It keeps collecting commits past that until the next sprint starts.\");\n }\n }\n return parts.join(\" \");\n })();\n\n const openDraft = (next: Draft, trigger: HTMLButtonElement) => {\n draftTriggerRef.current = trigger;\n setDraft(next);\n if (next.mode === \"create\") {\n setDraftStart(todayIso);\n setDraftEnd(isoFromDay(today + PLANNED_DAYS - 1));\n setEndTouched(false);\n } else {\n setDraftStart(isoFromDay(ranges[next.index].start));\n setDraftEnd(isoFromDay(ranges[next.index].end));\n setEndTouched(true);\n }\n };\n\n const changeDraftStart = (value: string) => {\n setDraftStart(value);\n if (!endTouched && ISO_DATE.test(value)) setDraftEnd(isoFromDay(dayNumber(value) + PLANNED_DAYS - 1));\n };\n\n const changeDraftEnd = (value: string) => {\n setDraftEnd(value);\n setEndTouched(true);\n };\n\n const cancelDraft = () => {\n setDraft(null);\n draftTriggerRef.current?.focus({ preventScroll: true });\n };\n\n const submitDraft = () => {\n if (draft === null || draftStartDay === null || draftEndDay === null || draftError) return;\n const range = { start: draftStartDay, end: draftEndDay };\n const span = `${longDate(range.start)} to ${longDate(range.end)}`;\n if (draft.mode === \"create\") {\n const index = ranges.length;\n saveRanges([...ranges.slice(0, -1), { start: newest.start, end: newestEndAfterCreate(range.start) }, range]);\n setDraft(null);\n setPagesBack(0);\n focusAfterCreate.current = index;\n setAnnouncement(`Sprint ${index + 1} created, ${span}.`);\n } else {\n saveRanges(ranges.map((r, i) => (i === draft.index ? range : r)));\n setDraft(null);\n setSelectedDay(null);\n draftTriggerRef.current?.focus({ preventScroll: true });\n setAnnouncement(`Sprint ${draft.index + 1} now runs ${span}.`);\n }\n };\n\n // Commit lands on today, so it is only offered where today is on screen: the\n // overview page holding the current sprint, or that sprint's own view.\n const currentOnScreen = currentIndex >= windowStart && currentIndex < windowEnd;\n const showCommitAction = selected === null ? currentOnScreen : isCurrentSprint;\n const showReset = Object.keys(extra).length > 0 || customRanges !== null;\n\n const enter = shouldReduceMotion ? { opacity: 0 } : { opacity: 0, y: 6 };\n\n const cellFill = (level: 0 | 1 | 2 | 3 | 4, upcoming: boolean, className: string) =>\n upcoming ? (\n \n ) : (\n <>\n \n