{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"trend-card","type":"registry:component","title":"Trend Card","description":"A minimal bento card for a key figure: a small label, the latest value and its change, and a smooth chart with a dot and a weekday or month under each value. Point at it to read any value.","dependencies":["framer-motion"],"files":[{"path":"registry/dot/trend-card.tsx","type":"registry:component","target":"components/dot/trend-card.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent } from \"react\";\nimport { animate, useReducedMotion } from \"framer-motion\";\n\nexport interface TrendCardProps {\n  /** The figures to chart, oldest to newest — e.g. seven months of sales */\n  values: number[];\n  /** Small heading, e.g. \"Sales\" */\n  label?: string;\n  /** Names under each point; when omitted they're weekdays from Sunday, or the months ending at `endDate` */\n  labels?: string[];\n  /** What each value covers, for the automatic labels: \"days\" names them Sun, Mon, Tue… */\n  period?: \"days\" | \"months\";\n  /** ISO 4217 code, e.g. \"USD\", \"EUR\", \"INR\" */\n  currency?: string;\n  /** BCP 47 locale for numbers and names, e.g. \"en-US\" */\n  locale?: string;\n  /** Month of the last value when `period` is \"months\"; defaults to today */\n  endDate?: string | Date;\n  /** Line, dots and area colour */\n  accentColor?: string;\n  background?: string;\n  textColor?: string;\n  /** Labels and secondary text */\n  mutedColor?: string;\n  borderColor?: string;\n  /** Chart height in px */\n  chartHeight?: number;\n  /** Corner radius in px */\n  radius?: number;\n  className?: string;\n  style?: CSSProperties;\n}\n\nconst SAMPLES = 120; // the line is drawn from this many samples, so edits morph smoothly\nconst POSITIVE = \"#22C55E\";\nconst NEGATIVE = \"#EF4444\";\n// Inter: the site's next/font Inter when it has one (--font-inter), else Inter from Google Fonts\nconst FONT = 'var(--font-inter, \"Inter\"), system-ui, sans-serif';\n\ntype XY = [number, number];\n\n/** True when the site already ships Inter through next/font, so there's nothing to download */\nconst siteHasInter = () =>\n  [document.documentElement, document.body].some((el) => getComputedStyle(el).getPropertyValue(\"--font-inter\").trim() !== \"\");\n\n// Inter from Google Fonts, once per page, unless the site already has it\nfunction loadInter() {\n  const id = \"dot-google-font-inter\";\n  if (document.getElementById(id) || siteHasInter()) return;\n  const link = document.createElement(\"link\");\n  link.id = id;\n  link.rel = \"stylesheet\";\n  link.href = \"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap\";\n  document.head.appendChild(link);\n}\n\n/** Smooth curve through the values (monotone cubic): no dips or peaks the data doesn't have */\nfunction spline(values: number[]) {\n  const n = values.length;\n  const d = values.slice(1).map((v, i) => v - values[i]);\n  const m = values.map((_, i) => (i === 0 ? d[0] : i === n - 1 ? d[n - 2] : d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2));\n  for (let i = 0; i < n - 1; i++) {\n    if (d[i] === 0) {\n      m[i] = m[i + 1] = 0;\n      continue;\n    }\n    const a = m[i] / d[i];\n    const b = m[i + 1] / d[i];\n    const s = a * a + b * b;\n    if (s > 9) {\n      m[i] = (3 / Math.sqrt(s)) * a * d[i];\n      m[i + 1] = (3 / Math.sqrt(s)) * b * d[i];\n    }\n  }\n  return (u: number) => {\n    const i = Math.min(n - 2, Math.max(0, Math.floor(u)));\n    const t = u - i;\n    const t2 = t * t;\n    const t3 = t2 * t;\n    return (2 * t3 - 3 * t2 + 1) * values[i] + (t3 - 2 * t2 + t) * m[i] + (-2 * t3 + 3 * t2) * values[i + 1] + (t3 - t2) * m[i + 1];\n  };\n}\n\nconst toPath = (pts: XY[]) => pts.map(([x, y], i) => `${i ? \"L\" : \"M\"}${x.toFixed(1)},${y.toFixed(1)}`).join(\"\");\n\nfunction Trend({ up, color }: { up: boolean; color: string }) {\n  return (\n    <svg aria-hidden width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke={color} strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" style={{ transform: up ? undefined : \"scaleY(-1)\" }}>\n      <path d=\"m3 17 6-6 4 4 8-8\" />\n      <path d=\"M15 7h6v6\" />\n    </svg>\n  );\n}\n\n/**\n * Bento-style trend card: a small label, the latest figure with its change, and a smooth chart\n * with a dot on each value and its weekday (from Sunday) or month underneath. Point at the chart (or use the arrow\n * keys) to read any value. Give it a handful of numbers; everything else is worked out.\n */\nexport function TrendCard({\n  values: input,\n  label = \"Sales\",\n  labels,\n  period = \"months\",\n  currency = \"USD\",\n  locale = \"en-US\",\n  endDate,\n  accentColor = \"#FFFFFF\",\n  background = \"#08080A\",\n  textColor = \"#FFFFFF\",\n  mutedColor = \"#8F8F99\",\n  borderColor = \"rgba(255,255,255,0.08)\",\n  chartHeight = 120,\n  radius = 0,\n  className,\n  style,\n}: TrendCardProps) {\n  const uid = useId().replace(/:/g, \"\");\n  const reduceMotion = useReducedMotion() ?? false;\n  // Keyed by the numbers themselves, so a new but identical array doesn't redraw the line\n  const key = input.filter(Number.isFinite).join(\",\");\n  const values = useMemo(() => (key ? key.split(\",\").map(Number) : []), [key]);\n  const [hover, setHover] = useState<number | null>(null);\n  const [width, setWidth] = useState(0);\n  const chartRef = useRef<HTMLDivElement | null>(null);\n  const lineRef = useRef<SVGPathElement | null>(null);\n  const areaRef = useRef<SVGPathElement | null>(null);\n  const revealRef = useRef<SVGRectElement | null>(null);\n  const dotRefs = useRef<(SVGGElement | null)[]>([]);\n  const drawn = useRef<XY[] | null>(null);\n  // The trend draws itself in, left to right, the first time the chart comes into view\n  const [intro, setIntro] = useState<\"waiting\" | \"playing\" | \"done\">(\"waiting\");\n  // With reduced motion the trend is simply there\n  const revealed = reduceMotion || intro === \"done\";\n\n  useEffect(loadInter, []);\n  useEffect(() => {\n    const node = chartRef.current;\n    if (!node) return;\n    const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const n = values.length;\n  const W = Math.max(1, width);\n  const H = chartHeight;\n  const lo = n ? Math.min(...values) : 0;\n  const hi = n ? Math.max(...values) : 1;\n  const spread = hi - lo || Math.abs(hi) * 0.1 || 1;\n  const min = lo - spread * 0.35;\n  const max = hi + spread * 0.12;\n  const px = (i: number) => (n > 1 ? (i / (n - 1)) * W : W / 2);\n  const py = (v: number) => H - ((v - min) / (max - min)) * H;\n\n  const target = useMemo<XY[] | null>(() => {\n    if (n < 2 || !width) return null;\n    const at = spline(values);\n    return Array.from({ length: SAMPLES }, (_, k) => {\n      const u = (k / (SAMPLES - 1)) * (n - 1);\n      return [(u / (n - 1)) * W, H - ((at(u) - min) / (max - min)) * H] as XY;\n    });\n  }, [values, n, width, W, H, min, max]);\n\n  // Draw by writing the path directly; when the values change, morph from the old line\n  useEffect(() => {\n    if (!target) return;\n    const paint = (pts: XY[]) => {\n      const line = toPath(pts);\n      lineRef.current?.setAttribute(\"d\", line);\n      areaRef.current?.setAttribute(\"d\", `${line}L${pts[pts.length - 1][0]},${H}L${pts[0][0]},${H}Z`);\n    };\n    const from = drawn.current;\n    if (!from || reduceMotion) {\n      drawn.current = target;\n      paint(target);\n      return;\n    }\n    const controls = animate(0, 1, {\n      duration: 0.5,\n      ease: [0.32, 0.72, 0, 1],\n      onUpdate: (k) => {\n        const pts = target.map(([x, y], i) => [from[i][0] + (x - from[i][0]) * k, from[i][1] + (y - from[i][1]) * k] as XY);\n        drawn.current = pts;\n        paint(pts);\n      },\n    });\n    return () => controls.stop();\n  }, [target, reduceMotion, H]);\n\n  // Wait until the chart is on screen before drawing the trend in\n  useEffect(() => {\n    if (intro !== \"waiting\" || reduceMotion) return;\n    const node = chartRef.current;\n    if (!node || n < 2) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting) setIntro(\"playing\");\n      },\n      { threshold: 0.35 }\n    );\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, [intro, reduceMotion, n]);\n\n  // Sweep a clip across the line and area, and pop each dot in as the line reaches it\n  useEffect(() => {\n    if (intro !== \"playing\" || reduceMotion || !target) return;\n    const sweep = W + 16;\n    const controls = animate(0, 1, {\n      duration: 1.4,\n      ease: [0.65, 0, 0.35, 1],\n      onUpdate: (p) => {\n        revealRef.current?.setAttribute(\"width\", String(sweep * p));\n        dotRefs.current.forEach((dot, i) => {\n          if (dot && px(i) <= sweep * p - 4) dot.style.transform = \"scale(1)\";\n        });\n      },\n      onComplete: () => setIntro(\"done\"),\n    });\n    return () => controls.stop();\n    // px follows W and n, which the sweep already depends on\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [intro, reduceMotion, target, W, n]);\n\n  const money = useMemo(() => {\n    const all = key ? key.split(\",\").map(Number) : [];\n    const digits = all.length && Math.max(...all.map(Math.abs)) < 100 ? 2 : 0;\n    const format = new Intl.NumberFormat(locale, { style: \"currency\", currency, minimumFractionDigits: digits, maximumFractionDigits: digits });\n    return (v: number) => format.format(v);\n  }, [key, locale, currency]);\n\n  // Names under the points: given; weekdays starting on Sunday; or the months ending at endDate\n  // (months only once in the browser, so a server in another time zone can't disagree)\n  const names = useMemo(() => {\n    if (labels?.length) return values.map((_, i) => labels[i] ?? \"\");\n    if (period === \"days\") {\n      const fmt = new Intl.DateTimeFormat(locale, { weekday: \"short\" });\n      // 4 Jan 2026 was a Sunday\n      return values.map((_, i) => fmt.format(new Date(2026, 0, 4 + (i % 7))).toUpperCase());\n    }\n    if (!width) return values.map(() => \"\");\n    const end = endDate ? new Date(endDate) : new Date();\n    const base = Number.isFinite(end.getTime()) ? end : new Date();\n    const fmt = new Intl.DateTimeFormat(locale, { month: \"short\" });\n    return values.map((_, i) => fmt.format(new Date(base.getFullYear(), base.getMonth() - (values.length - 1 - i), 1)).toUpperCase());\n  }, [labels, values, width, endDate, locale, period]);\n\n  const index = hover ?? n - 1;\n  const current = values[index];\n  const first = values[0];\n  const diff = n > 1 ? current - first : 0;\n  const pct = n > 1 && first ? (diff / Math.abs(first)) * 100 : 0;\n  const up = diff >= 0;\n  const changeColor = up ? POSITIVE : NEGATIVE;\n\n  const onMove = (e: PointerEvent<HTMLDivElement>) => {\n    if (n < 2) return;\n    const rect = e.currentTarget.getBoundingClientRect();\n    setHover(Math.min(n - 1, Math.max(0, Math.round(((e.clientX - rect.left) / rect.width) * (n - 1)))));\n  };\n  const onKey = (e: KeyboardEvent<HTMLDivElement>) => {\n    const step = e.key === \"ArrowLeft\" ? -1 : e.key === \"ArrowRight\" ? 1 : 0;\n    if (e.key === \"Escape\") setHover(null);\n    if (!step || n < 2) return;\n    e.preventDefault();\n    setHover(Math.min(n - 1, Math.max(0, index + step)));\n  };\n\n  const muted = mutedColor;\n\n  return (\n    <div\n      className={className}\n      style={{\n        position: \"relative\",\n        width: \"100%\",\n        boxSizing: \"border-box\",\n        padding: 24,\n        borderRadius: radius,\n        background,\n        border: `1px solid ${borderColor}`,\n        color: textColor,\n        fontFamily: FONT,\n        fontVariantNumeric: \"tabular-nums\",\n        overflow: \"hidden\",\n        ...style,\n      }}\n    >\n      {/* Label, or the hovered point's name */}\n      <div style={{ minHeight: 20, fontSize: 12, fontWeight: 500, letterSpacing: \"0.08em\", textTransform: \"uppercase\", color: muted }}>\n        {hover !== null && names[index] ? `${label} · ${names[index]}` : label}\n      </div>\n\n      {/* Figure and its change since the first value */}\n      <div style={{ marginTop: 14, fontSize: 42, fontWeight: 400, letterSpacing: \"-0.03em\", lineHeight: 1.05 }}>{n ? money(current) : \"—\"}</div>\n      <div style={{ display: \"flex\", alignItems: \"center\", gap: 8, marginTop: 12, minHeight: 18, fontSize: 14, color: changeColor }}>\n        {n > 1 && (\n          <>\n            <Trend up={up} color={changeColor} />\n            <span>\n              {up ? \"+\" : \"−\"}\n              {money(Math.abs(diff))} ({up ? \"+\" : \"−\"}\n              {Math.abs(pct).toFixed(2)}%)\n            </span>\n          </>\n        )}\n      </div>\n\n      {/* Chart */}\n      <div\n        ref={chartRef}\n        role=\"img\"\n        tabIndex={0}\n        aria-label={n > 1 ? `${label}: from ${money(first)} to ${money(values[n - 1])}. Use the arrow keys to read each value.` : `${label}: no data yet`}\n        onPointerMove={onMove}\n        onPointerDown={onMove}\n        onPointerLeave={() => setHover(null)}\n        onKeyDown={onKey}\n        onBlur={() => setHover(null)}\n        style={{ marginTop: 28, touchAction: \"pan-y\", cursor: \"crosshair\", outline: \"none\" }}\n      >\n        {n > 1 ? (\n          <>\n            <svg width=\"100%\" height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: \"block\", overflow: \"visible\" }}>\n              <defs>\n                <linearGradient id={`${uid}-fill`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                  <stop offset=\"0%\" stopColor={accentColor} stopOpacity={0.14} />\n                  <stop offset=\"100%\" stopColor={accentColor} stopOpacity={0} />\n                </linearGradient>\n                <linearGradient id={`${uid}-grid`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                  <stop offset=\"0%\" stopColor={textColor} stopOpacity={0} />\n                  <stop offset=\"100%\" stopColor={textColor} stopOpacity={0.08} />\n                </linearGradient>\n                {/* Grows from the left while the trend draws in */}\n                <clipPath id={`${uid}-reveal`}>\n                  <rect ref={revealRef} x={-8} y={-12} height={H + 24} width={revealed ? W + 16 : 0} />\n                </clipPath>\n              </defs>\n              {/* Faint vertical guide at each value */}\n              {values.map((_, i) => (\n                <line key={i} x1={px(i)} x2={px(i)} y1={0} y2={H} stroke={i === hover ? accentColor : `url(#${uid}-grid)`} strokeOpacity={i === hover ? 0.35 : 1} strokeWidth={1} />\n              ))}\n              <g clipPath={`url(#${uid}-reveal)`}>\n                <path ref={areaRef} fill={`url(#${uid}-fill)`} />\n                <path ref={lineRef} fill=\"none\" stroke={accentColor} strokeWidth={2} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n              </g>\n              {values.map((v, i) => (\n                <g\n                  key={i}\n                  ref={(el) => {\n                    dotRefs.current[i] = el;\n                  }}\n                  style={{\n                    transformBox: \"fill-box\",\n                    transformOrigin: \"center\",\n                    transform: revealed ? undefined : \"scale(0)\",\n                    transition: \"transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1)\",\n                  }}\n                >\n                  {i === hover && <circle cx={px(i)} cy={py(v)} r={9} fill={accentColor} fillOpacity={0.18} />}\n                  <circle cx={px(i)} cy={py(v)} r={i === hover ? 4.5 : 3.5} fill={accentColor} stroke={background} strokeWidth={1.5} />\n                </g>\n              ))}\n            </svg>\n            <div aria-hidden style={{ position: \"relative\", height: 16, marginTop: 14 }}>\n              {names.map((name, i) => (\n                <span\n                  key={i}\n                  style={{\n                    position: \"absolute\",\n                    left: px(i),\n                    transform: i === 0 ? \"none\" : i === n - 1 ? \"translateX(-100%)\" : \"translateX(-50%)\",\n                    fontSize: 11,\n                    fontWeight: 500,\n                    letterSpacing: \"0.04em\",\n                    whiteSpace: \"nowrap\",\n                    color: i === hover ? textColor : muted,\n                    transition: \"color 0.2s\",\n                  }}\n                >\n                  {name}\n                </span>\n              ))}\n            </div>\n          </>\n        ) : (\n          <div style={{ height: H + 30, display: \"grid\", placeItems: \"center\", fontSize: 14, color: muted }}>Add at least two values</div>\n        )}\n      </div>\n    </div>\n  );\n}\n"}],"docs":"Trend Card is ready. Props and a live canvas: https://bydot.co/component/trend-card","meta":{"tier":"free","category":"UI Elements","version":"1.0.0"}}