{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ball",
  "title": "useBall",
  "description": "The travelling ball: a round body that charges toward its destination, springs across and squashes against the wall it lands on (the Switch thumb physics for dots, thumbs, carets and rails).",
  "dependencies": [
    "motion"
  ],
  "devDependencies": [],
  "registryDependencies": [
    "https://reactmotionkit.com/r/motion-presets.json"
  ],
  "files": [
    {
      "path": "lib/ball.ts",
      "content": "\"use client\"\n\nimport {\n  animate,\n  type MotionValue,\n  type Transition,\n  useMotionValue,\n  useTransform,\n} from \"motion/react\"\nimport { useCallback, useEffect, useState } from \"react\"\n\nimport { type MotionTokens, springParams } from \"@/lib/motion\"\n\n/**\n * The travelling ball (\"la pallina\"), the first shape of the MotionKit shape language\n * (docs/plan/SHAPE-LANGUAGE.md). A round body rests on one of several stops; when\n * the person moves it, it charges (stretches from the side it rests on toward where\n * it will go), is thrown on the temperament's spring, and instead of overshooting\n * the track its overshoot becomes a squash against the wall it lands on, with part of\n * its volume kept so it reads as soft. Then it settles round. The Switch thumb is the\n * reference: this hook is that thumb's physics, for radio dots, slider thumbs, OTP\n * carets, pagination, stepper markers and sidebar rails.\n */\n\n/*\n * The temperament's squash is a fraction of an element's size. A ball is tiny\n * (8-28px), so the charge stretch is that amount amplified: about 6% calm, 20%\n * lively and 44% playful of the ball's width.\n */\nexport const CHARGE_STRETCH = 4\n\n/*\n * Wall squash stops at about a third of the ball's width: past that a small circle\n * stops reading as a soft ball and starts reading as broken.\n */\nexport const MAX_WALL_SQUASH = 0.35\n\n/*\n * Volume is only partly kept while flattening (exact preservation would be 1 + v):\n * the full bulge looks like the ball inflating, 0.6 of it reads as soft.\n */\nexport const WALL_BULGE = 0.6\n\n/*\n * A kick throws the ball at its own stop so the squash happens without travel (a status\n * dot on change, a thumb tapped in place). Velocity in ball widths per second: at 8 the\n * lively spring overshoots a 20px ball by about 3px, a 15% squash; the calm spring, with\n * no bounce, still shows a short press against the wall.\n */\nexport const KICK_WIDTHS_PER_SECOND = 8\n\n/**\n * The one wall-squash law of the shape language: a round body (a ball, or the tip of a pill\n * that is a ball) pressed `overflow` px past its wall flattens by that fraction of its `size`,\n * up to `MAX_WALL_SQUASH`. The kept volume bulges across by `impact * WALL_BULGE`.\n */\nexport function wallImpact(overflow: number, size: number) {\n  if (overflow <= 0 || size <= 0) return 0\n  return Math.min(overflow / size, MAX_WALL_SQUASH)\n}\n\n/**\n * A spring that honours a starting `velocity`, for a kick in place. Motion ignores the velocity\n * of a time-defined spring (`visualDuration` and `bounce`, the shape of every `useMotionKit`\n * token) and settles a spring with no distance at once, so a ball kicked at its own stop on a\n * token never moves. This is the same spring as physics (`springParams`, the token's duration is\n * already time-scaled), so the velocity carries it past the stop and the overshoot squashes.\n * Opt-in: `useBall().kick` and `throwTo` still pass the token as is.\n */\nexport function kickTransition(transition: Transition, velocity: number): Transition {\n  const { type, visualDuration, bounce } = transition as {\n    type?: unknown\n    visualDuration?: unknown\n    bounce?: unknown\n  }\n  if (type !== \"spring\" || typeof visualDuration !== \"number\") return { ...transition, velocity }\n  const physics = springParams(visualDuration, typeof bounce === \"number\" ? bounce : 0)\n  return { type: \"spring\", ...physics, velocity }\n}\n\nexport type Wall = 0 | 1\n\nexport interface BallOptions {\n  /** Where the ball should rest, in px from the first wall (0) along the axis. */\n  target: number\n  /** Distance between the two walls as the ball's center travels, in px. `target` is clamped to it. */\n  travel: number\n  /** Diameter of the ball, in px: squash is a fraction of it. */\n  size: number\n  /** Resolved motion tokens of the component (`useMotionKit(temperament)`). */\n  motion: MotionTokens\n  /**\n   * Spring that throws the ball. Defaults to `motion.springSmall`, the right weight for\n   * thumbs and dots; pass `motion.spring` for a ball that travels a long rail.\n   */\n  transition?: Transition\n  /**\n   * Where the overshoot becomes a squash. `walls` (default): only at the two ends of the\n   * rail, as a switch thumb does; the ball may overshoot a middle stop freely. `stop`: at\n   * every stop, so a radio dot, a sidebar marker or a stepper ball squashes against the\n   * item it lands on, from the side it arrives from.\n   */\n  squashOn?: \"walls\" | \"stop\"\n}\n\nexport interface BallPose {\n  /** Scale along the travel axis (`scaleX` for a horizontal ball). */\n  along: number\n  /** Scale across the travel axis (`scaleY` for a horizontal ball). */\n  across: number\n}\n\nexport interface Ball {\n  /** Clamped position along the axis, in px. Bind it to `x` (or `y`). */\n  position: MotionValue<number>\n  /**\n   * Raw spring value: it may overshoot the walls, the overshoot is what squashes. While\n   * dragging, stop the spring once (`raw.stop()`) and drive it by hand (`raw.set(px)`); the\n   * next `target` change springs from wherever it is.\n   */\n  raw: MotionValue<number>\n  /** Scale along the axis while squashed against a wall (1 at rest, down to 0.65). */\n  wallAlong: MotionValue<number>\n  /** Scale across the axis while squashed: the kept volume bulges (1 at rest, up to 1.21). */\n  wallAcross: MotionValue<number>\n  /** The wall the ball is travelling toward: the transform origin of the wall squash. */\n  wall: Wall\n  /** True between `charge()` and `release()`. */\n  charged: boolean\n  /** The side the ball rested on when charged: the transform origin of the charge stretch. */\n  anchor: Wall\n  /**\n   * Pose for the ball's body while charged: wider toward the travel direction, a touch\n   * flatter. Round again after release. Animate it with `motion.springSmall`.\n   */\n  chargePose: BallPose\n  /** Charge beat: call on pointer down or Space/Enter down. `toward` defaults to the far wall. */\n  charge: (toward?: Wall) => void\n  /** End of the charge beat: call on pointer up, leave, cancel, key up and blur. */\n  release: () => void\n  /**\n   * Throws the ball against the wall it rests on without travelling (a status dot on\n   * change). `toward` is the wall it hits: 1 for the far one. Needs `squashOn: \"stop\"` for\n   * a ball resting on a middle stop.\n   */\n  kick: (toward?: Wall) => void\n  /**\n   * Releases the ball toward its target with a starting velocity in px/s (a drawer or a\n   * slider thumb let go mid-drag): the spring carries the throw and the overshoot squashes.\n   */\n  throwTo: (velocity: number) => void\n}\n\n/**\n * Physics of the travelling ball. Returns motion values to bind on two nested layers:\n * the mover (`position`), the wall-squash layer (`wallAlong`, `wallAcross`, origin at\n * `wall`) and, inside it, the body that takes `chargePose` (origin at `anchor`).\n */\nexport function useBall({\n  target,\n  travel,\n  size,\n  motion,\n  transition,\n  squashOn = \"walls\",\n}: BallOptions): Ball {\n  const clampedTarget = Math.min(Math.max(target, 0), travel)\n  const raw = useMotionValue(clampedTarget)\n\n  /*\n   * The wall it travels toward: where the overshoot, and so the squash, happens. It is\n   * derived in the same render as the new target (React's \"adjust state while rendering\"),\n   * never in an effect: the transforms below read it on the trip's first frame, and a stale\n   * direction would draw the ball already at the new stop, fully squashed, for one frame.\n   */\n  const [trip, setTrip] = useState<{ target: number; wall: Wall }>(() => ({\n    target: clampedTarget,\n    wall: clampedTarget > travel / 2 ? 1 : 0,\n  }))\n  let wall = trip.wall\n  // NaN never equals itself: a target without a value must not set state on every render.\n  if (clampedTarget !== trip.target && !Number.isNaN(clampedTarget)) {\n    wall = clampedTarget > trip.target ? 1 : 0\n    setTrip({ target: clampedTarget, wall })\n  }\n\n  // In `stop` mode the stop it lands on is the wall: nothing is drawn past it.\n  const stopAt = squashOn === \"stop\" ? clampedTarget : wall === 1 ? travel : 0\n  const position = useTransform(raw, (v) => {\n    const clamped = Math.min(Math.max(v, 0), travel)\n    if (squashOn !== \"stop\") return clamped\n    return wall === 1 ? Math.min(clamped, stopAt) : Math.max(clamped, stopAt)\n  })\n  const impact = useTransform(raw, (v) => {\n    const overflow =\n      squashOn === \"stop\"\n        ? wall === 1\n          ? Math.max(0, v - stopAt)\n          : Math.max(0, stopAt - v)\n        : v > travel\n          ? v - travel\n          : v < 0\n            ? -v\n            : 0\n    return wallImpact(overflow, size)\n  })\n  const wallAlong = useTransform(impact, (v) => 1 - v)\n  const wallAcross = useTransform(impact, (v) => 1 + v * WALL_BULGE)\n  const [charged, setCharged] = useState(false)\n  const [anchor, setAnchor] = useState<Wall>(wall)\n\n  const spring = transition ?? motion.springSmall\n  useEffect(() => {\n    const controls = animate(raw, clampedTarget, spring)\n    return () => {\n      controls.stop()\n    }\n  }, [clampedTarget, raw, spring])\n\n  const charge = useCallback(\n    (toward?: Wall) => {\n      // It stretches away from the side it rests on, toward where it will go.\n      const resting: Wall = raw.get() > travel / 2 ? 1 : 0\n      setAnchor(toward === undefined ? resting : toward === 1 ? 0 : 1)\n      setCharged(true)\n    },\n    [raw, travel],\n  )\n  const release = useCallback(() => {\n    setCharged(false)\n  }, [])\n\n  const kick = useCallback(\n    (toward: Wall = wall) => {\n      if (motion.reduced) return\n      const velocity = (toward === 1 ? 1 : -1) * size * KICK_WIDTHS_PER_SECOND\n      animate(raw, clampedTarget, { ...spring, velocity })\n    },\n    [raw, clampedTarget, spring, size, wall, motion.reduced],\n  )\n\n  const throwTo = useCallback(\n    (velocity: number) => {\n      animate(raw, clampedTarget, motion.reduced ? spring : { ...spring, velocity })\n    },\n    [raw, clampedTarget, spring, motion.reduced],\n  )\n\n  const stretch = motion.values.squash * CHARGE_STRETCH\n  const chargePose: BallPose = charged\n    ? { along: 1 + stretch, across: 1 - motion.values.squash }\n    : { along: 1, across: 1 }\n\n  return {\n    position,\n    raw,\n    wallAlong,\n    wallAcross,\n    wall,\n    charged,\n    anchor,\n    chargePose,\n    charge,\n    release,\n    kick,\n    throwTo,\n  }\n}\n\nexport type BallAxis = \"x\" | \"y\"\n\n/** `chargePose` as Motion scale props for a horizontal (`x`) or vertical (`y`) ball. */\nexport function ballScale(pose: BallPose, axis: BallAxis) {\n  return axis === \"x\"\n    ? { scaleX: pose.along, scaleY: pose.across }\n    : { scaleX: pose.across, scaleY: pose.along }\n}\n\n/** Position of stop `index` among `count` equal stops along a `travel` long rail. */\nexport function stopPosition(index: number, count: number, travel: number) {\n  if (count <= 1) return 0\n  return (travel / (count - 1)) * Math.min(Math.max(index, 0), count - 1)\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Hop: a jump in place that lands on a stop\n * -----------------------------------------------------------------------------------------------*/\n\n/*\n * `kick` throws the ball at its own wall on `springSmall`: at lively it peaks in about 60 ms and\n * comes back with about 1% of squash, so no 80 ms frame shows a raised hand or a landing. A hop is\n * air time plus damped landing lobes, and the lobe that goes below the landing height is drawn with\n * the one wall law (`wallImpact`), never as travel. Pure functions: the component binds the height\n * to its own motion values.\n */\n\n/*\n * Air time as a share of the temperament's perceived duration: a 12 px hop that reads as a hop,\n * not a float (0.34 s at lively, peak near 170 ms, so an 80 ms frame grid always catches it up).\n */\nexport const HOP_AIR_SHARE = 0.85\n/*\n * Each landing lobe lasts 40% of the perceived duration (160 ms at lively): any 80 ms frame grid\n * lands inside the landing squash at least once, past 70% of its depth.\n */\nexport const HOP_LOBE_SHARE = 0.4\n/*\n * Landing squash as a multiple of the temperament's squash: 5% is invisible on a 48 px ball; 3.5x\n * gives 17.5% at lively and reaches the wall cap at playful. None at calm (no overshoot).\n */\nexport const HOP_SQUASH_GAIN = 3.5\n/* Three lobes: the squash, a small rebound, the settle. */\nconst HOP_LOBES = 3\n\nexport interface Hop {\n  /** Highest point of the jump, px above the ground. */\n  apex: number\n  /** Landing height, px above the ground (a raised stop). */\n  rest: number\n  /** Seconds in the air. */\n  air: number\n  /** Seconds of each landing lobe. */\n  lobe: number\n  /** Depth of the first lobe below `rest`, px: the overflow that becomes the squash. */\n  depth: number\n  bounce: number\n  lobes: number\n}\n\nexport interface HopOptions {\n  /** Diameter of the ball, px. */\n  size: number\n  /** Highest point, px above the ground. */\n  apex: number\n  /** Where it lands, px above the ground. */\n  rest: number\n}\n\n/** A hop for the temperament (time scale included); no landing squash at calm or reduced. */\nexport function hopOf(motion: MotionTokens, { size, apex, rest }: HopOptions): Hop {\n  const d = motion.seconds(motion.values.duration)\n  const squash =\n    motion.values.overshoot > 0\n      ? Math.min(motion.values.squash * HOP_SQUASH_GAIN, MAX_WALL_SQUASH)\n      : 0\n  return {\n    apex,\n    rest,\n    air: HOP_AIR_SHARE * d,\n    lobe: HOP_LOBE_SHARE * d,\n    depth: squash * size,\n    bounce: motion.values.bounce,\n    lobes: squash > 0 ? HOP_LOBES : 0,\n  }\n}\n\n/** Total seconds of a hop, air and lobes. */\nexport const hopDuration = (hop: Hop) => hop.air + hop.lobes * hop.lobe\n\n/**\n * Height above the ground `t` s after take-off from `from` px: a parabola from `from` to `rest`\n * whose top is `apex`, then lobes around `rest` (the first one dips below it: that is the squash).\n */\nexport function hopHeight(hop: Hop, from: number, t: number) {\n  if (t < hop.air) {\n    const u = Math.max(0, t) / hop.air\n    const lift = Math.max(0, 4 * (hop.apex - (from + hop.rest) / 2))\n    return from + (hop.rest - from) * u + lift * u * (1 - u)\n  }\n  const after = t - hop.air\n  const k = Math.floor(after / hop.lobe)\n  if (k >= hop.lobes) return hop.rest\n  const phase = (after - k * hop.lobe) / hop.lobe\n  const amp = hop.depth * Math.pow(hop.bounce, k)\n  return hop.rest + (k % 2 === 0 ? -1 : 1) * amp * Math.sin(Math.PI * phase)\n}\n\n/** The squash of a ball at `height` over a floor at `floor`: the wall law. */\nexport const hopImpact = (height: number, floor: number, size: number) =>\n  wallImpact(floor - height, size)\n",
      "type": "registry:lib"
    }
  ],
  "meta": {
    "tier": "free",
    "collection": "interface",
    "needsImage": false,
    "addedAt": "2026-10-16",
    "tags": [
      "shape",
      "ball",
      "spring",
      "squash"
    ],
    "tech": [],
    "presets": [],
    "keyboard": [],
    "heavy": false
  },
  "categories": [
    "internal"
  ],
  "type": "registry:lib"
}