{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "brush-chart",
  "type": "registry:item",
  "title": "Brush Chart",
  "description": "A long series with an overview strip: drag the window or its handles and the chart above zooms to it.",
  "categories": [
    "data"
  ],
  "dependencies": [
    "@shopify/react-native-skia",
    "react-native-gesture-handler",
    "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/brush-chart.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/brush-chart.tsx",
      "content": "import {\n  Canvas,\n  Circle,\n  Group,\n  Line,\n  LinearGradient,\n  Path,\n  Rect,\n  RoundedRect,\n  Skia,\n  vec,\n  type SkPath,\n} from '@shopify/react-native-skia';\nimport { useMemo, useState } from 'react';\nimport {\n  StyleSheet,\n  Text,\n  View,\n  type AccessibilityActionEvent,\n  type StyleProp,\n  type ViewStyle,\n} from 'react-native';\nimport { Gesture, GestureDetector } from 'react-native-gesture-handler';\nimport { useDerivedValue, useSharedValue, withSpring } from 'react-native-reanimated';\nimport { scheduleOnRN } from 'react-native-worklets';\n\nimport { useHaptic } from '../../lib/kinetik/hooks/use-haptic';\nimport { useReduceMotion } from '../../lib/kinetik/hooks/use-reduce-motion';\nimport { spring } from '../../lib/kinetik/motion/motion';\nimport { useKinetikTheme } from '../../lib/kinetik/tokens/theme';\nimport { withAlpha } from '../../lib/kinetik/tokens/tokens';\n\nexport type BrushChartProps = {\n  /** The series, oldest first. */\n  data: readonly number[];\n  /** One label per point, e.g. dates. Defaults to the point numbers. */\n  labels?: readonly string[];\n  /** The part shown at first, as fractions of the series. Defaults to the last third. */\n  initialWindow?: readonly [number, number];\n  onWindowChange?: (range: [number, number]) => void;\n  /** Formats values in the readout and for screen readers. */\n  formatValue?: (value: number) => string;\n  /** Main chart height. Defaults to 180. */\n  height?: number;\n  /** What the series is, e.g. \"Daily visitors\". */\n  accessibilityLabel: string;\n  /** A tick when the window settles. Defaults to true. */\n  haptics?: boolean;\n  testID?: string;\n  style?: StyleProp<ViewStyle>;\n};\n\nconst OVERVIEW = 52;\nconst HANDLE = 22;\nconst PAD_Y = 14;\n\ntype Window = { start: number; end: number };\n\n/** The first and last point indices inside a window of fractions. */\nexport function windowIndices(n: number, start: number, end: number): [number, number] {\n  'worklet';\n  const last = Math.max(0, n - 1);\n  return [\n    Math.max(0, Math.floor(start * last + 1e-6)),\n    Math.min(last, Math.ceil(end * last - 1e-6)),\n  ];\n}\n\nfunction linePath(\n  data: readonly number[],\n  i0: number,\n  i1: number,\n  x: (i: number) => number,\n  y: (v: number) => number,\n): SkPath {\n  'worklet';\n  const b = Skia.PathBuilder.Make();\n  for (let i = i0; i <= i1; i++) {\n    if (i === i0) b.moveTo(x(i), y(data[i]!));\n    else b.lineTo(x(i), y(data[i]!));\n  }\n  return b.detach();\n}\n\n/**\n * A dense series with an overview strip. Drag the window in the strip to\n * move through time, pull its handles to zoom, or tap outside it to jump;\n * the main chart above redraws the part inside the window on the UI thread,\n * rescaling as it goes. React only hears about the window when it settles.\n */\nexport function BrushChart({\n  data,\n  labels,\n  initialWindow = [2 / 3, 1],\n  onWindowChange,\n  formatValue = (v) => String(Math.round(v)),\n  height = 180,\n  accessibilityLabel,\n  haptics = true,\n  testID,\n  style,\n}: BrushChartProps) {\n  const { colors, font, radius, space } = useKinetikTheme();\n  const reduced = useReduceMotion();\n  const haptic = useHaptic(haptics);\n  const [width, setWidth] = useState(0);\n  const n = data.length;\n  const minSpan = n > 1 ? Math.max(4 / (n - 1), 0.04) : 1;\n\n  const start = useSharedValue(initialWindow[0]);\n  const end = useSharedValue(initialWindow[1]);\n  const begin = useSharedValue<Window>({ start: 0, end: 1 });\n  // The strip width for the gesture, which runs on the UI thread.\n  const strip = useSharedValue(0);\n  const mode = useSharedValue<'move' | 'left' | 'right'>('move');\n  const [range, setRange] = useState<[number, number]>(() =>\n    windowIndices(n, initialWindow[0], initialWindow[1]),\n  );\n\n  const label = (i: number) => labels?.[i] ?? String(i + 1);\n  const report = (i0: number, i1: number) => {\n    setRange((r) => (r[0] === i0 && r[1] === i1 ? r : [i0, i1]));\n  };\n  const commit = (i0: number, i1: number) => {\n    haptic('tick');\n    report(i0, i1);\n    onWindowChange?.([i0, i1]);\n  };\n\n  // The whole series in the overview strip, drawn once per size.\n  const overview = useMemo(() => {\n    if (width === 0 || n < 2) return null;\n    const lo = Math.min(...data);\n    const hi = Math.max(...data);\n    const span = hi - lo || 1;\n    const x = (i: number) => (i / (n - 1)) * width;\n    const y = (v: number) => 6 + (1 - (v - lo) / span) * (OVERVIEW - 12);\n    return linePath(data, 0, n - 1, x, y);\n  }, [data, n, width]);\n\n  // The main chart: the window's points, scaled to the window's own range.\n  const main = useDerivedValue(() => {\n    const [i0, i1] = windowIndices(n, start.get(), end.get());\n    if (width === 0 || i1 <= i0)\n      return {\n        line: Skia.PathBuilder.Make().detach(),\n        area: Skia.PathBuilder.Make().detach(),\n        lastX: 0,\n        lastY: 0,\n      };\n    let lo = Infinity;\n    let hi = -Infinity;\n    for (let i = i0; i <= i1; i++) {\n      lo = Math.min(lo, data[i]!);\n      hi = Math.max(hi, data[i]!);\n    }\n    const span = hi - lo || 1;\n    const s = start.get();\n    const k = width / Math.max(1e-6, end.get() - s);\n    const x = (i: number) => (i / (n - 1) - s) * k;\n    const y = (v: number) => PAD_Y + (1 - (v - lo) / span) * (height - PAD_Y * 2);\n    const line = linePath(data, i0, i1, x, y);\n    const area = Skia.PathBuilder.Make()\n      .addPath(line)\n      .lineTo(x(i1), height)\n      .lineTo(x(i0), height)\n      .close()\n      .detach();\n    return { line, area, lastX: x(i1), lastY: y(data[i1]!) };\n  });\n  const line = useDerivedValue(() => main.get().line);\n  const area = useDerivedValue(() => main.get().area);\n  const lastX = useDerivedValue(() => main.get().lastX);\n  const lastY = useDerivedValue(() => main.get().lastY);\n\n  const winX = useDerivedValue(() => start.get() * width);\n  const winW = useDerivedValue(() => (end.get() - start.get()) * width);\n  const leftShade = useDerivedValue(() => start.get() * width);\n  const rightX = useDerivedValue(() => end.get() * width);\n  const rightW = useDerivedValue(() => (1 - end.get()) * width);\n  const handleL = useDerivedValue(() => start.get() * width - 2);\n  const handleR = useDerivedValue(() => end.get() * width - 2);\n\n  const pan = Gesture.Pan()\n    .withTestId('brush-chart')\n    .minDistance(0)\n    .onBegin((e) => {\n      const width = strip.get();\n      if (width === 0) return;\n      const sx = start.get() * width;\n      const ex = end.get() * width;\n      if (Math.abs(e.x - sx) <= HANDLE && Math.abs(e.x - sx) <= Math.abs(e.x - ex)) {\n        mode.set('left');\n      } else if (Math.abs(e.x - ex) <= HANDLE) {\n        mode.set('right');\n      } else {\n        mode.set('move');\n        if (e.x < sx || e.x > ex) {\n          // A tap outside the window centres it there.\n          const half = (end.get() - start.get()) / 2;\n          const c = Math.max(half, Math.min(1 - half, e.x / width));\n          start.set(c - half);\n          end.set(c + half);\n        }\n      }\n      begin.set({ start: start.get(), end: end.get() });\n    })\n    .onUpdate((e) => {\n      const width = strip.get();\n      if (width === 0) return;\n      const d = e.translationX / width;\n      const b = begin.get();\n      const m = mode.get();\n      if (m === 'move') {\n        const span = b.end - b.start;\n        const s = Math.max(0, Math.min(1 - span, b.start + d));\n        start.set(s);\n        end.set(s + span);\n      } else if (m === 'left') {\n        start.set(Math.max(0, Math.min(b.end - minSpan, b.start + d)));\n      } else {\n        end.set(Math.min(1, Math.max(b.start + minSpan, b.end + d)));\n      }\n    })\n    .onFinalize(() => {\n      const [i0, i1] = windowIndices(n, start.get(), end.get());\n      scheduleOnRN(commit, i0, i1);\n    });\n\n  const nudge = (e: AccessibilityActionEvent) => {\n    const span = end.get() - start.get();\n    const step = span * 0.5 * (e.nativeEvent.actionName === 'increment' ? 1 : -1);\n    const s = Math.max(0, Math.min(1 - span, start.get() + step));\n    start.set(reduced ? s : withSpring(s, spring('smooth')));\n    end.set(reduced ? s + span : withSpring(s + span, spring('smooth')));\n    const [i0, i1] = windowIndices(n, s, s + span);\n    commit(i0, i1);\n  };\n\n  const [a, b] = range;\n  const first = data[a];\n  const last = data[b];\n  const change =\n    first !== undefined && last !== undefined && first !== 0 ? (last - first) / Math.abs(first) : 0;\n  const summary = `${label(a)} to ${label(b)}`;\n\n  return (\n    <View testID={testID} style={[{ gap: space[3] }, style]}>\n      <View style={styles.readout}>\n        <View style={styles.grow}>\n          <Text style={{ color: colors.textSubtle, fontSize: font.size.xs }}>{summary}</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            {last !== undefined ? formatValue(last) : '–'}\n          </Text>\n        </View>\n        <Text\n          style={{\n            color: change >= 0 ? colors.success : colors.danger,\n            fontSize: font.size.sm,\n            fontWeight: font.weight.semibold,\n            fontVariant: ['tabular-nums'],\n          }}\n        >\n          {change >= 0 ? '+' : '−'}\n          {Math.abs(change * 100).toFixed(1)}%\n        </Text>\n      </View>\n      <View\n        accessible\n        accessibilityRole=\"image\"\n        accessibilityLabel={`${accessibilityLabel}, ${summary}, from ${first !== undefined ? formatValue(first) : '–'} to ${last !== undefined ? formatValue(last) : '–'}`}\n        style={{ height }}\n        onLayout={(e) => {\n          setWidth(e.nativeEvent.layout.width);\n          strip.set(e.nativeEvent.layout.width);\n        }}\n      >\n        {width > 0 ? (\n          <Canvas style={{ width, height }}>\n            {[0.25, 0.5, 0.75].map((f) => (\n              <Line\n                key={f}\n                p1={vec(0, height * f)}\n                p2={vec(width, height * f)}\n                color={colors.border}\n                strokeWidth={1}\n                style=\"stroke\"\n              />\n            ))}\n            <Path path={area}>\n              <LinearGradient\n                start={vec(0, 0)}\n                end={vec(0, height)}\n                colors={[withAlpha(colors.azure, 0.28), withAlpha(colors.azure, 0)]}\n              />\n            </Path>\n            <Path\n              path={line}\n              style=\"stroke\"\n              strokeWidth={2}\n              strokeJoin=\"round\"\n              color={colors.azure}\n            />\n            <Circle cx={lastX} cy={lastY} r={4} color={colors.azure} />\n          </Canvas>\n        ) : null}\n      </View>\n      <GestureDetector gesture={pan}>\n        <View\n          collapsable={false}\n          accessible\n          accessibilityRole=\"adjustable\"\n          accessibilityLabel={`${accessibilityLabel} range`}\n          accessibilityValue={{ text: summary }}\n          accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}\n          onAccessibilityAction={nudge}\n          style={[styles.overview, { backgroundColor: colors.surface, borderRadius: radius.sm }]}\n        >\n          {width > 0 && overview ? (\n            <Canvas style={{ width, height: OVERVIEW }}>\n              <Path path={overview} style=\"stroke\" strokeWidth={1.25} color={colors.textSubtle} />\n              <Rect\n                x={0}\n                y={0}\n                width={leftShade}\n                height={OVERVIEW}\n                color={withAlpha(colors.background, 0.55)}\n              />\n              <Rect\n                x={rightX}\n                y={0}\n                width={rightW}\n                height={OVERVIEW}\n                color={withAlpha(colors.background, 0.55)}\n              />\n              <Group>\n                <Rect\n                  x={winX}\n                  y={0}\n                  width={winW}\n                  height={OVERVIEW}\n                  color={withAlpha(colors.azure, 0.12)}\n                />\n                <Rect\n                  x={winX}\n                  y={0.75}\n                  width={winW}\n                  height={OVERVIEW - 1.5}\n                  color={colors.azure}\n                  style=\"stroke\"\n                  strokeWidth={1.5}\n                />\n              </Group>\n              <RoundedRect\n                x={handleL}\n                y={OVERVIEW / 2 - 10}\n                width={4}\n                height={20}\n                r={2}\n                color={colors.azure}\n              />\n              <RoundedRect\n                x={handleR}\n                y={OVERVIEW / 2 - 10}\n                width={4}\n                height={20}\n                r={2}\n                color={colors.azure}\n              />\n            </Canvas>\n          ) : null}\n        </View>\n      </GestureDetector>\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  readout: { flexDirection: 'row', alignItems: 'flex-end', gap: 12 },\n  grow: { flex: 1, gap: 2 },\n  overview: { height: OVERVIEW, overflow: 'hidden' },\n});\n"
    }
  ],
  "meta": {
    "version": "1.0.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "data",
    "web": "live",
    "perf": {
      "budget": "Two Skia canvases. The visible part is rebuilt on the UI thread while dragging; the overview path is built once per size. Nothing runs at rest.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-13",
          "build": "release",
          "frameMs": 16,
          "p90Ms": 18,
          "baselineMs": 17,
          "jankyPercent": 2.93,
          "atRest": "idle",
          "memoryMb": 163,
          "notes": "Before the window stopped re-rendering React on every drag frame this was 32 ms median with 36% janky frames."
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Screen reader steps move the window at once instead of springing.",
      "screenReader": "The chart is an image that reads the visible range and its first and last values; the strip is an adjustable range.",
      "touchTarget": "The whole strip is the target, 52 pt tall; handles respond 22 pt either side."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { BrushChart } from '@/components/kinetik/brush-chart';\n\n<BrushChart\n  accessibilityLabel=\"Daily visitors\"\n  data={visitors}\n  labels={dates}\n  initialWindow={[0.7, 1]}\n  onWindowChange={([from, to]) => load(from, to)}\n/>;\n```\n\n## When to use\n\n- Long time series where people need both the shape of the whole and the detail of a part: traffic, prices, sensor readings.\n- Dashboards where the visible range drives other figures, via `onWindowChange`.\n\n## When not to use\n\n- A handful of points. Use Line Chart or Bar Chart.\n- Comparing several series. Use Line Chart with a legend.\n\n## Notes\n\n- Drag inside the window to move it, pull either handle to zoom, or tap outside it to jump there.\n- The main chart is rebuilt on the UI thread from the window and rescales to the visible range; the overview is drawn once per size.\n- The readout shows the last visible value and the change across the window, and updates when the window settles. The range is an adjustable element: screen readers step it by half a window.\n- `onWindowChange` receives the first and last visible point indices when the window settles.\n"
  },
  "docs": "Prefer `npx kinetik-ui add brush-chart`: it installs dependencies with expo install, so versions match your Expo SDK."
}
