{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "vintage-slider",
  "title": "Vintage Slider",
  "author": "Visant Labs <visantsupply@gmail.com>",
  "description": "Fader de console com curso e trilho gravados.",
  "registryDependencies": [
    "@visant/vintage-theme",
    "utils",
    "@visant/sfx-bus"
  ],
  "files": [
    {
      "path": "registry/vintage/ui/vintage-slider.tsx",
      "content": "\"use client\";\n\nimport { useState, useRef, useEffect, useCallback } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { playSfx } from \"@/lib/sfx-bus\";\n\ninterface VintageSliderProps {\n  label?: string;\n  min?: number;\n  max?: number;\n  value?: number;\n  accent?: string;\n  fmt?: (v: number) => string;\n  onChange?: (value: number) => void;\n  /**\n   * Aperta a caixa pra ~56px: rótulo, leitura e trilho continuam, só a régua\n   * min/max de baixo sai (os limites não mudam de um fader pro vizinho).\n   *\n   * Existe porque o rig nasceu para uma bancada larga, com poucos controles\n   * grandes. Num painel de parâmetros — dez ou quinze sliders empilhados numa\n   * coluna de 300px — a folga do rig vira rolagem, e o operador perde de vista\n   * metade dos controles que precisa comparar entre si.\n   *\n   * A LARGURA não é assunto desta prop: `cn` roda tailwind-merge, então\n   * `className=\"w-full\"` já ganha do w-[220px] padrão.\n   */\n  dense?: boolean;\n  className?: string;\n}\n\nexport function VintageSlider({\n  label = \"GAIN\",\n  min = 0,\n  max = 10,\n  value = 5,\n  accent,\n  fmt,\n  onChange,\n  dense = false,\n  className,\n}: VintageSliderProps) {\n  const [currentValue, setCurrentValue] = useState(value);\n  const [dragging, setDragging] = useState(false);\n  const [hover, setHover] = useState(false);\n  const trackRef = useRef<HTMLDivElement>(null);\n  const fillRef = useRef<HTMLDivElement>(null);\n  const thumbRef = useRef<HTMLDivElement>(null);\n  const valRef = useRef(currentValue);\n  valRef.current = currentValue;\n  /** Estalo a cada 1/20 do curso, só quando a mão move (nunca por prop). */\n  const passoSom = useRef<number | null>(null);\n  const estalarRef = useRef<(v: number) => void>(() => {});\n  const estalar = (v: number) => {\n    const passo = Math.round(((v - min) / (max - min)) * 20);\n    if (passoSom.current !== null && passo !== passoSom.current) playSfx(\"detent\");\n    passoSom.current = passo;\n  };\n  estalarRef.current = estalar;\n\n  useEffect(() => {\n    if (value !== valRef.current) setCurrentValue(value);\n  }, [value]);\n\n  /**\n   * O punho e a faixa são escritos no DOM na mão, dentro de um rAF.\n   *\n   * O relato era \"lag ao arrastar\", e a causa estava em dois lugares somados.\n   * O primeiro é o culpado óbvio, e era deliberado: `transition-[width]` e\n   * `transition-[left]` de 75ms no punho. Uma transição num valor que o dedo\n   * está ditando não suaviza nada — ela atrasa o desenho em 75ms fixos, e o\n   * punho passa o arraste inteiro correndo atrás do cursor. Some no arraste,\n   * volta quando o valor chega de fora (roda, duplo clique, prop).\n   *\n   * O segundo é o caminho do estado: cada `pointermove` disparava um render do\n   * componente E do dono do estado — no painel de dez faders da vitrine, um\n   * fader arrastado repintava os outros nove. Aqui o movimento escreve pixel\n   * direto e junta as amostras do frame num rAF só; o estado é atualizado uma\n   * vez por frame, para o número embaixo do trilho.\n   */\n  const pendente = useRef<{ x: number; fine: boolean } | null>(null);\n  const frame = useRef(0);\n\n  const pintar = useCallback((pct: number) => {\n    if (fillRef.current) fillRef.current.style.width = `${pct}%`;\n    if (thumbRef.current) thumbRef.current.style.left = `calc(${pct}% - 7px)`;\n  }, []);\n\n  const update = useCallback(\n    (clientX: number, fine: boolean) => {\n      const r = trackRef.current?.getBoundingClientRect();\n      if (!r) return;\n      const raw = (clientX - r.left) / r.width;\n      const pct = Math.max(0, Math.min(1, raw));\n      const v = min + pct * (max - min);\n      const snapped = fine\n        ? Math.round(v * 100) / 100\n        : Math.round(v * 10) / 10;\n      valRef.current = snapped;\n      pintar(((snapped - min) / (max - min)) * 100);\n      estalarRef.current(snapped);\n      setCurrentValue(snapped);\n      onChange?.(snapped);\n    },\n    [min, max, onChange, pintar]\n  );\n\n  const agendar = useCallback(\n    (clientX: number, fine: boolean) => {\n      pendente.current = { x: clientX, fine };\n      if (frame.current) return;\n      frame.current = requestAnimationFrame(() => {\n        frame.current = 0;\n        const p = pendente.current;\n        pendente.current = null;\n        if (p) update(p.x, p.fine);\n      });\n    },\n    [update]\n  );\n\n  useEffect(\n    () => () => {\n      if (frame.current) cancelAnimationFrame(frame.current);\n    },\n    []\n  );\n\n  // Pointer events com captura, e não listener de mouse no `document`.\n  //\n  // O motivo é um bug que aparece no primeiro arraste: sem `preventDefault` no\n  // mousedown o browser começa uma SELEÇÃO DE TEXTO junto, e arrastar o slider\n  // vai pintando de azul tudo que o cursor cruza. A captura resolve o outro\n  // lado do mesmo problema — os eventos continuam chegando aqui mesmo com o\n  // cursor fora do trilho, sem precisar ouvir o documento inteiro.\n  //\n  // É o mesmo desenho que o `scrub-input` já usa, e de quebra o controle passa\n  // a funcionar no toque, que o caminho de mouse nunca cobriu.\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.pointerType === \"mouse\" && e.button !== 0) return;\n    e.preventDefault();\n    e.currentTarget.setPointerCapture(e.pointerId);\n    setDragging(true);\n    passoSom.current = Math.round(((valRef.current - min) / (max - min)) * 20);\n    update(e.clientX, e.shiftKey);\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (dragging) agendar(e.clientX, e.shiftKey);\n  };\n\n  const endDrag = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.currentTarget.hasPointerCapture(e.pointerId)) {\n      e.currentTarget.releasePointerCapture(e.pointerId);\n    }\n    setDragging(false);\n  };\n\n  const handleWheel = (e: React.WheelEvent) => {\n    e.stopPropagation();\n    const step = e.shiftKey ? (max - min) * 0.002 : (max - min) * 0.01;\n    const dir = e.deltaY < 0 ? 1 : -1;\n    const next = Math.max(min, Math.min(max, currentValue + dir * step));\n    if (passoSom.current === null) estalar(currentValue);\n    estalar(next);\n    setCurrentValue(next);\n    onChange?.(next);\n  };\n\n  /*\n   * Teclado: o slider era só do ponteiro. Seta = 1% (Shift = 0,2%, o mesmo\n   * fino da roda), Page = 10%, Home/End = limites.\n   */\n  const handleKeyDown = (e: React.KeyboardEvent) => {\n    const faixa = max - min;\n    const passo = e.shiftKey ? faixa * 0.002 : faixa * 0.01;\n    let next: number | null = null;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowUp\") next = currentValue + passo;\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowDown\") next = currentValue - passo;\n    else if (e.key === \"PageUp\") next = currentValue + faixa * 0.1;\n    else if (e.key === \"PageDown\") next = currentValue - faixa * 0.1;\n    else if (e.key === \"Home\") next = min;\n    else if (e.key === \"End\") next = max;\n    if (next === null) return;\n    e.preventDefault();\n    e.stopPropagation();\n    next = Math.max(min, Math.min(max, next));\n    if (passoSom.current === null) estalar(currentValue);\n    estalar(next);\n    setCurrentValue(next);\n    onChange?.(next);\n  };\n\n  const handleDoubleClick = () => {\n    const mid = (min + max) / 2;\n    setCurrentValue(mid);\n    onChange?.(mid);\n  };\n\n  const percentage = ((currentValue - min) / (max - min)) * 100;\n  const cor = accent || \"var(--vintage-light)\";\n  const leitura = fmt ? fmt(currentValue) : currentValue.toFixed(1);\n  const gravado = \"var(--vintage-engrave)\";\n\n  return (\n    <div\n      className={cn(\n        // `select-none` no container inteiro: o rótulo e a faixa min/max ficam\n        // no caminho do arraste, e texto selecionável ali é o que faz o\n        // controle \"piscar azul\" enquanto o usuário mexe nele.\n        \"relative w-[220px] select-none rounded-[var(--r-control,10px)]\",\n        dense ? \"px-3 py-2\" : \"px-4 py-3\",\n        className\n      )}\n      onMouseEnter={() => setHover(true)}\n      onMouseLeave={() => setHover(false)}\n      onWheel={handleWheel}\n      onDoubleClick={handleDoubleClick}\n      title={`${label}: ${leitura}\narraste · shift = fino · roda · duplo clique = centro`}\n      style={{\n        // O painel do kit: chapa escura, luz de cima, sombra que fecha embaixo.\n        background: \"linear-gradient(180deg, var(--vintage-surface-3), var(--vintage-surface-2))\",\n        border: \"1px solid var(--vintage-surface-1)\",\n        boxShadow:\n          \"var(--vintage-panel-shadow)\",\n      }}\n    >\n      {/* Rótulo e leitura na mesma linha: o número fica onde o olho já está. */}\n      <div\n        className={cn(\n          \"flex items-baseline justify-between font-vintage-mono\",\n          dense ? \"mb-1\" : \"mb-2\"\n        )}\n      >\n        <span\n          className=\"text-[10px] font-semibold uppercase tracking-[0.18em]\"\n          style={{\n            color: hover || dragging ? \"var(--vintage-label)\" : \"var(--vintage-text-muted)\",\n            textShadow: gravado,\n            transition: \"color var(--dur-fast,160ms) var(--ease-out,ease)\",\n          }}\n        >\n          {label}\n        </span>\n        <span className=\"text-[11px] tabular-nums\" style={{ color: \"var(--vintage-value)\" }}>\n          {leitura}\n        </span>\n      </div>\n\n      <div\n        ref={trackRef}\n        className={cn(\n          // `touch-pan-y`: o arraste de lado é do slider, e em pé a página continua rolando.\n          \"relative cursor-ew-resize touch-pan-y rounded-[4px] outline-none pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-2.5\",\n          \"focus-visible:[box-shadow:var(--focus,0_0_0_2px_var(--vintage-value))]\",\n          dense ? \"h-6\" : \"h-8\"\n        )}\n        tabIndex={0}\n        role=\"slider\"\n        aria-label={label}\n        aria-valuemin={min}\n        aria-valuemax={max}\n        aria-valuenow={Number(currentValue.toFixed(2))}\n        aria-valuetext={leitura}\n        onKeyDown={handleKeyDown}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={endDrag}\n        onPointerCancel={endDrag}\n      >\n        {/* Régua serigrafada: onze traços, o do meio maior. */}\n        <div className=\"pointer-events-none absolute inset-x-[7px] top-0 flex h-full justify-between\">\n          {Array.from({ length: 11 }, (_, i) => (\n            <span\n              key={i}\n              className=\"w-px\"\n              style={{\n                height: i === 5 ? \"100%\" : i % 5 === 0 ? \"80%\" : \"45%\",\n                marginTop: \"auto\",\n                marginBottom: \"auto\",\n                background: \"var(--vintage-text-muted)\",\n                opacity: i % 5 === 0 ? 0.55 : 0.3,\n              }}\n            />\n          ))}\n        </div>\n\n        {/* O rasgo na chapa, e a faixa acesa dentro dele. */}\n        <div\n          className=\"absolute inset-x-0 top-1/2 h-[6px] -translate-y-1/2 overflow-hidden rounded-full\"\n          style={{\n            background: \"var(--vintage-surface-1)\",\n            boxShadow: \"inset 0 1px 2px rgba(0,0,0,0.9), 0 1px 0 var(--vintage-lip)\",\n          }}\n        >\n          <div\n            ref={fillRef}\n            className=\"h-full rounded-full\"\n            style={{\n              width: `${percentage}%`,\n              background: `linear-gradient(90deg, color-mix(in srgb, ${cor} 35%, transparent), ${cor})`,\n              boxShadow: `0 0 6px color-mix(in srgb, ${cor} 50%, transparent)`,\n              transition: dragging ? \"none\" : \"width 75ms linear\",\n            }}\n          />\n        </div>\n\n        {/* Capa do fader: metal escovado, frisos de pega, sombra pra baixo. */}\n        <div\n          ref={thumbRef}\n          className={cn(\n            \"absolute top-1/2 -translate-y-1/2 w-[14px] rounded-[3px] pointer-events-none\",\n            // O punho continua mais alto que o trilho: é o que dá o alvo de\n            // arraste e a leitura de peça física. Encolhe junto, não some.\n            dense ? \"h-6\" : \"h-8\"\n          )}\n          style={{\n            left: `calc(${percentage}% - 7px)`,\n            transition: dragging ? \"none\" : \"left 75ms linear\",\n            background:\n              \"linear-gradient(90deg, var(--vintage-metal-channel-dark) 0%, var(--vintage-metal-channel-light) 35%, var(--vintage-metal-mid) 65%, var(--vintage-metal-light) 100%)\",\n            boxShadow:\n              \"inset 0 1px 0 rgba(255,255,255,0.55), 0 0 0 1px var(--vintage-edge), 0 3px 4px rgba(0,0,0,0.55)\",\n          }}\n        >\n          <div\n            className=\"absolute inset-y-[5px] left-1/2 w-[2px] -translate-x-1/2\"\n            style={{ background: \"rgba(0,0,0,0.55)\" }}\n          />\n        </div>\n      </div>\n\n      {!dense && (\n        <div className=\"mt-1 flex justify-between font-vintage-mono text-[9px] tabular-nums\">\n          <span style={{ color: \"var(--vintage-text-muted)\" }}>{min}</span>\n          <span style={{ color: \"var(--vintage-text-muted)\" }}>{max}</span>\n        </div>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "uso": {
      "quando": "Fader de console pra volume ou mix em interface de áudio do kit vintage",
      "evite": "Slider de formulário ou produto: elastic-slider ou slosh-slider; simular conta, sim-slider"
    }
  },
  "categories": [
    "controles",
    "audio",
    "fader"
  ],
  "type": "registry:ui"
}