{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stream-chart",
  "title": "Stream chart",
  "description": "Stacked layers that swell and thin around a centre line, such as revenue by region over months, or up from zero on a value axis. The layer under the pointer, or the one the Up and Down arrows reach, stays bright while the rest step back; a guide follows the stop, with the total above the stream and the lit layer’s value below it. New data moves every layer from where it is, and a new offset morphs them.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/area-fill.json",
    "https://kinoui.com/r/chart-area-marks.json",
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-core.json",
    "https://kinoui.com/r/chart-frame.json",
    "https://kinoui.com/r/chart-line.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/line-path.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/stream-chart.tsx",
      "content": "'use client'\n\nimport { ChartYAxis } from '@/registry/components/kino/chart'\nimport { areaPathThrough } from '@/registry/lib/area-fill'\nimport {\n  type StreamOffset,\n  streamExtent,\n  streamMarks,\n  streamOrder,\n} from '@/registry/lib/chart-area-marks'\nimport {\n  type CategoryChartProps,\n  figureProps,\n  seriesWords,\n  useChartActive,\n  useDeclared,\n} from '@/registry/lib/chart-base'\nimport {\n  CartesianChartFrame,\n  type CartesianChartProps,\n  cartesianChartKeys,\n  cartesianSignature,\n  type CartesianStop,\n  cartesianWords,\n  type ChartPartDeclaration,\n  useCartesian,\n  useCartesianChart,\n} from '@/registry/lib/chart-cartesian'\nimport { type CartesianModel, markLayer } from '@/registry/lib/chart-frame'\nimport {\n  EntranceWipe,\n  framePoints,\n  frameTop,\n  LitDots,\n  mirror,\n  paintLitDots,\n  registerLineProperties,\n  unitFrame,\n} from '@/registry/lib/chart-line'\nimport { numberOf, rowValues, stepThrough } from '@/registry/lib/chart-math'\nimport {\n  type ChartItem,\n  ChartNumber,\n  type ChartPoint,\n  forcedSeriesColor,\n  forcedSeriesTextColor,\n  type MoveRole,\n  plotLayerClassName,\n  seriesColor,\n  stepBackInkClassName,\n  swatchClassName,\n  swatchStyle,\n  useFromRest,\n  usePointsMove,\n} from '@/registry/lib/chart-root'\nimport { bandCentre } from '@/registry/lib/chart-scale'\nimport {\n  alignLines,\n  type LinePoint,\n  pathThrough,\n  pointsAt,\n  sampleLine,\n} from '@/registry/lib/line-path'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { placeholderBreatheClassName } from '@/registry/lib/placeholder'\nimport { Swap } from '@/registry/lib/swap'\nimport {\n  Children,\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  Fragment,\n  isValidElement,\n  type ReactNode,\n  type RefObject,\n  use,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The Stream chart: every series stacked into one stream that swells and\n * thins around a centre line, such as income by region over months. Its\n * layers stack in d3's inside-out order, held from the first data it draws,\n * so new rows or a hidden layer never swap them. With callouts, the layer\n * under the pointer, or the one Up and Down reach, stays bright while the\n * rest step back; a guide follows the stop under the pointer or the keys,\n * and the callouts above and below the plot give the stream's total there\n * and the lit layer's value. Without them, the pointer\n * lights the whole stop, as the Area chart does, for the tooltip to read\n * out, and a dot on each layer's top marks it.\n *\n * Each layer is drawn through its points in fractions of the plot, as the\n * Area chart's are, and moves on the chart's clock: new data on `layout`, a\n * new offset on `morph`, so the layers' shared edges stay shared on every\n * frame. Layers run between their points as an S, d3's bump, or straight:\n * both keep each edge between the edges beside it, so no layer ever turns\n * inside out between two stops.\n */\n\n/** How a layer runs from one value to the next: an S, level at each value, or straight. */\ntype StreamCurve = 'bump' | 'linear'\n\ninterface StreamChartProps extends Omit<CategoryChartProps, 'patterns'> {\n  indexType?: CartesianChartProps['indexType']\n  timeZone?: CartesianChartProps['timeZone']\n  /**\n   * Where the layers sit: centred so the stream's edges change as little as\n   * they can, the default; centred on a line; or stacked up from zero,\n   * which takes a value axis.\n   */\n  offset?: StreamOffset\n  /** How each layer runs from one value to the next: an S, level at each value, the default, or straight. */\n  curve?: StreamCurve\n  /**\n   * How the layers arrive the first time the chart comes into view: growing\n   * out of the stream's centre line, drawn along from the reading start, or\n   * simply there, the default, since a page that loads doesn't animate into\n   * place.\n   */\n  entrance?: 'rise' | 'draw' | 'none'\n}\n\nconst streamChartKeys = [...cartesianChartKeys, 'offset', 'curve', 'entrance']\n\n/** What the stream's own parts read. */\ninterface StreamContextValue {\n  curve: StreamCurve\n  entrance: 'rise' | 'draw' | 'none'\n  /** What moves the layers now: a new offset morphs them, the entrance draws them in, the rest is layout. */\n  role: MoveRole\n  /** The series bottom first, as they stack. */\n  order: readonly string[]\n  /** A layer's points through the stops, its top and its bottom; on the stream's centre line when `rising`. */\n  pointsOf: (key: string, rising: boolean) => LinePoint[]\n  /** The sum of the shown layers' values at a stop. */\n  totalOf: (stop: ChartItem) => number\n  /**\n   * What the pointer lights: with callouts, the layer under it, which the\n   * guide and the value callout name; without, the whole stop, as the Area\n   * chart does, which the tooltip reads out.\n   */\n  lights: 'layer' | 'stop'\n  /**\n   * Writes a layer's points into its fill and the seam along its top, and\n   * while it is `moving`, carries its lit dot.\n   */\n  paint: (\n    key: string,\n    points: readonly LinePoint[],\n    fill: SVGPathElement | null,\n    moving: boolean,\n  ) => void\n  seams: RefObject<Map<string, SVGPathElement>>\n}\n\nconst StreamContext = createContext<StreamContextValue | null>(null)\n\nfunction useStream() {\n  const stream = use(StreamContext)\n  if (!stream) throw new Error('The stream’s parts go inside a `StreamChart`.')\n  return stream\n}\n\n/** The legend's keys are plain swatches. */\nfunction noMarker() {\n  return null\n}\n\n/**\n * The chart's root: it lays out the frame its parts draw in, places each\n * stop along the plot from edge to edge, and stacks the layers into one\n * stream that fills the plot's height, or with `offset='zero'`, up from\n * zero on a value axis.\n */\nfunction StreamChart(props: StreamChartProps) {\n  const {\n    data,\n    config,\n    offset = 'wiggle',\n    curve = 'bump',\n    entrance = 'none',\n    description,\n    empty,\n    className,\n    children,\n    ref,\n  } = props\n  const parts = partTypes(children)\n  // A centred stream's centre means nothing, so a value axis would mislead.\n  if (offset !== 'zero' && parts.has(ChartYAxis)) {\n    throw new Error(\n      `A stream centred with \\`offset='${offset}'\\` has no value axis. Use \\`offset='zero'\\` for one.`,\n    )\n  }\n  const lights = parts.has(StreamTotal) || parts.has(StreamValue) ? 'layer' : 'stop'\n  useLayoutEffect(registerLineProperties, [])\n  if (offset !== 'zero' && props.domain !== undefined) {\n    throw new Error(\n      `A stream centred with \\`offset='${offset}'\\` fits its own range, so it takes no \\`domain\\`. Use \\`offset='zero'\\` for one.`,\n    )\n  }\n  const keys = Object.keys(config)\n  const keyList = keys.join('\\u0000')\n  // The order, worked out from the first rows the chart draws and held, so new rows or a hidden\n  // layer never swap layers; again only for new series, which have no place in the old one. A\n  // stream that starts on zero keeps the config's order, as stacked areas do.\n  const [held, setHeld] = useState<{\n    keys: string\n    order: readonly string[]\n  } | null>(null)\n  let order = held?.keys === keyList ? held.order : null\n  if (order === null && data.length > 0) {\n    order = offset === 'zero' ? keys : streamOrder(data.length, rowValues(data), keys)\n    setHeld({ keys: keyList, order })\n  }\n  const stacked = order ?? keys\n  const made = useCartesianChart(props, {\n    kinds: [streamMarks(offset, stacked)],\n    orientation: 'vertical',\n    stack: 'stacked',\n    entrance: entrance !== 'none',\n    // A centred stream fills the plot's height; on zero, its axis rounds out to ticks from zero.\n    y: { nice: offset === 'zero', zero: offset === 'zero' },\n  })\n  const { model, placeholder, phase } = made\n  // A new offset morphs the layers, until new data or a hidden layer moves them again.\n  const hiddenList = made.chart.hidden.join('\\u0000')\n  const [shape, setShape] = useState({\n    offset,\n    data,\n    hidden: hiddenList,\n    morph: false,\n  })\n  if (shape.offset !== offset) {\n    setShape({ offset, data, hidden: hiddenList, morph: true })\n  } else if (shape.morph && (shape.data !== data || shape.hidden !== hiddenList)) {\n    setShape({ offset, data, hidden: hiddenList, morph: false })\n  }\n  // A layer's fill is one colour on a unit frame, which a pattern's tiles would stretch.\n  const chart = { ...made.chart, patternOf: () => 'solid' as const }\n  const shown = chart.series.filter((key) => !chart.hidden.includes(key))\n  const litDots = useRef(new Map<string, HTMLElement>())\n  const seams = useRef(new Map<string, SVGPathElement>())\n  const scale = model.y.value\n  const centreOf = (index: number) =>\n    offset === 'zero' ? 1 - model.baselines.value : streamCentre(model, index)\n  const totalOf = (stop: ChartItem) =>\n    shown.reduce((sum, key) => sum + (numberOf(chart.valueOf(key, stop)) ?? 0), 0)\n  const pointsOf = (key: string, rising: boolean) => {\n    const points = framePoints(chart, model, key, false, true)\n    return rising\n      ? points.map((point, at) => {\n          const centre = centreOf(at)\n          return { ...point, y: centre, base: centre }\n        })\n      : points\n  }\n  const stream: StreamContextValue = {\n    curve,\n    entrance,\n    role: phase === 'entering' ? 'draw' : shape.morph ? 'morph' : 'layout',\n    order: stacked,\n    pointsOf,\n    totalOf,\n    lights,\n    paint: (key, points, fill, moving) => {\n      const area = areaPathThrough(points, curve, 1, 1)\n      fill?.setAttribute('d', area)\n      seams.current.get(key)?.setAttribute('d', pathThrough(points, curve, 1, 1))\n      paintLitDots([litDots.current.get(key), undefined], points, moving)\n    },\n    seams,\n  }\n  // Top first, as they read on the screen.\n  const onScreen = [...stacked].reverse().filter((key) => shown.includes(key))\n  const percent = numberFormatter(chart.locale, {\n    style: 'percent',\n    maximumFractionDigits: 0,\n  })\n  const labelOf = (key: string) => {\n    const label = config[key]?.label\n    return typeof label === 'string' ? label : key\n  }\n  // What a stop says: the lit layer alone, with its share of the total, so Up and Down are heard\n  // to move; with none lit, every layer and the total.\n  const stopText = (item: ChartItem) => {\n    const total = totalOf(item)\n    const lit = chart.emphasis\n    if (lit !== null && shown.includes(lit)) {\n      const value = numberOf(chart.valueOf(lit, item))\n      const share =\n        value === null || total === 0\n          ? ''\n          : `, ${chart.messages.outOf(percent.format(value / total), chart.valueText(total))}`\n      return `${labelOf(lit)} ${chart.seriesText(item, lit)}${share}`\n    }\n    return [\n      ...shown.map((key) => `${labelOf(key)} ${chart.seriesText(item, key)}`),\n      `${chart.messages.total} ${chart.valueText(total)}`,\n    ].join(', ')\n  }\n  const written = seriesWords(chart, cartesianWords(chart, null))\n  const spoken = seriesWords(chart, cartesianWords(chart, { name: '', text: stopText }))\n  const byKey = new Map(chart.current.map((stop) => [stop.key, stop]))\n  const words = {\n    describe: spoken.describe,\n    tooltip: written.tooltip,\n    // One column a layer, and the total.\n    table: {\n      ...written.table,\n      columns: [...written.table.columns, chart.messages.total],\n      rows: written.table.rows.map((row) => {\n        const stop = byKey.get(row.key)\n        return {\n          ...row,\n          cells: [...row.cells, stop ? chart.valueText(totalOf(stop)) : ''],\n        }\n      }),\n    },\n  }\n  // Beside the guide, at the lit layer's middle, or the stream's, so it covers neither callout\n  // nor the axis: the middle of the layers, even when they stack up from zero.\n  const anchor = (stop: CartesianStop, series: string | null): ChartPoint => {\n    const centre = bandCentre(stop.band)\n    const span = series === null ? null : (model.spans[series]?.[stop.index] ?? null)\n    return {\n      x: chart.direction === 'rtl' ? 1 - centre : centre,\n      y: span\n        ? 1 - scale.place((span[0] + span[1]) / 2)\n        : streamCentre(model, stop.index),\n      side: 'inline-end',\n    }\n  }\n  return (\n    <StreamContext value={stream}>\n      <CartesianChartFrame\n        chart={{ ...made, chart }}\n        slot='stream-chart'\n        markerOf={noMarker}\n        anchor={anchor}\n        words={words}\n        // With callouts, the pointer lights the layer it is over, and Up and Down step through\n        // them, top first; without, it lights the stop, as the Area chart's does.\n        browse={\n          lights === 'stop'\n            ? { kind: 'x' }\n            : {\n                kind: 'x-series',\n                seriesAt: (point) =>\n                  layerAt(\n                    shown.map((key) => ({ key, points: pointsOf(key, false) })),\n                    curve,\n                    point,\n                  ),\n                step: (_at, from, step) => stepThrough(onScreen, from, step),\n              }\n        }\n        description={description}\n        empty={empty}\n        placeholder={placeholder && <StreamPlaceholder />}\n        // A row above the plot and one below it for the callouts, which take no room without them.\n        className={cn(\n          'grid-rows-[auto_auto_auto_minmax(0,1fr)_auto_auto_auto] [grid-template-areas:\"top_top_top\"_\"._top-axis_.\"_\"._stream-above_.\"_\"start-axis_plot_end-axis\"_\"._stream-below_.\"_\"._bottom-axis_.\"_\"bottom_bottom_bottom\"]',\n          className,\n        )}\n        ref={ref}\n        {...figureProps(props, streamChartKeys)}\n      >\n        {children}\n        <StreamSeams />\n        {/* With callouts, a guide that they sit on; without, a dot on each layer's top, as the\n          Area chart's. */}\n        {lights === 'layer' ? (\n          <StreamGuide />\n        ) : (\n          <LitDots\n            slot='stream-chart-lit'\n            dots={litDots}\n            topOf={(key, stop) => frameTop(model, key, stop)}\n          />\n        )}\n      </CartesianChartFrame>\n    </StreamContext>\n  )\n}\n\n/**\n * The kinds of part written straight inside the chart, or in a fragment\n * there, as the chart reads its parts (`chartParts`).\n */\nfunction partTypes(children: ReactNode): Set<unknown> {\n  const types = new Set<unknown>()\n  const visit = (nodes: ReactNode) => {\n    Children.forEach(nodes, (node) => {\n      if (!isValidElement<{ children?: ReactNode }>(node)) return\n      if (node.type === Fragment) visit(node.props.children)\n      else types.add(node.type)\n    })\n  }\n  visit(children)\n  return types\n}\n\n/** Where the stream's centre sits at the stop at `index`, as a fraction of the plot from its top. */\nfunction streamCentre(model: CartesianModel, index: number): number {\n  const spans = Object.values(model.spans)\n    .map((layer) => layer[index])\n    .filter((span) => span !== null && span !== undefined)\n  if (spans.length === 0) return 0.5\n  const [low, high] = streamExtent({ stop: spans })\n  return 1 - model.y.value.place((low + high) / 2)\n}\n\n/**\n * The layer whose shape holds `point`, as fractions of the plot from its\n * reading start and its top, among `layers` drawn with `curve` through\n * points along the same stops; null over none, such as above or below the\n * stream, or past a layer with nothing in it.\n */\nfunction layerAt(\n  layers: readonly { key: string; points: readonly LinePoint[] }[],\n  curve: StreamCurve,\n  point: { x: number; y: number },\n): string | null {\n  const stops = layers[0]?.points ?? []\n  if (stops.length === 0) return null\n  const after = stops.findIndex((stop) => stop.x >= point.x)\n  // The place along the stops, fractional between two, as `sampleLine` reads it.\n  const place =\n    after === -1\n      ? stops.length - 1\n      : after === 0\n        ? 0\n        : (() => {\n            const low = stops[after - 1]!\n            const high = stops[after]!\n            const share = high.x === low.x ? 1 : (point.x - low.x) / (high.x - low.x)\n            return after - 1 + share\n          })()\n  for (const layer of layers) {\n    const at = sampleLine(layer.points, curve)(place)\n    const bottom = at.base ?? at.y\n    if (bottom - at.y > 0 && point.y >= at.y && point.y <= bottom) return layer.key\n  }\n  return null\n}\n\n/** A layer's points as one string, so the same points from a new render move nothing. */\nfunction pointsSignature(points: readonly LinePoint[]) {\n  return points\n    .map(\n      (point) =>\n        `${point.key}:${point.x.toFixed(5)}:${point.y.toFixed(5)}:${point.base?.toFixed(5)}`,\n    )\n    .join('|')\n}\n\n/** The placeholder's swell while the data loads, as fractions of the plot's height. */\nconst PLACEHOLDER_SWELL = [0.36, 0.56, 0.5, 0.76, 0.62, 0.86, 0.7] as const\n\n/** Where the layers wait while the data loads: flat along the placeholder's centre line, which they grow out of. */\nconst LOADING_POINTS: readonly LinePoint[] = PLACEHOLDER_SWELL.map((_, at) => ({\n  key: null,\n  x: at / (PLACEHOLDER_SWELL.length - 1),\n  y: 0.5,\n  base: 0.5,\n  defined: true,\n}))\n\nconst NO_POINTS: readonly LinePoint[] = []\n\ntype StreamLayerProps = Omit<ComponentProps<'div'>, 'children' | 'color'> & {\n  /** The key of this series' values in the data, and of its entry in the config. */\n  dataKey: string\n}\n\n/**\n * One series' layer of the stream, in its colour, from where the layer under\n * it ends. While another layer is brought forward, it steps back. A hidden\n * layer thins to nothing where it sits.\n */\nfunction StreamLayer({ dataKey, className, style, ...props }: StreamLayerProps) {\n  useDeclared('StreamLayer', StreamLayer.declare({ dataKey }), cartesianSignature)\n  const chart = useCartesian()\n  const stream = useStream()\n  const fill = useRef<SVGPathElement>(null)\n  const hidden = chart.hidden.includes(dataKey)\n  const rising = !chart.entered && stream.entrance === 'rise'\n  // While the chart loads, the layer folds into the placeholder's centre line and fades, and\n  // grows back out of it when the data arrives.\n  const loading = chart.status === 'loading'\n  const drawn = chart.status === 'ready' || chart.status === 'hidden'\n  const to = loading\n    ? LOADING_POINTS\n    : drawn\n      ? stream.pointsOf(dataKey, rising)\n      : NO_POINTS\n  const signature = pointsSignature(to)\n  // A layer that arrives on an empty chart grows out of the stream's centre line.\n  const start = drawn ? stream.pointsOf(dataKey, true) : NO_POINTS\n  usePointsMove(stream.role, to, signature, start, stream.curve, {\n    align: (from, next) => alignLines(from, next, stream.curve),\n    at: pointsAt,\n    draw: (points, moving) => stream.paint(dataKey, points, fill.current, moving),\n  })\n  // Drawn as it renders, so the server and the first frame show it; moves write it after.\n  const area = useMemo(\n    () => areaPathThrough(to, stream.curve, 1, 1),\n    // The points are compared by their signature.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [signature, stream.curve],\n  )\n  if (!drawn && !loading) return null\n  const slot = chart.series.indexOf(dataKey)\n  const stepsBack = chart.emphasis !== null && chart.emphasis !== dataKey\n  return (\n    <div\n      data-slot='stream-chart-layer'\n      data-series={dataKey}\n      data-hidden={hidden || loading ? '' : undefined}\n      aria-hidden\n      className={cn(\n        plotLayerClassName,\n        markLayer.area,\n        'transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-hidden:opacity-0',\n        className,\n      )}\n      style={{ '--mark-color': seriesColor(dataKey), ...style } as CSSProperties}\n      {...props}\n    >\n      <EntranceWipe draws={stream.entrance === 'draw'}>\n        <svg\n          {...unitFrame}\n          data-dim={stepsBack ? '' : undefined}\n          className={cn(\n            'absolute inset-0 size-full overflow-visible text-(--mark-ink) transition-[color] duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)',\n            stepBackInkClassName,\n            forcedSeriesTextColor(slot),\n          )}\n        >\n          <g transform={mirror(chart.direction)}>\n            <path ref={fill} d={area} className='fill-current' />\n          </g>\n        </svg>\n      </EntranceWipe>\n    </div>\n  )\n}\n\nStreamLayer.declare = ({\n  dataKey,\n}: Pick<StreamLayerProps, 'dataKey'>): ChartPartDeclaration => ({\n  series: { key: dataKey, mark: 'area' },\n})\n\n/** Keeps `element` in `map` under `key` while it is mounted. */\nfunction keep(map: RefObject<Map<string, SVGPathElement>>, key: string) {\n  return (element: SVGPathElement | null) => {\n    if (!element) return\n    map.current.set(key, element)\n    return () => {\n      if (map.current.get(key) === element) map.current.delete(key)\n    }\n  }\n}\n\n/**\n * The seams: a thin line of the page's background along each layer's top,\n * over every layer, so neighbours read apart whatever their colours. Its\n * width is `--stream-chart-gap`.\n */\nfunction StreamSeams() {\n  const chart = useCartesian()\n  const stream = useStream()\n  // Kept while the data loads, fading as the layers fold away, as they do.\n  if (\n    chart.status !== 'ready' &&\n    chart.status !== 'hidden' &&\n    chart.status !== 'loading'\n  ) {\n    return null\n  }\n  const rising = !chart.entered && stream.entrance === 'rise'\n  return (\n    <div\n      aria-hidden\n      data-slot='stream-chart-seams'\n      data-hidden={chart.status === 'loading' ? '' : undefined}\n      className={cn(\n        plotLayerClassName,\n        'z-7 transition-opacity duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-hidden:opacity-0',\n      )}\n    >\n      <EntranceWipe draws={stream.entrance === 'draw'}>\n        <svg {...unitFrame} className='absolute inset-0 size-full overflow-visible'>\n          <g transform={mirror(chart.direction)}>\n            {stream.order.map((key) => (\n              <path\n                key={key}\n                ref={keep(stream.seams, key)}\n                d={pathThrough(stream.pointsOf(key, rising), stream.curve, 1, 1)}\n                className='stroke-background fill-none [stroke-width:var(--stream-chart-gap,1px)] [vector-effect:non-scaling-stroke] forced-colors:stroke-[Canvas]'\n              />\n            ))}\n          </g>\n        </svg>\n      </EntranceWipe>\n    </div>\n  )\n}\n\n/**\n * Where the guide is: the stop lit now, or the last one while the guide\n * fades; whether it shows; its place across the plot from the left, as a\n * fraction; and whether it was lit from rest, so it appears in place.\n */\nfunction useStreamGuide() {\n  const chart = useCartesian()\n  const at = useChartActive().spotlit\n  const fromRest = useFromRest(at)\n  const [last, setLast] = useState(at)\n  if (at !== null && at !== last) setLast(at)\n  const shownAt = at ?? last\n  const stop = shownAt === null ? undefined : chart.current[shownAt]\n  const ready = chart.status === 'ready' && chart.entered && stop !== undefined\n  const centre = stop ? bandCentre(stop.band) : 0\n  return {\n    stop,\n    ready,\n    shown: ready && at !== null,\n    x: chart.direction === 'rtl' ? 1 - centre : centre,\n    snap: fromRest,\n  }\n}\n\n/** How the guide and its callouts glide from stop to stop, and appear in place from rest. */\nconst guideGlide =\n  'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-snap:transition-none motion-reduce:transition-none'\n\n/** How the guide and its callouts fade in, and out where they are. */\nconst guideFade =\n  'transition-opacity duration-(--motion-enter-duration) ease-(--motion-enter-easing) data-hidden:opacity-0 data-hidden:duration-(--motion-exit-duration) data-hidden:ease-(--motion-exit-easing)'\n\n/**\n * The guide down the plot at the lit stop: a line of the page's background\n * over the layers, which cuts through the stream.\n */\nfunction StreamGuide() {\n  const guide = useStreamGuide()\n  if (!guide.ready) return null\n  return (\n    <div\n      aria-hidden\n      data-slot='stream-chart-guide'\n      data-hidden={guide.shown ? undefined : ''}\n      className={cn(plotLayerClassName, guideFade, 'z-7')}\n    >\n      <div\n        data-snap={guide.snap ? '' : undefined}\n        className={cn('absolute inset-y-0 left-0', guideGlide)}\n        style={{ translate: `${guide.x * 100}cqw 0` }}\n      >\n        <div className='bg-background absolute inset-y-0 w-0.5 -translate-x-1/2 forced-colors:w-px forced-colors:bg-[CanvasText]' />\n      </div>\n    </div>\n  )\n}\n\n/**\n * A callout at the guide, in its row above or below the plot, held inside\n * the plot's width at either end. It glides with the guide and fades with it.\n */\nfunction Callout({\n  slot,\n  side,\n  shown,\n  children,\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  slot: string\n  side: 'above' | 'below'\n  /** Whether it shows, beside the guide's own. */\n  shown: boolean\n  children: ReactNode\n}) {\n  const guide = useStreamGuide()\n  return (\n    <div\n      aria-hidden\n      data-slot={slot}\n      className={cn(\n        'pointer-events-none relative h-7 [container-type:inline-size]',\n        side === 'above' ? '[grid-area:stream-above]' : '[grid-area:stream-below]',\n        className,\n      )}\n      {...props}\n    >\n      {guide.ready && (\n        <div\n          data-snap={guide.snap ? '' : undefined}\n          className={cn(\n            'absolute left-0 [translate:clamp(0px,calc(var(--stream-guide-x)*100cqw_-_50%),calc(100cqw_-_100%))_0]',\n            side === 'above' ? 'bottom-1' : 'top-1',\n            guideGlide,\n          )}\n          style={{ '--stream-guide-x': guide.x } as CSSProperties}\n        >\n          <div\n            data-hidden={guide.shown && shown ? undefined : ''}\n            className={cn(\n              'bg-background text-foreground flex h-6 items-center gap-1.5 rounded-(--control-radius-xs) px-2 whitespace-nowrap shadow-xs ring-1 ring-foreground/15 forced-colors:outline forced-colors:outline-1',\n              guideFade,\n            )}\n          >\n            {children}\n          </div>\n        </div>\n      )}\n    </div>\n  )\n}\n\n/** The stream's total at the guide, in a callout above the plot; it rolls as the guide moves. */\nfunction StreamTotal({ className, ...props }: Omit<ComponentProps<'div'>, 'children'>) {\n  const chart = useCartesian()\n  const stream = useStream()\n  const guide = useStreamGuide()\n  return (\n    <Callout\n      slot='stream-chart-total'\n      side='above'\n      shown\n      className={className}\n      {...props}\n    >\n      {guide.stop && (\n        <>\n          <span className='text-muted-foreground forced-colors:text-[CanvasText]'>\n            {chart.messages.total}\n          </span>\n          <span className='font-medium tabular-nums'>\n            <ChartNumber\n              value={stream.totalOf(guide.stop)}\n              format={chart.format}\n              locale={chart.locale}\n            />\n          </span>\n        </>\n      )}\n    </Callout>\n  )\n}\n\n/**\n * The lit layer's value at the guide, with its swatch and name, in a\n * callout below the plot. It shows while a layer is lit, by the pointer, the\n * keys or the legend, and rolls as the guide or the layer changes.\n */\nfunction StreamValue({ className, ...props }: Omit<ComponentProps<'div'>, 'children'>) {\n  const chart = useCartesian()\n  const guide = useStreamGuide()\n  const lit =\n    chart.emphasis !== null && !chart.hidden.includes(chart.emphasis)\n      ? chart.emphasis\n      : null\n  // The layer last lit, which the callout keeps showing while it fades.\n  const [last, setLast] = useState(lit)\n  if (lit !== null && lit !== last) setLast(lit)\n  const key = lit ?? last\n  const value =\n    key === null || !guide.stop ? null : numberOf(chart.valueOf(key, guide.stop))\n  return (\n    <Callout\n      slot='stream-chart-value'\n      side='below'\n      shown={lit !== null}\n      className={className}\n      {...props}\n    >\n      {key !== null && (\n        <>\n          <span\n            aria-hidden\n            className={cn(\n              swatchClassName,\n              'transition-[background-color] duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)',\n              forcedSeriesColor(chart.series.indexOf(key)),\n            )}\n            style={swatchStyle(key, 'solid')}\n          />\n          {/* Two fifths of the plot's width, so a long name leaves the value room in a narrow chart. */}\n          <span className='text-muted-foreground flex min-w-0 max-w-[40cqw] forced-colors:text-[CanvasText]'>\n            <Swap align='start' className='max-w-full'>\n              <span data-cut className='block truncate'>\n                {chart.config[key]?.label ?? key}\n              </span>\n            </Swap>\n          </span>\n          <span className='font-medium tabular-nums'>\n            {value === null ? (\n              chart.messages.noValue\n            ) : (\n              <ChartNumber value={value} format={chart.format} locale={chart.locale} />\n            )}\n          </span>\n        </>\n      )}\n    </Callout>\n  )\n}\n\n/**\n * The placeholder while the data loads: a soft stream breathing slowly,\n * three bands deep, which the layers grow out of when the data arrives.\n */\nfunction StreamPlaceholder() {\n  const bands = [0.84, 0.54, 0.24].map((depth) =>\n    PLACEHOLDER_SWELL.map((swell, at): LinePoint => ({\n      key: null,\n      x: at / (PLACEHOLDER_SWELL.length - 1),\n      y: 0.5 - (swell * depth) / 2,\n      base: 0.5 + (swell * depth) / 2,\n      defined: true,\n    })),\n  )\n  return (\n    <div\n      data-slot='stream-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\n        className={cn(\n          'text-foreground/8 dark:text-foreground/12 absolute inset-0 forced-colors:text-[GrayText]!',\n          placeholderBreatheClassName,\n        )}\n      >\n        <svg {...unitFrame} className='absolute inset-0 size-full overflow-visible'>\n          {bands.map((points, at) => (\n            <path\n              key={at}\n              d={areaPathThrough(points, 'bump', 1, 1)}\n              className='fill-current'\n            />\n          ))}\n        </svg>\n      </div>\n    </div>\n  )\n}\n\nexport {\n  layerAt,\n  StreamChart,\n  type StreamChartProps,\n  type StreamCurve,\n  StreamLayer,\n  type StreamLayerProps,\n  type StreamOffset,\n  StreamTotal,\n  StreamValue,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/stream-chart.tsx"
    }
  ],
  "type": "registry:component"
}