{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stream-graph",
  "type": "registry:item",
  "title": "Stream Graph",
  "description": "Layered streams on a centred baseline that morph between datasets; tap a layer to lift it and read its share.",
  "categories": [
    "data"
  ],
  "dependencies": [
    "@shopify/react-native-skia",
    "react-native-reanimated",
    "react-native-worklets"
  ],
  "registryDependencies": [
    "https://kinetik-ui.dev/r/kinetik-tokens.json",
    "https://kinetik-ui.dev/r/kinetik-motion.json",
    "https://kinetik-ui.dev/r/kinetik-haptics.json"
  ],
  "files": [
    {
      "path": "src/components/kinetik/stream-graph.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/stream-graph.tsx",
      "content": "import { Canvas, Path, Skia, type SkPath } from '@shopify/react-native-skia';\nimport { useEffect, useMemo, useState } from 'react';\nimport {\n  Pressable,\n  StyleSheet,\n  Text,\n  View,\n  type GestureResponderEvent,\n  type StyleProp,\n  type ViewStyle,\n} from 'react-native';\nimport {\n  useDerivedValue,\n  useSharedValue,\n  withSpring,\n  withTiming,\n  type SharedValue,\n} from 'react-native-reanimated';\n\nimport { useHaptic } from '../../lib/kinetik/hooks/use-haptic';\nimport { useReduceMotion } from '../../lib/kinetik/hooks/use-reduce-motion';\nimport { spring, timing } from '../../lib/kinetik/motion/motion';\nimport { useKinetikTheme } from '../../lib/kinetik/tokens/theme';\nimport { minTouchTarget, withAlpha } from '../../lib/kinetik/tokens/tokens';\n\nexport type StreamLayer = {\n  key: string;\n  label: string;\n  /** One value per step; every layer needs the same number of values. */\n  values: readonly number[];\n  /** Overrides the layer's colour. */\n  color?: string;\n};\n\nexport type StreamGraphProps = {\n  layers: readonly StreamLayer[];\n  /** Plot height. Defaults to 200. */\n  height?: number;\n  /** Formats totals in the readout and for screen readers. */\n  formatValue?: (value: number) => string;\n  /** What the graph shows, e.g. \"Listening by genre\". */\n  accessibilityLabel: string;\n  /** A tick when a layer is isolated. Defaults to true. */\n  haptics?: boolean;\n  testID?: string;\n  style?: StyleProp<ViewStyle>;\n};\n\nconst PAD = 6;\n\n/**\n * Builds one closed, smooth shape per layer, stacked around a centred\n * baseline so the whole stream wiggles about the middle. Every shape has the\n * same structure for a given number of steps, so two datasets can morph.\n */\nexport function streamPaths(\n  layers: readonly { values: readonly number[] }[],\n  width: number,\n  height: number,\n): SkPath[] {\n  const steps = Math.max(0, ...layers.map((l) => l.values.length));\n  if (steps < 2 || width === 0) return layers.map(() => Skia.PathBuilder.Make().detach());\n  const totals = Array.from({ length: steps }, (_, t) =>\n    layers.reduce((sum, l) => sum + Math.max(0, l.values[t] ?? 0), 0),\n  );\n  const peak = Math.max(1, ...totals);\n  const k = (height - PAD * 2) / peak;\n  const x = (t: number) => (t / (steps - 1)) * width;\n  const mid = height / 2;\n  const below = totals.map((total) => mid - (total * k) / 2);\n  return layers.map((layer) => {\n    const lo = below.map((y) => y);\n    const hi = lo.map((y, t) => y + Math.max(0, layer.values[t] ?? 0) * k);\n    for (let t = 0; t < steps; t++) below[t] = hi[t]!;\n    const b = Skia.PathBuilder.Make();\n    b.moveTo(x(0), hi[0]!);\n    curve(b, hi, x, false);\n    b.lineTo(x(steps - 1), lo[steps - 1]!);\n    curve(b, lo, x, true);\n    b.close();\n    return b.detach();\n  });\n}\n\n/** Catmull-Rom through the points as cubic Béziers, forwards or backwards. */\nfunction curve(\n  b: ReturnType<typeof Skia.PathBuilder.Make>,\n  ys: number[],\n  x: (t: number) => number,\n  back: boolean,\n) {\n  const n = ys.length;\n  const at = (i: number) => (back ? n - 1 - i : i);\n  for (let s = 0; s < n - 1; s++) {\n    const p0 = at(Math.max(0, s - 1));\n    const p1 = at(s);\n    const p2 = at(s + 1);\n    const p3 = at(Math.min(n - 1, s + 2));\n    const c1x = x(p1) + (x(p2) - x(p0)) / 6;\n    const c1y = ys[p1]! + (ys[p2]! - ys[p0]!) / 6;\n    const c2x = x(p2) - (x(p3) - x(p1)) / 6;\n    const c2y = ys[p2]! - (ys[p3]! - ys[p1]!) / 6;\n    b.cubicTo(c1x, c1y, c2x, c2y, x(p2), ys[p2]!);\n  }\n}\n\n/**\n * Layered streams on a centred baseline. New data morphs every shape into\n * place, and tapping a layer (or its key) lifts it while the others fade back,\n * with its total in the readout.\n */\nexport function StreamGraph({\n  layers,\n  height = 200,\n  formatValue = (v) => String(Math.round(v)),\n  accessibilityLabel,\n  haptics = true,\n  testID,\n  style,\n}: StreamGraphProps) {\n  const { colors, font, radius, space } = useKinetikTheme();\n  const reduced = useReduceMotion();\n  const haptic = useHaptic(haptics);\n  const [width, setWidth] = useState(0);\n  const [focus, setFocus] = useState<string | null>(null);\n\n  const palette = [\n    colors.azure,\n    colors.sky,\n    colors.ice,\n    withAlpha(colors.azure, 0.55),\n    withAlpha(colors.sky, 0.5),\n    withAlpha(colors.ice, 0.5),\n  ];\n  const tint = (i: number) => layers[i]?.color ?? palette[i % palette.length]!;\n\n  // Keyed on the numbers, so a parent passing a fresh but equal array does not morph.\n  const dataKey = JSON.stringify(layers.map((l) => l.values));\n  const next = useMemo(\n    () => streamPaths(layers, width, height),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [dataKey, width, height],\n  );\n  // Shapes morph from the previous dataset; the first one grows out of the baseline.\n  const [shapes, setShapes] = useState<{ next: SkPath[]; prev: SkPath[]; gen: number }>(() => ({\n    next,\n    prev: next,\n    gen: 0,\n  }));\n  if (shapes.next !== next) {\n    const flat = streamPaths(\n      layers.map((l) => ({ values: l.values.map(() => 0) })),\n      width,\n      height,\n    );\n    const prev = shapes.next.length === next.length && shapes.gen > 0 ? shapes.next : flat;\n    setShapes({ next, prev, gen: shapes.gen + 1 });\n  }\n  const t = useSharedValue(1);\n  useEffect(() => {\n    if (shapes.gen === 0) return;\n    if (reduced) {\n      t.set(1);\n      return;\n    }\n    t.set(0);\n    t.set(withSpring(1, spring('smooth')));\n  }, [shapes.gen, reduced, t]);\n\n  const choose = (key: string | null) => {\n    haptic('tick');\n    setFocus((f) => (f === key ? null : key));\n  };\n\n  const tap = (e: GestureResponderEvent) => {\n    const { locationX, locationY } = e.nativeEvent;\n    const hit = next.findIndex((p) => p.contains(locationX, locationY));\n    choose(hit >= 0 ? layers[hit]!.key : null);\n  };\n\n  const sums = layers.map((l) => l.values.reduce((a, b) => a + b, 0));\n  const all = sums.reduce((a, b) => a + b, 0);\n  const fi = layers.findIndex((l) => l.key === focus);\n  const summary = layers.map((l, i) => `${l.label} ${formatValue(sums[i]!)}`).join(', ');\n\n  return (\n    <View testID={testID} style={[{ gap: space[3] }, style]}>\n      <View style={styles.readout}>\n        <Text style={{ color: colors.textSubtle, fontSize: font.size.xs }}>\n          {fi >= 0 ? layers[fi]!.label : 'All'}\n        </Text>\n        <Text\n          style={{\n            color: colors.text,\n            fontSize: font.size.xl,\n            fontWeight: font.weight.semibold,\n            fontVariant: ['tabular-nums'],\n          }}\n        >\n          {formatValue(fi >= 0 ? sums[fi]! : all)}\n          {fi >= 0 && all > 0 ? (\n            <Text\n              style={{\n                color: colors.textMuted,\n                fontSize: font.size.sm,\n                fontWeight: font.weight.regular,\n              }}\n            >\n              {`  ${Math.round((sums[fi]! / all) * 100)}%`}\n            </Text>\n          ) : null}\n        </Text>\n      </View>\n      <Pressable\n        onPress={tap}\n        onLayout={(e) => setWidth(e.nativeEvent.layout.width)}\n        accessibilityRole=\"image\"\n        accessibilityLabel={`${accessibilityLabel}. ${summary}`}\n        style={{ height }}\n      >\n        {width > 0 ? (\n          <Canvas style={{ width, height }} pointerEvents=\"none\">\n            {shapes.next.map((p, i) => (\n              <Layer\n                key={layers[i]?.key ?? i}\n                next={p}\n                prev={shapes.prev[i] ?? p}\n                t={t}\n                color={tint(i)}\n                dim={focus !== null && layers[i]?.key !== focus}\n                reduced={reduced}\n              />\n            ))}\n          </Canvas>\n        ) : null}\n      </Pressable>\n      <View style={styles.legend}>\n        {layers.map((l, i) => {\n          const on = focus === l.key;\n          return (\n            <Pressable\n              key={l.key}\n              onPress={() => choose(l.key)}\n              accessibilityRole=\"button\"\n              accessibilityLabel={`${l.label}, ${formatValue(sums[i]!)}`}\n              accessibilityState={{ selected: on }}\n              style={styles.key}\n            >\n              <View\n                style={[\n                  styles.keyInner,\n                  {\n                    borderRadius: radius.pill,\n                    backgroundColor: on ? colors.surfaceRaised : undefined,\n                    borderColor: on ? colors.borderStrong : 'transparent',\n                  },\n                ]}\n              >\n                <View style={[styles.swatch, { backgroundColor: tint(i) }]} />\n                <Text\n                  style={{ color: on ? colors.text : colors.textMuted, fontSize: font.size.sm }}\n                >\n                  {l.label}\n                </Text>\n              </View>\n            </Pressable>\n          );\n        })}\n      </View>\n    </View>\n  );\n}\n\ntype LayerProps = {\n  next: SkPath;\n  prev: SkPath;\n  t: SharedValue<number>;\n  color: string;\n  dim: boolean;\n  reduced: boolean;\n};\n\nfunction Layer({ next, prev, t, color, dim, reduced }: LayerProps) {\n  const fade = useSharedValue(dim ? 0.18 : 1);\n  useEffect(() => {\n    fade.set(withTiming(dim ? 0.18 : 1, timing('base', reduced)));\n  }, [dim, reduced, fade]);\n  const path = useDerivedValue(() => {\n    const p = t.get();\n    if (p >= 1) return next;\n    return next.interpolate(prev, Math.max(0, p)) ?? next;\n  });\n  const opacity = useDerivedValue(() => fade.get());\n  return <Path path={path} color={color} opacity={opacity} />;\n}\n\nconst styles = StyleSheet.create({\n  readout: { gap: 2 },\n  legend: { flexDirection: 'row', flexWrap: 'wrap', columnGap: 4 },\n  key: { height: minTouchTarget, justifyContent: 'center' },\n  keyInner: {\n    flexDirection: 'row',\n    alignItems: 'center',\n    gap: 6,\n    paddingHorizontal: 10,\n    height: 30,\n    borderWidth: 1,\n  },\n  swatch: { width: 10, height: 10, borderRadius: 3 },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "data",
    "web": "live",
    "perf": {
      "budget": "One Skia canvas, one path per layer; a morph interpolates the paths on the UI thread. Shapes are built once per dataset. Nothing runs at rest.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-13",
          "build": "release",
          "frameMs": 18,
          "p90Ms": 30,
          "baselineMs": 18,
          "jankyPercent": 9.39,
          "atRest": "idle",
          "memoryMb": 147
        }
      ]
    },
    "a11y": {
      "reducedMotion": "New data replaces the shapes at once; isolating a layer still fades the others.",
      "screenReader": "The graph is an image that reads each layer's total; each key is a button with a selected state.",
      "touchTarget": "The keys are 44 pt tall; the whole graph can be tapped."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { StreamGraph } from '@/components/kinetik/stream-graph';\n\n<StreamGraph\n  accessibilityLabel=\"Hours of listening by genre\"\n  layers={[\n    { key: 'pop', label: 'Pop', values: [32, 38, 35, 42] },\n    { key: 'jazz', label: 'Jazz', values: [12, 14, 18, 16] },\n  ]}\n  formatValue={(v) => `${Math.round(v)} h`}\n/>;\n```\n\n## When to use\n\n- How a whole is made up over time, when the overall flow matters more than exact values: listening by genre, traffic by source.\n- Switching between periods or segments, where the morph shows what changed.\n\n## When not to use\n\n- Exact comparisons between layers. Use Bar Chart or Line Chart.\n- Data with negative values. Streams can only stack amounts.\n\n## Notes\n\n- Layers stack around a centred baseline and are smoothed with Catmull-Rom curves. Every layer needs the same number of values.\n- New data morphs each shape into place; the first draw grows out of the middle line.\n- Tap a layer, or its key, to isolate it: the others fade and the readout shows its total and share. Tap again to let go.\n- Data is compared by value, so passing a new but equal array does not replay the morph.\n"
  },
  "docs": "Prefer `npx kinetik-ui add stream-graph`: it installs dependencies with expo install, so versions match your Expo SDK."
}
