|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useRef, useState } from 'react' |
| 4 | +import { cn, scrollFadeAttributes, scrollFadeXClass, Tooltip, useScrollEdges } from '@sim/emcn' |
| 5 | +import type { OrganizationUsageCalendar } from '@/lib/api/contracts/organization-usage' |
| 6 | +import { formatCreditsLabel } from '@/lib/billing/credits/conversion' |
| 7 | +import { USAGE_PALETTE_CLASS } from '@/ee/organization-usage/constants' |
| 8 | + |
| 9 | +const LEVEL_CLASSES = [ |
| 10 | + 'bg-[var(--surface-active)]', |
| 11 | + 'bg-[color-mix(in_srgb,var(--usage-workflow)_25%,var(--surface-2))]', |
| 12 | + 'bg-[color-mix(in_srgb,var(--usage-workflow)_50%,var(--surface-2))]', |
| 13 | + 'bg-[color-mix(in_srgb,var(--usage-workflow)_75%,var(--surface-2))]', |
| 14 | + 'bg-[var(--usage-workflow)]', |
| 15 | +] as const |
| 16 | +const WEEKDAY_LABELS = ['Mon', '', 'Wed', '', 'Fri', '', 'Sun'] as const |
| 17 | +const ARROW_OFFSETS: Record<string, number> = { |
| 18 | + ArrowLeft: -7, |
| 19 | + ArrowRight: 7, |
| 20 | + ArrowUp: -1, |
| 21 | + ArrowDown: 1, |
| 22 | +} |
| 23 | +const DAY_FORMAT = new Intl.DateTimeFormat('en-US', { |
| 24 | + timeZone: 'UTC', |
| 25 | + weekday: 'long', |
| 26 | + month: 'long', |
| 27 | + day: 'numeric', |
| 28 | + year: 'numeric', |
| 29 | +}) |
| 30 | +const MONTH_FORMAT = new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', month: 'short' }) |
| 31 | + |
| 32 | +interface UsageHeatmapProps { |
| 33 | + days: OrganizationUsageCalendar['days'] |
| 34 | +} |
| 35 | + |
| 36 | +function formatDayUsage(day: OrganizationUsageCalendar['days'][number]) { |
| 37 | + return `${formatCreditsLabel(day.credits)} on ${DAY_FORMAT.format(new Date(`${day.date}T00:00:00Z`))}` |
| 38 | +} |
| 39 | + |
| 40 | +/** Calendar dates stay in UTC for layout; they already describe the viewer's local days. */ |
| 41 | +export function UsageHeatmap({ days }: UsageHeatmapProps) { |
| 42 | + const scrollRef = useRef<HTMLDivElement>(null) |
| 43 | + const gridRef = useRef<HTMLDivElement>(null) |
| 44 | + const edges = useScrollEdges(scrollRef, { axis: 'x' }) |
| 45 | + const [focusedIndex, setFocusedIndex] = useState<number | null>(null) |
| 46 | + const [selectedDate, setSelectedDate] = useState<string | null>(null) |
| 47 | + const selectedDay = days.find((day) => day.date === selectedDate) |
| 48 | + const first = days[0] |
| 49 | + if (!first) return null |
| 50 | + const firstDate = new Date(`${first.date}T00:00:00Z`) |
| 51 | + const offset = (firstDate.getUTCDay() + 6) % 7 |
| 52 | + const weeks = Math.ceil((offset + days.length) / 7) |
| 53 | + const peak = Math.max(...days.map((day) => day.credits), 1) |
| 54 | + const total = days.reduce((sum, day) => sum + day.credits, 0) |
| 55 | + const months = days.flatMap((day, index) => { |
| 56 | + const date = new Date(`${day.date}T00:00:00Z`) |
| 57 | + if (date.getUTCDate() !== 1) return [] |
| 58 | + const column = Math.floor((index + offset) / 7) |
| 59 | + if (column > weeks - 3) return [] |
| 60 | + return [{ date: day.date, column, label: MONTH_FORMAT.format(date) }] |
| 61 | + }) |
| 62 | + |
| 63 | + return ( |
| 64 | + <div className={cn('flex min-w-0 flex-col gap-3', USAGE_PALETTE_CLASS)}> |
| 65 | + <div |
| 66 | + ref={scrollRef} |
| 67 | + className={cn('overflow-x-auto pb-1', scrollFadeXClass)} |
| 68 | + {...scrollFadeAttributes(edges)} |
| 69 | + > |
| 70 | + <div className='min-w-[660px] max-w-[860px] p-1'> |
| 71 | + <div |
| 72 | + className='mb-2 ml-8 grid gap-[3px] text-[var(--text-muted)] text-small' |
| 73 | + style={{ gridTemplateColumns: `repeat(${weeks}, minmax(0, 1fr))` }} |
| 74 | + aria-hidden='true' |
| 75 | + > |
| 76 | + {months.map((month) => ( |
| 77 | + <span key={month.date} style={{ gridColumn: `${month.column + 1} / span 3` }}> |
| 78 | + {month.label} |
| 79 | + </span> |
| 80 | + ))} |
| 81 | + </div> |
| 82 | + <div className='relative'> |
| 83 | + <div |
| 84 | + className='absolute inset-y-0 left-0 grid w-6 grid-rows-7 gap-[3px] text-[var(--text-muted)] text-small' |
| 85 | + aria-hidden='true' |
| 86 | + > |
| 87 | + {WEEKDAY_LABELS.map((label, index) => ( |
| 88 | + <span key={index} className='flex items-center'> |
| 89 | + {label} |
| 90 | + </span> |
| 91 | + ))} |
| 92 | + </div> |
| 93 | + <div |
| 94 | + ref={gridRef} |
| 95 | + role='group' |
| 96 | + aria-label='Daily credit usage. Use arrow keys to move between days, Home for the first day, or End for today.' |
| 97 | + className='ml-8 grid gap-[3px]' |
| 98 | + style={{ gridTemplateColumns: `repeat(${weeks}, minmax(0, 1fr))` }} |
| 99 | + > |
| 100 | + {days.map((day, index) => { |
| 101 | + const position = index + offset |
| 102 | + const level = |
| 103 | + day.credits === 0 ? 0 : Math.min(4, Math.ceil(Math.sqrt(day.credits / peak) * 4)) |
| 104 | + const label = formatDayUsage(day) |
| 105 | + return ( |
| 106 | + <Tooltip.Root key={day.date}> |
| 107 | + <Tooltip.Trigger asChild> |
| 108 | + <button |
| 109 | + type='button' |
| 110 | + aria-label={label} |
| 111 | + aria-pressed={day.date === selectedDate} |
| 112 | + data-day-index={index} |
| 113 | + tabIndex={index === (focusedIndex ?? days.length - 1) ? 0 : -1} |
| 114 | + className={cn( |
| 115 | + 'aspect-square rounded-[3px] outline-offset-2 hover:outline hover:outline-1 hover:outline-[var(--text-tertiary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--text-primary)]', |
| 116 | + LEVEL_CLASSES[level], |
| 117 | + day.date === selectedDate && |
| 118 | + 'outline outline-2 outline-[var(--text-primary)]' |
| 119 | + )} |
| 120 | + style={{ |
| 121 | + gridColumn: Math.floor(position / 7) + 1, |
| 122 | + gridRow: (position % 7) + 1, |
| 123 | + }} |
| 124 | + onClick={() => |
| 125 | + setSelectedDate((current) => (current === day.date ? null : day.date)) |
| 126 | + } |
| 127 | + onFocus={() => setFocusedIndex(index)} |
| 128 | + onKeyDown={(event) => { |
| 129 | + if (event.key === 'Escape' && selectedDate) { |
| 130 | + event.preventDefault() |
| 131 | + setSelectedDate(null) |
| 132 | + return |
| 133 | + } |
| 134 | + const delta = ARROW_OFFSETS[event.key] |
| 135 | + const next = |
| 136 | + event.key === 'Home' |
| 137 | + ? 0 |
| 138 | + : event.key === 'End' |
| 139 | + ? days.length - 1 |
| 140 | + : delta === undefined |
| 141 | + ? null |
| 142 | + : Math.max(0, Math.min(days.length - 1, index + delta)) |
| 143 | + if (next === null) return |
| 144 | + event.preventDefault() |
| 145 | + gridRef.current |
| 146 | + ?.querySelector<HTMLButtonElement>(`[data-day-index="${next}"]`) |
| 147 | + ?.focus() |
| 148 | + }} |
| 149 | + /> |
| 150 | + </Tooltip.Trigger> |
| 151 | + <Tooltip.Content>{label}</Tooltip.Content> |
| 152 | + </Tooltip.Root> |
| 153 | + ) |
| 154 | + })} |
| 155 | + </div> |
| 156 | + </div> |
| 157 | + </div> |
| 158 | + </div> |
| 159 | + <div className='flex flex-wrap items-center justify-between gap-2 text-[var(--text-muted)] text-small'> |
| 160 | + <span aria-live='polite'> |
| 161 | + {selectedDay |
| 162 | + ? formatDayUsage(selectedDay) |
| 163 | + : `${formatCreditsLabel(total)} in the last 365 days`} |
| 164 | + </span> |
| 165 | + <div |
| 166 | + className='flex items-center gap-1' |
| 167 | + aria-label='Color intensity: less to more daily usage' |
| 168 | + > |
| 169 | + <span className='mr-1'>Less</span> |
| 170 | + {LEVEL_CLASSES.map((className) => ( |
| 171 | + <span |
| 172 | + key={className} |
| 173 | + className={cn('size-3 rounded-[3px]', className)} |
| 174 | + aria-hidden='true' |
| 175 | + /> |
| 176 | + ))} |
| 177 | + <span className='ml-1'>More</span> |
| 178 | + </div> |
| 179 | + </div> |
| 180 | + </div> |
| 181 | + ) |
| 182 | +} |
0 commit comments