{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ridgeline",
  "type": "registry:item",
  "title": "Ridgeline",
  "description": "Overlapping distributions that rise one by one; tap a row to lift its ridge and mark its quartiles.",
  "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/ridgeline.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/ridgeline.tsx",
      "content": "import { Canvas, Group, Line, Path, Skia, vec, type SkPath } from '@shopify/react-native-skia';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Pressable, StyleSheet, Text, View, type StyleProp, type ViewStyle } from 'react-native';\nimport {\n  interpolateColor,\n  useDerivedValue,\n  useSharedValue,\n  withDelay,\n  withSpring,\n  withTiming,\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';\n\nexport type RidgeGroup = {\n  key: string;\n  label: string;\n  /** Raw samples; the curve is a smoothed estimate of how they are spread. */\n  values: readonly number[];\n};\n\nexport type RidgelineProps = {\n  groups: readonly RidgeGroup[];\n  /** The range on the x axis. Defaults to the range of all samples. */\n  domain?: readonly [number, number];\n  /** Formats values on the axis, in the readout and for screen readers. */\n  formatValue?: (value: number) => string;\n  /** The colour behind the chart, used to keep ridges in front solid. Defaults to the theme surface. */\n  ground?: string;\n  /** What the chart shows, e.g. \"Commute times by city\". */\n  accessibilityLabel: string;\n  /** A tick when a ridge is lifted. Defaults to true. */\n  haptics?: boolean;\n  testID?: string;\n  style?: StyleProp<ViewStyle>;\n};\n\nconst ROW = 44;\nconst RISE = ROW * 1.7;\nconst LABEL_W = 76;\nconst STEPS = 64;\n\n/** The value below which a share `q` of sorted samples falls. */\nexport function quantile(sorted: readonly number[], q: number): number {\n  if (sorted.length === 0) return 0;\n  const at = (sorted.length - 1) * q;\n  const lo = Math.floor(at);\n  const hi = Math.ceil(at);\n  return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (at - lo);\n}\n\n/** A Gaussian kernel density estimate at `STEPS` points across the domain. */\nexport function density(values: readonly number[], lo: number, hi: number): number[] {\n  const n = values.length;\n  if (n === 0) return new Array<number>(STEPS).fill(0);\n  const mean = values.reduce((a, b) => a + b, 0) / n;\n  const sd = Math.sqrt(values.reduce((a, b) => a + (b - mean) ** 2, 0) / n) || (hi - lo) / 10 || 1;\n  const bw = 1.06 * sd * n ** -0.2;\n  return Array.from({ length: STEPS }, (_, i) => {\n    const x = lo + ((hi - lo) * i) / (STEPS - 1);\n    let sum = 0;\n    for (const v of values) sum += Math.exp(-0.5 * ((x - v) / bw) ** 2);\n    return sum / (n * bw * Math.sqrt(2 * Math.PI));\n  });\n}\n\n/**\n * Overlapping distributions, one ridge per group. The ridges rise from their\n * baselines one after another; tap a row and its ridge lifts in front while\n * the others fade back, with its median and middle half marked beneath.\n */\nexport function Ridgeline({\n  groups,\n  domain,\n  formatValue = (v) => String(Math.round(v)),\n  ground,\n  accessibilityLabel,\n  haptics = true,\n  testID,\n  style,\n}: RidgelineProps) {\n  const { colors, font, 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  const plotW = Math.max(0, width - LABEL_W);\n  const top = RISE - ROW + 8;\n  const height = top + groups.length * ROW;\n\n  const all = groups.flatMap((g) => g.values);\n  const lo = domain?.[0] ?? (all.length ? Math.min(...all) : 0);\n  const hi = domain?.[1] ?? (all.length ? Math.max(...all) : 1);\n  const x = (v: number) => LABEL_W + ((v - lo) / (hi - lo || 1)) * plotW;\n\n  const stats = useMemo(\n    () =>\n      groups.map((g) => {\n        const sorted = [...g.values].sort((a, b) => a - b);\n        return {\n          q1: quantile(sorted, 0.25),\n          median: quantile(sorted, 0.5),\n          q3: quantile(sorted, 0.75),\n          curve: density(g.values, lo, hi),\n        };\n      }),\n    [groups, lo, hi],\n  );\n  const peak = Math.max(1e-9, ...stats.flatMap((s) => s.curve));\n\n  const ridges = useMemo(() => {\n    if (plotW === 0) return [];\n    return stats.map((s, r) => {\n      const base = top + (r + 1) * ROW - 6;\n      const b = Skia.PathBuilder.Make();\n      const pts = s.curve.map((d, i) => ({\n        x: LABEL_W + (plotW * i) / (STEPS - 1),\n        y: base - (d / peak) * RISE,\n      }));\n      b.moveTo(pts[0]!.x, base);\n      for (const p of pts) b.lineTo(p.x, p.y);\n      b.lineTo(pts[pts.length - 1]!.x, base);\n      const fill = b.close().detach();\n      const line = Skia.PathBuilder.Make();\n      pts.forEach((p, i) => (i === 0 ? line.moveTo(p.x, p.y) : line.lineTo(p.x, p.y)));\n      return { fill, line: line.detach(), base };\n    });\n  }, [stats, plotW, peak, top]);\n\n  const fi = groups.findIndex((g) => g.key === focus);\n  const fs = fi >= 0 ? stats[fi] : undefined;\n\n  return (\n    <View testID={testID} style={[{ gap: space[2] }, style]}>\n      <Text style={{ color: colors.textMuted, fontSize: font.size.sm, minHeight: 20 }}>\n        {fs && fi >= 0\n          ? `${groups[fi]!.label}: median ${formatValue(fs.median)} · middle half ${formatValue(fs.q1)}–${formatValue(fs.q3)}`\n          : 'Tap a row to compare it'}\n      </Text>\n      <View\n        accessibilityLabel={accessibilityLabel}\n        style={{ height }}\n        onLayout={(e) => setWidth(e.nativeEvent.layout.width)}\n      >\n        {width > 0 ? (\n          <Canvas style={StyleSheet.absoluteFill} pointerEvents=\"none\">\n            {/* The lifted ridge is drawn last so it sits in front of its neighbours. */}\n            {ridges\n              .map((r, i) => ({ r, i }))\n              .sort((a, b) => (a.i === fi ? 1 : 0) - (b.i === fi ? 1 : 0))\n              .map(({ r, i }) => (\n                <Ridge\n                  key={groups[i]!.key}\n                  index={i}\n                  fill={r.fill}\n                  line={r.line}\n                  base={r.base}\n                  ground={ground ?? colors.surface}\n                  state={focus === null ? 'rest' : focus === groups[i]!.key ? 'up' : 'back'}\n                  reduced={reduced}\n                />\n              ))}\n            {fs && fi >= 0\n              ? [fs.q1, fs.median, fs.q3].map((v, k) => (\n                  <Line\n                    key={k}\n                    p1={vec(x(v), ridges[fi]!.base - (k === 1 ? 14 : 8) - 6)}\n                    p2={vec(x(v), ridges[fi]!.base - 6)}\n                    color={k === 1 ? colors.text : colors.textMuted}\n                    strokeWidth={k === 1 ? 2 : 1.5}\n                    style=\"stroke\"\n                  />\n                ))\n              : null}\n          </Canvas>\n        ) : null}\n        {groups.map((g, i) => {\n          const s = stats[i]!;\n          const on = focus === g.key;\n          return (\n            <Pressable\n              key={g.key}\n              onPress={() => {\n                haptic('tick');\n                setFocus((f) => (f === g.key ? null : g.key));\n              }}\n              accessibilityRole=\"button\"\n              accessibilityLabel={`${g.label}, median ${formatValue(s.median)}, middle half ${formatValue(s.q1)} to ${formatValue(s.q3)}`}\n              accessibilityState={{ selected: on }}\n              style={[styles.row, { top: top + i * ROW }]}\n            >\n              <Text\n                numberOfLines={1}\n                style={[\n                  styles.label,\n                  {\n                    color: on ? colors.text : colors.textMuted,\n                    fontSize: font.size.sm,\n                    fontWeight: on ? font.weight.semibold : font.weight.regular,\n                  },\n                ]}\n              >\n                {g.label}\n              </Text>\n            </Pressable>\n          );\n        })}\n      </View>\n      <View style={[styles.axis, { marginLeft: LABEL_W }]}>\n        <Text style={{ color: colors.textSubtle, fontSize: font.size.xs }}>{formatValue(lo)}</Text>\n        <Text style={{ color: colors.textSubtle, fontSize: font.size.xs }}>{formatValue(hi)}</Text>\n      </View>\n    </View>\n  );\n}\n\ntype RidgeProps = {\n  index: number;\n  fill: SkPath;\n  line: SkPath;\n  base: number;\n  ground: string;\n  state: 'rest' | 'up' | 'back';\n  reduced: boolean;\n};\n\nfunction Ridge({ index, fill, line, base, ground, state, reduced }: RidgeProps) {\n  const { colors } = useKinetikTheme();\n  const grow = useSharedValue(reduced ? 1 : 0);\n  const lift = useSharedValue(0);\n  const dim = useSharedValue(1);\n  useEffect(() => {\n    grow.set(reduced ? 1 : withDelay(index * 70, withSpring(1, spring('smooth'))));\n  }, [index, reduced, grow]);\n  useEffect(() => {\n    lift.set(withSpring(state === 'up' ? 1 : 0, spring('smooth', reduced)));\n    dim.set(withTiming(state === 'back' ? 0.3 : 1, timing('base', reduced)));\n  }, [state, reduced, lift, dim]);\n\n  const transform = useDerivedValue(() => [\n    { translateY: base - lift.get() * 6 },\n    { scaleY: Math.max(0.001, grow.get()) * (1 + lift.get() * 0.08) },\n    { translateY: -base },\n  ]);\n  const opacity = useDerivedValue(() => dim.get());\n  // One opaque fill: the ground tinted towards blue, so ridges in front hide the ones behind.\n  const tint = useDerivedValue(() =>\n    interpolateColor(0.14 + lift.get() * 0.22, [0, 1], [ground, colors.azure]),\n  );\n\n  return (\n    <Group transform={transform} opacity={opacity}>\n      <Path path={fill} color={tint} />\n      <Path path={line} style=\"stroke\" strokeWidth={1.6} strokeJoin=\"round\" color={colors.azure} />\n    </Group>\n  );\n}\n\nconst styles = StyleSheet.create({\n  row: { position: 'absolute', left: 0, right: 0, height: ROW, justifyContent: 'flex-end' },\n  label: { width: LABEL_W - 8, paddingBottom: 8 },\n  axis: { flexDirection: 'row', justifyContent: 'space-between' },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "data",
    "web": "live",
    "perf": {
      "budget": "One Skia canvas; curves are estimated once per dataset and each ridge moves by a group transform on three shared values. Nothing runs at rest.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-13",
          "build": "release",
          "frameMs": 17,
          "p90Ms": 18,
          "baselineMs": 17,
          "jankyPercent": 0.46,
          "atRest": "idle",
          "memoryMb": 156
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Ridges appear at full height and the chosen one does not lift.",
      "screenReader": "Each row is a button that reads the group, its median and its middle half, with a selected state.",
      "touchTarget": "Rows are 44 pt tall and span the full width."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { Ridgeline } from '@/components/kinetik/ridgeline';\n\n<Ridgeline\n  accessibilityLabel=\"Commute times by city, in minutes\"\n  groups={[\n    { key: 'lis', label: 'Lisbon', values: lisbonMinutes },\n    { key: 'ber', label: 'Berlin', values: berlinMinutes },\n  ]}\n  domain={[0, 100]}\n  formatValue={(v) => `${Math.round(v)} min`}\n/>;\n```\n\n## When to use\n\n- Comparing how values are spread across a few groups: response times by region, prices by category, scores by class.\n- Showing that two groups with the same average behave differently.\n\n## When not to use\n\n- A single number per group. Use Bar Chart.\n- Very few samples per group (under ten or so); the smoothed curve would suggest a shape the data does not have.\n\n## Notes\n\n- Pass raw samples: each ridge is a Gaussian kernel density estimate, scaled against the tallest ridge so heights compare fairly.\n- Ridges overlap upwards; `ground` should match the colour behind the chart so the ones in front stay solid.\n- Tap a row to lift its ridge and mark its quartiles; the readout and each row's label give the median and middle half for screen readers.\n- With reduced motion the ridges appear at full height and do not lift.\n"
  },
  "docs": "Prefer `npx kinetik-ui add ridgeline`: it installs dependencies with expo install, so versions match your Expo SDK."
}
