# Animated Sparkline for UI SDK (/docs/components/sparkline)

A word-sized trend in plain SVG and CSS, no charting library: a line, an area or a row of bars from a list of numbers, with its last point marked. It draws itself on arrival, tweens into new data (a week into a month and back), colours itself by its news if you ask, and lets people scrub it with the pointer or the arrow keys while its value rolls in a small readout. Its trend and change are readable by screen readers and agents.

<ComponentPreview slug="sparkline" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport { SegmentedControl, SegmentedControlItem } from \&#x22;@/components/keyframery/segmented-control\&#x22;\nimport { percent, Sparkline } from \&#x22;@/components/keyframery/sparkline\&#x22;\n\n/* The demo plays itself: someone scrubs the overshirt's last month, switches to the last week (every\n   line tweens into its new shape), reads the beanie's week, and goes back to the month. */\nconst row = (id: string, i: number) => `[data-product=\&#x22;${id}\&#x22;] [data-slot=sparkline-point][data-index=\&#x22;${i}\&#x22;]`\nconst period = (value: string) => `[aria-label=\&#x22;Period\&#x22;] [data-slot=\&#x22;segmented-control-item\&#x22;]:nth-of-type(${value === \&#x22;7\&#x22; ? 1 : 2})`\n\n/* Units sold per day for the last 60 days, oldest first: a slow drift, a weekly rhythm and a little\n   noise, the same on every load. */\nfunction daily(seed: number, start: number, end: number) {\n  return Array.from({ length: 60 }, (_, i) => {\n    const t = i / 59\n    const weekly = Math.sin((i + seed) * ((2 * Math.PI) / 7)) * 0.09\n    const noise = Math.sin(i * 12.9898 + seed * 78.233) * 0.07\n    return Math.max(1, Math.round((start + (end - start) * t * t) * (1 + weekly + noise)))\n  })\n}\n\nconst products = [\n  { id: \&#x22;overshirt\&#x22;, name: \&#x22;Linen overshirt\&#x22;, kind: \&#x22;Shirts\&#x22;, sales: daily(1, 22, 41) },\n  { id: \&#x22;crew\&#x22;, name: \&#x22;Merino crew\&#x22;, kind: \&#x22;Knitwear\&#x22;, sales: daily(3, 30, 37) },\n  { id: \&#x22;tote\&#x22;, name: \&#x22;Canvas tote\&#x22;, kind: \&#x22;Bags\&#x22;, sales: daily(5, 18, 18.4) },\n  { id: \&#x22;beanie\&#x22;, name: \&#x22;Wool beanie\&#x22;, kind: \&#x22;Accessories\&#x22;, sales: daily(2, 34, 19) },\n]\n\nconst today = new Date(2026, 10, 19)\nconst dayLabel = (back: number) => {\n  const d = new Date(today)\n  d.setDate(d.getDate() - back)\n  return d.toLocaleDateString(\&#x22;en-US\&#x22;, { month: \&#x22;short\&#x22;, day: \&#x22;numeric\&#x22; })\n}\nconst units = (n: number) => `${n.toLocaleString(\&#x22;en-US\&#x22;)} sold`\n\ntype Days = \&#x22;7\&#x22; | \&#x22;30\&#x22;\n\nexport default function SparklineDemo({\n  type = \&#x22;area\&#x22;,\n  curve = \&#x22;smooth\&#x22;,\n  days = \&#x22;30\&#x22;,\n  trendColor = true,\n  extremes = false,\n  reference = false,\n  rows = 4,\n  title = \&#x22;Best sellers\&#x22;,\n  height = 32,\n  width = 132,\n  stroke = 1.75,\n  dot = 6,\n  color = \&#x22;\&#x22;,\n  positive = \&#x22;\&#x22;,\n  negative = \&#x22;\&#x22;,\n}: {\n  type?: \&#x22;area\&#x22; | \&#x22;line\&#x22; | \&#x22;bar\&#x22;\n  curve?: \&#x22;smooth\&#x22; | \&#x22;linear\&#x22;\n  days?: Days\n  trendColor?: boolean\n  extremes?: boolean\n  reference?: boolean\n  rows?: number\n  title?: string\n  height?: number\n  width?: number\n  stroke?: number\n  dot?: number\n  color?: string\n  positive?: string\n  negative?: string\n}) {\n  const [span, setSpan] = React.useState<Days>(days)\n  React.useEffect(() => setSpan(days), [days])\n  const n = Number(span)\n  const labels = React.useMemo(() => Array.from({ length: n }, (_, i) => dayLabel(n - 1 - i)), [n])\n\n  const vars = {\n    \&#x22;--sparkline-height\&#x22;: `${height}px`,\n    \&#x22;--sparkline-stroke\&#x22;: `${stroke}px`,\n    \&#x22;--sparkline-dot\&#x22;: `${dot}px`,\n    ...(color ? { \&#x22;--sparkline-color\&#x22;: color } : null),\n    ...(positive ? { \&#x22;--sparkline-positive\&#x22;: positive } : null),\n    ...(negative ? { \&#x22;--sparkline-negative\&#x22;: negative } : null),\n  } as React.CSSProperties\n\n  return (\n    <div className=\&#x22;@container w-full max-w-[560px]\&#x22;>\n      <div\n        style={vars}\n        className=\&#x22;rounded-[18px] bg-background p-2 shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04),0_12px_32px_-14px_rgb(0_0_0/0.14)] dark:bg-card dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]\&#x22;\n      >\n        <div className=\&#x22;flex flex-wrap items-center justify-between gap-3 px-3 pt-2 pb-3\&#x22;>\n          <div className=\&#x22;min-w-[9rem] flex-1\&#x22;>\n            <div className=\&#x22;truncate text-[15px] font-semibold tracking-tight\&#x22;>{title}</div>\n            <div className=\&#x22;mt-1 text-[12px] text-muted-foreground\&#x22;>Units sold per day</div>\n          </div>\n          <SegmentedControl aria-label=\&#x22;Period\&#x22; value={span} onValueChange={(next) => next && setSpan(next as Days)}>\n            <SegmentedControlItem value=\&#x22;7\&#x22;>7 days</SegmentedControlItem>\n            <SegmentedControlItem value=\&#x22;30\&#x22;>30 days</SegmentedControlItem>\n          </SegmentedControl>\n        </div>\n        <ul>\n          {products.slice(0, rows).map((p) => {\n            const now = p.sales.slice(-n)\n            const before = p.sales.slice(-2 * n, -n)\n            const total = now.reduce((a, b) => a + b, 0)\n            const prior = before.reduce((a, b) => a + b, 0)\n            const change = (total - prior) / prior\n            const flat = Math.abs(change) < 0.01\n            const up = change > 0\n            return (\n              <li\n                key={p.id}\n                data-product={p.id}\n                className=\&#x22;grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-3 py-3 @[440px]:grid-cols-[minmax(0,1fr)_var(--w)_5.5rem] [&+li]:border-t [&+li]:border-[color:color-mix(in_oklch,var(--border)_70%,transparent)]\&#x22;\n                style={{ \&#x22;--w\&#x22;: `${width}px` } as React.CSSProperties}\n              >\n                <div className=\&#x22;min-w-0\&#x22;>\n                  <div className=\&#x22;truncate text-[13px] leading-[1.3] font-medium\&#x22;>{p.name}</div>\n                  <div className=\&#x22;mt-0.5 truncate text-[12px] leading-[1.3] text-muted-foreground\&#x22;>{p.kind}</div>\n                </div>\n                <Sparkline\n                  className=\&#x22;col-span-2 row-start-2 @[440px]:col-span-1 @[440px]:row-start-auto\&#x22;\n                  data={now}\n                  labels={labels}\n                  type={type}\n                  curve={curve}\n                  trendColor={trendColor}\n                  extremes={extremes}\n                  reference={reference ? prior / n : null}\n                  label={`${p.name}, units sold per day`}\n                  period={`last ${n} days`}\n                  formatValue={units}\n                />\n                <div className=\&#x22;text-right\&#x22;>\n                  <div className=\&#x22;text-[13px] leading-[1.3] font-medium tabular-nums\&#x22;>{total.toLocaleString(\&#x22;en-US\&#x22;)}</div>\n                  <div\n                    className={\n                      \&#x22;mt-0.5 text-[12px] leading-[1.3] font-medium tabular-nums \&#x22; +\n                      (flat ? \&#x22;text-muted-foreground\&#x22; : up ? \&#x22;text-[oklch(0.55_0.15_150)] dark:text-[oklch(0.74_0.16_150)]\&#x22; : \&#x22;text-destructive\&#x22;)\n                    }\n                  >\n                    {flat ? \&#x22;No change\&#x22; : `${up ? \&#x22;+\&#x22; : \&#x22;−\&#x22;}${percent(change)}`}\n                  </div>\n                </div>\n              </li>\n            )\n          })}\n        </ul>\n      </div>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;type&#x22;:[1863,1869],&#x22;curve&#x22;:[1881,1889],&#x22;days&#x22;:[1900,1904],&#x22;trendColor&#x22;:[1921,1925],&#x22;extremes&#x22;:[1940,1945],&#x22;reference&#x22;:[1961,1966],&#x22;rows&#x22;:[1977,1978],&#x22;title&#x22;:[1990,2004],&#x22;height&#x22;:[2017,2019],&#x22;width&#x22;:[2031,2034],&#x22;stroke&#x22;:[2047,2051],&#x22;dot&#x22;:[2061,2062],&#x22;color&#x22;:[2074,2076],&#x22;positive&#x22;:[2091,2093],&#x22;negative&#x22;:[2108,2110]},&#x22;root&#x22;:[3006,6340],&#x22;importOffset&#x22;:215}" />

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add @keyframery/sparkline
```

This adds `components/keyframery/sparkline.tsx` and its primitive to your project, and installs UI SDK. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.9 @ui-sdk/react@0.1.0-beta.9 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"springy"` (the default), `"calm"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Copy the component**

**components/keyframery/sparkline.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/sparkline"

/* Styled sparkline: the animated primitive plus the Keyframery look. A 1.75px line over a faint
   wash, the last point ringed in the surface colour, bars that go quiet except the last one, a
   dashed reference line, and the tooltip's dark pill for the readout.

   It draws in the first chart colour. With `trendColor` it draws in the colour of its news instead:
   green when the trend is good, the destructive colour when it is bad, muted when flat (a fall is
   good news with `downIsGood`).

   Theming: set these CSS variables on the sparkline or anything around it. Each falls back to the
   theme's own token, so it looks the same until you set one.
     --sparkline-color       the marks, without trendColor      (default: --chart-1)
     --sparkline-positive    good news, with trendColor         (default: green oklch(0.62 0.16 150))
     --sparkline-negative    bad news, with trendColor          (default: --destructive)
     --sparkline-height      the height                         (default: 2.5rem)
     --sparkline-stroke      the line's width                   (default: 1.75px)
     --sparkline-dot         the dots' size                     (default: 6px)
     --sparkline-surface     the ring round the dots: the surface it sits on (default: --background, --card in dark)
     --sparkline-reference   the dashed reference line          (default: --muted-foreground) */

import * as React from "react"

import { Sparkline as SparklinePrimitive, SparklinePlot as SparklinePlotPrimitive } from "@/components/keyframery/primitives/sparkline"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const look = cn(
  "h-[var(--sparkline-height,2.5rem)] w-full text-[12px]",
  "[--sparkline-tone:var(--sparkline-color,var(--chart-1))]",
  "data-trend-color:data-[tone=positive]:[--sparkline-tone:var(--sparkline-positive,oklch(0.62_0.16_150))] dark:data-trend-color:data-[tone=positive]:[--sparkline-tone:var(--sparkline-positive,oklch(0.72_0.16_150))]",
  "data-trend-color:data-[tone=negative]:[--sparkline-tone:var(--sparkline-negative,var(--destructive))]",
  "data-trend-color:data-[tone=neutral]:[--sparkline-tone:var(--sparkline-color,var(--muted-foreground))]",
  "[--sparkline-ring:var(--sparkline-surface,var(--background))] dark:[--sparkline-ring:var(--sparkline-surface,var(--card))]",
)

const plot = cn(
  /* Line and area. */
  "[&_[data-slot=sparkline-line]]:[stroke:var(--sparkline-tone)] [&_[data-slot=sparkline-line]]:[stroke-width:var(--sparkline-stroke,1.75px)] [&_[data-slot=sparkline-line]]:[stroke-linecap:round] [&_[data-slot=sparkline-line]]:[stroke-linejoin:round]",
  /* Bars: quiet, the last one and the one being read in full. */
  "[&_[data-slot=sparkline-bar]]:rounded-t-[2px] [&_[data-slot=sparkline-bar][data-negative]]:rounded-t-none [&_[data-slot=sparkline-bar][data-negative]]:rounded-b-[2px]",
  "[&_[data-slot=sparkline-bar]]:bg-[color-mix(in_oklch,var(--sparkline-tone)_42%,transparent)] [&_[data-slot=sparkline-bar]:is([data-last],[data-active])]:bg-[var(--sparkline-tone)]",
  /* The last point: solid, ringed in the surface colour so it sits cleanly on the line. */
  "[&>[data-slot=sparkline-end]]:rounded-full [&>[data-slot=sparkline-end]]:bg-[var(--sparkline-tone)] [&>[data-slot=sparkline-end]]:shadow-[0_0_0_2px_var(--sparkline-ring)]",
  /* Highest and lowest: hollow. */
  "[&>[data-slot=sparkline-extreme]]:rounded-full [&>[data-slot=sparkline-extreme]]:bg-[var(--sparkline-ring)] [&>[data-slot=sparkline-extreme]]:shadow-[inset_0_0_0_1.5px_var(--sparkline-tone)]",
  "[&>[data-slot=sparkline-reference]]:border-t [&>[data-slot=sparkline-reference]]:border-dashed [&>[data-slot=sparkline-reference]]:border-[color:color-mix(in_oklch,var(--sparkline-reference,var(--muted-foreground))_60%,transparent)]",
  "[&>[data-slot=sparkline-cursor]]:bg-[color-mix(in_oklch,var(--foreground)_22%,transparent)]",
  "[&>[data-slot=sparkline-marker]]:rounded-full [&>[data-slot=sparkline-marker]]:bg-[var(--sparkline-tone)] [&>[data-slot=sparkline-marker]]:shadow-[0_0_0_2px_var(--sparkline-ring),0_1px_3px_rgb(0_0_0/0.25)] dark:[&>[data-slot=sparkline-marker]]:shadow-[0_0_0_2px_var(--sparkline-ring),0_1px_3px_rgb(0_0_0/0.6)]",
  /* The readout: the tooltip's dark pill. */
  "[&>[data-slot=sparkline-readout]]:flex [&>[data-slot=sparkline-readout]]:items-center [&>[data-slot=sparkline-readout]]:gap-1.5 [&>[data-slot=sparkline-readout]]:rounded-[8px] [&>[data-slot=sparkline-readout]]:bg-foreground [&>[data-slot=sparkline-readout]]:px-2 [&>[data-slot=sparkline-readout]]:py-1 [&>[data-slot=sparkline-readout]]:text-[12px] [&>[data-slot=sparkline-readout]]:leading-[1.3] [&>[data-slot=sparkline-readout]]:font-medium [&>[data-slot=sparkline-readout]]:text-background",
  "[&>[data-slot=sparkline-readout]>[data-readout-label]]:font-normal [&>[data-slot=sparkline-readout]>[data-readout-label]]:opacity-65",
  /* The keyboard's point: a soft band. */
  "[&_[data-slot=sparkline-point]]:rounded-[3px] [&_[data-slot=sparkline-point]]:focus-visible:bg-[color-mix(in_oklch,var(--ring)_14%,transparent)]",
)

type SparklineProps = React.ComponentProps<typeof SparklinePrimitive> &
  SpeedProps & {
    /** Draws in the colour of its news: green when good, red when bad, muted when flat. */
    trendColor?: boolean
  }

function Sparkline({ speed, trendColor = false, className, children, ...props }: SparklineProps) {
  return (
    <Speed speed={speed}>
      <SparklinePrimitive
        {...(trendColor ? { "data-trend-color": "" } : null)}
        className={withClass(look, className)}
        {...props}
      >
        {children ?? <SparklinePlot />}
      </SparklinePrimitive>
    </Speed>
  )
}

function SparklinePlot({ className, ...props }: React.ComponentProps<typeof SparklinePlotPrimitive>) {
  return <SparklinePlotPrimitive className={withClass(plot, className)} {...props} />
}

export { Sparkline, SparklinePlot }
```

**components/keyframery/primitives/sparkline.tsx**

```tsx
"use client"

/* Animated sparkline, on UI SDK's core. UI SDK ships no sparkline, so the behaviour and the geometry
   are defined in `@/components/core/sparkline` with `definePrimitive` and rendered here. No charting
   library: the line and area are SVG in a 0–100 box, bars and dots are elements placed by CSS
   variables. This file adds the layout those variables need and the motion. Colours, radii and
   sizes stay yours; the marks draw in `--sparkline-tone` (falling back to the text colour).

   - Draw: a line draws itself from the left with its area unrolling under it; then the last point
     pops in. Bars Cascade: they grow from the baseline one after another, left to right.
   - Tween: new data moves the line, the area, every bar and the last point on a spring. Paths of any
     length up to 97 points tween into each other (see the core).
   - Glide: while someone scrubs, a hairline and a dot ride to the point under the pointer or the
     arrow keys, and the readout follows them with its value Rolling.

   Every moving value is a CSS variable from the core (`--sparkline-x`, `--sparkline-y`,
   `--sparkline-w`, `--sparkline-h` in percent, `--sparkline-path`). */

import type { SlotName, StateOf } from "@ui-sdk/core"
import { type PartProps, usePart, usePrimitive } from "@ui-sdk/react/primitive"
import * as React from "react"

import { sparkline, type SparklineOptions } from "@/components/keyframery/core/sparkline-core"
import { cn } from "@/lib/utils"

type SparklinePart<Slot extends SlotName<typeof sparkline>, Tag extends keyof React.JSX.IntrinsicElements = "div"> = PartProps<Tag, StateOf<typeof sparkline, Slot>>

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* ---------------------------------------------------------------- Roll */

/* Roll: every digit is a column of 0 to 9 that slides to its value on a spring. Positions are keyed
   from the right, so a new leading digit is added instead of everything shifting. */
function Roll({ text, className }: { text: string; className?: string }) {
  const chars = text.split("")
  return (
    <>
      <span className="sr-only">{text}</span>
      <span data-roll="" aria-hidden className={cn("inline-flex h-[1lh] overflow-hidden whitespace-pre tabular-nums", className)}>
        {chars.map((c, i) => {
          const key = chars.length - i
          return /\d/.test(c) ? (
            <span
              key={key}
              style={{ "--d": Number(c) } as React.CSSProperties}
              className="flex flex-col transition-[translate] duration-[calc(480ms*var(--kf-speed,1))] ease-spring [translate:0_calc(var(--d)*-1lh)] motion-reduce:transition-none!"
            >
              {Array.from({ length: 10 }, (_, d) => (
                <span key={d} className="h-[1lh]">
                  {d}
                </span>
              ))}
            </span>
          ) : (
            <span key={key}>{c}</span>
          )
        })}
      </span>
    </>
  )
}

/* ---------------------------------------------------------------- root */

type SparklineProps = SparklineOptions & Omit<SparklinePart<"root">, keyof SparklineOptions>

/** The sparkline. With no children it draws the plot with its marks, the last point and the
    readout. Name it with `label` and `period` (it reads "Revenue, last 14 days, up 12%"), or
    with your own `aria-label`. */
function Sparkline({
  data,
  labels,
  type,
  curve,
  label,
  period,
  formatValue,
  downIsGood,
  flatThreshold,
  reference,
  extremes,
  includeZero,
  activeIndex,
  defaultActiveIndex,
  onActiveIndexChange,
  className,
  children,
  ...props
}: SparklineProps) {
  const handle = usePrimitive(sparkline, {
    data,
    labels,
    type,
    curve,
    label,
    period,
    formatValue,
    downIsGood,
    flatThreshold,
    reference,
    extremes,
    includeZero,
    activeIndex,
    defaultActiveIndex,
    onActiveIndexChange,
  })
  return usePart(
    handle,
    "root",
    {},
    {
      ...props,
      className: withClass("group/sparkline relative isolate block min-w-0", className),
      children: children ?? <SparklinePlot />,
    },
    "div",
  )
}

/* ---------------------------------------------------------------- plot */

/** The marks' box, inset by `--sparkline-inset` (default 4px) so the dots at the ends stay inside.
    With no children: the reference line, the marks, the extremes, the cursor, the last point and
    the readout. The points (the keyboard layer) are always added. */
function SparklinePlot({ className, children, ...props }: SparklinePart<"plot">) {
  return usePart(
    sparkline,
    "plot",
    {},
    {
      ...props,
      className: withClass("absolute inset-[var(--sparkline-inset,4px)] touch-pan-y", className),
      children: (state) => (
        <>
          {typeof children === "function"
            ? children(state)
            : (children ?? (
                <>
                  <SparklineReference />
                  <SparklineCursor />
                  {state.type === "bar" ? <SparklineBars count={state.count} /> : <SparklineSvg />}
                  <SparklineExtreme value="max" />
                  <SparklineExtreme value="min" />
                  <SparklineMarker />
                  <SparklineEnd />
                  <SparklineReadout />
                </>
              ))}
          <SparklinePoints />
        </>
      ),
    },
    "div",
  )
}

/* ---------------------------------------------------------------- line and area */

/* The line draws itself from the left; it tweens to new values on a spring. */
const lineMotion = cn(
  "fill-none [d:var(--sparkline-path)] [vector-effect:non-scaling-stroke]",
  "[clip-path:inset(-50%_-6%_-50%_-6%)] starting:[clip-path:inset(-50%_106%_-50%_-6%)]",
  `[transition:d_calc(720ms*var(--kf-speed,1))_var(--ease-spring),clip-path_calc(900ms*var(--kf-speed,1))_var(--ease-house)]`,
  "motion-reduce:transition-none",
)

/** The SVG with the area's gradient, the area and the line. */
function SparklineSvg({ className, children, ...props }: SparklinePart<"svg", "svg">) {
  const id = React.useId().replace(/[^\w-]/g, "")
  return usePart(
    sparkline,
    "svg",
    {},
    {
      ...props,
      className: withClass("pointer-events-none absolute inset-0 size-full overflow-visible", className),
      children: children ?? (
        <>
          <defs>
            <linearGradient id={`${id}-fill`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" style={{ stopColor: "var(--sparkline-tone,currentColor)", stopOpacity: "var(--sparkline-fill-top,0.24)" }} />
              <stop offset="1" style={{ stopColor: "var(--sparkline-tone,currentColor)", stopOpacity: "var(--sparkline-fill-bottom,0)" }} />
            </linearGradient>
          </defs>
          <SparklineArea fill={`url(#${id}-fill)`} />
          <SparklineLine />
        </>
      ),
    },
    "svg",
  )
}

/** The line. */
function SparklineLine({ className, ...props }: SparklinePart<"line", "path">) {
  return usePart(sparkline, "line", {}, { ...props, className: withClass(lineMotion, className) }, "path")
}

/** The fill under the line, for `type="area"`. Give it `fill`, as `SparklineSvg` does with a gradient. */
function SparklineArea({ className, ...props }: SparklinePart<"area", "path">) {
  return usePart(sparkline, "area", {}, { ...props, className: withClass(lineMotion.replace("fill-none ", ""), className) }, "path")
}

/* ---------------------------------------------------------------- bars */

/* Bars grow from the baseline one after another; the cascade takes about 520ms whatever the count. */
const barMotion = cn(
  "absolute left-[calc(var(--sparkline-x)*1%)] w-[calc(var(--sparkline-w)*1%)] bottom-[calc(var(--sparkline-y)*1%)] h-[calc(var(--sparkline-h)*1%)] starting:h-0",
  "data-negative:bottom-auto data-negative:top-[calc((100-var(--sparkline-y)-var(--sparkline-h))*1%)]",
  "data-dim:opacity-45",
  `transition-[left,width,bottom,top,height,opacity] duration-[calc(640ms*var(--kf-speed,1))] ease-spring`,
  `[transition-delay:calc(var(--sparkline-i,0)*calc(520ms*var(--kf-speed,1))/var(--sparkline-n,1)),calc(var(--sparkline-i,0)*calc(520ms*var(--kf-speed,1))/var(--sparkline-n,1)),calc(var(--sparkline-i,0)*calc(520ms*var(--kf-speed,1))/var(--sparkline-n,1)),calc(var(--sparkline-i,0)*calc(520ms*var(--kf-speed,1))/var(--sparkline-n,1)),calc(var(--sparkline-i,0)*calc(520ms*var(--kf-speed,1))/var(--sparkline-n,1)),0ms]`,
  "motion-reduce:transition-none",
)

/** The bars, for `type="bar"`. */
function SparklineBars({ count, className, ...props }: { count: number } & React.ComponentProps<"div">) {
  return (
    <div aria-hidden className={cn("pointer-events-none absolute inset-0", className)} style={{ "--sparkline-n": Math.max(1, count) } as React.CSSProperties} {...props}>
      {Array.from({ length: count }, (_, i) => (
        <SparklineBar key={i} value={String(i)} />
      ))}
    </div>
  )
}

/** One bar, keyed by its index as a string. */
function SparklineBar({ value, className, ...props }: { value: string } & Omit<SparklinePart<"bar">, "value">) {
  return usePart(sparkline, "bar", { value }, { ...props, className: withClass(barMotion, className) }, "div")
}

/* ---------------------------------------------------------------- reference, extremes, end */

const pointBox = "absolute left-[calc(var(--sparkline-x)*1%)] top-[calc(var(--sparkline-y)*1%)] -translate-1/2"
const follow = `[transition:left_calc(720ms*var(--kf-speed,1))_var(--ease-spring),top_calc(720ms*var(--kf-speed,1))_var(--ease-spring),scale_calc(360ms*var(--kf-speed,1))_var(--ease-pop),opacity_calc(200ms*var(--kf-speed,1))_var(--ease-house)]`

/** The dashed line at `reference`. It glides when the value or the range changes. */
function SparklineReference({ className, ...props }: SparklinePart<"reference">) {
  return usePart(
    sparkline,
    "reference",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "pointer-events-none absolute inset-x-0 top-[calc(var(--sparkline-y)*1%)] h-0 starting:opacity-0",
          `[transition:top_calc(720ms*var(--kf-speed,1))_var(--ease-spring),opacity_calc(400ms*var(--kf-speed,1))_var(--ease-house)] motion-reduce:transition-none`,
        ),
        className,
      ),
    },
    "div",
  )
}

/** A dot on the highest (`value="max"`) or lowest (`value="min"`) point, shown by `extremes`. */
function SparklineExtreme({ value, className, ...props }: { value: "max" | "min" } & Omit<SparklinePart<"extreme">, "value">) {
  return usePart(
    sparkline,
    "extreme",
    { value },
    {
      ...props,
      className: withClass(
        cn(
          pointBox,
          "pointer-events-none size-[var(--sparkline-dot,6px)] starting:scale-0 starting:opacity-0",
          follow,
          `[transition-delay:0ms,0ms,calc(760ms*var(--kf-speed,1)),calc(760ms*var(--kf-speed,1))] motion-reduce:transition-none`,
        ),
        className,
      ),
    },
    "div",
  )
}

/** The last point. It pops in once the line has drawn up to it, and follows new data. On bars it
    marks nothing: the styled part colours the last bar instead. */
function SparklineEnd({ className, ...props }: SparklinePart<"end">) {
  return usePart(
    sparkline,
    "end",
    {},
    {
      ...props,
      className: withClass(
        cn(
          pointBox,
          "pointer-events-none size-[var(--sparkline-dot,6px)] starting:scale-0 starting:opacity-0 data-[type=bar]:hidden",
          "group-data-active/sparkline:scale-75 group-data-active/sparkline:opacity-50",
          follow,
          `[transition-delay:0ms,0ms,calc(820ms*var(--kf-speed,1)),calc(820ms*var(--kf-speed,1))] motion-reduce:transition-none`,
        ),
        className,
      ),
    },
    "div",
  )
}

/* ---------------------------------------------------------------- scrub */

const glide = `[transition:left_calc(320ms*var(--kf-speed,1))_var(--ease-spring),top_calc(320ms*var(--kf-speed,1))_var(--ease-spring),translate_calc(320ms*var(--kf-speed,1))_var(--ease-spring),scale_calc(300ms*var(--kf-speed,1))_var(--ease-pop),opacity_calc(160ms*var(--kf-speed,1))_var(--ease-house)]`

/** The hairline at the point being read. */
function SparklineCursor({ className, ...props }: SparklinePart<"cursor">) {
  return usePart(
    sparkline,
    "cursor",
    {},
    {
      ...props,
      className: withClass(
        cn("pointer-events-none absolute inset-y-0 left-[calc(var(--sparkline-x)*1%)] w-px -translate-x-1/2 opacity-0 data-open:opacity-100", glide, "motion-reduce:transition-none"),
        className,
      ),
    },
    "div",
  )
}

/** The dot that rides to the point being read, on lines and areas. */
function SparklineMarker({ className, ...props }: SparklinePart<"marker">) {
  return usePart(
    sparkline,
    "marker",
    {},
    {
      ...props,
      className: withClass(
        cn(pointBox, "pointer-events-none size-[calc(var(--sparkline-dot,6px)+2px)] scale-40 opacity-0 data-open:scale-100 data-open:opacity-100", glide, "motion-reduce:transition-none"),
        className,
      ),
    },
    "div",
  )
}

/** The value under the pointer, above the plot. With no children it shows the point's label and
    its value, whose digits Roll. */
function SparklineReadout({ className, children, ...props }: SparklinePart<"readout">) {
  return usePart(
    sparkline,
    "readout",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "pointer-events-none absolute bottom-[calc(100%+var(--sparkline-inset,4px)+6px)] left-[calc(var(--sparkline-x)*1%)] z-10 w-max",
          "[translate:-50%_0] data-[side=left]:[translate:calc(-100%+10px)_0] data-[side=right]:[translate:-10px_0]",
          "origin-bottom scale-[0.7] opacity-0 data-open:scale-100 data-open:opacity-100",
          glide,
          "motion-reduce:transition-none",
        ),
        className,
      ),
      children:
        children ??
        ((state) => (
          <>
            {state.label ? <span data-readout-label="">{state.label}</span> : null}
            <Roll text={state.text} />
          </>
        )),
    },
    "div",
  )
}

/** The keyboard and screen reader layer: one tab stop, arrow keys between points. */
function SparklinePoints({ className, ...props }: SparklinePart<"points">) {
  return usePart(
    sparkline,
    "points",
    {},
    {
      ...props,
      className: withClass("absolute inset-0 outline-none", className),
      children: (state) => state.keys.map((key) => <SparklinePoint key={key} value={key} />),
    },
    "div",
  )
}

function SparklinePoint({ value, className, ...props }: { value: string } & Omit<SparklinePart<"point">, "value">) {
  return usePart(
    sparkline,
    "point",
    { value },
    { ...props, className: withClass("absolute inset-y-0 left-[calc(var(--sparkline-x)*1%)] w-[calc(var(--sparkline-w)*1%)] outline-none", className) },
    "div",
  )
}

export {
  Roll,
  Sparkline,
  SparklineArea,
  SparklineBar,
  SparklineBars,
  SparklineCursor,
  SparklineEnd,
  SparklineExtreme,
  SparklineLine,
  SparklineMarker,
  SparklinePlot,
  SparklinePoint,
  SparklinePoints,
  type SparklineProps,
  SparklineReadout,
  SparklineReference,
  SparklineSvg,
}
export { percent, type SparklineCurve, type SparklineTone, type SparklineTrend, type SparklineType } from "@/components/keyframery/core/sparkline-core"
```

**components/keyframery/core/sparkline-core.ts**

```ts
/* A sparkline, as a UI SDK primitive. UI SDK ships no sparkline, so it is defined with its core: the
   same definition renders in React, Vue, Svelte, Solid and web components.

   A word-sized trend: a line, an area or a row of bars drawn from a plain list of numbers, with its
   last point marked. It follows `chart`'s conventions: geometry goes out as CSS variables in percent
   of the plot (and as SVG paths in a 0–100 box), so it lays out on the server and CSS tweens every
   change; one tab stop over the points, arrow keys, Home and End; names for every point.

     <Sparkline data={[12, 14, 13, 18, 21]} label="Revenue" period="last 14 days" />

   Its trend (up, down or flat, first point to last) and its change in percent are state, so the
   styled part can colour by trend and an agent can read them. `downIsGood` turns the meaning round
   for numbers that should fall, like refunds.

   Every line and area path is built from the same number of cubic segments (96) whatever the number
   of points, by splitting each real segment exactly. So a 7-day line tweens into a 30-day or 90-day
   one instead of jumping. */

import { type ChangeDetails, createChange, createRovingFocus, css, definePrimitive } from "@ui-sdk/core"

/* ---------------------------------------------------------------- types */

type SparklineType = "line" | "area" | "bar"
type SparklineCurve = "smooth" | "linear"
type SparklineTrend = "up" | "down" | "flat"
/** Whether the trend is good news: `positive`, `negative`, or `neutral` when it is flat. */
type SparklineTone = "positive" | "negative" | "neutral"
type SparklineValueFormatter = (value: number) => string

type ActiveReason = "item-hover" | "item-press" | "list-navigation" | "focus-in" | "focus-out" | "escape-key" | "pointer-leave"

type SparklineOptions = {
  /** The numbers, oldest first. */
  data?: number[]
  /** A name for each point, like "Nov 12", for the readout and the point names. */
  labels?: string[]
  /** `line` (the default), `area` or `bar`. */
  type?: SparklineType
  /** `smooth` (the default, never overshooting a point) or `linear`. */
  curve?: SparklineCurve
  /** What it measures, like "Revenue". Starts the accessible summary. */
  label?: string
  /** The span it covers, like "last 14 days". Goes in the accessible summary. */
  period?: string
  /** Formats a value for the readout and the point names. */
  formatValue?: SparklineValueFormatter
  /** A fall is good news (refunds, churn, response time): the tone turns round. */
  downIsGood?: boolean
  /** A change smaller than this share of the first value counts as flat. Defaults to 0.01 (1%). */
  flatThreshold?: number
  /** A value to draw a dashed line at: a target, a budget, last period's average. */
  reference?: number | null
  /** Marks the highest and the lowest point. */
  extremes?: boolean
  /** Keeps zero in the value range. Defaults to true for bars, false for lines and areas. */
  includeZero?: boolean
  /** The point (index) under the pointer or the keyboard, controlled. `null` for none. */
  activeIndex?: number | null
  defaultActiveIndex?: number | null
  onActiveIndexChange?: (index: number | null, details: ChangeDetails<ActiveReason>) => void
}

type Inputs = {
  values: number[]
  labels: string[]
  type: SparklineType
  curve: SparklineCurve
  label: string
  period: string
  formatValue: SparklineValueFormatter
  downIsGood: boolean
  flatThreshold: number
  reference: number | null
  extremes: boolean
  includeZero: boolean
}

type Point = { x: number; y: number }
type SparklineBar = { index: number; x: number; w: number; y: number; h: number; negative: boolean }

type SparklineLayout = {
  points: Point[]
  line: string
  area: string
  bars: SparklineBar[]
  /** The baseline (bars and areas grow from it), in percent from the top. */
  base: number
  /** The reference line, in percent from the top, or null. */
  referenceY: number | null
  minIndex: number
  maxIndex: number
  /** Each point's band across the plot, in percent: where the pointer picks it. */
  bands: { start: number; size: number }[]
}

type SparklineState = Inputs & {
  activeIndex: number | null
  /** The point that was active last: the readout fades out where it was. */
  lastIndex: number | null
  focused: string | null
  trend: SparklineTrend
  /** The change from the first point to the last, as a share of the first: 0.12 is up 12%. */
  change: number
  tone: SparklineTone
  /** "Revenue, last 14 days, up 12%". */
  summary: string
  layout: SparklineLayout
}

/* ---------------------------------------------------------------- defaults */

const groupFormat = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 })
const defaultFormat: SparklineValueFormatter = (value) => groupFormat.format(value)
const emptyNumbers: number[] = []
const emptyLabels: string[] = []

const round = (value: number) => Math.round(value * 100) / 100
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))
const finite = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0)

function inputsOf(options: SparklineOptions): Inputs {
  const type = options.type ?? "line"
  return {
    values: options.data ? options.data.map(finite) : emptyNumbers,
    labels: options.labels ?? emptyLabels,
    type,
    curve: options.curve ?? "smooth",
    label: options.label ?? "",
    period: options.period ?? "",
    formatValue: options.formatValue ?? defaultFormat,
    downIsGood: options.downIsGood ?? false,
    flatThreshold: clamp(options.flatThreshold ?? 0.01, 0, 1),
    reference: typeof options.reference === "number" && Number.isFinite(options.reference) ? options.reference : null,
    extremes: options.extremes ?? false,
    includeZero: options.includeZero ?? type === "bar",
  }
}

/* ---------------------------------------------------------------- math */

/** The number of cubic segments every path is built from, so any two paths tween. */
const SEGMENTS = 96

type Cubic = [Point, Point, Point, Point]

/* Monotone tangents (Fritsch–Carlson, as d3's curveMonotoneX), so a value never looks higher than it was. */
function tangents(points: Point[]) {
  const n = points.length
  const t = new Array<number>(n).fill(0)
  if (n < 2) return t
  const slope = (a: Point, b: Point) => (b.y - a.y) / (b.x - a.x || 1)
  for (let i = 1; i < n - 1; i++) {
    const s0 = slope(points[i - 1], points[i])
    const s1 = slope(points[i], points[i + 1])
    const h0 = points[i].x - points[i - 1].x
    const h1 = points[i + 1].x - points[i].x
    const p = (s0 * h1 + s1 * h0) / (h0 + h1 || 1)
    t[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0
  }
  const end = (a: Point, b: Point, inner: number) => {
    const h = b.x - a.x
    return h ? ((3 * (b.y - a.y)) / h - inner) / 2 : inner
  }
  t[0] = n > 2 ? end(points[0], points[1], t[1]) : slope(points[0], points[1])
  t[n - 1] = n > 2 ? end(points[n - 1], points[n - 2], t[n - 2]) : t[0]
  return t
}

function cubicsOf(points: Point[], curve: SparklineCurve): Cubic[] {
  const t = curve === "smooth" ? tangents(points) : []
  const out: Cubic[] = []
  for (let i = 0; i < points.length - 1; i++) {
    const a = points[i]
    const b = points[i + 1]
    const dx = (b.x - a.x) / 3
    out.push(
      curve === "smooth"
        ? [a, { x: a.x + dx, y: a.y + dx * t[i] }, { x: b.x - dx, y: b.y - dx * t[i + 1] }, b]
        : [a, { x: a.x + dx, y: a.y + (b.y - a.y) / 3 }, { x: b.x - dx, y: b.y - (b.y - a.y) / 3 }, b],
    )
  }
  return out
}

const lerp = (a: Point, b: Point, t: number): Point => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t })

/** Splits a cubic at `t` into two that draw exactly the same curve (de Casteljau). */
function split([p0, p1, p2, p3]: Cubic, t: number): [Cubic, Cubic] {
  const a = lerp(p0, p1, t)
  const b = lerp(p1, p2, t)
  const c = lerp(p2, p3, t)
  const d = lerp(a, b, t)
  const e = lerp(b, c, t)
  const f = lerp(d, e, t)
  return [
    [p0, a, d, f],
    [f, e, c, p3],
  ]
}

/** The same curve as `cubics`, cut into exactly `count` segments when it has no more than that. */
function resample(cubics: Cubic[], count: number): Cubic[] {
  if (!cubics.length || cubics.length >= count) return cubics
  const each = Math.floor(count / cubics.length)
  const extra = count % cubics.length
  const out: Cubic[] = []
  cubics.forEach((cubic, i) => {
    let rest = cubic
    for (let k = i < extra ? each + 1 : each; k > 1; k--) {
      const [head, tail] = split(rest, 1 / k)
      out.push(head)
      rest = tail
    }
    out.push(rest)
  })
  return out
}

const pt = (p: Point) => `${round(p.x)},${round(p.y)}`

/** The line through the points as an SVG path of `M` and 96 `C`s (more when there are more points). */
function sparklinePath(points: Point[], curve: SparklineCurve) {
  if (!points.length) return ""
  const through = points.length === 1 ? [{ x: 0, y: points[0].y }, { x: 100, y: points[0].y }] : points
  const cubics = resample(cubicsOf(through, curve), SEGMENTS)
  return `M${pt(cubics[0][0])}` + cubics.map((c) => `C${pt(c[1])},${pt(c[2])},${pt(c[3])}`).join("")
}

/** The change from the first value to the last, as a share of the first, and what it means. */
function trendOf(values: number[], flatThreshold: number, downIsGood: boolean) {
  const first = values[0] ?? 0
  const last = values.at(-1) ?? 0
  const change = values.length < 2 ? 0 : first !== 0 ? (last - first) / Math.abs(first) : last === 0 ? 0 : Math.sign(last)
  const trend: SparklineTrend = Math.abs(change) <= flatThreshold ? "flat" : change > 0 ? "up" : "down"
  const tone: SparklineTone = trend === "flat" ? "neutral" : (trend === "up") !== downIsGood ? "positive" : "negative"
  return { change, trend, tone }
}

/** "12%", or "4.2%" under ten. */
function percent(share: number) {
  const value = Math.abs(share) * 100
  return `${value < 10 ? Math.round(value * 10) / 10 : Math.round(value)}%`
}

function summaryOf(input: Inputs, trend: SparklineTrend, change: number) {
  const words = trend === "flat" ? "flat" : `${trend} ${percent(change)}`
  return [input.label || "Trend", input.period, input.values.length ? words : "no data"].filter(Boolean).join(", ")
}

function sparklineLayout(input: Inputs): SparklineLayout {
  const { values, type } = input
  const n = values.length
  const empty: SparklineLayout = { points: [], line: "", area: "", bars: [], base: 100, referenceY: null, minIndex: -1, maxIndex: -1, bands: [] }
  if (!n) return empty

  let lo = Math.min(...values)
  let hi = Math.max(...values)
  if (input.reference !== null) {
    lo = Math.min(lo, input.reference)
    hi = Math.max(hi, input.reference)
  }
  if (input.includeZero) {
    lo = Math.min(lo, 0)
    hi = Math.max(hi, 0)
  }
  if (hi === lo) {
    hi += 1
    lo -= 1
  }
  /* A line keeps some air under its lowest point, so it never runs along the floor. */
  if (type !== "bar" && !input.includeZero) lo -= (hi - lo) * 0.18
  /* y in percent from the top. */
  const y = (value: number) => round(100 - ((value - lo) / (hi - lo)) * 100)
  const base = input.includeZero ? y(0) : 100

  let minIndex = 0
  let maxIndex = 0
  values.forEach((v, i) => {
    if (v < values[minIndex]) minIndex = i
    if (v > values[maxIndex]) maxIndex = i
  })

  if (type === "bar") {
    const size = 100 / n
    const gap = n > 1 ? 0.3 : 0
    const bars = values.map((v, i) => {
      const top = Math.min(y(v), base)
      const bottom = Math.max(y(v), base)
      return { index: i, x: round(i * size + (size * gap) / 2), w: round(size * (1 - gap)), y: round(100 - bottom), h: round(bottom - top), negative: v < 0 }
    })
    const points = values.map((v, i) => ({ x: round((i + 0.5) * size), y: y(v) }))
    return { ...empty, points, bars, base, referenceY: input.reference === null ? null : y(input.reference), minIndex, maxIndex, bands: values.map((_, i) => ({ start: round(i * size), size: round(size) })) }
  }

  const points = values.map((v, i) => ({ x: n > 1 ? round((i / (n - 1)) * 100) : 100, y: y(v) }))
  const line = sparklinePath(points, input.curve)
  const area = line ? `${line}L100,${base}L0,${base}Z` : ""
  const step = n > 1 ? 100 / (n - 1) : 100
  const bands = points.map((p) => ({ start: round(clamp(p.x - step / 2, 0, 100)), size: round(Math.min(100, p.x + step / 2) - clamp(p.x - step / 2, 0, 100)) }))
  return { points, line, area, bars: [], base, referenceY: input.reference === null ? null : y(input.reference), minIndex, maxIndex, bands }
}

function derived(input: Inputs) {
  const { change, trend, tone } = trendOf(input.values, input.flatThreshold, input.downIsGood)
  return { change: Number(change.toFixed(4)), trend, tone, summary: summaryOf(input, trend, change), layout: sparklineLayout(input) }
}

/* ---------------------------------------------------------------- the primitive */

const keyOf = (index: number) => String(index)

const sparkline = definePrimitive({
  name: "sparkline",
  options: {
    data: "list",
    labels: "list",
    type: "string",
    curve: "string",
    label: "string",
    period: "string",
    formatValue: "value",
    downIsGood: "boolean",
    flatThreshold: "number",
    reference: "value",
    extremes: "boolean",
    includeZero: "boolean",
    activeIndex: "value",
    defaultActiveIndex: "value",
    onActiveIndexChange: "callback",
  },
  /* The values, trend, change and summary are read-only: an agent can read them, not set them. */
  controlled: ["activeIndex", "values", "trend", "change", "summary"],
  state: (options: SparklineOptions): SparklineState => {
    const inputs = inputsOf(options)
    const activeIndex = options.activeIndex ?? options.defaultActiveIndex ?? null
    return { ...inputs, ...derived(inputs), activeIndex, lastIndex: activeIndex, focused: null }
  },
  sync: (options) => ({
    ...inputsOf(options),
    ...(options.activeIndex === undefined ? {} : { activeIndex: options.activeIndex }),
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const inputKeys = ["values", "labels", "type", "curve", "label", "period", "downIsGood", "flatThreshold", "reference", "extremes", "includeZero"] as const
    const same = (a: unknown, b: unknown) =>
      a === b || (Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => v === b[i]))
    let from = store.get()
    context.onDestroy(
      store.subscribe(() => {
        const now = store.get()
        if (now.activeIndex !== null && now.activeIndex !== now.lastIndex) store.set({ lastIndex: now.activeIndex })
        if (inputKeys.every((key) => same(now[key], from[key]))) return
        const next = derived(now)
        from = { ...now, ...next }
        store.set(next)
        const count = now.values.length
        if (now.activeIndex !== null && now.activeIndex >= count) store.set({ activeIndex: null })
        if (now.lastIndex !== null && now.lastIndex >= count) store.set({ lastIndex: null })
      }),
    )

    const roving = createRovingFocus<SparklineState, { value: string }>(context, {
      slot: "point",
      key: "focused",
      orientation: () => "horizontal",
      preferred: (item) => {
        const { activeIndex } = store.get()
        return activeIndex !== null && keyOf(activeIndex) === item.key
      },
    })

    const setActive = (index: number | null, reason: ActiveReason, event?: Event) => {
      const next = index === null || index < 0 || index >= store.get().values.length ? null : index
      if (store.get().activeIndex === next) return false
      return change("activeIndex", next, { reason, event })
    }
    let navigating = false

    return {
      roving,
      /** Shows the value of a point, by index, as if it were hovered. `null` lets go. */
      selectIndex: (index: number | null) => setActive(index, "item-press"),
      /** Shows the last point's value. */
      selectLast: () => setActive(store.get().values.length - 1, "item-press"),
      /** Lets go of the shown point. */
      clearActive: () => setActive(null, "item-press"),
      pointer(event: PointerEvent, el: HTMLElement) {
        const rect = el.getBoundingClientRect()
        const { values, type } = store.get()
        const n = values.length
        if (!n || rect.width <= 0) return
        const at = clamp((event.clientX - rect.left) / rect.width, 0, 1)
        const index = type === "bar" ? Math.min(n - 1, Math.floor(at * n)) : Math.round(at * (n - 1))
        setActive(index, "item-hover", event)
      },
      leave: (event: PointerEvent) => setActive(null, "pointer-leave", event),
      keydown(event: KeyboardEvent, el: HTMLElement) {
        if (event.key === "Escape") {
          if (store.get().activeIndex !== null) {
            event.preventDefault()
            setActive(null, "escape-key", event)
          }
          return
        }
        navigating = true
        const moved = roving.keydown(event, el)
        navigating = false
        if (moved) setActive(Number(moved.key), "list-navigation", event)
      },
      focusPoint(key: string, event: FocusEvent) {
        if (!navigating) setActive(Number(key), "focus-in", event)
      },
      pressPoint: (key: string, event?: Event) => setActive(Number(key), "item-press", event),
      blurPoints: (event: FocusEvent) => setActive(null, "focus-out", event),
    }
  },
  slots: (slot) => {
    const shownIndex = (state: SparklineState) => state.activeIndex ?? state.lastIndex
    const pointName = (state: SparklineState, index: number) => {
      const value = state.values[index]
      if (value === undefined) return ""
      const name = state.labels[index] ?? `Point ${index + 1} of ${state.values.length}`
      return `${name}: ${state.formatValue(value)}`
    }
    const pointStyle = (point: Point | undefined) => (point ? css({ "--sparkline-x": point.x, "--sparkline-y": point.y }) : undefined)

    return {
      /* A figure named by its summary, unless you name it yourself with `aria-label`. */
      root: slot<{}, { type: SparklineType; trend: SparklineTrend; tone: SparklineTone; change: number; summary: string; active: boolean; empty: boolean }>({
        role: "figure",
        state: (state) => ({
          type: state.type,
          trend: state.trend,
          tone: state.tone,
          change: state.change,
          summary: state.summary,
          active: state.activeIndex !== null,
          empty: state.values.length === 0,
        }),
        attrs: (state) => ({
          "aria-label": state.summary,
          "data-type": state.type,
          "data-trend": state.trend,
          "data-tone": state.tone,
          "data-active": state.activeIndex !== null ? "" : undefined,
          "data-empty": state.values.length ? undefined : "",
        }),
      }),

      /* The marks' box. It hears the pointer: the point under it shows its value. */
      plot: slot<{}, { type: SparklineType; count: number }>({
        state: (state) => ({ type: state.type, count: state.values.length }),
        attrs: (state) => ({ "data-type": state.type }),
        on: {
          pointermove: (event, { el, api }) => {
            if (el) api.pointer(event as PointerEvent, el)
          },
          pointerleave: (event, { api }) => api.leave(event as PointerEvent),
        },
      }),

      /* The drawing surface for the line and area: a 0–100 box stretched to the plot. */
      svg: slot({
        present: (state) => state.type !== "bar",
        attrs: () => ({ "aria-hidden": "true", viewBox: "0 0 100 100", preserveAspectRatio: "none", focusable: "false" }),
      }),
      line: slot({
        present: (state) => state.type !== "bar",
        attrs: (state) => ({ d: state.layout.line, style: css({ "--sparkline-path": `path('${state.layout.line}')` }) }),
      }),
      /* The fill under the line. Give it a `fill` (a gradient's url) of your own. */
      area: slot({
        present: (state) => state.type === "area",
        attrs: (state) => ({ d: state.layout.area, style: css({ "--sparkline-path": `path('${state.layout.area}')` }) }),
      }),
      /* One bar, keyed by its index. */
      bar: slot<{ value: string }>({
        props: { value: "string" },
        attrs: (state, part) => {
          const bar = state.layout.bars[Number(part.key)]
          if (!bar) return { "data-hidden": "" }
          const active = state.activeIndex
          return {
            "data-index": part.key,
            "data-active": active === bar.index ? "" : undefined,
            "data-last": bar.index === state.values.length - 1 ? "" : undefined,
            "data-negative": bar.negative ? "" : undefined,
            "data-dim": active !== null && active !== bar.index ? "" : undefined,
            style: css({ "--sparkline-x": bar.x, "--sparkline-w": bar.w, "--sparkline-y": bar.y, "--sparkline-h": bar.h, "--sparkline-i": bar.index }),
          }
        },
      }),
      /* The dashed line at `reference`. */
      reference: slot({
        present: (state) => state.layout.referenceY !== null,
        attrs: (state) => ({ "aria-hidden": "true", style: css({ "--sparkline-y": state.layout.referenceY ?? 0 }) }),
      }),
      /* The highest ("max") and lowest ("min") point, shown by `extremes`. */
      extreme: slot<{ value: string }>({
        props: { value: "string" },
        present: (state) => state.extremes && state.values.length > 1,
        attrs: (state, part) => {
          const index = part.key === "max" ? state.layout.maxIndex : state.layout.minIndex
          return { "aria-hidden": "true", "data-kind": part.key, style: pointStyle(state.layout.points[index]) }
        },
      }),
      /* The last point's mark. */
      end: slot({
        present: (state) => state.values.length > 0,
        attrs: (state) => ({ "aria-hidden": "true", "data-type": state.type, style: pointStyle(state.layout.points.at(-1)) }),
      }),
      /* The hairline at the point being read. */
      cursor: slot({
        attrs: (state) => {
          const index = shownIndex(state)
          return { "aria-hidden": "true", "data-open": state.activeIndex !== null ? "" : undefined, style: pointStyle(index === null ? undefined : state.layout.points[index]) }
        },
      }),
      /* The dot that rides to the point being read. */
      marker: slot({
        present: (state) => state.type !== "bar",
        attrs: (state) => {
          const index = shownIndex(state)
          return { "aria-hidden": "true", "data-open": state.activeIndex !== null ? "" : undefined, style: pointStyle(index === null ? undefined : state.layout.points[index]) }
        },
      }),
      /* The value under the pointer. Words for the eye; the points carry them for screen readers. */
      readout: slot<{}, { open: boolean; label: string; text: string; value: number | null }>({
        state: (state) => {
          const index = shownIndex(state)
          const value = index === null ? undefined : state.values[index]
          return {
            open: state.activeIndex !== null,
            label: index === null ? "" : (state.labels[index] ?? ""),
            text: value === undefined ? "" : state.formatValue(value),
            value: value ?? null,
          }
        },
        attrs: (state) => {
          const index = shownIndex(state)
          const point = index === null ? undefined : state.layout.points[index]
          return {
            "aria-hidden": "true",
            "data-open": state.activeIndex !== null ? "" : undefined,
            "data-side": point && point.x > 70 ? "left" : point && point.x < 30 ? "right" : "center",
            style: pointStyle(point),
          }
        },
      }),

      /* The points, one tab stop with arrow keys between them, each named with its value. */
      points: slot<{}, { keys: string[] }>({
        role: "listbox",
        keys: { none: "Each point moves focus with the arrow keys itself, through roving focus." },
        state: (state) => ({ keys: state.values.map((_, i) => keyOf(i)) }),
        attrs: (state) => ({ "aria-label": state.summary, "aria-orientation": "horizontal" }),
        on: {
          focusout: (event, { el, api }) => {
            const next = (event as FocusEvent).relatedTarget as Node | null
            if (el && (!next || !el.contains(next))) api.blurPoints(event as FocusEvent)
          },
        },
      }),
      point: slot<{ value: string }, { active: boolean; index: number }>({
        role: "option",
        focus: "roving",
        props: { value: "string" },
        state: (state, part) => ({ active: Number(part.key) === state.activeIndex, index: Number(part.key) }),
        attrs: (state, part) => {
          const index = Number(part.key)
          const band = state.layout.bands[index]
          return {
            "aria-selected": String(index === state.activeIndex),
            "aria-label": pointName(state, index),
            tabindex: part.api.roving.tabIndex(state, part),
            "data-index": part.key,
            "data-active": index === state.activeIndex ? "" : undefined,
            style: band ? css({ "--sparkline-x": band.start, "--sparkline-w": band.size }) : undefined,
          }
        },
        press: ({ api, key }, event) => api.pressPoint(key, event),
        on: {
          keydown: (event, { el, api }) => {
            if (el) api.keydown(event as KeyboardEvent, el)
          },
          focus: (event, { key, api }) => api.focusPoint(key, event as FocusEvent),
        },
        bind: (el, part) => part.api.roving.bind(el, part),
      }),
    }
  },
  agent: { actions: ["selectIndex", "selectLast", "clearActive"] },
})

export {
  percent,
  sparkline,
  sparklineLayout,
  type SparklineBar,
  type SparklineCurve,
  type SparklineLayout,
  type SparklineOptions,
  sparklinePath,
  type SparklineState,
  type SparklineTone,
  type SparklineTrend,
  type SparklineType,
  type SparklineValueFormatter,
  trendOf,
}
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

## Usage [#usage]

```tsx
import { Sparkline } from "@/components/keyframery/sparkline"

export default function Usage() {
  return <Sparkline data={[12, 14, 13, 18, 21, 19, 24]} label="Revenue" period="last 7 days" />
}
```

## Examples [#examples]

### Coloured by its news [#coloured-by-its-news]

`trendColor` draws a rising line green and a falling one red. Refunds should fall, so `downIsGood` turns the colour round.

<ExamplePreview name="sparkline/trend">
  ```tsx
  import { Sparkline } from "@/components/keyframery/sparkline"

  const visits = [820, 870, 860, 940, 910, 1020, 1080, 1050, 1160, 1210]
  const refunds = [3.1, 3.0, 3.2, 2.9, 2.7, 2.8, 2.5, 2.4, 2.3, 2.1]

  export default function SparklineTrend() {
    return (
      <div className="grid w-full max-w-[280px] gap-5 text-[13px]">
        <div className="grid gap-1.5">
          <span className="font-medium">Visits</span>
          <Sparkline type="area" trendColor data={visits} label="Visits" period="last 10 days" />
        </div>
        <div className="grid gap-1.5">
          <span className="font-medium">Refund rate</span>
          <Sparkline trendColor downIsGood data={refunds} label="Refund rate" period="last 10 days" formatValue={(v) => `${v}%`} />
        </div>
      </div>
    )
  }
  ```
</ExamplePreview>

### Bars, a target and the high and low [#bars-a-target-and-the-high-and-low]

`type="bar"` grows the bars one after another. `reference` draws a dashed line at a value; `extremes` marks the highest and lowest point.

<ExamplePreview name="sparkline/bars">
  ```tsx
  import { Sparkline } from "@/components/keyframery/sparkline"

  const orders = [42, 38, 51, 47, 63, 58, 44, 49, 55, 61, 67, 59, 71, 64]
  const days = orders.map((_, i) => `Nov ${i + 6}`)

  export default function SparklineBars() {
    return (
      <Sparkline
        className="max-w-[280px] [--sparkline-height:3rem]"
        type="bar"
        data={orders}
        labels={days}
        reference={50}
        extremes
        label="Orders"
        period="last 14 days"
        formatValue={(v) => `${v} orders`}
      />
    )
  }
  ```
</ExamplePreview>

### Read the point under the pointer [#read-the-point-under-the-pointer]

`onActiveIndexChange` tells you which point someone is reading, by pointer or arrow keys, so a headline can follow it.

<ExamplePreview name="sparkline/scrub">
  ```tsx
  import * as React from "react"

  import { Roll, Sparkline } from "@/components/keyframery/sparkline"

  const revenue = [4210, 4480, 4390, 4720, 5010, 4880, 5240, 5530, 5410, 5860, 6020, 6310]
  const months = ["Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov"]
  const money = (v: number) => `$${v.toLocaleString("en-US")}`

  export default function SparklineScrub() {
    const [index, setIndex] = React.useState<number | null>(null)
    const at = index ?? revenue.length - 1
    return (
      <div className="grid w-full max-w-[280px] gap-2">
        <div className="text-[13px] text-muted-foreground">{months[at]} revenue</div>
        <div className="text-[24px] leading-none font-semibold tracking-tight">
          <Roll text={money(revenue[at])} />
        </div>
        <Sparkline type="area" data={revenue} labels={months} label="Revenue" period="last 12 months" formatValue={money} onActiveIndexChange={setIndex} />
      </div>
    )
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                                                                 |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Draw**    | A line draws itself from the left with its area unrolling under it; the last point pops in once the line reaches it.                                         |
| **Cascade** | Bars grow from the baseline one after another, left to right, in about half a second whatever their number.                                                  |
| **Spring**  | New data tweens the line, the area, every bar, the reference line and the last point to their new places. Up to 97 points, any length tweens into any other. |
| **Glide**   | While someone scrubs, a hairline and a dot ride to the point under the pointer and the readout follows them, swinging inward near the edges.                 |
| **Roll**    | The readout's value rolls to each new number.                                                                                                                |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this sparkline moves, pass `speed`:

```tsx
<Sparkline speed="fast">
  …
</Sparkline>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                | What it changes                                  | Default                      |
| ----------------------- | ------------------------------------------------ | ---------------------------- |
| `--sparkline-color`     | The marks, without trendColor                    | --chart-1                    |
| `--sparkline-positive`  | Good news, with trendColor                       | oklch(0.62 0.16 150)         |
| `--sparkline-negative`  | Bad news, with trendColor                        | --destructive                |
| `--sparkline-height`    | The height                                       | 2.5rem                       |
| `--sparkline-stroke`    | The line's width                                 | 1.75px                       |
| `--sparkline-dot`       | The dots' size                                   | 6px                          |
| `--sparkline-surface`   | The ring round the dots (the surface it sits on) | --background; --card in dark |
| `--sparkline-reference` | The dashed reference line                        | --muted-foreground           |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### Sparkline [#sparkline]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast it moves: \&#x22;fast\&#x22;, \&#x22;normal\&#x22;, \&#x22;slow\&#x22; or a multiplier.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;data&#x22;,&#x22;type&#x22;:&#x22;number[]&#x22;,&#x22;full&#x22;:&#x22;number[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The numbers, oldest first.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;labels&#x22;,&#x22;type&#x22;:&#x22;string[]&#x22;,&#x22;full&#x22;:&#x22;string[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A name for each point, like \&#x22;Nov 12\&#x22;, shown in the readout and read out for each point.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;type&#x22;,&#x22;type&#x22;:&#x22;\&#x22;area\&#x22; | \&#x22;line\&#x22; | \&#x22;bar\&#x22;&#x22;,&#x22;full&#x22;:&#x22;SparklineType&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;line\&#x22; (the default), \&#x22;area\&#x22; or \&#x22;bar\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;curve&#x22;,&#x22;type&#x22;:&#x22;\&#x22;linear\&#x22; | \&#x22;smooth\&#x22;&#x22;,&#x22;full&#x22;:&#x22;SparklineCurve&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;\&#x22;smooth\&#x22; (the default, never overshooting a point) or \&#x22;linear\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What it measures, like \&#x22;Revenue\&#x22;. Starts the accessible summary and the name agents see.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;period&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The span it covers, like \&#x22;last 14 days\&#x22;. The summary reads \&#x22;Revenue, last 14 days, up 12%\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;formatValue&#x22;,&#x22;type&#x22;:&#x22;SparklineValueFormatter&#x22;,&#x22;full&#x22;:&#x22;SparklineValueFormatter&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Formats a value for the readout and the point names: `(value) => string`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;downIsGood&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A fall is good news (refunds, churn, response time): the tone, and so the trend colour, turns round.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;flatThreshold&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A change from the first point to the last smaller than this share counts as flat. Defaults to 0.01.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;reference&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A value to draw a dashed line at: a target, a budget, last period's average. `null` for none.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;extremes&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Marks the highest and the lowest point with a hollow dot.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;includeZero&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Keeps zero in the value range. Defaults to true for bars and false for lines and areas.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;activeIndex&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The point being read (hovered or focused), controlled. `null` for none.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultActiveIndex&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The point shown at first, when you don't control it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onActiveIndexChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(index: number | null, details: ChangeDetails<\&#x22;item-press\&#x22; | \&#x22;list-navigation\&#x22; | \&#x22;item-hover\&#x22; | \&#x22;escape-key\&#x22; | \&#x22;focus-out\&#x22; | \&#x22;focus-in\&#x22; | \&#x22;pointer-leave\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs when the point being read changes, with details.reason \&#x22;item-hover\&#x22;, \&#x22;item-press\&#x22;, \&#x22;list-navigation\&#x22;, \&#x22;focus-in\&#x22;, \&#x22;focus-out\&#x22;, \&#x22;escape-key\&#x22; or \&#x22;pointer-leave\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;trendColor&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Draws in the colour of its news: green when the trend is good, the destructive colour when bad, muted when flat.&#x22;,&#x22;required&#x22;:false}]" />

### Roll [#roll]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;text&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### SparklineBars [#sparklinebars]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;count&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `SparklinePlot`: a `<div>`
* `SparklineArea`
* `SparklineBar`: a `<div>`
* `SparklineCursor`: a `<div>`
* `SparklineEnd`: a `<div>`
* `SparklineExtreme`: a `<div>`
* `SparklineLine`
* `SparklineMarker`: a `<div>`
* `SparklinePoint`: a `<div>`
* `SparklinePoints`: a `<div>`
* `SparklineReadout`: a `<div>`
* `SparklineReference`: a `<div>`
* `SparklineSvg`

## Keyboard [#keyboard]

| Key                   | What it does                                                                       |
| --------------------- | ---------------------------------------------------------------------------------- |
| <kbd>Tab</kbd>        | Moves focus to the sparkline's points as one tab stop and shows the point's value. |
| <kbd>ArrowRight</kbd> | Moves to the next point and shows its value.                                       |
| <kbd>ArrowLeft</kbd>  | Moves to the previous point.                                                       |
| <kbd>Home</kbd>       | Moves to the first point.                                                          |
| <kbd>End</kbd>        | Moves to the last point.                                                           |
| <kbd>Escape</kbd>     | Hides the readout; any arrow brings it back.                                       |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a sparkline, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/sparkline-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/sparkline`.

## Questions

### How does the animated Sparkline for UI SDK move?

Draw: A line draws itself from the left with its area unrolling under it; the last point pops in once the line reaches it. Cascade: Bars grow from the baseline one after another, left to right, in about half a second whatever their number. Spring: New data tweens the line, the area, every bar, the reference line and the last point to their new places. Up to 97 points, any length tweens into any other. Glide: While someone scrubs, a hairline and a dot ride to the point under the pointer and the readout follows them, swinging inward near the edges. Roll: The readout's value rolls to each new number.

### Do I need Motion or Framer Motion for the animated Sparkline?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no sparkline. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/sparkline-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Sparkline when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
