{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "day-grid",
  "type": "registry:component",
  "title": "Day Grid",
  "description": "A run of days as a field of dots, each sized by how much happened on it.",
  "dependencies": [
    "@base-ui/react",
    "tailwind-variants"
  ],
  "registryDependencies": [],
  "cssVars": {
    "light": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    },
    "dark": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    }
  },
  "files": [
    {
      "path": "components/panelui/day-grid.tsx",
      "type": "registry:component",
      "target": "@components/panelui/day-grid.tsx",
      "content": "'use client';\n\n/**\n * DayGrid — a run of days as a field of dots, each sized by how much happened\n * on it.\n *\n * ```tsx\n * <DayGrid cells={days} columns={7} />\n * <DayGrid.Legend />\n * ```\n *\n * ## Size carries the amount, not only shade\n *\n * A day is level 0 to 4, and its dot grows with the level: a speck for a day\n * with nothing on it, a full disc for the busiest. The period reads the way a\n * halftone print does, heavy where a lot happened and thin where little did,\n * and it still reads for someone who cannot tell two shades of one colour\n * apart.\n *\n * ## The pointer is a lens\n *\n * Dots swell as the pointer comes near and settle as it leaves, so the day\n * under the pointer is the largest thing on the grid and its neighbours lean\n * towards it. The day's `label` is shown in a tag above it. The lens changes\n * nothing about what the grid says; it is there to make one day easy to\n * single out among forty.\n *\n * ## Days you can ask about\n *\n * Pass `onValueChange` and each day becomes a button. The grid then behaves as\n * one control to the keyboard: a single Tab stop, with the arrow keys moving\n * between days, so forty days are not forty presses of Tab.\n */\nimport {\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type KeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n  type ReactNode,\n} from 'react';\nimport { tv } from 'tailwind-variants';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\n/** How much happened on a day: 0 is nothing, 4 is the most. */\nexport type DayLevel = 0 | 1 | 2 | 3 | 4;\n\n/** Which of the theme's roles the dots are drawn in. */\nexport type DayGridColor = 'primary' | 'info' | 'success' | 'warning' | 'destructive';\n\nexport interface DayCell {\n  level: DayLevel;\n  /** What the day is, for the tag and a screen reader: \"14 May, 6 commits\". */\n  label?: string;\n}\n\n/** How many days have something on them, and how many there are. */\nexport interface DayGridSummaryCounts {\n  /** Days whose level is above 0. */\n  active: number;\n  /** Every day in the grid. */\n  total: number;\n}\n\nconst dayGridVariants = tv({\n  slots: {\n    root: 'relative grid w-full gap-1',\n    // The cell is the target and keeps its size. Only the dot inside it grows.\n    cell: 'relative flex aspect-square w-full items-center justify-center rounded-full outline-none',\n    /*\n     * One scale made of three parts: how big the level is, how near the\n     * pointer is, and whether the grid has arrived yet. Kept as variables so\n     * each can change without a class changing.\n     */\n    dot: 'block size-full rounded-full [scale:calc(var(--pu-size)*(1+var(--pu-lens,0)*0.5)*var(--pu-in,1))] transition-[scale,box-shadow] duration-200 ease-[cubic-bezier(0.34,1.56,0.64,1)] motion-reduce:transition-none',\n    tag: 'pointer-events-none absolute z-20 whitespace-nowrap rounded-lg bg-foreground px-2 py-1 text-xs font-medium text-background shadow-lg',\n    legend: 'flex items-center gap-1.5 text-xs text-muted-foreground',\n    // One row per day, matching the grid's own rows, so each name sits level with its days.\n    weekdays: 'grid gap-1 text-xs leading-none text-muted-foreground',\n    weekday: 'flex items-center',\n    // The picked day, written out under the grid.\n    caption: 'flex flex-col gap-0.5',\n    title: 'text-sm font-medium',\n    description: 'text-sm text-muted-foreground',\n    swatch: 'flex size-4 items-center justify-center',\n  },\n  variants: {\n    /*\n     * The colour is written to one variable and every dot reads it. The legend\n     * is a sibling of the grid, not a child, so it takes the same variant.\n     */\n    color: {\n      primary: { root: '[--pu-color:var(--primary)]', legend: '[--pu-color:var(--primary)]' },\n      info: { root: '[--pu-color:var(--info)]', legend: '[--pu-color:var(--info)]' },\n      success: { root: '[--pu-color:var(--success)]', legend: '[--pu-color:var(--success)]' },\n      warning: { root: '[--pu-color:var(--warning)]', legend: '[--pu-color:var(--warning)]' },\n      destructive: {\n        root: '[--pu-color:var(--destructive)]',\n        legend: '[--pu-color:var(--destructive)]',\n      },\n    },\n    level: {\n      0: { dot: 'bg-muted-foreground/30 [--pu-size:0.2]' },\n      1: { dot: 'bg-[color-mix(in_oklab,var(--pu-color)_45%,transparent)] [--pu-size:0.42]' },\n      2: { dot: 'bg-[color-mix(in_oklab,var(--pu-color)_65%,transparent)] [--pu-size:0.6]' },\n      3: { dot: 'bg-[color-mix(in_oklab,var(--pu-color)_85%,transparent)] [--pu-size:0.8]' },\n      // The busiest days carry a little light of their own.\n      4: {\n        dot: 'bg-[var(--pu-color)] shadow-[0_0_14px_color-mix(in_oklab,var(--pu-color)_45%,transparent)] [--pu-size:1]',\n      },\n    },\n    interactive: {\n      true: {\n        cell: 'cursor-pointer focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',\n      },\n    },\n    selected: {\n      true: { cell: 'ring-2 ring-foreground ring-offset-2 ring-offset-background' },\n    },\n  },\n});\n\nconst LEVELS = [0, 1, 2, 3, 4] as const;\n\n/** How far the lens reaches, in cells. */\nconst LENS_REACH = 2.4;\n/** Milliseconds between one diagonal of dots arriving and the next. */\nconst STAGGER = 22;\n\nexport interface DayGridProps extends Omit<ComponentProps<'div'>, 'children' | 'onChange' | 'color'> {\n  /** The days, in order. They fill the grid row by row. */\n  cells: DayCell[];\n  /** Cells per row. Seven makes each row a week. */\n  columns?: number;\n  /**\n   * Cells per column. Giving this fills the grid column by column, and\n   * `columns` is ignored. Seven makes each column a week, which lays a long\n   * period out wide and short.\n   */\n  rows?: number;\n  /**\n   * Empty slots before the first day, for a period that starts partway\n   * through the first row or column. Use it when a month does not begin on\n   * the first day of the week: `rows={7}` with `offset={4}` leaves four slots\n   * in the first column and puts the first day on a Friday. The offset is not\n   * a day: it holds space only, so it is left out of the summary and never\n   * becomes a button.\n   */\n  offset?: number;\n  /** Which of the theme's roles the dots are drawn in. */\n  color?: DayGridColor;\n  /** The index of the selected day, when the caller holds it. */\n  value?: number | null;\n  /**\n   * Called with the index of a day when it is pressed. Passing this makes the\n   * days buttons; without it the grid is a picture.\n   */\n  onValueChange?: (index: number) => void;\n  /** Set to `false` for dots that hold still under the pointer. */\n  lens?: boolean;\n  /** What a screen reader calls the grid. */\n  label?: string;\n  /**\n   * The sentence a screen reader says for the whole grid, written in the\n   * reader's language. It is given `active`, the days with something on them,\n   * and `total`, every day in the grid. Without it the grid says the same\n   * thing in English.\n   */\n  summary?: (counts: DayGridSummaryCounts) => string;\n}\n\nfunction DayGridRoot({\n  cells,\n  columns = 7,\n  rows: perColumn,\n  offset = 0,\n  color = 'primary',\n  value = null,\n  onValueChange,\n  lens = true,\n  label = 'Activity',\n  summary: formatSummary,\n  className,\n  style,\n  onPointerMove,\n  onPointerLeave,\n  render,\n  ...props\n}: DayGridProps & RenderProp<'div'>) {\n  const slots = dayGridVariants({ color });\n  const root = useRef<HTMLDivElement>(null);\n  const nodes = useRef<(HTMLElement | null)[]>([]);\n  const frame = useRef(0);\n  const interactive = onValueChange !== undefined;\n  // The day whose tag is showing: the one under the pointer, or with focus.\n  const [pointed, setPointed] = useState<number | null>(null);\n  // The dots start at nothing and arrive along the diagonals.\n  const [arrived, setArrived] = useState<'no' | 'arriving' | 'yes'>('no');\n\n  // Which way the days run: along each row, or down each column.\n  const byColumn = perColumn !== undefined;\n  // Empty slots before the first day. They take a place in the grid and in the\n  // entrance, but they are not days: the summary counts only `cells`.\n  const lead = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0;\n  const total = cells.length + lead;\n  const across = byColumn ? Math.ceil(total / Math.max(1, perColumn)) : columns;\n  const rows = byColumn ? Math.max(1, perColumn) : Math.ceil(total / Math.max(1, columns));\n\n  useEffect(() => {\n    const start = requestAnimationFrame(() => setArrived('arriving'));\n    // Once the last diagonal is in, the delays come off. Left on, they would\n    // hold every dot back from the lens by its own share of the stagger.\n    const settle = setTimeout(() => setArrived('yes'), (rows + across) * STAGGER + 450);\n    return () => {\n      cancelAnimationFrame(start);\n      clearTimeout(settle);\n    };\n  }, [rows, across]);\n\n  useEffect(() => () => cancelAnimationFrame(frame.current), []);\n\n  const summary = useMemo(() => {\n    const counts = { active: cells.filter((cell) => cell.level > 0).length, total: cells.length };\n    // Written here even when the caller supplies a sentence, so a formatter in\n    // another language is handed the counts instead of walking the days again.\n    return formatSummary\n      ? formatSummary(counts)\n      : `${label}: something on ${counts.active} of ${counts.total} days.`;\n  }, [cells, label, formatSummary]);\n\n  const moveLens = (event: ReactPointerEvent<HTMLDivElement>) => {\n    onPointerMove?.(event);\n    // A finger covers what a lens would show, and has no hover to end it.\n    if (event.pointerType === 'touch') return;\n    const still = !lens || window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n    const { clientX, clientY } = event;\n    cancelAnimationFrame(frame.current);\n    frame.current = requestAnimationFrame(() => {\n      let nearest: number | null = null;\n      let best = Infinity;\n      nodes.current.forEach((node, index) => {\n        if (!node) return;\n        const box = node.getBoundingClientRect();\n        const distance = Math.hypot(clientX - (box.left + box.width / 2), clientY - (box.top + box.height / 2));\n        if (!still) {\n          const near = Math.max(0, 1 - distance / (box.width * LENS_REACH));\n          // Eased, so the swell has a soft edge and a round top.\n          node.style.setProperty('--pu-lens', (near * near * (3 - 2 * near)).toFixed(3));\n        }\n        if (distance < best && distance < box.width * 0.75) {\n          best = distance;\n          nearest = index;\n        }\n      });\n      setPointed(nearest);\n    });\n  };\n\n  const leave = (event: ReactPointerEvent<HTMLDivElement>) => {\n    onPointerLeave?.(event);\n    cancelAnimationFrame(frame.current);\n    for (const node of nodes.current) node?.style.removeProperty('--pu-lens');\n    setPointed(null);\n  };\n\n  const layout = byColumn\n    ? {\n        gridTemplateRows: `repeat(${rows}, auto)`,\n        gridAutoFlow: 'column' as const,\n        gridAutoColumns: 'minmax(0, 1fr)',\n        ...style,\n      }\n    : { gridTemplateColumns: `repeat(${across}, minmax(0, 1fr))`, ...style };\n\n  /** Where a dot is in its entrance, as the styles that put it there. */\n  const dotStyle = (index: number): CSSProperties | undefined => {\n    if (arrived === 'yes') return undefined;\n    // The offset takes part in the diagonals, so the stagger follows what is\n    // on screen rather than starting at the top-left of the grid.\n    const position = lead + index;\n    const diagonal = byColumn\n      ? Math.floor(position / rows) + (position % rows)\n      : Math.floor(position / across) + (position % across);\n    return {\n      ['--pu-in' as string]: arrived === 'no' ? 0 : 1,\n      transitionDelay: `${diagonal * STAGGER}ms`,\n      transitionDuration: '420ms',\n    };\n  };\n\n  const tag = (() => {\n    if (pointed === null) return null;\n    const text = cells[pointed]?.label;\n    const node = nodes.current[pointed];\n    const box = root.current;\n    if (!text || !node || !box) return null;\n    const centre = node.offsetLeft + node.offsetWidth / 2;\n    // Hung from whichever side keeps it inside the grid.\n    const share = centre / box.offsetWidth;\n    const shift = share < 0.25 ? '-12%' : share > 0.75 ? '-88%' : '-50%';\n    return (\n      <span\n        aria-hidden=\"true\"\n        className={slots.tag()}\n        style={{ left: centre, top: node.offsetTop - 6, translate: `${shift} -100%` }}\n      >\n        {text}\n      </span>\n    );\n  })();\n\n\n  // The offset is drawn as empty grid items, so the first day starts after\n  // them whichever way the grid fills. They are hidden from assistive\n  // technology, and the summary already counts days rather than slots.\n  const leadSlots =\n    lead > 0\n      ? Array.from({ length: lead }, (_, index) => <span key={`lead-${index}`} aria-hidden=\"true\" />)\n      : null;\n\n  // One Tab stop for the grid: the selected day, or the first.\n  const focusable = value !== null && value >= 0 && value < cells.length ? value : 0;\n\n  const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {\n    const rtl = getComputedStyle(event.currentTarget).direction === 'rtl';\n    const moves: Record<string, number> = {\n      // One day along a row, or one whole column when the days run downwards.\n      ArrowLeft: (rtl ? 1 : -1) * (byColumn ? rows : 1),\n      ArrowRight: (rtl ? -1 : 1) * (byColumn ? rows : 1),\n      ArrowUp: byColumn ? -1 : -across,\n      ArrowDown: byColumn ? 1 : across,\n    };\n    let next: number | undefined;\n    if (event.key in moves) next = index + (moves[event.key] ?? 0);\n    else if (event.key === 'Home') next = 0;\n    else if (event.key === 'End') next = cells.length - 1;\n    if (next === undefined || next < 0 || next >= cells.length) return;\n    // Home or End on the day that already has focus is not a move. Swallow the\n    // key so the page does not scroll, but report nothing: a caller that clears\n    // the selection when the same day is pressed again would lose it here.\n    event.preventDefault();\n    if (next === index) return;\n    nodes.current[next]?.focus();\n    onValueChange?.(next);\n  };\n\n  // Called before the branch below, so a prop that changes later cannot change the hook count.\n  const rendered = useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        ref: root,\n        role: 'group',\n        'aria-label': summary,\n        className: slots.root({ className }),\n        style: layout,\n        onPointerMove: moveLens,\n        onPointerLeave: leave,\n        children: (\n          <>\n            {leadSlots}\n            {cells.map((cell, index) => {\n              const part = dayGridVariants({\n                level: cell.level,\n                interactive: true,\n                selected: value === index,\n              });\n              return (\n                <button\n                  key={index}\n                  ref={(node) => {\n                    nodes.current[index] = node;\n                  }}\n                  type=\"button\"\n                  aria-label={cell.label ?? `Day ${index + 1}, level ${cell.level} of 4`}\n                  aria-pressed={value === index}\n                  tabIndex={index === focusable ? 0 : -1}\n                  onClick={() => onValueChange?.(index)}\n                  onKeyDown={(event) => onKeyDown(event, index)}\n                  onFocus={(event) => {\n                    // Only for focus that came from the keyboard: a click focuses\n                    // too, and the pointer is already showing that day's tag.\n                    if (event.currentTarget.matches(':focus-visible')) setPointed(index);\n                  }}\n                  onBlur={() => setPointed((current) => (current === index ? null : current))}\n                  className={part.cell()}\n                >\n                  <span className={part.dot()} style={dotStyle(index)} />\n                </button>\n              );\n            })}\n            {tag}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n  if (!interactive) {\n    return (\n      <div\n        ref={root}\n        role=\"img\"\n        aria-label={summary}\n        className={slots.root({ className })}\n        style={layout}\n        onPointerMove={moveLens}\n        onPointerLeave={leave}\n        {...props}\n      >\n        {leadSlots}\n        {cells.map((cell, index) => {\n          const part = dayGridVariants({ level: cell.level });\n          return (\n            <span\n              key={index}\n              ref={(node) => {\n                nodes.current[index] = node;\n              }}\n              className={part.cell()}\n            >\n              <span className={part.dot()} style={dotStyle(index)} />\n            </span>\n          );\n        })}\n        {tag}\n      </div>\n    );\n  }\n  return rendered;\n}\nDayGridRoot.displayName = 'DayGrid';\n\nexport interface DayGridLegendProps extends Omit<ComponentProps<'div'>, 'children' | 'color'> {\n  /** The same role the grid is drawn in. */\n  color?: DayGridColor;\n  /** The word at the quiet end of the scale. */\n  less?: ReactNode;\n  /** The word at the busy end of the scale. */\n  more?: ReactNode;\n}\n\n/** The five sizes, quietest to busiest, with a word at each end. */\nfunction DayGridLegend({\n  color = 'primary',\n  less = 'Less',\n  more = 'More',\n  className,\n  render,\n  ...props\n}: DayGridLegendProps & RenderProp<'div'>) {\n  const slots = dayGridVariants({ color });\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        className: slots.legend({ className }),\n        children: (\n          <>\n            <span>{less}</span>\n            {LEVELS.map((level) => (\n              <span key={level} aria-hidden=\"true\" className={slots.swatch()}>\n                <span className={dayGridVariants({ level }).dot({ className: 'shadow-none' })} />\n              </span>\n            ))}\n            <span>{more}</span>\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nDayGridLegend.displayName = 'DayGrid.Legend';\n\nexport interface DayGridWeekdaysProps extends Omit<ComponentProps<'div'>, 'children'> {\n  /**\n   * The name written beside each row, first row first. An empty string leaves\n   * a row unnamed. Default Monday to Sunday with every other name left out.\n   */\n  labels?: string[];\n}\n\n/**\n * The days of the week down the side of a grid that runs a week to a column.\n * Put it beside the grid, in a row with it. Hidden from screen readers, which\n * are given each day's own label.\n */\nfunction DayGridWeekdays({\n  labels = ['Mon', '', 'Wed', '', 'Fri', '', 'Sun'],\n  className,\n  style,\n  render,\n  ...props\n}: DayGridWeekdaysProps & RenderProp<'div'>) {\n  const slots = dayGridVariants();\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'aria-hidden': 'true',\n        'data-slot': 'day-grid-weekdays',\n        className: slots.weekdays({ className }),\n        style: { gridTemplateRows: `repeat(${labels.length}, minmax(0, 1fr))`, ...style },\n        children: (\n          <>\n            {labels.map((day, index) => (\n              <span key={index} className={slots.weekday()}>\n                {day}\n              </span>\n            ))}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nDayGridWeekdays.displayName = 'DayGrid.Weekdays';\n\nexport interface DayGridCaptionProps extends ComponentProps<'div'> {}\n\n/**\n * What the picked day holds, written out beside the grid: a `DayGrid.Title`\n * over a `DayGrid.Description`. Read out politely each time the pick changes.\n */\nfunction DayGridCaption({ className, render, ...props }: DayGridCaptionProps & RenderProp<'div'>) {\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      { 'aria-live': 'polite', 'data-slot': 'day-grid-caption', className: dayGridVariants().caption({ className }) },\n      props\n    ),\n  });\n}\nDayGridCaption.displayName = 'DayGrid.Caption';\n\nexport interface DayGridTitleProps extends ComponentProps<'p'> {}\n\n/** The picked day's figure: \"17 merged\". */\nfunction DayGridTitle({ className, render, ...props }: DayGridTitleProps & RenderProp<'p'>) {\n  return useRender({\n    defaultTagName: 'p',\n    render,\n    props: mergeProps({ 'data-slot': 'day-grid-title', className: dayGridVariants().title({ className }) }, props),\n  });\n}\nDayGridTitle.displayName = 'DayGrid.Title';\n\nexport interface DayGridDescriptionProps extends ComponentProps<'p'> {}\n\n/** The picked day's date, quieter, under its figure. */\nfunction DayGridDescription({ className, render, ...props }: DayGridDescriptionProps & RenderProp<'p'>) {\n  return useRender({\n    defaultTagName: 'p',\n    render,\n    props: mergeProps(\n      { 'data-slot': 'day-grid-description', className: dayGridVariants().description({ className }) },\n      props\n    ),\n  });\n}\nDayGridDescription.displayName = 'DayGrid.Description';\n\nexport const DayGrid = Object.assign(DayGridRoot, {\n  Legend: DayGridLegend,\n  Weekdays: DayGridWeekdays,\n  Caption: DayGridCaption,\n  Title: DayGridTitle,\n  Description: DayGridDescription,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport { DayGridLegend, DayGridWeekdays, DayGridCaption, DayGridTitle, DayGridDescription };\n"
    }
  ]
}
