{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scatter-chart",
  "title": "Scatter chart",
  "description": "Points placed by two values on the chart core’s XY frame, or bubbles sized by a third, each series in its own colour and shape so colour is never the only sign. The point nearest the pointer stays bright while the rest step back, the arrows step through the points by x and by y, and new data glides every point to its new place.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/chart-point-marks.json",
    "https://kinoui.com/r/chart-points.json",
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/scatter-chart.tsx",
      "content": "'use client'\n\nimport {\n  type CategoryChartProps,\n  figureProps,\n  numberAxis,\n  plotFraction,\n  plotPlace,\n  seriesWords,\n  useChartActive,\n  useDeclared,\n} from '@/registry/lib/chart-base'\nimport {\n  CartesianChartFrame,\n  type CartesianChartValue,\n  cartesianChartKeys,\n  cartesianSignature,\n  type CartesianStop,\n  cartesianTable,\n  cartesianWords,\n  type ChartPartDeclaration,\n  useCartesian,\n  useCartesianChart,\n} from '@/registry/lib/chart-cartesian'\nimport {\n  allWhole,\n  type ChartDatum,\n  numberOf,\n  type XYValue,\n} from '@/registry/lib/chart-math'\nimport { pointMarks } from '@/registry/lib/chart-point-marks'\nimport { markerAt, type PlacedPoint, PointSeries } from '@/registry/lib/chart-points'\nimport {\n  type ChartFormat,\n  type ChartItem,\n  forcedSeriesTextColor,\n  formatterOf,\n  drawingSize,\n  plotLayerClassName,\n  seriesColor,\n} from '@/registry/lib/chart-root'\nimport type { DomainEnd } from '@/registry/lib/chart-scale'\nimport {\n  placeholderBreatheClassName,\n  placeholderFillClassName,\n} from '@/registry/lib/placeholder'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  use,\n  useMemo,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Scatter chart: each row a point placed by two values, and with\n * `size`, a bubble whose area is a third. Each series has its colour and a\n * shape of its own, so colour is never the only sign. The point nearest the\n * pointer stays bright while the rest step back, and new data glides every\n * point from where it was to where it goes, so each one can be followed.\n * It is the chart core's XY frame: the x axis, the grid and reference lines\n * read its x scale, and the pointer and the keys find points in two\n * dimensions.\n */\n\ninterface ScatterChartProps extends Omit<CategoryChartProps, 'ordered' | 'patterns'> {\n  /** The key of each row's value along the x axis. */\n  x: string\n  /** The key of each row's value up the y axis. */\n  y: string\n  /** The key of each row's value that sizes its bubble by area; without it, every point is the same size. */\n  size?: string\n  /**\n   * The key of each row's series, a key of the config, which gives the point\n   * its colour and shape; without it, every point is the config's first series.\n   */\n  series?: string\n  /** What the x values are: the x axis's title, and in the tooltip and the table; the key by default. */\n  xLabel?: string\n  /** What the y values are: the y axis's title, and in the tooltip and the table; the key by default. */\n  yLabel?: string\n  /** What the sizes are, in the tooltip and the table; the key by default. */\n  sizeLabel?: string\n  /** How x values are written, and the x axis by default; the chart's `format` by default. */\n  xFormat?: ChartFormat\n  /** How sizes are written; the chart's `format` by default. */\n  sizeFormat?: ChartFormat\n  /** The values at the ends of the x axis; `'auto'` fits the data. */\n  xDomain?: readonly [DomainEnd, DomainEnd]\n  /** About how many ticks the x axis marks. */\n  xTickCount?: number\n}\n\nconst scatterChartKeys = [\n  ...cartesianChartKeys,\n  'x',\n  'y',\n  'size',\n  'series',\n  'xLabel',\n  'yLabel',\n  'sizeLabel',\n  'xFormat',\n  'sizeFormat',\n  'xDomain',\n  'xTickCount',\n]\n\n/** A point's radius, in px, without a `size`. */\nconst POINT_RADIUS = 5\n\n/** The smallest and largest bubble's radius, in px. */\nconst BUBBLE_RADIUS = { min: 4, max: 22 } as const\n\n/**\n * A bubble's radius in px for `value` among sizes up to `largest`: its\n * area in proportion, as a bubble is read, but never under the smallest\n * that still reads as a mark. A missing size, or one of zero or less, takes\n * the smallest.\n */\nfunction bubbleRadius(value: number | null, largest: number): number {\n  if (value === null || value <= 0 || largest <= 0) return BUBBLE_RADIUS.min\n  return Math.max(BUBBLE_RADIUS.min, BUBBLE_RADIUS.max * Math.sqrt(value / largest))\n}\n\n/**\n * The rows that are points: those with a number for both `x` and `y`, since\n * a point needs both, in a series the config names, by `seriesOf`, so a row\n * with a mistyped series is left out rather than drawn as another's. Each\n * holds its `y` under its series' key too, where the frame reads a series'\n * values, as it does in rows that hold every series.\n */\nfunction scatterRows(\n  data: readonly ChartDatum[],\n  x: string,\n  y: string,\n  seriesOf: (row: ChartDatum) => string | null = () => '',\n): readonly ChartDatum[] {\n  return data.flatMap((row) => {\n    const series = seriesOf(row)\n    if (numberOf(row[x]) === null || numberOf(row[y]) === null || series === null)\n      return []\n    return [{ ...row, [series]: row[y] }]\n  })\n}\n\n/**\n * The series a row's point is in: its `series` value, or with no `series`\n * key, the config's only or first series; null when the config has no such\n * series.\n */\nfunction pointSeries(\n  row: ChartDatum,\n  seriesKey: string | undefined,\n  keys: readonly string[],\n): string | null {\n  const named = seriesKey === undefined ? keys[0] : String(row[seriesKey])\n  return named !== undefined && keys.includes(named) ? named : null\n}\n\n/**\n * The order points are drawn in, from the back: the largest first, so a\n * small bubble is never hidden behind a large one, then in data order.\n */\nfunction drawOrder(radii: readonly number[]): number[] {\n  return radii\n    .map((radius, index) => ({ radius, index }))\n    .toSorted((a, b) => b.radius - a.radius || a.index - b.index)\n    .map(({ index }) => index)\n}\n\n/** A point's row: each of a scatter's stops is one of its rows. */\nfunction rowOf(stop: CartesianStop): ChartDatum {\n  if (!stop.datum) throw new Error('A scatter draws a point for each of its rows.')\n  return stop.datum\n}\n\ninterface ScatterContextValue {\n  /** A point's two values, from its row: a leaving one keeps the ones it had. */\n  valueOf: (stop: CartesianStop) => XYValue\n  /** Each point's series. */\n  seriesOf: (stop: CartesianStop) => string\n  /** Each point's radius in px. */\n  radiusOf: (stop: CartesianStop) => number\n  /** Where each point sits from the back, by its stop's key. */\n  depthOf: (key: string) => number\n  markerOf: (key: string) => string\n}\n\nconst ScatterContext = createContext<ScatterContextValue | null>(null)\n\nfunction useScatter() {\n  const scatter = use(ScatterContext)\n  if (!scatter) throw new Error('`Scatter` goes inside a `ScatterChart`.')\n  return scatter\n}\n\n/**\n * The chart's root: it places each row's point by its two values, lays out\n * the frame its parts draw in, and keeps the largest bubble clear of the\n * plot's edges.\n */\nfunction ScatterChart(props: ScatterChartProps) {\n  const {\n    data,\n    config,\n    x,\n    y,\n    size,\n    series: seriesKey,\n    xLabel = x,\n    yLabel = y,\n    sizeLabel = size ?? '',\n    format,\n    xFormat,\n    sizeFormat,\n    xDomain,\n    xTickCount,\n    allowDecimals,\n    locale,\n    description,\n    empty,\n    className,\n    children,\n    ref,\n  } = props\n  const keys = Object.keys(config)\n  // Every row drawn is in a series the config names, which `scatterRows` makes sure of.\n  const seriesOfRow = (row: ChartDatum) => pointSeries(row, seriesKey, keys) ?? ''\n  const rows = useMemo(\n    () =>\n      scatterRows(data, x, y, (row) => pointSeries(row, seriesKey, Object.keys(config))),\n    [data, x, y, seriesKey, config],\n  )\n  // Sizes count every row, the hidden series too, so hiding one never resizes the rest.\n  const largest = size ? Math.max(0, ...rows.map((row) => numberOf(row[size]) ?? 0)) : 0\n  const radiusOfRow = (row: ChartDatum) =>\n    size ? bubbleRadius(numberOf(row[size]), largest) : POINT_RADIUS\n  const made = useCartesianChart(\n    {\n      ...props,\n      data: rows,\n      allowDecimals: allowDecimals ?? !allWhole(rows, [y]),\n    },\n    {\n      kinds: [pointMarks],\n      orientation: 'vertical',\n      stack: 'none',\n      entrance: false,\n      seriesOfRow,\n      keyOf: (row) => `${seriesOfRow(row)}\\u0000${String(row[props.index])}`,\n      inset: size ? BUBBLE_RADIUS.max + 2 : POINT_RADIUS + 2,\n      // Every point is one row, placed by both values rather than in a band.\n      x: {\n        key: x,\n        domain: xDomain,\n        tickCount: xTickCount,\n        allowDecimals: !allWhole(rows, [x]),\n        format: xFormat,\n        label: xLabel,\n      },\n      y: { zero: false, label: yLabel },\n    },\n  )\n  const { model, placeholder } = made\n  // A shape, not a pattern, tells series apart.\n  const chart = { ...made.chart, patternOf: () => 'solid' as const }\n  const xText = formatterOf(locale, xFormat ?? format)\n  const sizeText = formatterOf(locale, sizeFormat ?? format)\n  const several = keys.length > 1\n  const seriesName = (key: string) => {\n    const label = config[key]?.label\n    return typeof label === 'string' ? label : key\n  }\n  const radii = chart.stops.map((stop) => radiusOfRow(rowOf(stop)))\n  const depth = new Map(\n    drawOrder(radii).map((at, place) => [chart.stops[at]?.key ?? '', place]),\n  )\n  const scatter: ScatterContextValue = {\n    valueOf: (stop) => ({\n      x: numberOf(rowOf(stop)[x]) ?? 0,\n      y: numberOf(rowOf(stop)[y]) ?? 0,\n    }),\n    seriesOf: (stop) => seriesOfRow(rowOf(stop)),\n    radiusOf: (stop) => radiusOfRow(rowOf(stop)),\n    depthOf: (key) => depth.get(key) ?? 0,\n    markerOf: (key) => markerAt(Math.max(0, keys.indexOf(key))),\n  }\n  // What a point holds, in the order it is read: its series, then each value.\n  const valuesOf = (stop: CartesianStop) => {\n    const row = rowOf(stop)\n    const values = [\n      [xLabel, xText(numberOf(row[x]) ?? 0)],\n      [yLabel, chart.valueText(numberOf(row[y]) ?? 0)],\n    ]\n    if (size) {\n      const value = numberOf(row[size])\n      values.push([sizeLabel, value === null ? chart.messages.noValue : sizeText(value)])\n    }\n    return values\n  }\n  const { width, height } = drawingSize(chart.plotSize)\n  const byKey = new Map(chart.current.map((stop) => [stop.key, stop]))\n  // What a point says: its series, when there are several, then each of its values.\n  const said = (item: ChartItem) => {\n    const stop = byKey.get(item.key)\n    if (!stop) return ''\n    const values = valuesOf(stop).map(([name, value]) => `${name} ${value}`)\n    return [several ? seriesName(seriesOfRow(rowOf(stop))) : null, ...values]\n      .filter(Boolean)\n      .join(', ')\n  }\n  const words = {\n    ...seriesWords(chart, cartesianWords(chart, { name: '', text: said })),\n    tooltip: (item: ChartItem) => (\n      <ScatterTooltipContent\n        index={item.index}\n        values={valuesOf}\n        seriesName={several ? seriesName : undefined}\n      />\n    ),\n    table: cartesianTable(\n      chart,\n      [\n        ...(several ? [chart.messages.series] : []),\n        xLabel,\n        yLabel,\n        ...(size ? [sizeLabel] : []),\n      ],\n      (stop) => [\n        ...(several ? [seriesName(seriesOfRow(rowOf(stop)))] : []),\n        ...valuesOf(stop).map(([, value]) => value ?? ''),\n      ],\n    ),\n  }\n  return (\n    <ScatterContext value={scatter}>\n      <CartesianChartFrame\n        chart={{ ...made, chart }}\n        ref={ref}\n        slot='scatter-chart'\n        description={description}\n        empty={empty}\n        className={className}\n        placeholder={placeholder && <ScatterPlaceholder />}\n        markerOf={scatter.markerOf}\n        // The tooltip sits over the point, clear of its bubble.\n        anchor={(stop) => {\n          const point = model.point(stop.index)\n          if (!point) return null\n          const place = plotPlace(point.place, chart.direction)\n          return {\n            x: plotFraction(place.x, width, chart.inset),\n            y:\n              plotFraction(place.y, height, chart.inset) -\n              (height === 0 ? 0 : scatter.radiusOf(stop) / height),\n            side: 'top',\n          }\n        }}\n        words={words}\n        browse={{\n          kind: 'points',\n          point: (stop) => model.point(stop.index),\n          inset: chart.inset,\n        }}\n        {...figureProps(props, scatterChartKeys)}\n      >\n        {children}\n      </CartesianChartFrame>\n    </ScatterContext>\n  )\n}\n\n/**\n * Where a point with `value` sits on the plot, as fractions of it from its\n * physical left and its top: a leaving one keeps the values it had, placed\n * on the axes as they are now.\n */\nfunction pointPlace(\n  chart: Pick<CartesianChartValue, 'frame' | 'direction'>,\n  value: XYValue,\n): XYValue {\n  const along = numberAxis(chart, 'x')\n  if (!along) throw new Error('A scatter places its points along an x axis of numbers.')\n  return plotPlace(\n    { x: along.scale.place(value.x), y: chart.frame.y.value.scale.place(value.y) },\n    chart.direction,\n  )\n}\n\n/**\n * A point's tooltip: its name, its series beside its shape when the chart\n * has several, and each of its values.\n */\nfunction ScatterTooltipContent({\n  index,\n  values,\n  seriesName,\n}: {\n  index: number\n  values: (stop: CartesianStop) => string[][]\n  seriesName?: (key: string) => string\n}) {\n  const chart = useCartesian()\n  const scatter = useScatter()\n  const stop = chart.current[index]\n  if (!stop) return null\n  const key = scatter.seriesOf(stop)\n  return (\n    // The tooltip sits outside the chart, so it carries the chart's id for its colours.\n    <div data-chart={chart.id} className='grid min-w-36 gap-1'>\n      <div className='font-medium'>{chart.stopText(stop)}</div>\n      {seriesName && (\n        <div className='flex items-center gap-2'>\n          <svg\n            aria-hidden\n            viewBox='-1.2 -1.2 2.4 2.4'\n            className={cn(\n              'size-2.5 shrink-0 fill-(--swatch)',\n              forcedSeriesTextColor(chart.series.indexOf(key)),\n              'forced-colors:fill-current',\n            )}\n            style={{ '--swatch': seriesColor(key) } as CSSProperties}\n          >\n            <path d={scatter.markerOf(key)} />\n          </svg>\n          <span className='text-background/75 min-w-0 flex-1 truncate forced-colors:text-[CanvasText]'>\n            {seriesName(key)}\n          </span>\n        </div>\n      )}\n      {/* One grid, so the values line up from row to row. */}\n      <div className='grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1'>\n        {values(stop).map(([name, value]) => (\n          <div key={name} className='col-span-full grid grid-cols-subgrid'>\n            <span className='text-background/75 min-w-0 truncate forced-colors:text-[CanvasText]'>\n              {name}\n            </span>\n            {/* A value with a unit reads in its own order whatever the page's direction. */}\n            <span dir='auto' className='text-end font-medium tabular-nums'>\n              {value}\n            </span>\n          </div>\n        ))}\n      </div>\n    </div>\n  )\n}\n\nScatter.declare = ({ dataKey }: ScatterProps): ChartPartDeclaration => ({\n  series: { key: dataKey, mark: 'point' },\n})\n\n/**\n * One series' points: a layer of the plot holding a point for each row of\n * the series, in its colour and shape, sized by `size` as a bubble. While a\n * point is lit, the layer steps back as one, a single filter whatever the\n * number of points, and the lit point is drawn again over every series, so\n * it stays bright and whole. New data glides each point to its new place.\n */\ntype ScatterProps = Omit<ComponentProps<'div'>, 'children'> & {\n  /** The series' key in the config: the rows of this series are its points. */\n  dataKey: string\n}\n\nfunction Scatter(props: ScatterProps) {\n  const { dataKey, ...rest } = props\n  useDeclared('Scatter', Scatter.declare(props), cartesianSignature)\n  const chart = useCartesian()\n  const scatter = useScatter()\n  const { spotlit } = useChartActive()\n  if (chart.status === 'empty') return null\n  const placed = (stop: CartesianStop): PlacedPoint => ({\n    key: stop.key,\n    ...pointPlace(chart, scatter.valueOf(stop)),\n    radius: scatter.radiusOf(stop),\n    depth: scatter.depthOf(stop.key),\n    leaving: stop.leaving,\n  })\n  const litNow = spotlit === null ? undefined : chart.current[spotlit]\n  const lit =\n    litNow !== undefined && !litNow.leaving && scatter.seriesOf(litNow) === dataKey\n      ? { ...placed(litNow), depth: 0 }\n      : undefined\n  return (\n    <PointSeries\n      name='scatter-chart'\n      dataKey={dataKey}\n      points={chart.stops\n        .filter((stop) => scatter.seriesOf(stop) === dataKey)\n        .map(placed)}\n      lit={lit}\n      seriesIndex={chart.series.indexOf(dataKey)}\n      marker={scatter.markerOf(dataKey)}\n      dim={spotlit !== null || (chart.emphasis !== null && chart.emphasis !== dataKey)}\n      around={(marks) => marks}\n      {...rest}\n    />\n  )\n}\n\n/** The placeholder's points, as fractions of the plot from its left and top: a loose rising cloud. */\nconst PLACEHOLDER_POINTS = [\n  [0.08, 0.78],\n  [0.16, 0.62],\n  [0.22, 0.72],\n  [0.3, 0.52],\n  [0.36, 0.66],\n  [0.44, 0.46],\n  [0.5, 0.58],\n  [0.58, 0.38],\n  [0.64, 0.5],\n  [0.72, 0.3],\n  [0.8, 0.42],\n  [0.88, 0.22],\n] as const\n\n/** The placeholder while the data loads: a loose cloud of points, breathing slowly. */\nfunction ScatterPlaceholder() {\n  return (\n    <div\n      data-slot='scatter-chart-placeholder'\n      aria-hidden\n      className={cn(\n        plotLayerClassName,\n        'z-10 transition-opacity duration-(--motion-enter-duration) ease-(--motion-enter-easing) group-data-mounted/chart:starting:opacity-0',\n      )}\n    >\n      <div className={cn('absolute inset-0', placeholderBreatheClassName)}>\n        {PLACEHOLDER_POINTS.map(([x, y]) => (\n          <span\n            key={`${x}-${y}`}\n            className={cn(\n              'absolute size-2.5 -translate-1/2 rounded-full rtl:translate-x-1/2',\n              placeholderFillClassName,\n            )}\n            style={{ insetInlineStart: `${x * 100}%`, top: `${y * 100}%` }}\n          />\n        ))}\n      </div>\n    </div>\n  )\n}\n\nexport {\n  Scatter,\n  ScatterChart,\n  type ScatterChartProps,\n  bubbleRadius,\n  drawOrder,\n  markerAt,\n  pointSeries,\n  scatterRows,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/scatter-chart.tsx"
    }
  ],
  "type": "registry:component"
}