{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "route-profile",
  "title": "Route Profile",
  "author": "Visant Labs <visantsupply@gmail.com>",
  "description": "Perfil de terreno que se lê arrastando: a altitude e a rampa sob o cursor, e um clinômetro cuja agulha balança com a inclinação.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "@visant/use-idle",
    "@visant/use-tilt"
  ],
  "files": [
    {
      "path": "registry/visant/ui/route-profile.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, useMotionValue, useMotionValueEvent, useReducedMotion, useSpring, useTransform } from \"motion/react\";\n\nimport { useIdle, useInView } from \"@/hooks/use-idle\";\nimport { useTilt } from \"@/hooks/use-tilt\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface RouteProfileProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  /** As altitudes da rota, em metros, igualmente espaçadas. */\n  altitudes?: number[];\n  /**\n   * Distância total, em km.\n   * @min 1\n   * @max 200\n   * @step 1\n   */\n  distance?: number;\n  /**\n   * Onde o cursor nasce, de 0 a 1.\n   * @min 0\n   * @max 1\n   * @step 0.01\n   */\n  defaultPosition?: number;\n  /** Sozinho na tela, o cursor passeia até alguém pegar nele. */\n  idle?: boolean;\n  /** Nome do controle para leitor de tela. */\n  label?: string;\n  onPositionChange?: (position: number) => void;\n}\n\n// Rota de exemplo: um relevo liso e determinístico, sem dado de lugar nenhum.\nconst ROTA = Array.from({ length: 121 }, (_, i) => {\n  const t = i / 120;\n  return 620 + 1040 * (0.72 * Math.sin(Math.PI * t) ** 1.4 + (0.16 * (1 + Math.sin(t * 13))) / 2 + (0.1 * (1 + Math.sin(t * 29 + 1))) / 2);\n});\nconst ESCALA = [-20, -10, 0, 10, 20];\nconst inteiro = new Intl.NumberFormat(\"pt-BR\", { maximumFractionDigits: 0 });\nconst limita01 = (v: number) => Math.max(0, Math.min(1, v));\nconst anguloDe = (rampa: number) => Math.max(-62, Math.min(62, (Math.atan(rampa / 100) * 180 * 4) / Math.PI));\n\n/**\n * Perfil de rota: leia o caminho pela forma do terreno, com um clinômetro que balança até\n * a inclinação sob o cursor.\n *\n * - **O relevo é a interface.** Da versão do laboratório saíram paradas nomeadas, a linha\n *   de quilômetro e a de subida restante: rótulo demais. Ficaram a altitude, a rampa e a\n *   agulha, e o resto se lê no desenho.\n * - **A agulha pendura por gravidade.** Mola subamortecida: a rampa se sente antes de se ler.\n * - **Inclinar também anda.** O primeiro toque que termina na peça pede o giroscópio, e inclinar o celular rola\n *   o cursor com inércia. Arrasto e teclado continuam sempre lá.\n * - **O passeio sozinho para de vez** quando alguém pega no cursor, para nunca tirar a\n *   pessoa do ponto que ela escolheu.\n * - **`pan-y` no terreno, e o dedo só mexe no cursor depois de andar de lado.** Sem isso, o\n *   começo de uma rolagem em pé já movia a rota. Toque parado também escolhe, ao soltar.\n * - **Movimento reduzido:** cursor e agulha pousam, sem mola nem passeio.\n */\nexport function RouteProfile({\n  altitudes = ROTA,\n  distance = 18,\n  defaultPosition = 0.2,\n  idle = true,\n  label = \"Posição na rota\",\n  onPositionChange,\n  className,\n  ...rest\n}: RouteProfileProps) {\n  const reduz = useReducedMotion();\n  const caixa = React.useRef<HTMLDivElement>(null);\n  const visivel = useInView(caixa);\n  const dados = React.useMemo(() => {\n    const n = Math.max(altitudes.length - 1, 1);\n    const topo = Math.max(...altitudes);\n    const base = Math.min(...altitudes);\n    const yEm = (a: number) => 0.14 + (0.72 * (topo - a)) / (topo - base || 1);\n    const linha = altitudes.map((a, i) => `${i ? \"L\" : \"M\"}${((i / n) * 320).toFixed(1)} ${(yEm(a) * 120).toFixed(1)}`).join(\" \");\n    return { n, yEm, linha };\n  }, [altitudes]);\n  const rampaEm = React.useCallback(\n    (i: number) => {\n      const a = Math.max(0, i - 1);\n      const b = Math.min(dados.n, i + 1);\n      return (altitudes[b] - altitudes[a]) / (((b - a) * distance) / dados.n) / 10; // m por km → %\n    },\n    [altitudes, dados.n, distance],\n  );\n\n  const bruto = useMotionValue(limita01(defaultPosition));\n  const suave = useSpring(bruto, { stiffness: 260, damping: 32 });\n  const p = reduz ? bruto : suave;\n  const [i, setI] = React.useState(() => Math.round(limita01(defaultPosition) * dados.n));\n  const agulha = useSpring(anguloDe(rampaEm(i)), { stiffness: 120, damping: 9 });\n  const tocado = React.useRef(false);\n  const preso = React.useRef<{ x: number; y: number; decidido: boolean } | null>(null);\n  const gama = React.useRef(0);\n\n  const x = useTransform(p, (v) => `${v * 100}%`);\n  const y = useTransform(p, (v) => `${dados.yEm(altitudes[Math.round(limita01(v) * dados.n)]) * 100}%`);\n  const resto = useTransform(p, (v) => 1 - v);\n\n  useMotionValueEvent(p, \"change\", (v) => {\n    setI(Math.round(limita01(v) * dados.n));\n    onPositionChange?.(limita01(v));\n  });\n  React.useEffect(() => {\n    const a = anguloDe(rampaEm(i));\n    if (reduz) agulha.jump(a);\n    else agulha.set(a);\n  }, [i, reduz, agulha, rampaEm]);\n\n  const giro = useTilt((g) => (gama.current = g));\n  React.useEffect(() => {\n    if (!giro.on || !visivel) return;\n    let raf = 0;\n    let v = 0;\n    const laco = () => {\n      const g = Math.abs(gama.current) < 6 ? 0 : gama.current;\n      v = (v + (g / 30) * 0.0004) * 0.94;\n      if (!preso.current && Math.abs(v) > 0.00001) bruto.set(limita01(bruto.get() + v));\n      raf = requestAnimationFrame(laco);\n    };\n    raf = requestAnimationFrame(laco);\n    return () => cancelAnimationFrame(raf);\n  }, [giro.on, visivel, bruto]);\n\n  const poke = useIdle(\n    caixa,\n    () => {\n      if (!tocado.current) bruto.set((bruto.get() + 0.13) % 1);\n    },\n    2800,\n    idle,\n  );\n  const pegar = () => {\n    tocado.current = true;\n    poke();\n  };\n  const doX = (e: React.PointerEvent) => {\n    const r = e.currentTarget.getBoundingClientRect();\n    bruto.set(limita01((e.clientX - r.left) / r.width));\n  };\n\n  const rampa = rampaEm(i);\n  const km = (i / dados.n) * distance;\n  const sinal = rampa > 0.5 ? \"+\" : rampa < -0.5 ? \"−\" : \"\";\n\n  return (\n    <div ref={caixa} className={cn(\"flex w-full max-w-md flex-col gap-3 text-foreground\", className)} {...rest}>\n      <div className=\"flex items-end justify-between gap-3\">\n        <div className=\"flex min-w-0 items-baseline gap-3\">\n          <span className=\"text-[clamp(1.75rem,8vw,2.5rem)] font-medium leading-none tracking-[-0.02em] tabular-nums [font-family:var(--font-display,inherit)]\">\n            {inteiro.format(altitudes[i])} m\n          </span>\n          <span className=\"text-sm tabular-nums text-muted-foreground\">\n            {sinal}\n            {inteiro.format(Math.abs(rampa))}%\n          </span>\n        </div>\n        <div aria-hidden className=\"relative h-12 w-20 shrink-0 overflow-hidden rounded-t-full border border-b-0 border-border\">\n          {ESCALA.map((g) => (\n            <span key={g} style={{ transform: `rotate(${anguloDe(g)}deg)` }} className=\"absolute bottom-0 left-1/2 h-10 w-px origin-bottom\">\n              <span className={cn(\"absolute left-0 top-0 h-1.5 w-px\", g === 0 ? \"bg-foreground\" : \"bg-muted-foreground\")} />\n            </span>\n          ))}\n          <motion.span style={{ rotate: agulha, x: \"-50%\" }} className=\"absolute bottom-0 left-1/2 h-9 w-0.5 origin-bottom rounded-full bg-foreground\" />\n          <span className=\"absolute -bottom-1 left-1/2 size-2 -translate-x-1/2 rounded-full bg-[var(--brand)] ring-1 ring-foreground\" />\n        </div>\n      </div>\n\n      <div\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-valuemin={0}\n        aria-valuemax={distance}\n        aria-valuenow={Number(km.toFixed(1))}\n        aria-valuetext={`km ${km.toFixed(1)}, ${inteiro.format(altitudes[i])} metros, rampa de ${inteiro.format(rampa)}%`}\n        onPointerDown={(e) => {\n          e.currentTarget.setPointerCapture(e.pointerId);\n          const dedo = e.pointerType === \"touch\";\n          preso.current = { x: e.clientX, y: e.clientY, decidido: !dedo };\n          if (!dedo) {\n            pegar();\n            doX(e);\n          }\n        }}\n        onPointerMove={(e) => {\n          const i = preso.current;\n          if (!i) return;\n          if (!i.decidido) {\n            const dx = Math.abs(e.clientX - i.x);\n            if (dx < 6 || dx < Math.abs(e.clientY - i.y)) return;\n            i.decidido = true;\n            pegar();\n          }\n          doX(e);\n        }}\n        onPointerUp={(e) => {\n          const i = preso.current;\n          preso.current = null;\n          if (e.pointerType !== \"touch\" || !i) return;\n          giro.enable(); // o iOS só concede o sensor num toque que terminou aqui\n          if (!i.decidido) {\n            pegar();\n            doX(e);\n          }\n        }}\n        onPointerCancel={() => (preso.current = null)}\n        onKeyDown={(e) => {\n          const agora = Math.round(bruto.get() * dados.n);\n          const mapa: Record<string, number> = {\n            ArrowRight: agora + 1,\n            ArrowUp: agora + 1,\n            ArrowLeft: agora - 1,\n            ArrowDown: agora - 1,\n            PageUp: agora + 10,\n            PageDown: agora - 10,\n            Home: 0,\n            End: dados.n,\n          };\n          if (!(e.key in mapa)) return;\n          e.preventDefault();\n          pegar();\n          bruto.set(limita01(mapa[e.key] / dados.n));\n        }}\n        className=\"relative h-40 w-full cursor-grab touch-pan-y select-none overflow-hidden rounded-[var(--r-control,0.5rem)] bg-muted outline-none focus-visible:[box-shadow:var(--focus)] active:cursor-grabbing\"\n      >\n        <svg viewBox=\"0 0 320 120\" preserveAspectRatio=\"none\" aria-hidden className=\"absolute inset-0 size-full\">\n          <path d={`${dados.linha} L320 120 L0 120 Z`} className=\"fill-[var(--brand)]\" />\n          <path d={dados.linha} fill=\"none\" strokeWidth=\"2\" vectorEffect=\"non-scaling-stroke\" className=\"stroke-foreground\" />\n        </svg>\n        {/* O que ainda vem fica sob um véu, e só `transform` move o véu. */}\n        <motion.div style={{ scaleX: resto }} className=\"pointer-events-none absolute inset-0 origin-right [background:color-mix(in_srgb,var(--muted)_72%,transparent)]\" />\n        <motion.div style={{ x }} className=\"pointer-events-none absolute inset-0\">\n          <span className=\"absolute inset-y-0 left-0 w-px bg-foreground\" />\n          <motion.span style={{ y }} className=\"absolute inset-0\">\n            <span className=\"absolute left-0 top-0 size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-background bg-foreground\" />\n          </motion.span>\n        </motion.div>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "meta": {
    "uso": {
      "quando": "Mostrar uma rota, trilha ou prova pelo relevo, com leitura ponto a ponto",
      "evite": "Uma série de números sem terreno: streamgraph; só um nível, sem percurso: gauge"
    }
  },
  "categories": [
    "conteudo",
    "rota",
    "grafico",
    "altitude",
    "terreno",
    "clinometro"
  ],
  "type": "registry:ui"
}