Try 'magnetic button'
View code

Number 67: Trend line with a gliding crosshair

Specification

Catalogue
No. 67 of 110
Interaction
Hover
Element
Chart, Tabs
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2, framer-motion 12.40.0
Added

Notes

This period against the previous one, a crosshair that glides from day to day with both values beside it, legend buttons that hide either line, and paths that change shape between 7, 30 and 90 days.

The chart a SaaS or finance client asks for most often, done calmly: one accent line, one grey dashed line for comparison, and the headline figure with its change written out above.

Each range is resampled to the same number of points, so switching range morphs both paths on a 0.45s spring with no bounce instead of redrawing them. The crosshair and its tooltip glide over 120ms cubic-bezier(.22, 1, .36, 1) and flip to the left near the right edge. This period is the stage accent and solid, the previous period grey and dashed, so the two differ by more than colour; the legend is always shown. The plot takes focus and the arrow keys, Home and End read it day by day. No area fill under the line. The total rolls with NumberFlow. Instant under reduced motion.

The visits are sample content.

Code

React and plain CSS
"use client";

import { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
import { animate } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { physicalSpring } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { Num, radioArrows } from "@/components/pieces/shared";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./trend-line.css";

type Range = 7 | 30 | 90;
type Series = "now" | "before";

const RANGES: Range[] = [7, 30, 90];
const W = 400;
const H = 170;
const PAD = { l: 34, r: 8, t: 10, b: 22 };
/** Every range is resampled to this many points, so a path can morph from one range to another. */
const SAMPLES = 90;
const SETTLE = physicalSpring(0.45);
const END = Date.UTC(2026, 10, 30);

/** 180 days of daily visits, seeded so every render agrees: a slow rise, a weekly rhythm and some noise. */
function dailyVisits(): number[] {
  let seed = 11;
  const rand = () => {
    seed = (seed * 16807) % 2147483647;
    return seed / 2147483647;
  };
  return Array.from({ length: 180 }, (_, i) => Math.round(260 + i * 0.9 + 46 * Math.sin((i / 7) * Math.PI * 2) + (rand() - 0.5) * 70));
}

function resample(values: number[]): number[] {
  return Array.from({ length: SAMPLES }, (_, k) => {
    const t = (k / (SAMPLES - 1)) * (values.length - 1);
    const i = Math.floor(t);
    const f = t - i;
    return values[i]! + ((values[Math.min(i + 1, values.length - 1)] ?? values[i]!) - values[i]!) * f;
  });
}

const ALL = dailyVisits();
const TARGETS = Object.fromEntries(RANGES.map((r) => [r, { now: resample(ALL.slice(-r)), before: resample(ALL.slice(-r * 2, -r)) }])) as Record<Range, { now: number[]; before: number[] }>;

const day = (offset: number) => new Date(END - offset * 86400000).toLocaleDateString("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });
const sum = (a: number[]) => a.reduce((s, v) => s + v, 0);

function TrendLineDemo() {
  const reduce = useSafeReducedMotion();
  const uid = useId();
  const [range, setRange] = useState<Range>(30);
  const [visible, setVisible] = useState<Record<Series, boolean>>({ now: true, before: true });
  const [hover, setHover] = useState<number | null>(null);
  const now = ALL.slice(-range);
  const before = ALL.slice(-range * 2, -range);
  const target = TARGETS[range];
  const [paths, setPaths] = useState(target);
  const shown = useRef(target);

  useEffect(() => {
    const from = shown.current;
    // Both paths morph from the old range's shape to the new one's.
    const run = animate(0, 1, {
      ...(reduce ? { duration: 0 } : SETTLE),
      onUpdate: (t) => {
        const next = {
          now: target.now.map((v, i) => from.now[i]! + (v - from.now[i]!) * t),
          before: target.before.map((v, i) => from.before[i]! + (v - from.before[i]!) * t),
        };
        shown.current = next;
        setPaths(next);
      },
    });
    return () => run.stop();
  }, [target, reduce]);

  const lo = 150;
  const hi = 500;
  const x = (i: number, n: number) => PAD.l + (i / (n - 1)) * (W - PAD.l - PAD.r);
  const y = (v: number) => PAD.t + (1 - (v - lo) / (hi - lo)) * (H - PAD.t - PAD.b);
  const line = (vals: number[]) => vals.map((v, i) => `${i ? "L" : "M"}${x(i, vals.length).toFixed(1)} ${y(v).toFixed(1)}`).join(" ");

  const pick = (e: PointerEvent<SVGRectElement>) => {
    const r = e.currentTarget.getBoundingClientRect();
    const f = (e.clientX - r.left) / r.width;
    setHover(Math.max(0, Math.min(range - 1, Math.round(f * (range - 1)))));
  };
  const onKey = (e: KeyboardEvent<SVGSVGElement>) => {
    const at = hover ?? range - 1;
    let next: number | null = null;
    if (e.key === "ArrowLeft") next = Math.max(0, at - 1);
    else if (e.key === "ArrowRight") next = Math.min(range - 1, at + 1);
    else if (e.key === "Home") next = 0;
    else if (e.key === "End") next = range - 1;
    else if (e.key === "Escape") {
      setHover(null);
      return;
    }
    if (next === null) return;
    e.preventDefault();
    setHover(next);
  };

  const totalNow = sum(now);
  const change = Math.round(((totalNow - sum(before)) / sum(before)) * 100);
  const hx = hover === null ? 0 : x(hover, range);
  const tipLeft = hover !== null && hx > W * 0.6;

  return (
    <div className="dm tl">
      <div className="tl-top">
        <div>
          <p className="tl-kicker">Visits, last {range} days</p>
          <p className="tl-total">
            <Num value={totalNow} />
            <span className="tl-change">
              {change >= 0 ? "+" : "-"}
              {Math.abs(change)}% on the {range} days before
            </span>
          </p>
        </div>
        <div className="tl-ranges" role="radiogroup" aria-label="Range" onKeyDown={radioArrows}>
          {RANGES.map((r) => (
            <button key={r} type="button" role="radio" aria-checked={range === r} tabIndex={range === r ? 0 : -1} className="tl-range" onClick={() => {
                setHover(null);
                setRange(r);
              }}>
              {r}d
            </button>
          ))}
        </div>
      </div>
      <div className="tl-plot">
        <svg
          viewBox={`0 0 ${W} ${H}`}
          width={W}
          height={H}
          tabIndex={0}
          role="img"
          aria-labelledby={`${uid}-sum`}
          aria-describedby={`${uid}-tip`}
          onKeyDown={onKey}
          onBlur={() => setHover(null)}
        >
          {[200, 300, 400].map((v) => (
            <g key={v}>
              <line x1={PAD.l} x2={W - PAD.r} y1={y(v)} y2={y(v)} className="tl-grid" />
              <text x={PAD.l - 6} y={y(v) + 3} textAnchor="end" className="tl-tick">
                {v}
              </text>
            </g>
          ))}
          <text x={PAD.l} y={H - 4} className="tl-tick">
            {day(range - 1)}
          </text>
          <text x={W - PAD.r} y={H - 4} textAnchor="end" className="tl-tick">
            {day(0)}
          </text>
          {visible.before && <path d={line(paths.before)} className="tl-line" data-series="before" />}
          {visible.now && <path d={line(paths.now)} className="tl-line" data-series="now" />}
          {hover !== null && (
            <g className="tl-cross" style={{ translate: `${hx}px 0` }}>
              <line x1={0} x2={0} y1={PAD.t} y2={H - PAD.b} />
              {visible.before && <circle cx={0} cy={y(before[hover]!)} r={4} data-series="before" />}
              {visible.now && <circle cx={0} cy={y(now[hover]!)} r={4} data-series="now" />}
            </g>
          )}
          <rect x={PAD.l} y={PAD.t} width={W - PAD.l - PAD.r} height={H - PAD.t - PAD.b} className="tl-hit" onPointerMove={pick} onPointerEnter={pick} onPointerLeave={() => setHover(null)} />
        </svg>
        <p id={`${uid}-tip`} className="tl-tip" data-on={hover !== null || undefined} data-left={tipLeft || undefined} style={{ left: hover === null ? 0 : hx }} aria-live="polite">
          {hover !== null && (
            <>
              <strong>{day(range - 1 - hover)}</strong>
              {visible.now && <span data-series="now">This period {now[hover]}</span>}
              {visible.before && <span data-series="before">Before {before[hover]}</span>}
            </>
          )}
        </p>
      </div>
      <div className="tl-legend" aria-label="Series">
        {(["now", "before"] as const).map((s) => (
          <button key={s} type="button" className="tl-key" data-series={s} aria-pressed={visible[s]} onClick={() => setVisible((v) => ({ ...v, [s]: !v[s] }))}>
            <span className="tl-swatch" aria-hidden="true" />
            {s === "now" ? "This period" : "Previous period"}
          </button>
        ))}
      </div>
      <p id={`${uid}-sum`} className="sr-only">
        Visits over the last {range} days: {totalNow}, {change >= 0 ? "up" : "down"} {Math.abs(change)}% on the {range} days before. Use the arrow keys to read each day.
      </p>
    </div>
  );
}

// What a hovered card shows: the crosshair gliding across the month, then the paths morphing to 90 days.
const TOUR: Tour = [
  { sweep: ".tl-hit", from: [0.05, 0.5], to: [0.95, 0.5], ms: 1200, wait: 300 },
  { click: ".tl-range", text: "90d", wait: 1200 },
];

export default function TrendLineEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Trend line with a gliding crosshair" tour={TOUR} sample>
      <TrendLineDemo />
    </PieceStage>
  );
}

More like this

Traffic in stacked bars

HoverCharts and numbers

Donut that changes period

Hover, PressCharts and numbers

Slope chart for before and after

Hover, PressCharts and numbers

Context window meter

Hover, PressCharts and numbers

Comparison bars

Layout AnimationCharts and numbers

How the tools connect

HoverCharts and numbers