{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "now-playing",
  "type": "registry:item",
  "title": "Now Playing",
  "description": "A dark music widget: the cover springs forward on play, the icon morphs and progress runs on the UI thread.",
  "categories": [
    "card"
  ],
  "dependencies": [
    "react-native-reanimated",
    "react-native-svg",
    "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/now-playing.tsx",
      "type": "registry:file",
      "target": "~/components/kinetik/now-playing.tsx",
      "content": "import { useEffect, useRef, useState } from 'react';\nimport {\n  Image,\n  Platform,\n  Pressable,\n  StyleSheet,\n  Text,\n  View,\n  type GestureResponderEvent,\n  type ImageSourcePropType,\n  type StyleProp,\n  type ViewStyle,\n} from 'react-native';\nimport Animated, {\n  Easing,\n  cancelAnimation,\n  useAnimatedStyle,\n  useSharedValue,\n  withSequence,\n  withSpring,\n  withTiming,\n  type SharedValue,\n} from 'react-native-reanimated';\nimport Svg, { Path } from 'react-native-svg';\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 { gradient } from '../../lib/kinetik/tokens/gradient';\nimport { useKinetikTheme } from '../../lib/kinetik/tokens/theme';\nimport { palettes, withAlpha } from '../../lib/kinetik/tokens/tokens';\n\nexport type NowPlayingTrack = {\n  id: string;\n  title: string;\n  /** Line under the title: the artist, or the piece. */\n  subtitle: string;\n  cover: ImageSourcePropType;\n  /** Length in seconds. */\n  duration: number;\n};\n\nexport type NowPlayingProps = {\n  tracks: readonly NowPlayingTrack[];\n  /** Start playing at once. Defaults to false. Ignored when `playing` is set. */\n  autoPlay?: boolean;\n  /** Whether it plays, owned by your app. Leave unset to let the player keep its own state. */\n  playing?: boolean;\n  /**\n   * Seconds into the current track, reported by your audio engine. Setting it turns the\n   * player's own clock off: the bar and the time follow this value.\n   */\n  position?: number;\n  /** The id of the current track, owned by your app (say, after a skip from the lock screen). */\n  trackId?: string;\n  /** Called with the track that starts. */\n  onTrackChange?: (track: NowPlayingTrack) => void;\n  onPlayingChange?: (playing: boolean) => void;\n  /** Called with the seconds to jump to when the bar is tapped, stepped or Previous restarts. */\n  onSeek?: (seconds: number) => void;\n  /** Colour of the progress and the play button. Defaults to amber orange. */\n  accent?: string;\n  /** A tick on each control. Defaults to true. */\n  haptics?: boolean;\n  style?: StyleProp<ViewStyle>;\n};\n\n// Player icons from Tabler Icons (MIT, https://tabler.io/icons), via iconstack.io.\nconst ICONS = {\n  play: 'M7 4v16l13 -8z',\n  pause:\n    'M6 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z M14 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z',\n  next: 'M3 5v14l8 -7z M14 5v14l8 -7z',\n  prev: 'M21 5v14l-8 -7z M10 5v14l-8 -7z',\n};\n\nconst SERIF = Platform.select({ ios: 'Georgia', android: 'serif', default: 'Georgia, serif' });\n\n/** \"1:09\" for elapsed time. */\nexport function clock(seconds: number, pad = false): string {\n  const s = Math.max(0, Math.floor(seconds));\n  const m = Math.floor(s / 60);\n  return `${pad ? String(m).padStart(2, '0') : m}:${String(s % 60).padStart(2, '0')}`;\n}\n\n/**\n * Playback state for a single track: a 0–1 progress shared value that runs\n * on the UI thread while playing, and the elapsed seconds as text (updated a\n * few times a second, never per frame). Given a `position`, the own clock is\n * off and the bar follows the reported seconds instead.\n */\nfunction usePlayback(\n  duration: number,\n  playing: boolean,\n  track: string,\n  onEnd: () => void,\n  position?: number,\n) {\n  const controlled = position !== undefined;\n  const progress = useSharedValue(0);\n  const [elapsed, setElapsed] = useState(0);\n  const [seeks, setSeeks] = useState(0);\n  const ended = useRef(onEnd);\n  useEffect(() => {\n    ended.current = onEnd;\n  });\n\n  // A new track starts from the top: the readout resets during render, the bar in an effect.\n  const [current, setCurrent] = useState(track);\n  if (current !== track) {\n    setCurrent(track);\n    setElapsed(0);\n  }\n  useEffect(() => {\n    cancelAnimation(progress);\n    progress.set(0);\n  }, [track, progress]);\n\n  useEffect(() => {\n    if (controlled || !playing || duration <= 0) {\n      cancelAnimation(progress);\n      return;\n    }\n    const from = progress.get();\n    progress.set(\n      withTiming(1, { duration: Math.max(0, (1 - from) * duration * 1000), easing: Easing.linear }),\n    );\n    const id = setInterval(() => {\n      const p = progress.get();\n      setElapsed(Math.floor(p * duration));\n      if (p >= 1) ended.current();\n    }, 250);\n    return () => {\n      clearInterval(id);\n      cancelAnimation(progress);\n    };\n  }, [controlled, playing, duration, track, seeks, progress]);\n\n  // Driven from outside: glide to each reported position, so sparse updates still read smoothly.\n  useEffect(() => {\n    if (position === undefined || duration <= 0) return;\n    const p = Math.max(0, Math.min(1, position / duration));\n    progress.set(withTiming(p, { duration: 250, easing: Easing.linear }));\n  }, [position, duration, track, progress]);\n\n  /** Moves the bar at once and returns the seconds to jump to. */\n  const seek = (share: number) => {\n    const p = Math.max(0, Math.min(1, share));\n    cancelAnimation(progress);\n    progress.set(p);\n    if (!controlled) {\n      setElapsed(Math.floor(p * duration));\n      setSeeks((n) => n + 1);\n    }\n    // Whole milliseconds, so a ten-second step reports 59, not 58.99999.\n    return Math.round(p * duration * 1000) / 1000;\n  };\n\n  const shown =\n    position === undefined ? elapsed : Math.floor(Math.max(0, Math.min(duration, position)));\n  return { progress, elapsed: shown, seek };\n}\n\n/**\n * A dark now-playing widget: the cover glows into the card, the title is set\n * in a serif, and the progress runs on the UI thread. Play springs the cover\n * forward and morphs the icon; skipping slides the next cover in.\n */\nexport function NowPlaying({\n  tracks,\n  autoPlay = false,\n  playing: playingProp,\n  position,\n  trackId,\n  onTrackChange,\n  onPlayingChange,\n  onSeek,\n  accent = 'hsl(28, 96%, 54%)',\n  haptics = true,\n  style,\n}: NowPlayingProps) {\n  const { radius, space, font } = useKinetikTheme();\n  // A dark widget on either theme, like a lock-screen player.\n  const colors = palettes.dark;\n  const reduced = useReduceMotion();\n  const haptic = useHaptic(haptics);\n  const [ownIndex, setOwnIndex] = useState(0);\n  const [ownPlaying, setOwnPlaying] = useState(autoPlay);\n  const [width, setWidth] = useState(0);\n  const [barWidth, setBarWidth] = useState(0);\n  // Each of these is the app's when it passes the prop, the player's own otherwise.\n  const picked = trackId === undefined ? -1 : tracks.findIndex((t) => t.id === trackId);\n  const index = picked >= 0 ? picked : ownIndex;\n  const playing = playingProp ?? ownPlaying;\n  const track = tracks[index];\n\n  const go = (to: number) => {\n    const next = (to + tracks.length) % tracks.length;\n    if (trackId === undefined) setOwnIndex(next);\n    const t = tracks[next];\n    if (t) onTrackChange?.(t);\n  };\n  const { progress, elapsed, seek } = usePlayback(\n    track?.duration ?? 0,\n    playing,\n    track?.id ?? '',\n    () => go(index + 1),\n    position,\n  );\n  const seekTo = (share: number) => {\n    const seconds = seek(share);\n    onSeek?.(seconds);\n  };\n\n  const lift = useSharedValue(playing ? 1 : 0);\n  useEffect(() => {\n    lift.set(reduced ? (playing ? 1 : 0) : withSpring(playing ? 1 : 0, spring('bouncy')));\n  }, [playing, reduced, lift]);\n  const swap = useSharedValue(1);\n  useEffect(() => {\n    if (reduced) return;\n    swap.set(withSequence(withTiming(0, { duration: 0 }), withTiming(1, timing('slow'))));\n  }, [index, reduced, swap]);\n\n  const art = useAnimatedStyle(() => ({\n    opacity: 0.35 + swap.get() * 0.65,\n    transform: [\n      { translateX: (1 - swap.get()) * 18 },\n      { scale: (0.94 + lift.get() * 0.06) * (0.96 + swap.get() * 0.04) },\n    ],\n  }));\n  const words = useAnimatedStyle(() => ({\n    opacity: swap.get(),\n    transform: [{ translateY: (1 - swap.get()) * 8 }],\n  }));\n  // A transform, not a width, so the bar never asks for layout while it plays.\n  const fill = useAnimatedStyle(() => ({ transform: [{ scaleX: progress.get() }] }));\n\n  if (!track) return null;\n  const cover = width > 0 ? Math.min(150, width * 0.38) : 120;\n\n  const toggle = () => {\n    haptic('tap');\n    if (playingProp === undefined) setOwnPlaying(!playing);\n    onPlayingChange?.(!playing);\n  };\n  const back = () => {\n    haptic('tick');\n    if (elapsed > 3) seekTo(0);\n    else go(index - 1);\n  };\n  const ahead = () => {\n    haptic('tick');\n    go(index + 1);\n  };\n\n  return (\n    <View\n      onLayout={(e) => setWidth(e.nativeEvent.layout.width)}\n      style={[\n        styles.card,\n        {\n          borderRadius: radius.xl + 4,\n          padding: space[4],\n          gap: space[5],\n          borderColor: colors.border,\n        },\n        gradient(\n          `linear-gradient(105deg, hsl(30, 32%, 20%) 0%, ${colors.background} 48%, ${colors.background} 100%)`,\n        ),\n        style,\n      ]}\n    >\n      <Animated.View\n        style={[\n          styles.cover,\n          {\n            width: cover,\n            height: cover,\n            borderRadius: radius.xl - 6,\n            boxShadow: '0px 10px 30px hsla(30, 40%, 30%, 0.45)',\n          },\n          art,\n        ]}\n      >\n        <Image\n          source={track.cover}\n          style={StyleSheet.absoluteFill}\n          resizeMode=\"cover\"\n          accessibilityIgnoresInvertColors\n        />\n      </Animated.View>\n\n      <View style={[styles.grow, { gap: space[4] }]}>\n        <Animated.View\n          style={words}\n          accessible\n          accessibilityLabel={`${track.title}, ${track.subtitle}`}\n        >\n          <Text\n            numberOfLines={1}\n            style={{\n              color: colors.highlight,\n              fontFamily: SERIF,\n              fontSize: font.size['2xl'],\n              fontWeight: font.weight.bold,\n            }}\n          >\n            {track.title}\n          </Text>\n          <Text numberOfLines={1} style={{ color: colors.textMuted, fontSize: font.size.sm + 1 }}>\n            {track.subtitle}\n          </Text>\n        </Animated.View>\n\n        <View style={{ gap: 8 }}>\n          <Pressable\n            accessibilityRole=\"adjustable\"\n            accessibilityLabel=\"Playback position\"\n            accessibilityValue={{\n              min: 0,\n              max: track.duration,\n              now: elapsed,\n              text: `${clock(elapsed)} of ${clock(track.duration)}`,\n            }}\n            accessibilityActions={[{ name: 'increment' }, { name: 'decrement' }]}\n            onAccessibilityAction={(e) => {\n              const step = 10 / track.duration;\n              const now = elapsed / track.duration;\n              seekTo(now + (e.nativeEvent.actionName === 'increment' ? step : -step));\n            }}\n            onLayout={(e) => setBarWidth(e.nativeEvent.layout.width)}\n            onPress={(e: GestureResponderEvent) =>\n              barWidth > 0 && seekTo(e.nativeEvent.locationX / barWidth)\n            }\n            style={styles.barHit}\n          >\n            <View style={[styles.bar, { backgroundColor: withAlpha(colors.text, 0.16) }]}>\n              <Animated.View style={[styles.barFill, { backgroundColor: accent }, fill]} />\n            </View>\n          </Pressable>\n          <View style={styles.times}>\n            <Text style={[styles.time, { color: colors.textMuted }]}>{clock(elapsed)}</Text>\n            <Text style={[styles.time, { color: colors.textMuted }]}>\n              -{clock(track.duration - elapsed, true)}\n            </Text>\n          </View>\n        </View>\n\n        <View style={[styles.controls, { gap: space[2] }]}>\n          <Control label=\"Previous\" icon={ICONS.prev} onPress={back} tone={colors.surfaceRaised} />\n          <PlayButton playing={playing} onPress={toggle} tone={accent} />\n          <Control label=\"Next\" icon={ICONS.next} onPress={ahead} tone={colors.surfaceRaised} />\n        </View>\n      </View>\n    </View>\n  );\n}\n\nfunction Control({\n  label,\n  icon,\n  onPress,\n  tone,\n}: {\n  label: string;\n  icon: string;\n  onPress: () => void;\n  tone: string;\n}) {\n  const ink = palettes.dark.highlight;\n  return (\n    <Pressable\n      accessibilityRole=\"button\"\n      accessibilityLabel={label}\n      onPress={onPress}\n      style={({ pressed }) => [\n        styles.button,\n        { backgroundColor: tone, transform: [{ scale: pressed ? 0.94 : 1 }] },\n      ]}\n    >\n      <Svg width={18} height={18} viewBox=\"0 0 24 24\">\n        <Path d={icon} fill={ink} stroke={ink} strokeWidth={2} strokeLinejoin=\"round\" />\n      </Svg>\n    </Pressable>\n  );\n}\n\n/** Play and pause cross-fade and turn, so the icon seems to morph. */\nfunction PlayButton({\n  playing,\n  onPress,\n  tone,\n}: {\n  playing: boolean;\n  onPress: () => void;\n  tone: string;\n}) {\n  const reduced = useReduceMotion();\n  const on = useSharedValue(playing ? 1 : 0);\n  useEffect(() => {\n    on.set(reduced ? (playing ? 1 : 0) : withSpring(playing ? 1 : 0, spring('snappy')));\n  }, [playing, reduced, on]);\n  return (\n    <Pressable\n      accessibilityRole=\"button\"\n      accessibilityLabel={playing ? 'Pause' : 'Play'}\n      onPress={onPress}\n      style={({ pressed }) => [\n        styles.button,\n        { backgroundColor: tone, transform: [{ scale: pressed ? 0.94 : 1 }] },\n      ]}\n    >\n      <Glyph icon={ICONS.play} on={on} show={0} />\n      <Glyph icon={ICONS.pause} on={on} show={1} />\n    </Pressable>\n  );\n}\n\nfunction Glyph({ icon, on, show }: { icon: string; on: SharedValue<number>; show: 0 | 1 }) {\n  const ink = palettes.dark.highlight;\n  const style = useAnimatedStyle(() => {\n    const v = show ? on.get() : 1 - on.get();\n    return {\n      opacity: v,\n      transform: [{ scale: 0.6 + v * 0.4 }, { rotate: `${(1 - v) * (show ? -90 : 90)}deg` }],\n    };\n  });\n  return (\n    <Animated.View style={[styles.glyph, style]}>\n      <Svg width={18} height={18} viewBox=\"0 0 24 24\">\n        <Path d={icon} fill={ink} stroke={ink} strokeWidth={2} strokeLinejoin=\"round\" />\n      </Svg>\n    </Animated.View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  card: { flexDirection: 'row', alignItems: 'center', borderWidth: 1, overflow: 'hidden' },\n  cover: { overflow: 'hidden' },\n  grow: { flex: 1, minWidth: 0 },\n  // 44 pt to touch, with the extra height taken back so the bar keeps its place.\n  barHit: { height: 44, marginVertical: -13, justifyContent: 'center' },\n  bar: { height: 6, borderRadius: 3, overflow: 'hidden' },\n  barFill: { height: 6, width: '100%', transformOrigin: 'left center' },\n  times: { flexDirection: 'row', justifyContent: 'space-between' },\n  time: { fontSize: 13, fontVariant: ['tabular-nums'] },\n  controls: { flexDirection: 'row' },\n  button: {\n    flex: 1,\n    height: 44,\n    borderRadius: 12,\n    alignItems: 'center',\n    justifyContent: 'center',\n  },\n  glyph: { position: 'absolute' },\n});\n"
    }
  ],
  "meta": {
    "version": "1.1.0",
    "kind": "component",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "category": "card",
    "web": "live",
    "perf": {
      "budget": "Progress is one UI-thread timing per track; the time labels re-render four times a second while playing. Paused, nothing animates.",
      "measurements": [
        {
          "device": "Pixel 9 emulator, API 35",
          "kind": "emulator",
          "date": "2026-10-14",
          "build": "release",
          "frameMs": 17,
          "p90Ms": 21,
          "baselineMs": 17,
          "jankyPercent": 0.75,
          "atRest": "idle",
          "memoryMb": 174
        }
      ]
    },
    "a11y": {
      "reducedMotion": "Play, pause and skipping change state without the cover spring, slide or icon turn.",
      "screenReader": "Title and subtitle read as one line; the progress is adjustable (\"1:09 of 3:43\", ten-second steps); Previous, Play/Pause and Next are buttons.",
      "touchTarget": "Buttons are 44 pt tall; the progress bar's touch area is 44 pt tall."
    },
    "requires": "React Native New Architecture (Reanimated 4)",
    "guide": "## Usage\n\n```tsx\nimport { NowPlaying } from '@/components/kinetik/now-playing';\n\n<NowPlaying\n  tracks={queue.map((t) => ({\n    id: t.id,\n    title: t.title,\n    subtitle: t.artist,\n    cover: { uri: t.artwork },\n    duration: t.seconds,\n  }))}\n  onTrackChange={(t) => player.load(t.id)}\n  onPlayingChange={(on) => (on ? player.play() : player.pause())}\n/>;\n```\n\n### With a real audio engine\n\nPass `playing`, `position` and `trackId` from your player, and the widget follows it instead of keeping its own clock. Buffering, a seek from the lock screen or a skip from headphones then shows up as it happens.\n\n```tsx\nconst { playing, position, trackId } = usePlayerState(); // from your audio library\n\n<NowPlaying\n  tracks={tracks}\n  playing={playing}\n  position={position}\n  trackId={trackId}\n  onPlayingChange={(on) => (on ? player.play() : player.pause())}\n  onTrackChange={(t) => player.skipTo(t.id)}\n  onSeek={(seconds) => player.seekTo(seconds)}\n/>;\n```\n\n## When to use\n\n- A compact player for a queue: a widget, a mini player or a now-playing sheet header.\n\n## When not to use\n\n- When people need to scrub precisely, say through podcasts or audiobooks: the bar seeks on a tap, not a drag.\n\n## Notes\n\n- Without `position` it keeps its own clock, which is fine for a preview or a demo. With real audio, pass `position` so the audio engine stays the source of truth. Updates a few times a second are enough: the bar glides between them.\n- Each of `playing`, `position` and `trackId` is optional and independent. Whatever you leave unset, the widget keeps on its own.\n- `onSeek` fires for a tap on the bar, a screen-reader step and Previous restarting the track.\n\n- Previous restarts the track if more than three seconds have played, as most players do; otherwise it goes back a track.\n- Tap the progress bar to seek. Screen readers adjust it in ten-second steps.\n- On its own clock, when a track ends the next one starts. The queue wraps around.\n- `clock(seconds)` is exported for the same `1:09` format elsewhere.\n- The widget is dark on both themes. `accent` colours the progress and the play button.\n"
  },
  "docs": "Prefer `npx kinetik-ui add now-playing`: it installs dependencies with expo install, so versions match your Expo SDK."
}
