{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"effort-slider-01","title":"Effort Slider","description":"A model-effort picker: a stepped slider whose thumb is pulled toward the nearest level and springs onto it, with a cross-fading level name, a recommended mark and a pixel field that lights the track at the top level.","dependencies":["@base-ui/react","cn"],"files":[{"path":"registry/blocks/effort-slider-01/components/effort-slider.tsx","content":"\"use client\"\n\nimport * as React from \"react\"\nimport { useDirection } from \"@base-ui/react/direction-provider\"\nimport { Slider as SliderPrimitive } from \"@base-ui/react/slider\"\n\nimport { cn } from \"cn\"\n\nimport { drawPixelField } from \"@/registry/blocks/effort-slider-01/lib/pixel-field\"\n\nconst defaultLevels = [\"Low\", \"Medium\", \"High\", \"Extra\", \"Max\", \"Ultra\"]\n\nconst clamp = (value: number, last: number) =>\n  Math.min(last, Math.max(0, value))\n\nconst revealAt = (elapsed: number) => {\n  const t = Math.min(1, elapsed / 1000)\n  return t * t * (3 - 2 * t)\n}\n\nconst prefersReducedMotion = () =>\n  window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n\nconst stepAt = (index: number, last: number) =>\n  `calc(var(--thumb) / 2 + (100% - var(--thumb)) * ${index / last})`\n\nconst keyTargets: Record<\n  string,\n  (level: number, last: number, rtl: boolean) => number\n> = {\n  ArrowLeft: (level, _, rtl) => (rtl ? level + 1 : level - 1),\n  ArrowDown: (level) => level - 1,\n  PageDown: (level) => level - 1,\n  ArrowRight: (level, _, rtl) => (rtl ? level - 1 : level + 1),\n  ArrowUp: (level) => level + 1,\n  PageUp: (level) => level + 1,\n  Home: () => 0,\n  End: (_, last) => last,\n}\n\nconst DETENT_RADIUS = 0.45\nconst DETENT_PULL = 0.9\n\nfunction detent(value: number) {\n  const level = Math.round(value)\n  const offset = value - level\n  const closeness = 1 - Math.abs(offset) / DETENT_RADIUS\n  if (closeness <= 0) return value\n  return level + offset * (1 - DETENT_PULL * closeness * closeness)\n}\n\nconst SPRING_FREQUENCY = 30\nconst SPRING_DAMPING_RATIO = 0.65\nconst MAX_SPEED = 8\nconst MAX_OFFSET = 0.49\nconst SPEED_SMOOTHING = 0.5\n\nfunction springOffset(offset: number, speed: number, t: number) {\n  const decay = SPRING_DAMPING_RATIO * SPRING_FREQUENCY\n  const frequency = SPRING_FREQUENCY * Math.sqrt(1 - SPRING_DAMPING_RATIO ** 2)\n  return (\n    Math.exp(-decay * t) *\n    (offset * Math.cos(frequency * t) +\n      ((speed + decay * offset) / frequency) * Math.sin(frequency * t))\n  )\n}\n\nfunction useSnappingValue(initial: number, last: number) {\n  const [value, setValue] = React.useState(initial)\n  const current = React.useRef(initial)\n  const motion = React.useRef({ speed: 0, time: 0 })\n  const frame = React.useRef(0)\n\n  React.useEffect(() => () => cancelAnimationFrame(frame.current), [])\n\n  const set = React.useCallback((next: number) => {\n    current.current = next\n    setValue(next)\n  }, [])\n\n  const drag = (raw: number) => {\n    cancelAnimationFrame(frame.current)\n    const next = detent(raw)\n    const now = performance.now()\n    const seconds = (now - motion.current.time) / 1000\n    const instant =\n      seconds > 0 && seconds < 0.1 ? (next - current.current) / seconds : 0\n    motion.current = {\n      speed:\n        motion.current.speed +\n        (instant - motion.current.speed) * SPEED_SMOOTHING,\n      time: now,\n    }\n    set(next)\n  }\n\n  const jump = React.useCallback(\n    (target: number) => {\n      cancelAnimationFrame(frame.current)\n      motion.current = { speed: 0, time: 0 }\n      set(target)\n    },\n    [set]\n  )\n\n  const release = () => {\n    const target = Math.round(current.current)\n    const offset = current.current - target\n    const idle = performance.now() - motion.current.time > 100\n    const speed = idle\n      ? 0\n      : Math.max(-MAX_SPEED, Math.min(MAX_SPEED, motion.current.speed))\n    motion.current = { speed: 0, time: 0 }\n    if (prefersReducedMotion() || (Math.abs(offset) < 0.001 && !speed)) {\n      set(target)\n      return target\n    }\n    const start = performance.now()\n    const step = (time: number) => {\n      const t = (time - start) / 1000\n      const now = springOffset(offset, speed, t)\n      const settled =\n        Math.abs(now) < 0.001 && Math.exp(-SPRING_FREQUENCY * t) < 0.01\n      if (settled) {\n        set(target)\n        return\n      }\n      set(\n        clamp(target + Math.max(-MAX_OFFSET, Math.min(MAX_OFFSET, now)), last)\n      )\n      frame.current = requestAnimationFrame(step)\n    }\n    frame.current = requestAnimationFrame(step)\n    return target\n  }\n\n  return { value, drag, jump, release }\n}\n\nconst LevelName = React.memo(function LevelName({\n  levels,\n  level,\n}: {\n  levels: string[]\n  level: number\n}) {\n  const [shown, setShown] = React.useState({\n    level,\n    leaving: null as number | null,\n    rising: true,\n  })\n  if (shown.level !== level) {\n    setShown({ level, leaving: shown.level, rising: level > shown.level })\n  }\n\n  return (\n    <span\n      className={cn(\n        \"relative inline-grid transition-colors duration-200\",\n        level === levels.length - 1 && \"text-primary\"\n      )}\n    >\n      {levels.map((name) => (\n        <span key={name} aria-hidden className=\"invisible [grid-area:1/1]\">\n          {name}\n        </span>\n      ))}\n      {shown.leaving !== null && (\n        <span\n          key={`leaving-${shown.leaving}-${shown.level}`}\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute inset-0 animate-out duration-150 fill-mode-forwards fade-out motion-reduce:hidden\",\n            shown.rising ? \"slide-out-to-top-1\" : \"slide-out-to-bottom-1\"\n          )}\n          onAnimationEnd={() =>\n            setShown((state) => ({ ...state, leaving: null }))\n          }\n        >\n          {levels[shown.leaving]}\n        </span>\n      )}\n      <span\n        key={shown.level}\n        className={cn(\n          \"absolute inset-0\",\n          shown.leaving !== null &&\n            cn(\n              \"animate-in duration-150 fade-in motion-reduce:animate-none\",\n              shown.rising ? \"slide-in-from-bottom-1\" : \"slide-in-from-top-1\"\n            )\n        )}\n      >\n        {levels[level]}\n      </span>\n    </span>\n  )\n})\n\nconst StepMarks = React.memo(function StepMarks({\n  levels,\n  recommended,\n  hidden,\n}: {\n  levels: string[]\n  recommended?: number\n  hidden: boolean\n}) {\n  const rtl = useDirection() === \"rtl\"\n\n  return levels.map((name, index) => (\n    <span\n      key={name}\n      aria-hidden\n      className={cn(\n        \"pointer-events-none absolute top-1/2 -translate-y-1/2 transition-opacity duration-200\",\n        rtl ? \"translate-x-1/2\" : \"-translate-x-1/2\",\n        hidden && \"opacity-0\"\n      )}\n      style={{ insetInlineStart: stepAt(index, levels.length - 1) }}\n    >\n      {index === recommended ? (\n        <span className=\"block h-3 w-[3px] rounded-xs bg-foreground/30\" />\n      ) : (\n        <span className=\"block size-1 rounded-full bg-foreground/30\" />\n      )}\n    </span>\n  ))\n})\n\nconst PixelField = React.memo(function PixelField({\n  active,\n}: {\n  active: boolean\n}) {\n  const ref = React.useRef<HTMLCanvasElement>(null)\n  const rtl = useDirection() === \"rtl\"\n\n  React.useEffect(() => {\n    const canvas = ref.current\n    if (!canvas || !active) return\n    canvas.getContext(\"2d\")?.clearRect(0, 0, canvas.width, canvas.height)\n    const reduced = prefersReducedMotion()\n    const style = getComputedStyle(canvas)\n    const draw = (elapsed: number, reveal: number) => {\n      drawPixelField(canvas, { elapsed, reveal, color: style.color })\n    }\n    const resize = () => {\n      const ratio = Math.min(window.devicePixelRatio || 1, 2)\n      const width = Math.round(canvas.clientWidth * ratio)\n      const height = Math.round(canvas.clientHeight * ratio)\n      if (canvas.width !== width || canvas.height !== height) {\n        canvas.width = width\n        canvas.height = height\n      }\n      if (reduced) draw(0, 1)\n    }\n    resize()\n    const observer = new ResizeObserver(resize)\n    observer.observe(canvas)\n\n    const started = performance.now()\n    let frame = 0\n    if (!reduced) {\n      let drawnAt = 0\n      const loop = (time: number) => {\n        if (time - drawnAt >= 33) {\n          drawnAt = time\n          const elapsed = time - started\n          draw(elapsed, revealAt(elapsed))\n        }\n        frame = requestAnimationFrame(loop)\n      }\n      frame = requestAnimationFrame(loop)\n    }\n    return () => {\n      cancelAnimationFrame(frame)\n      observer.disconnect()\n    }\n  }, [active])\n\n  return (\n    <canvas\n      ref={ref}\n      aria-hidden\n      className={cn(\n        \"pointer-events-none absolute inset-0 size-full [mask-image:linear-gradient(to_right,transparent,black_70%)] text-primary transition-opacity duration-200\",\n        rtl && \"-scale-x-100\",\n        active ? \"opacity-100\" : \"opacity-0\"\n      )}\n    />\n  )\n})\n\ntype EffortSliderProps = Omit<React.ComponentProps<\"div\">, \"onChange\"> & {\n  /** Level names, lowest first. The last one lights the track. */\n  levels?: string[]\n  /** Index of the selected level, when controlled. */\n  value?: number\n  /** Index of the level the picker starts on. */\n  defaultValue?: number\n  /** Index of the level marked as recommended on the track. */\n  recommended?: number\n  /** Called with the level's index when the thumb settles on another level. */\n  onValueChange?: (level: number) => void\n  label?: string\n  minLabel?: string\n  maxLabel?: string\n}\n\nfunction EffortSlider({\n  className,\n  levels = defaultLevels,\n  value: controlled,\n  defaultValue = 2,\n  recommended = 1,\n  onValueChange,\n  label = \"Effort\",\n  minLabel = \"Faster\",\n  maxLabel = \"Smarter\",\n  ...props\n}: EffortSliderProps) {\n  const last = levels.length - 1\n  const initial = clamp(Math.round(controlled ?? defaultValue), last)\n  const { value, drag, jump, release } = useSnappingValue(initial, last)\n  const level = clamp(Math.round(value), last)\n  const top = level === last\n  const rtl = useDirection() === \"rtl\"\n\n  const settled = React.useRef(initial)\n  const [settleCount, setSettleCount] = React.useState(0)\n  const settle = (target: number) => {\n    if (settled.current === target) return\n    settled.current = target\n    onValueChange?.(target)\n    setSettleCount((count) => count + 1)\n  }\n\n  React.useEffect(() => {\n    if (controlled === undefined) return\n    const target = clamp(Math.round(controlled), last)\n    if (settled.current === target) return\n    settled.current = target\n    jump(target)\n  }, [controlled, last, jump, settleCount])\n\n  return (\n    <div\n      data-slot=\"effort-slider\"\n      className={cn(\n        \"flex w-72 flex-col gap-4 rounded-4xl bg-card p-5 text-sm shadow-2xs ring-1 ring-border [--thumb:--spacing(5)]\",\n        className\n      )}\n      {...props}\n    >\n      <div className=\"flex items-center gap-1.5 text-base font-medium\">\n        <span className=\"text-muted-foreground\">{label}</span>\n        <LevelName levels={levels} level={level} />\n      </div>\n      <div className=\"flex flex-col gap-2\">\n        <div aria-hidden className=\"flex justify-between text-muted-foreground\">\n          <span>{minLabel}</span>\n          <span>{maxLabel}</span>\n        </div>\n        <SliderPrimitive.Root\n          value={[value]}\n          onValueChange={(next, { reason }) => {\n            const raw = Array.isArray(next) ? next[0] : next\n            if (reason !== \"input-change\") return drag(raw)\n            const nearest = clamp(Math.round(raw), last)\n            const target =\n              nearest !== level\n                ? nearest\n                : clamp(level + Math.sign(raw - value), last)\n            jump(target)\n            settle(target)\n          }}\n          onValueCommitted={() => settle(release())}\n          min={0}\n          max={last}\n          step={0.001}\n          thumbAlignment=\"edge\"\n        >\n          <SliderPrimitive.Control className=\"relative flex h-6 w-full cursor-ew-resize touch-none items-center select-none\">\n            <SliderPrimitive.Track className=\"relative size-full overflow-hidden rounded-sm bg-fill-2\">\n              <SliderPrimitive.Indicator\n                className={cn(\n                  \"box-content h-full rounded-sm bg-fill-4 pr-[calc(var(--thumb)/2)] transition-opacity duration-200\",\n                  top && \"opacity-0\"\n                )}\n              />\n              <PixelField active={top} />\n              <StepMarks\n                levels={levels}\n                recommended={recommended}\n                hidden={top}\n              />\n            </SliderPrimitive.Track>\n            <SliderPrimitive.Thumb\n              aria-label={label}\n              getAriaValueText={(_, thumbValue) => {\n                const index = Math.round(thumbValue)\n                return index === recommended\n                  ? `${levels[index]}, recommended`\n                  : levels[index]\n              }}\n              onKeyDown={(event) => {\n                const target = keyTargets[event.key]\n                if (!target) return\n                event.preventDefault()\n                event.stopPropagation()\n                const next = clamp(target(level, last, rtl), last)\n                jump(next)\n                settle(next)\n              }}\n              className=\"z-10 h-6 w-(--thumb) rounded-sm bg-white shadow-md ring-1 ring-black/10 transition-[scale,box-shadow] duration-200 select-none not-dark:bg-clip-padding hover:ring-4 hover:ring-ring/30 active:scale-[0.96] has-focus-visible:ring-4 has-focus-visible:ring-ring/30\"\n            />\n          </SliderPrimitive.Control>\n        </SliderPrimitive.Root>\n      </div>\n    </div>\n  )\n}\n\nexport { EffortSlider, type EffortSliderProps }\n","type":"registry:component"},{"path":"registry/blocks/effort-slider-01/lib/pixel-field.ts","content":"export type PixelFieldFrame = {\n  /** Milliseconds since the field appeared. */\n  elapsed: number\n  /** 0 → 1: how far the field has swept in from the right edge. */\n  reveal: number\n  color: string\n}\n\nconst ROWS = 7\nconst GAP = 0.25\nconst ROUNDING = 0.3\n\nconst REST = 0.7\nconst FLARE = 0.8\nconst BAND = 0.5\nconst DIMS = [\n  { opacity: 0.5, weight: 3 },\n  { opacity: 0.4, weight: 2 },\n  { opacity: 0.3, weight: 3 },\n  { opacity: 0.2, weight: 3 },\n]\nconst DIM_WEIGHT = DIMS.reduce((sum, dim) => sum + dim.weight, 0)\n\nconst CYCLE_MIN = 600\nconst CYCLE_MAX = 2000\nconst DIM_CHANCE = 0.85\nconst FLARE_CHANCE = 0.1\nconst EVENT_LENGTH = 0.25\n\nconst BAND_SLOT = 5\nconst BAND_CHANCE = 0.1\nconst BAND_STEP_MS = 4000\n\nconst SWEEP_EDGE = 0.15\n\nfunction noise(a: number, b: number, c = 0) {\n  let h = Math.imul(a | 0, 0x27d4eb2d) ^ Math.imul(b | 0, 0x165667b1)\n  h = Math.imul(h ^ Math.imul(c | 0, 0x9e3779b1), 0x85ebca6b)\n  h ^= h >>> 13\n  h = Math.imul(h, 0xc2b2ae35)\n  h ^= h >>> 16\n  return (h >>> 0) / 4294967296\n}\n\nconst easeInOut = (t: number) => t * t * (3 - 2 * t)\n\nfunction cellOpacity(column: number, row: number, elapsed: number) {\n  const length = CYCLE_MIN + noise(column, row, 1) * (CYCLE_MAX - CYCLE_MIN)\n  const time = elapsed + noise(column, row, 2) * length\n  const cycle = Math.floor(time / length)\n  const position = (time % length) / length\n\n  const roll = noise(column, row, 100 + cycle)\n  const start = noise(column, row, 200 + cycle) * (1 - EVENT_LENGTH)\n  const inEvent = position >= start && position < start + EVENT_LENGTH\n  const depth = inEvent\n    ? 1 - Math.abs(((position - start) / EVENT_LENGTH) * 2 - 1)\n    : 0\n\n  if (depth > 0 && roll < FLARE_CHANCE) return depth > 0.2 ? FLARE : REST\n  if (depth > 0 && roll < FLARE_CHANCE + DIM_CHANCE) {\n    let pick = noise(column, row, 300 + cycle) * DIM_WEIGHT\n    const target = DIMS.find((dim) => (pick -= dim.weight) < 0) ?? DIMS[0]\n    const steps = Math.round((REST - target.opacity) * 10)\n    const reached = Math.ceil(Math.min(1, depth * 2) * steps)\n    return Math.min(BAND, REST - reached / 10)\n  }\n  return REST\n}\n\nfunction inBand(column: number, row: number, elapsed: number) {\n  const steps = elapsed / BAND_STEP_MS\n  const offset = Math.floor(steps) + easeInOut(steps % 1)\n  const slot = Math.floor(column / BAND_SLOT + offset)\n  return noise(slot, row, 400) < BAND_CHANCE\n}\n\nfunction fillCell(\n  context: CanvasRenderingContext2D,\n  x: number,\n  y: number,\n  size: number\n) {\n  if (!context.roundRect) return context.fillRect(x, y, size, size)\n  context.beginPath()\n  context.roundRect(x, y, size, size, size * ROUNDING)\n  context.fill()\n}\n\nexport function drawPixelField(\n  canvas: HTMLCanvasElement,\n  { elapsed, reveal, color }: PixelFieldFrame\n) {\n  const context = canvas.getContext(\"2d\")\n  if (!context || !canvas.width || !canvas.height) return\n  const ratio = canvas.width / canvas.clientWidth || 1\n  const width = canvas.clientWidth\n  const height = canvas.clientHeight\n  context.setTransform(ratio, 0, 0, ratio, 0, 0)\n  context.clearRect(0, 0, width, height)\n  context.fillStyle = color\n\n  const pitch = height / ROWS\n  const gap = pitch * GAP\n  const size = pitch - gap\n  const columns = Math.ceil(width / pitch)\n  const edge = 1 - reveal * (1 + SWEEP_EDGE)\n\n  for (let row = 0; row < ROWS; row += 1) {\n    for (let column = 0; column < columns; column += 1) {\n      const along = (column + 0.5) / columns\n      const swept = Math.min(1, Math.max(0, (along - edge) / SWEEP_EDGE))\n      if (swept === 0) continue\n\n      let opacity = cellOpacity(column, row, elapsed)\n      if (opacity === REST && inBand(column, row, elapsed)) opacity = BAND\n      const alpha = Math.round(opacity * swept * 10) / 10\n      if (alpha === 0) continue\n\n      context.globalAlpha = alpha\n      fillCell(context, column * pitch + gap / 2, row * pitch + gap / 2, size)\n    }\n  }\n  context.globalAlpha = 1\n}\n","type":"registry:lib"}],"cssVars":{"theme":{"color-fill-2":"var(--fill-2)","color-fill-4":"var(--fill-4)","text-sm--letter-spacing":"-0.005em"},"light":{"fill-2":"oklch(0.556 0 0 / 8%)","fill-4":"oklch(0.556 0 0 / 16%)"},"dark":{"fill-2":"oklch(1 0 0 / 10%)","fill-4":"oklch(1 0 0 / 18%)"}},"meta":{"kind":"block","pro":false,"iframeHeight":360},"categories":["ai"],"type":"registry:block"}