{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"activity-heatmap","type":"registry:block","title":"Activity heatmap","description":"A contribution-style heatmap of daily activity over 26 weeks, with a diagonal reveal, weekday and month labels, hover/focus tooltips, and a Less-to-More legend.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/activity-heatmap/activity-heatmap.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\nexport type ActivityHeatmapProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  /** 26 weeks × 7 days (Mon–Sun) of daily counts. Defaults to a deterministic demo. */\n  values?: number[][];\n  /** What the counts represent, e.g. \"contributions\". */\n  unitLabel?: string;\n  formatCount?: (count: number) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* geometry constants                                                  */\n/* ------------------------------------------------------------------ */\n\nconst WEEKS = 26;\nconst DAYS = 7;\nconst GAP = 3;\nconst MIN_CELL = 3;\nconst GUTTER_LEFT = 30;\nconst GUTTER_TOP = 16;\nconst GUTTER_RIGHT = 4;\nconst GUTTER_BOTTOM = 4;\n\nconst DAY_NAMES = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\nconst MONTH_NAMES = [\n  \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n  \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n];\n\n/* Monday of the most recent week, in UTC, so dates are identical on the\n   server and the client (no locale/timezone surprises during hydration). */\nconst ANCHOR_MS = Date.UTC(2026, 10, 2);\n\n/* opacity ramp for the four non-empty intensity levels (level 0 is muted) */\nconst LEVEL_OPACITY = [0.28, 0.5, 0.72, 1];\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data (seeded PRNG — no Math.random / Date.now)    */\n/* ------------------------------------------------------------------ */\n\nfunction mulberry32(seed: number) {\n  let a = seed >>> 0;\n  return function () {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n/* bend a raw random toward a realistic rhythm: a broad seasonal wave,\n   slightly lighter weekends, a quiet summer lull, and a final sprint.\n   Tuned so ~70% of days land in a non-empty level (see levelFromR). */\nfunction modulate(r: number, week: number, day: number) {\n  const wave = 0.5 + 0.5 * Math.sin((week / WEEKS) * Math.PI * 2 - 0.9);\n  let v = r * 0.6 + wave * 0.4;\n  if (day >= 5) v *= 0.7;\n  if (week >= 7 && week <= 9) v *= 0.55;\n  if (week >= 21) v = Math.min(1, v * 1.2 + 0.08);\n  return v;\n}\n\n/* roughly 30% empty, 26% / 20% / 14% / 10% for levels 1–4 */\nfunction levelFromR(r: number): number {\n  if (r < 0.3) return 0;\n  if (r < 0.56) return 1;\n  if (r < 0.76) return 2;\n  if (r < 0.9) return 3;\n  return 4;\n}\n\n/* a count within the level's range, so the tooltip reads like real data */\nconst COUNT_RANGE: [number, number][] = [\n  [0, 0],\n  [1, 3],\n  [4, 7],\n  [8, 12],\n  [13, 26],\n];\n\nfunction countFor(level: number, jitter: number): number {\n  const [lo, hi] = COUNT_RANGE[level];\n  return Math.min(hi, lo + Math.floor(jitter * (hi - lo + 1)));\n}\n\nfunction generateDefaultCounts(): number[][] {\n  const rand = mulberry32(0x9e3779b9);\n  return Array.from({ length: WEEKS }, (_, w) =>\n    Array.from({ length: DAYS }, (_, d) => {\n      const level = levelFromR(modulate(rand(), w, d));\n      return countFor(level, rand());\n    })\n  );\n}\n\nconst DEFAULT_VALUES = generateDefaultCounts();\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction clamp(v: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, v));\n}\n\nfunction levelFromCount(count: number): number {\n  if (count <= 0) return 0;\n  if (count <= 3) return 1;\n  if (count <= 7) return 2;\n  if (count <= 12) return 3;\n  return 4;\n}\n\nfunction cellFill(level: number): { fill: string; opacity: number } {\n  if (level === 0) return { fill: \"var(--muted)\", opacity: 1 };\n  return { fill: \"var(--chart-1)\", opacity: LEVEL_OPACITY[level - 1] };\n}\n\nfunction dateForCell(week: number, day: number): Date {\n  const offset = (week - (WEEKS - 1)) * DAYS + day;\n  return new Date(ANCHOR_MS + offset * 86_400_000);\n}\n\nfunction formatDay(date: Date): string {\n  const weekday = DAY_NAMES[(date.getUTCDay() + 6) % 7];\n  return `${weekday}, ${MONTH_NAMES[date.getUTCMonth()]} ${date.getUTCDate()}`;\n}\n\ntype Geometry = {\n  width: number;\n  height: number;\n  cell: number;\n  gap: number;\n  radius: number;\n  left: number;\n  top: number;\n  gridW: number;\n  gridH: number;\n  cellX: (week: number) => number;\n  cellY: (day: number) => number;\n};\n\nfunction buildGeometry(width: number): Geometry {\n  const available = width - GUTTER_LEFT - GUTTER_RIGHT;\n  const cell = Math.max(\n    (available - (WEEKS - 1) * GAP) / WEEKS,\n    MIN_CELL\n  );\n  const gridW = WEEKS * cell + (WEEKS - 1) * GAP;\n  const gridH = DAYS * cell + (DAYS - 1) * GAP;\n  const height = GUTTER_TOP + gridH + GUTTER_BOTTOM;\n  return {\n    width,\n    height,\n    cell,\n    gap: GAP,\n    radius: clamp(cell * 0.22, 1, 3),\n    left: GUTTER_LEFT,\n    top: GUTTER_TOP,\n    gridW,\n    gridH,\n    cellX: (week: number) => GUTTER_LEFT + week * (cell + GAP),\n    cellY: (day: number) => GUTTER_TOP + day * (cell + GAP),\n  };\n}\n\ntype Day = {\n  week: number;\n  day: number;\n  count: number;\n  level: number;\n  label: string;\n};\n\n/* ------------------------------------------------------------------ */\n/* component                                                           */\n/* ------------------------------------------------------------------ */\n\nexport function ActivityHeatmap({\n  className,\n  title = \"Activity\",\n  description = \"Daily contributions over the last 26 weeks.\",\n  values,\n  unitLabel = \"contributions\",\n  formatCount = (count: number) => count.toLocaleString(\"en-US\"),\n}: ActivityHeatmapProps) {\n  const cardRef = useRef<HTMLDivElement>(null);\n  const chartRef = useRef<HTMLDivElement>(null);\n\n  const inView = useInView(cardRef, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n\n  const [size, setSize] = useState<{ width: number } | null>(null);\n  const [active, setActive] = useState<{ week: number; day: number } | null>(\n    null\n  );\n\n  /* measure the chart container so the SVG matches its pixel size */\n  useEffect(() => {\n    const el = chartRef.current;\n    if (!el) return;\n    const update = () => {\n      const width = el.getBoundingClientRect().width;\n      setSize((prev) => (prev && prev.width === width ? prev : { width }));\n    };\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  const geometry = useMemo<Geometry | null>(\n    () => (size && size.width > 0 ? buildGeometry(size.width) : null),\n    [size]\n  );\n\n  /* normalise counts into day records + derived levels */\n  const days = useMemo<Day[]>(() => {\n    const rows = Array.isArray(values) ? values : DEFAULT_VALUES;\n    const out: Day[] = [];\n    for (let w = 0; w < WEEKS; w++) {\n      const row = rows[w] ?? [];\n      for (let d = 0; d < DAYS; d++) {\n        const raw = row[d];\n        const count = Math.max(\n          0,\n          Math.round(typeof raw === \"number\" && Number.isFinite(raw) ? raw : 0)\n        );\n        out.push({\n          week: w,\n          day: d,\n          count,\n          level: levelFromCount(count),\n          label: formatDay(dateForCell(w, d)),\n        });\n      }\n    }\n    return out;\n  }, [values]);\n\n  const total = useMemo(\n    () => days.reduce((sum, day) => sum + day.count, 0),\n    [days]\n  );\n\n  const monthLabels = useMemo(() => {\n    const labels: { week: number; label: string }[] = [];\n    let prev = -1;\n    for (let w = 0; w < WEEKS; w++) {\n      const month = dateForCell(w, 0).getUTCMonth();\n      if (month !== prev) {\n        labels.push({ week: w, label: MONTH_NAMES[month] });\n        prev = month;\n      }\n    }\n    return labels;\n  }, []);\n\n  const activeDay = active\n    ? days[active.week * DAYS + active.day] ?? null\n    : null;\n\n  /* tooltip placement, clamped inside the chart container */\n  let tipLeft = 4;\n  let tipTop = 8;\n  if (geometry && active) {\n    const cx = geometry.cellX(active.week) + geometry.cell / 2;\n    const cy = geometry.cellY(active.day) + geometry.cell / 2;\n    tipLeft = clamp(cx - 76, 4, geometry.width - 152);\n    const above = cy - geometry.cell - 48;\n    tipTop = above < 4 ? cy + geometry.cell + 6 : above;\n    tipTop = clamp(tipTop, 4, geometry.height - 52);\n  }\n\n  const firstDate = dateForCell(0, 0);\n  const lastDate = dateForCell(WEEKS - 1, DAYS - 1);\n  const ariaLabel = `${title}. Contribution heatmap of ${total} ${unitLabel} over ${WEEKS} weeks, from ${formatDay(\n    firstDate\n  )} to ${formatDay(lastDate)}.`;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.div\n        ref={cardRef}\n        initial={{ opacity: 0, y: 20 }}\n        animate={show ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}\n        transition={{ duration: 0.6, ease: EASE }}\n        className={cn(\n          \"rounded-xl border border-border bg-card text-card-foreground shadow-sm\",\n          className\n        )}\n      >\n        <div className=\"p-5 sm:p-6\">\n          <div>\n            <h2 className=\"text-[15px] font-semibold tracking-tight\">{title}</h2>\n            {description ? (\n              <p className=\"mt-0.5 text-[13px] text-muted-foreground\">\n                {description}\n              </p>\n            ) : null}\n          </div>\n\n          <div ref={chartRef} className=\"relative mt-4 w-full\">\n            {geometry && (\n              <svg\n                viewBox={`0 0 ${geometry.width} ${geometry.height}`}\n                role=\"img\"\n                aria-label={ariaLabel}\n                tabIndex={0}\n                onFocus={() => {\n                  setActive((a) => a ?? { week: 12, day: 3 });\n                }}\n                onBlur={() => setActive(null)}\n                onKeyDown={(e) => {\n                  if (!geometry) return;\n                  const key = e.key;\n                  const dirs: Record<string, [number, number]> = {\n                    ArrowRight: [1, 0],\n                    ArrowLeft: [-1, 0],\n                    ArrowDown: [0, 1],\n                    ArrowUp: [0, -1],\n                  };\n                  if (key === \"Home\") {\n                    e.preventDefault();\n                    setActive({ week: 0, day: active?.day ?? 0 });\n                    return;\n                  }\n                  if (key === \"End\") {\n                    e.preventDefault();\n                    setActive({ week: WEEKS - 1, day: active?.day ?? 0 });\n                    return;\n                  }\n                  const dir = dirs[key];\n                  if (!dir) return;\n                  e.preventDefault();\n                  setActive((a) => {\n                    const base = a ?? { week: 12, day: 3 };\n                    return {\n                      week: clamp(base.week + dir[0], 0, WEEKS - 1),\n                      day: clamp(base.day + dir[1], 0, DAYS - 1),\n                    };\n                  });\n                }}\n                className=\"block h-auto w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n              >\n                {/* month labels */}\n                <g>\n                  {monthLabels.map((m) => (\n                    <text\n                      key={m.week}\n                      x={geometry.cellX(m.week)}\n                      y={geometry.top - 5}\n                      className=\"fill-muted-foreground text-[10px] font-medium\"\n                    >\n                      {m.label}\n                    </text>\n                  ))}\n                </g>\n\n                {/* weekday labels (Mon / Wed / Fri) */}\n                <g>\n                  {[0, 2, 4].map((d) => (\n                    <text\n                      key={d}\n                      x={geometry.left - 6}\n                      y={geometry.cellY(d) + geometry.cell / 2 + 3.5}\n                      textAnchor=\"end\"\n                      className=\"fill-muted-foreground text-[10px]\"\n                    >\n                      {DAY_NAMES[d]}\n                    </text>\n                  ))}\n                </g>\n\n                {/* cells — fade in as a diagonal wave */}\n                {days.map((day) => {\n                  const fill = cellFill(day.level);\n                  const cx = geometry.cellX(day.week) + geometry.cell / 2;\n                  const cy = geometry.cellY(day.day) + geometry.cell / 2;\n                  const delay = reduce ? 0 : 0.05 + (day.week + day.day) * 0.016;\n                  return (\n                    <motion.rect\n                      key={day.week * DAYS + day.day}\n                      x={geometry.cellX(day.week)}\n                      y={geometry.cellY(day.day)}\n                      width={geometry.cell}\n                      height={geometry.cell}\n                      rx={geometry.radius}\n                      fill={fill.fill}\n                      fillOpacity={fill.opacity}\n                      initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.4 }}\n                      animate={\n                        show\n                          ? { opacity: 1, scale: 1 }\n                          : { opacity: 0, scale: 0.4 }\n                      }\n                      transition={\n                        reduce\n                          ? { duration: 0 }\n                          : { duration: 0.5, delay, ease: EASE }\n                      }\n                      style={{ transformOrigin: `${cx}px ${cy}px` }}\n                    />\n                  );\n                })}\n\n                {/* active cell: a lens ring with a glint dot */}\n                {active && (\n                  <motion.g\n                    initial={false}\n                    animate={{ opacity: 1 }}\n                    transition={{ duration: 0.15 }}\n                  >\n                    <rect\n                      x={geometry.cellX(active.week) - 1.5}\n                      y={geometry.cellY(active.day) - 1.5}\n                      width={geometry.cell + 3}\n                      height={geometry.cell + 3}\n                      rx={geometry.radius + 1.5}\n                      fill=\"none\"\n                      stroke=\"var(--foreground)\"\n                      strokeOpacity={0.35}\n                      strokeWidth={1}\n                    />\n                    <circle\n                      cx={geometry.cellX(active.week) + geometry.cell + 1.5}\n                      cy={geometry.cellY(active.day) - 1.5}\n                      r={1.5}\n                      fill=\"var(--foreground)\"\n                    />\n                  </motion.g>\n                )}\n\n                {/* pointer hit area */}\n                <rect\n                  x={geometry.left}\n                  y={geometry.top}\n                  width={geometry.gridW}\n                  height={geometry.gridH}\n                  fill=\"transparent\"\n                  onPointerMove={(e) => {\n                    const el = chartRef.current;\n                    if (!el || !geometry) return;\n                    const rect = el.getBoundingClientRect();\n                    const col = Math.floor(\n                      (e.clientX - rect.left - geometry.left) /\n                        (geometry.cell + geometry.gap)\n                    );\n                    const row = Math.floor(\n                      (e.clientY - rect.top - geometry.top) /\n                        (geometry.cell + geometry.gap)\n                    );\n                    setActive({\n                      week: clamp(col, 0, WEEKS - 1),\n                      day: clamp(row, 0, DAYS - 1),\n                    });\n                  }}\n                  onPointerLeave={() => setActive(null)}\n                  style={{ cursor: \"crosshair\" }}\n                />\n              </svg>\n            )}\n\n            <AnimatePresence>\n              {active && activeDay && (\n                <motion.div\n                  key=\"tooltip\"\n                  initial={{ opacity: 0, scale: 0.96, y: 4 }}\n                  animate={{ opacity: 1, scale: 1, y: 0 }}\n                  exit={{ opacity: 0, scale: 0.96, y: 4 }}\n                  transition={{ duration: 0.16, ease: \"easeOut\" }}\n                  className=\"pointer-events-none absolute z-10 min-w-[140px] rounded-lg border border-border bg-card px-3 py-2 shadow-lg\"\n                  style={{ left: tipLeft, top: tipTop }}\n                >\n                  <div className=\"text-[11.5px] text-muted-foreground\">\n                    {activeDay.label}\n                  </div>\n                  <div className=\"mt-1 flex items-center gap-1.5\">\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"h-2 w-2 shrink-0 rounded-[3px]\"\n                      style={{\n                        backgroundColor: cellFill(activeDay.level).fill,\n                        opacity: cellFill(activeDay.level).opacity,\n                      }}\n                    />\n                    <span className=\"text-[12.5px] font-medium tabular-nums\">\n                      {activeDay.count === 0\n                        ? `No ${unitLabel}`\n                        : `${formatCount(activeDay.count)} ${unitLabel}`}\n                    </span>\n                  </div>\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n\n          {/* summary + legend */}\n          <div className=\"mt-4 flex flex-wrap items-center justify-between gap-3\">\n            <p className=\"text-[12px] text-muted-foreground\">\n              <span className=\"font-medium tabular-nums text-foreground\">\n                {formatCount(total)}\n              </span>{\" \"}\n              {unitLabel} · last {WEEKS} weeks\n            </p>\n            <div\n              role=\"img\"\n              aria-label={`Legend: activity intensity from less to more, in ${5} levels`}\n              className=\"flex items-center gap-1.5 text-[11px] text-muted-foreground\"\n            >\n              <span className=\"mr-0.5\">Less</span>\n              {[0, 1, 2, 3, 4].map((level) => (\n                <span\n                  key={level}\n                  aria-hidden=\"true\"\n                  className=\"h-2.5 w-2.5 rounded-[3px]\"\n                  style={{\n                    backgroundColor: cellFill(level).fill,\n                    opacity: cellFill(level).opacity,\n                  }}\n                />\n              ))}\n              <span className=\"ml-0.5\">More</span>\n            </div>\n          </div>\n        </div>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default ActivityHeatmap;\n"}]}