{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"line-charts-period-comparison","type":"registry:component","title":"Line charts · Period comparison","description":"This period in solid volt against the last in dashed neutral, the gap shaded, with week, month and quarter tabs that morph both lines together.","author":"GetUrUI <hello@geturui.dev>","dependencies":["motion","lucide-react"],"registryDependencies":[],"files":[{"path":"registry/geturui/examples/line-charts/period-comparison.tsx","type":"registry:component","target":"components/examples/line-charts/period-comparison.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useInView, useReducedMotion } from \"motion/react\";\nimport { TrendingDown, TrendingUp } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface ComparisonPeriod {\n  /** Tab label, e.g. \"Month\". */\n  key: string;\n  /** Point labels, same length as the series. Every period should use the same point count so lines can morph. */\n  labels: string[];\n  current: number[];\n  previous: number[];\n  /** Wording for the comparison, e.g. \"last month\". */\n  previousLabel: string;\n}\n\nexport interface PeriodComparisonChartProps {\n  title?: string;\n  periods?: ComparisonPeriod[];\n  defaultPeriod?: string;\n  formatValue?: (n: number) => string;\n  className?: string;\n}\n\nconst cum = (xs: number[]) => xs.reduce<number[]>((acc, x) => [...acc, (acc[acc.length - 1] ?? 0) + x], []);\nconst PERIODS: ComparisonPeriod[] = [\n  { key: \"Week\", previousLabel: \"last week\", labels: [\"Mon 9a\", \"Mon 6p\", \"Tue 9a\", \"Tue 6p\", \"Wed 9a\", \"Wed 6p\", \"Thu 9a\", \"Thu 6p\", \"Fri 9a\", \"Fri 6p\", \"Sat\", \"Sun\"], current: cum([1.2, 1.6, 1.4, 1.9, 1.5, 2.1, 1.7, 2.4, 1.9, 2.2, 1.1, 0.9]), previous: cum([1.1, 1.3, 1.5, 1.4, 1.6, 1.7, 1.5, 1.9, 1.8, 2.0, 1.2, 1.0]) },\n  { key: \"Month\", previousLabel: \"last month\", labels: [\"Sep 1\", \"Sep 4\", \"Sep 6\", \"Sep 9\", \"Sep 11\", \"Sep 14\", \"Sep 16\", \"Sep 19\", \"Sep 21\", \"Sep 24\", \"Sep 26\", \"Sep 29\"], current: cum([5.2, 6.1, 5.8, 7.4, 6.6, 8.1, 7.2, 7.9, 6.8, 8.6, 7.7, 6.9]), previous: cum([5.6, 5.9, 6.2, 6.4, 6.0, 6.9, 6.5, 7.0, 6.3, 7.1, 6.8, 6.1]) },\n  { key: \"Quarter\", previousLabel: \"last quarter\", labels: [\"W1\", \"W2\", \"W3\", \"W4\", \"W5\", \"W6\", \"W7\", \"W8\", \"W9\", \"W10\", \"W11\", \"W12\"], current: cum([17.4, 18.2, 16.9, 19.6, 21.3, 20.1, 22.4, 21.8, 23.5, 24.2, 22.9, 25.7]), previous: cum([18.1, 18.6, 19.0, 18.4, 19.7, 20.3, 19.9, 20.8, 21.2, 20.6, 21.9, 22.4]) },\n];\n\nfunction niceTop(max: number, count = 4) {\n  const raw = Math.max(max, 1e-6) / count;\n  const mag = 10 ** Math.floor(Math.log10(raw));\n  const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;\n  return Array.from({ length: count + 1 }, (_, i) => i * step);\n}\n\nfunction smooth(pts: [number, number][], move = true) {\n  const f = (n: number) => n.toFixed(2);\n  return pts\n    .map((p, i) => {\n      if (i === 0) return `${move ? \"M\" : \"L\"}${f(p[0])},${f(p[1])}`;\n      const a = pts[i - 2] ?? pts[i - 1];\n      const b = pts[i - 1];\n      const c = pts[i + 1] ?? p;\n      return `C${f(b[0] + (p[0] - a[0]) / 6)},${f(b[1] + (p[1] - a[1]) / 6)} ${f(p[0] - (c[0] - b[0]) / 6)},${f(p[1] - (c[1] - b[1]) / 6)} ${f(p[0])},${f(p[1])}`;\n    })\n    .join(\"\");\n}\n\n/** This period against the last: solid volt vs dashed neutral, the gap between them shaded, period tabs that morph both lines with a spring. */\nexport function PeriodComparisonChart({ title = \"Cumulative bookings\", periods = PERIODS, defaultPeriod = \"Month\", formatValue = (n) => `$${n.toFixed(1)}k`, className }: PeriodComparisonChartProps) {\n  const reduce = useReducedMotion() ?? false;\n  const ref = React.useRef<HTMLDivElement>(null);\n  const inView = useInView(ref, { once: true, margin: \"-40px\" });\n  const uid = React.useId().replace(/[^a-zA-Z0-9_-]/g, \"\");\n  const [key, setKey] = React.useState(defaultPeriod);\n  const [active, setActive] = React.useState<number | null>(null);\n  const p = periods.find((x) => x.key === key) ?? periods[0];\n  const n = p.labels.length;\n\n  const ticks = niceTop(Math.max(...p.current, ...p.previous));\n  const top = ticks[ticks.length - 1] || 1;\n  const xp = (i: number) => (n > 1 ? (i / (n - 1)) * 100 : 50);\n  const yp = (v: number) => (1 - v / top) * 100;\n  const cur = p.current.map((v, i) => [xp(i), yp(v)] as [number, number]);\n  const prev = p.previous.map((v, i) => [xp(i), yp(v)] as [number, number]);\n  const dCur = smooth(cur);\n  const dPrev = smooth(prev);\n  const dGap = `${dCur}${smooth([...prev].reverse(), false)}Z`;\n  const spring = reduce ? { duration: 0 } : { type: \"spring\" as const, stiffness: 180, damping: 28 };\n\n  const total = p.current[n - 1] ?? 0;\n  const before = p.previous[n - 1] ?? 0;\n  const delta = before ? (total - before) / before : 0;\n  const up = delta >= 0;\n\n  function onMove(e: React.PointerEvent<HTMLDivElement>) {\n    const r = e.currentTarget.getBoundingClientRect();\n    setActive(Math.max(0, Math.min(n - 1, Math.round(((e.clientX - r.left) / r.width) * (n - 1)))));\n  }\n  function onKey(e: React.KeyboardEvent) {\n    if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault();\n      setActive((a) => Math.max(0, Math.min(n - 1, (a ?? n - 1) + (e.key === \"ArrowRight\" ? 1 : -1))));\n    } else if (e.key === \"Escape\") setActive(null);\n  }\n\n  const a = active ?? null;\n  const aCur = a !== null ? p.current[a] ?? 0 : 0;\n  const aPrev = a !== null ? p.previous[a] ?? 0 : 0;\n\n  return (\n    <figure className={cn(\"@container w-full rounded-xl border border-border bg-surface-raised p-4 shadow-sm sm:p-5\", className)}>\n      <div className=\"flex flex-wrap items-start justify-between gap-3\">\n        <figcaption>\n          <p className=\"text-[13px] font-medium text-ink-muted\">{title}</p>\n          <p className=\"mt-1 font-display text-[30px] font-semibold leading-none tracking-[-0.8px] tabular-nums text-ink\">{formatValue(total)}</p>\n          <p className=\"mt-2 flex flex-wrap items-center gap-x-1.5 text-[12px]\">\n            <span className={cn(\"inline-flex items-center gap-1 font-semibold\", up ? \"text-success\" : \"text-danger\")}>\n              {up ? <TrendingUp aria-hidden className=\"size-3.5\" /> : <TrendingDown aria-hidden className=\"size-3.5\" />}\n              {up ? \"Ahead\" : \"Behind\"} {Math.abs(delta * 100).toFixed(1)}%\n            </span>\n            <span className=\"text-ink-subtle\">\n              vs {formatValue(before)} {p.previousLabel}\n            </span>\n          </p>\n        </figcaption>\n        <div role=\"group\" aria-label=\"Period\" className=\"flex rounded-full bg-surface p-0.5\">\n          {periods.map((x) => (\n            <button\n              key={x.key}\n              type=\"button\"\n              aria-pressed={x.key === p.key}\n              onClick={() => setKey(x.key)}\n              className={cn(\"relative h-7 rounded-full px-3 text-[12px] font-medium outline-none focus-visible:shadow-[var(--focus-ring)]\", x.key === p.key ? \"text-ink\" : \"text-ink-subtle hover:text-ink\")}\n            >\n              {x.key === p.key && <motion.span layoutId={`${uid}-tab`} transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 420, damping: 32 }} className=\"absolute inset-0 rounded-full bg-surface-raised shadow-sm\" />}\n              <span className=\"relative\">{x.key}</span>\n            </button>\n          ))}\n        </div>\n      </div>\n\n      <div className=\"mt-5 grid grid-cols-[2.75rem_minmax(0,1fr)] gap-x-2\">\n        <div aria-hidden className=\"relative h-48 @md:h-56\">\n          {ticks.map((t, i) => (\n            <span key={i} className=\"absolute right-0 -translate-y-1/2 font-mono text-[10.5px] tabular-nums text-ink-subtle\" style={{ top: `${(1 - i / (ticks.length - 1)) * 100}%` }}>\n              {t ? formatValue(t).replace(\".0k\", \"k\") : \"0\"}\n            </span>\n          ))}\n        </div>\n        <div\n          ref={ref}\n          tabIndex={0}\n          role=\"group\"\n          aria-label={`${title} chart. Use left and right arrow keys to compare each point.`}\n          onPointerMove={onMove}\n          onPointerLeave={() => setActive(null)}\n          onFocus={() => setActive((v) => v ?? n - 1)}\n          onBlur={() => setActive(null)}\n          onKeyDown={onKey}\n          className=\"relative h-48 touch-none rounded-xs outline-none focus-visible:shadow-[var(--focus-ring)] @md:h-56\"\n        >\n          <svg role=\"img\" aria-label={`${title} this ${p.key.toLowerCase()}: ${formatValue(total)}, ${up ? \"up\" : \"down\"} ${Math.abs(delta * 100).toFixed(1)}% on ${p.previousLabel} (${formatValue(before)}).`} viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\" className=\"absolute inset-0 size-full overflow-visible\">\n            <defs>\n              <clipPath id={`${uid}-reveal`}>\n                <motion.rect x={-2} y={-10} height={120} initial={{ width: reduce ? 104 : 0 }} animate={{ width: inView || reduce ? 104 : 0 }} transition={{ duration: reduce ? 0 : 1.2, ease: [0.65, 0, 0.35, 1] }} />\n              </clipPath>\n            </defs>\n            {ticks.map((_, i) => (\n              <line key={i} x1={0} x2={100} y1={(i / (ticks.length - 1)) * 100} y2={(i / (ticks.length - 1)) * 100} className=\"stroke-border\" strokeDasharray={i === ticks.length - 1 ? undefined : \"2 4\"} vectorEffect=\"non-scaling-stroke\" />\n            ))}\n            <g clipPath={`url(#${uid}-reveal)`}>\n              <motion.path initial={false} animate={{ d: dGap }} transition={spring} style={{ fill: \"var(--volt-soft)\" }} />\n              <motion.path initial={false} animate={{ d: dPrev }} transition={spring} fill=\"none\" className=\"stroke-ink-subtle\" strokeWidth={1.75} strokeDasharray=\"5 4\" vectorEffect=\"non-scaling-stroke\" />\n              <motion.path initial={false} animate={{ d: dCur }} transition={spring} fill=\"none\" style={{ stroke: \"var(--volt-ink)\" }} strokeWidth={2.5} strokeLinecap=\"round\" vectorEffect=\"non-scaling-stroke\" />\n            </g>\n            {a !== null && <line x1={xp(a)} x2={xp(a)} y1={0} y2={100} className=\"stroke-ink-subtle\" strokeDasharray=\"3 3\" vectorEffect=\"non-scaling-stroke\" />}\n          </svg>\n\n          {a !== null && (\n            <>\n              <motion.span aria-hidden initial={false} animate={{ left: `${xp(a)}%`, top: `${yp(aPrev)}%` }} transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 520, damping: 38 }} className=\"pointer-events-none absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-ink-subtle bg-surface-raised\" />\n              <motion.span aria-hidden initial={false} animate={{ left: `${xp(a)}%`, top: `${yp(aCur)}%` }} transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 520, damping: 38 }} className=\"pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface-raised bg-volt-ink\" />\n            </>\n          )}\n          <AnimatePresence>\n            {a !== null && (\n              <motion.div\n                key=\"tip\"\n                aria-hidden\n                initial={{ opacity: 0, scale: 0.96, left: `${xp(a)}%` }}\n                animate={{ opacity: 1, scale: 1, left: `${xp(a)}%` }}\n                exit={{ opacity: 0, transition: { duration: 0.1 } }}\n                transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 480, damping: 36 }}\n                style={{ x: xp(a) > 55 ? \"calc(-100% - 12px)\" : \"12px\" }}\n                className=\"pointer-events-none absolute top-1 z-10 min-w-40 rounded-sm border border-border bg-surface-raised px-2.5 py-2 text-xs shadow-md\"\n              >\n                <p className=\"mb-1 font-medium text-ink-muted\">{p.labels[a]}</p>\n                <p className=\"flex justify-between gap-4\">\n                  <span className=\"text-ink-muted\">This {p.key.toLowerCase()}</span>\n                  <span className=\"font-mono font-semibold tabular-nums text-ink\">{formatValue(aCur)}</span>\n                </p>\n                <p className=\"flex justify-between gap-4\">\n                  <span className=\"text-ink-subtle\">Previous</span>\n                  <span className=\"font-mono tabular-nums text-ink-muted\">{formatValue(aPrev)}</span>\n                </p>\n                <p className={cn(\"mt-1 border-t border-border pt-1 text-right font-mono font-semibold tabular-nums\", aCur >= aPrev ? \"text-success\" : \"text-danger\")}>\n                  {aCur >= aPrev ? \"+\" : \"−\"}\n                  {formatValue(Math.abs(aCur - aPrev))}\n                </p>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n        <div />\n        <div aria-hidden className=\"relative mt-2 h-4\">\n          {p.labels.map((l, i) =>\n            i % 3 === 0 || i === n - 1 ? (\n              <span key={i} className={cn(\"absolute whitespace-nowrap font-mono text-[10.5px] text-ink-subtle\", i === 0 ? \"\" : i === n - 1 ? \"-translate-x-full\" : \"-translate-x-1/2\", i === n - 1 && \"hidden @md:block\")} style={{ left: `${xp(i)}%` }}>\n                {l}\n              </span>\n            ) : null,\n          )}\n        </div>\n      </div>\n      <div className=\"mt-3 flex flex-wrap gap-4 text-[12px] text-ink-muted\">\n        <span className=\"inline-flex items-center gap-1.5\">\n          <span aria-hidden className=\"h-[3px] w-4 rounded-full bg-volt-ink\" />\n          This {p.key.toLowerCase()}\n        </span>\n        <span className=\"inline-flex items-center gap-1.5\">\n          <span aria-hidden className=\"w-4 border-t-2 border-dashed border-ink-subtle\" />\n          {p.previousLabel.charAt(0).toUpperCase() + p.previousLabel.slice(1)}\n        </span>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {a !== null ? `${p.labels[a]}: ${formatValue(aCur)} this ${p.key.toLowerCase()}, ${formatValue(aPrev)} ${p.previousLabel}.` : \"\"}\n      </p>\n    </figure>\n  );\n}\n"},{"path":"LICENSE-geturui.md","type":"registry:file","target":"LICENSE-geturui.md","content":"MIT License\n\nCopyright (c) 2026 geturui.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"}],"categories":["examples","chart","line chart","time series","comparison","annotations","tooltip","crosshair","svg"],"meta":{"tier":"free","license":"MIT","docs":"https://geturui.com/docs/line-charts#period-comparison"}}