Try 'magnetic button'
View code

Number 109: Traffic in stacked bars

Specification

Catalogue
No. 109 of 110
Interaction
Hover
Element
Chart, Tabs, Counter
Preview
Live component
Imports
react 19.3.1
Added

Notes

A traffic card: the total, a Day and Week switch, and twenty stacked bars split into direct, search, referral and social visits, with bounced visits hanging below the line. Point at a bar and the rest dim, and a small panel beside it gives the range and the split.

The bounced visits sit under the axis in a slot of their own, so the stacks share one baseline and the loss reads as a separate thing rather than one more colour in the pile. Switching range moves every segment's share at once (flex-grow on each segment) and rolls the total. The panel flips to the left of the bar once the pointer passes 60% of the chart. On the entry page the chart takes focus, and Left, Right, Home and End read it bar by bar.

The colours are the site's category hues; the figures are sample data.

Code

React and plain CSS
"use client";

import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { RollingNumber } from "@/components/ui/RollingNumber";
import styles from "./traffic-bars.module.css";

type Range = "day" | "week";
type Column = { label: string; parts: number[]; bounced: number };

/** Stacked from the bottom: direct, search, referral, social. Bounced visits hang below the line. */
const SERIES = [
  { name: "Direct", hue: 1 },
  { name: "Search", hue: 5 },
  { name: "Referral", hue: 3 },
  { name: "Social", hue: 7 },
];
const BOUNCED_HUE = 4;
const COLUMNS = 20;
const CHART_H = 92;
const BOUNCE_H = 14;

/** Small deterministic noise, so the server and the browser draw the same bars. */
function noise(seed: number): number {
  const x = Math.sin(seed * 12.9898) * 43758.5453;
  return x - Math.floor(x);
}

const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

function makeData(range: Range): Column[] {
  const start = range === "week" ? Date.UTC(2026, 4, 25) : Date.UTC(2026, 8, 16);
  const step = range === "week" ? 7 : 1;
  const scale = range === "week" ? 1 : 1 / 7.4;
  return Array.from({ length: COLUMNS }, (_, i) => {
    const day = new Date(start + i * step * 86400000);
    const end = new Date(day.getTime() + 6 * 86400000);
    const label =
      range === "week"
        ? `${MONTHS[day.getUTCMonth()]} ${day.getUTCDate()} to ${day.getUTCMonth() === end.getUTCMonth() ? "" : `${MONTHS[end.getUTCMonth()]} `}${end.getUTCDate()}`
        : `${MONTHS[day.getUTCMonth()]} ${day.getUTCDate()}`;
    const seed = i + (range === "week" ? 1 : 101);
    const lift = 1 + 0.25 * Math.sin(i / 3.1);
    const parts = [3100, 1700, 1050, 820].map((base, k) => Math.round(base * scale * lift * (0.72 + 0.5 * noise(seed * 7 + k))));
    return { label, parts, bounced: Math.round(52 * scale * (0.6 + 0.8 * noise(seed * 13))) };
  });
}

const fmt = (n: number) => n.toLocaleString("en-GB");
const DEMO_PATH = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 16, 15, 12, 9, 6];

export default function TrafficBars({ active, context }: LivePreviewProps) {
  const card = context === "card";
  const [range, setRange] = useState<Range>("week");
  const [hover, setHover] = useState<number | null>(null);
  const [tick, setTick] = useState(0);
  const chartRef = useRef<HTMLDivElement>(null);
  const demo = card && active;

  const [running, setRunning] = useState(demo);
  if (running !== demo) {
    setRunning(demo);
    setTick(0);
  }

  // The card demo sweeps a pointer across the weeks, then once across the days.
  useEffect(() => {
    if (!demo) return;
    const id = window.setTimeout(() => setTick((t) => t + 1), tick % DEMO_PATH.length === 0 ? 600 : 150);
    return () => window.clearTimeout(id);
  }, [demo, tick]);

  const shownRange: Range = demo ? (Math.floor(tick / DEMO_PATH.length) % 2 === 1 ? "day" : "week") : card ? "week" : range;
  const data = useMemo(() => makeData(shownRange), [shownRange]);
  const max = useMemo(() => Math.max(...data.map((c) => c.parts.reduce((a, b) => a + b, 0))), [data]);
  const total = useMemo(() => data.reduce((sum, c) => sum + c.parts.reduce((a, b) => a + b, 0), 0), [data]);
  const current = demo ? (tick % DEMO_PATH.length === 0 ? null : (DEMO_PATH[tick % DEMO_PATH.length] ?? null)) : card ? null : hover;
  const column = current === null ? undefined : data[current];

  function pointAt(event: PointerEvent<HTMLDivElement>) {
    const chart = chartRef.current;
    if (!chart) return;
    const rect = chart.getBoundingClientRect();
    const index = Math.floor(((event.clientX - rect.left) / rect.width) * COLUMNS);
    setHover(Math.max(0, Math.min(COLUMNS - 1, index)));
  }

  function onKey(event: KeyboardEvent<HTMLDivElement>) {
    if (event.key !== "ArrowLeft" && event.key !== "ArrowRight" && event.key !== "Home" && event.key !== "End") return;
    event.preventDefault();
    setHover((h) => {
      if (event.key === "Home") return 0;
      if (event.key === "End") return COLUMNS - 1;
      const from = h ?? (event.key === "ArrowRight" ? -1 : COLUMNS);
      return Math.max(0, Math.min(COLUMNS - 1, from + (event.key === "ArrowRight" ? 1 : -1)));
    });
  }

  const tab = card ? -1 : 0;
  const tipLeft = current === null ? 0 : (current + 0.5) / COLUMNS;

  return (
    <div className={styles.area}>
      <div className={styles.panel}>
        <div className={styles.head}>
          <span className={styles.title}>Traffic</span>
          <div className={styles.switch} role="radiogroup" aria-label="Range">
            <span className={styles.thumb} data-at={shownRange} aria-hidden="true" />
            {(["day", "week"] as const).map((r) => (
              <button key={r} type="button" role="radio" aria-checked={shownRange === r} tabIndex={tab} className={styles.option} onClick={() => setRange(r)}>
                {r === "day" ? "Day" : "Week"}
              </button>
            ))}
          </div>
        </div>
        <p className={styles.total}>
          <RollingNumber value={total} className={styles.totalValue} />
          <span className={styles.unit}>visits</span>
        </p>
        <div
          ref={chartRef}
          className={styles.chart}
          data-hovering={current !== null || undefined}
          tabIndex={tab}
          role="group"
          aria-label={`Visits by ${shownRange}. Use the arrow keys to read each ${shownRange}.`}
          onPointerMove={card ? undefined : pointAt}
          onPointerLeave={() => setHover(null)}
          onBlur={() => setHover(null)}
          onKeyDown={card ? undefined : onKey}
        >
          {data.map((c, i) => {
            const sum = c.parts.reduce((a, b) => a + b, 0);
            return (
              <div key={i} className={styles.column} data-on={current === i || undefined}>
                <div className={styles.stack} style={{ height: `${(sum / max) * CHART_H}px` }}>
                  {c.parts.map((v, k) => (
                    <span key={k} className={styles.seg} style={{ flexGrow: v, "--hue": `var(--cat-${SERIES[k]?.hue}, var(--accent, currentColor))` } as CSSProperties} />
                  ))}
                </div>
                <span
                  className={styles.bounce}
                  style={{ height: `${Math.max(3, Math.min(BOUNCE_H, c.bounced / (shownRange === "week" ? 6 : 1)))}px`, "--hue": `var(--cat-${BOUNCED_HUE}, var(--accent, currentColor))` } as CSSProperties}
                />
              </div>
            );
          })}
          {column && (
            <div className={styles.tip} style={{ "--x": tipLeft, "--flip": tipLeft > 0.6 ? 1 : 0 } as CSSProperties} aria-hidden="true">
              <div className={styles.tipHead}>
                <span>{column.label}</span>
                <span>{fmt(column.parts.reduce((a, b) => a + b, 0))}</span>
              </div>
              {SERIES.slice(0, 2).map((s, k) => (
                <div key={s.name} className={styles.tipRow} style={{ "--hue": `var(--cat-${s.hue}, var(--accent, currentColor))` } as CSSProperties}>
                  <span>{s.name}</span>
                  <span>{fmt(column.parts[k] ?? 0)}</span>
                </div>
              ))}
              <div className={styles.tipRow} style={{ "--hue": `var(--cat-${BOUNCED_HUE}, var(--accent, currentColor))` } as CSSProperties}>
                <span>Bounced</span>
                <span>{fmt(column.bounced)}</span>
              </div>
            </div>
          )}
        </div>
        <div className={styles.axis} aria-hidden="true">
          <span>{data[0]?.label.split(" to ")[0]}</span>
          <span>{data[COLUMNS - 1]?.label.split(" to ")[0]}</span>
        </div>
        <p className="visually-hidden" role="status">
          {column ? `${column.label}: ${fmt(column.parts.reduce((a, b) => a + b, 0))} visits, ${fmt(column.bounced)} bounced.` : ""}
        </p>
      </div>
    </div>
  );
}

More like this

Donut that changes period

Hover, PressCharts and numbers

Trend line with a gliding crosshair

HoverCharts and numbers

Context window meter

Hover, PressCharts and numbers

Slope chart for before and after

Hover, PressCharts and numbers

Comparison bars

Layout AnimationCharts and numbers

How the tools connect

HoverCharts and numbers