Skip to content
Star

Line chart

Today so far and projected, against yesterday, with a range switch, a project picker, toggles and a readout. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.

$npx designme add line-chart
$npx shadcn@latest add https://designme.dev/r/shadcn/line-chart.json

Need this designed into your product? Book a call

Active editors

01

Install

Add it to your project with the CLI.

HTML, CSS and JS

$npx designme add line-chart

React

$npx designme add line-chart --react

Astro

$npx designme add line-chart --astro

shadcn, React

$npx shadcn@latest add https://designme.dev/r/shadcn/line-chart.json

shadcn, Astro

$npx shadcn@latest add https://designme.dev/r/shadcn/astro/line-chart.json

The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.

02

About

What it is for and what it does.

A line chart that shows one metric over a period against the period before, such as active editors today against yesterday. The main series is a solid line in the accent with a fill that fades to nothing at the bottom, up to the latest point, where an open ring sits with "Now" under it; from there a projection carries it to the period's end as a dotted line in the same colour over a fainter fill, so the chart always runs full width. The comparison runs across the whole period as a dotted line in the chart palette's second colour. A legend under the plot turns each line on and off, and a readout card follows the pointer or the arrow keys. In an agent product it suits a usage or growth metric on a dashboard.

  • When you want to show how a period is going so far, and where it is heading, against the same period before.
  • When people switch between a few ranges, like a day, a week and a month, or between a few projects or teams.
  • When people need exact values at each point without a full analytics tool.
03

Usage

Import it in React and drive it from your own state, or place it in an Astro page.

React

import { LineChart } from '@/components/designme/line-chart/LineChart';

React example

The demo above as a React component, 47 lines you can copy.

'use client';
// The preview from designme.dev, rebuilt from the React component: active editors on a project, today against yesterday,
// this week against last week, or this month against last month.
import { LineChart, type LineChartView } from './LineChart';

const PROJECTS = [{ key: 'web', label: 'Website', size: 1 }, { key: 'app', label: 'Mobile app', size: .58 }, { key: 'docs', label: 'Docs', size: .27 }];
const HOURS = Array.from({ length: 24 }, (_, h) => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'));
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const NOV = Array.from({ length: 30 }, (_, d) => 'Nov ' + (d + 1));
// it is 2pm on Thursday 19 November. November starts on a Sunday and October on a Thursday
const RANGES: Record<string, { points: string[]; ticks?: string[]; now: number; main: string; compare: string; grid: number[]; a: number[]; b: number[]; ka: number; kb: number }> = {
  day: { points: HOURS, now: 14, main: 'Today', compare: 'Yesterday', grid: [1, 2, 3, 4, 6, 12], ka: 1.05, kb: .93,
    a: [110, 80, 64, 58, 62, 96, 210, 460, 820, 1120, 1290, 1360, 1180, 1260, 1330, 1250, 1130, 960, 720, 510, 360, 260, 190, 140], b: [] },
  week: { points: DAYS, ticks: DAYS.map(d => d.slice(0, 3)), now: 3, main: 'This week', compare: 'Last week', grid: [1], ka: 1.04, kb: .92,
    a: [4380, 4720, 4610, 4890, 4420, 1680, 1240], b: [] },
  month: { points: NOV, now: 18, main: 'This month', compare: 'Last month', grid: [1, 7, 14], ka: 1.02, kb: .95,
    a: NOV.map((_, d) => d % 7 === 0 || d % 7 === 6 ? 1500 : 4500), b: NOV.map((_, d) => (4 + d) % 7 === 0 || (4 + d) % 7 === 6 ? 1450 : 4400) }
};
// a small seeded wobble, so each project's numbers differ but are the same on every visit
const wob = (s: number, i: number) => { const x = Math.sin(s * 91.7 + i * 12.9898) * 43758.5453; return x - Math.floor(x) - .5; };

function projectMonth(g: (typeof RANGES)[string], p: number, size: number) {
  const now = Math.round(g.a[g.now] * g.ka * size * (1 + wob(p + 1, g.now) * .14)), shape = g.a.map((v, i) => v * (1 + wob(p + 13, i) * .06));
  return shape.slice(g.now).map(v => Math.round(now * v / shape[g.now]));
}

function view({ source, range }: { source: string; range: string }): LineChartView {
  const g = RANGES[range], p = PROJECTS.findIndex(x => x.key === source), size = PROJECTS[p].size;
  return {
    points: g.points, ticks: g.ticks, now: g.now, grid: g.grid,
    main: { label: g.main, values: g.a.slice(0, g.now + 1).map((v, i) => Math.round(v * g.ka * size * (1 + wob(p + 1, i) * .14))) },
    compare: { label: g.compare, values: (g.b.length ? g.b : g.a).map((v, i) => Math.round(v * g.kb * size * (1 + wob(p + 7, i) * .14))) },
    // the rest of the month is projected along its own weekdays (October's weekends fall on other dates); the day and the week
    // take the chart's default, the latest value carried forward along the comparison's shape
    projected: g.b.length ? projectMonth(g, p, size) : undefined
  };
}

export default function LineChartDemo() {
  return (
    <div style={{ width: '100%' }}>
      <LineChart title="Active editors" sources={PROJECTS.map(({ key, label }) => ({ key, label }))} sourceLabel="Project"
        ranges={[{ key: 'day', label: 'Day' }, { key: 'week', label: 'Week' }, { key: 'month', label: 'Month' }]} pointName="Point" data={view} />
    </div>
  );
}

Astro

In a page in src/pages. It plays the demo above; change its line-chart.js to show your own data. Attributes like class go on its root element.

---
import LineChart from '../components/designme/line-chart/LineChart.astro';
---
<LineChart />
<LineChart data-style="soft" class="my-class" />
04

Props

Everything LineChart takes.

PropTypeWhat it does
titlerequiredstringThe quiet title at the head's start, like "Active editors"
sourcesLineChartOption[]What the picker beside the title chooses between, like projects. Leave it out for no picker
sourcestringKey of the picked source. Leave it out to let the picker change it
defaultSourcestring
onSourceChange(key: string) => void
sourceLabelstringNames the picker for screen readers, like "Project"
ranges{ key: string; label: string }[]The range switch's options, like Day, Week and Month. Leave it out for no switch
rangestring
defaultRangestring
onRangeChange(key: string) => void
datarequiredLineChartView | ((pick: { source: string; range: string }) => LineChartView)What to draw: one view, or a function that gives the view for the picked source and range
nowLabelstringUnder the latest point. Defaults to "Now"
projectedLabelstringNames the projection in the legend and the readout. Defaults to "Projected"
pointNamestringHeads the first column of the screen reader table, like "Hour"
visibleLineChartLine[]Which lines show. Leave it out to let the legend under the plot turn each on and off; one always stays on
defaultVisibleLineChartLine[]
onVisibleChange(lines: LineChartLine[]) => void
format(n: number) => stringWrites a value in the readout. Defaults to whole numbers like 1,240
formatAxis(n: number) => stringWrites the values on the left. Defaults to short numbers like 1.5k
classNamestring
05

Code

The full source, as the CLI installs it.

LineChart.tsxReact · 273 lines
'use client';
import { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
import { formatCount } from '../lib/chart';
import { cx } from '../lib/cx';
import { useControllable, useIsoLayoutEffect, useReducedMotion } from '../lib/hooks';
import { Icon } from '../lib/icons';
import { Seg } from '../lib/motion';
import { usePopover } from '../lib/popover';
import '../designme.css';
import './line-chart.css';

export interface LineChartSeries {
  /** Names the series in the readout, like "Today" */
  label: string;
  /** One value per point, oldest first. The main series may stop at `now` */
  values: number[];
}

export interface LineChartView {
  /** Names each point in the readout's head and the screen reader table, like "2pm" or "Thursday" */
  points: string[];
  /** Shorter names for the axis and the chip under the point read, like "Thu". Defaults to `points` */
  ticks?: string[];
  /** Index of the latest point: the solid line ends there with a ring and "Now" under it, and the projection carries on to the
      last point. Defaults to the last point */
  now?: number;
  /** The main series: a solid line in the accent with a fill that fades to nothing at the bottom */
  main: LineChartSeries;
  /** The series to compare against, like yesterday: a dotted line in the chart palette's second colour across every point */
  compare?: LineChartSeries;
  /** The rest of the main series after `now`, so the chart runs to the period's end: a dotted line in the main colour over a fill at
      half strength, one value per point from `now` to the last. Left out, the value at `now` is carried forward along the
      comparison's shape (held level without one); false draws none */
  projected?: number[] | false;
  /** How many points a gridline may fall every, smallest first; the chart takes the first that keeps them about 40px apart. Defaults to [1, 2, 3, 4, 6, 12] */
  grid?: number[];
}

export interface LineChartOption {
  key: string;
  /** On the picker and in its menu, like "Website" */
  label: string;
  /** A letter or two on the option's mark, like "W". Defaults to the label's first letter */
  mark?: string;
  /** The mark's fill and its letter's colour. Default to the avatar colours, in order */
  color?: string;
  ink?: string;
}

export type LineChartLine = 'main' | 'projected' | 'compare';

export interface LineChartProps {
  /** The quiet title at the head's start, like "Active editors" */
  title: string;
  /** What the picker beside the title chooses between, like projects. Leave it out for no picker */
  sources?: LineChartOption[];
  /** Key of the picked source. Leave it out to let the picker change it */
  source?: string;
  defaultSource?: string;
  onSourceChange?: (key: string) => void;
  /** Names the picker for screen readers, like "Project" */
  sourceLabel?: string;
  /** The range switch's options, like Day, Week and Month. Leave it out for no switch */
  ranges?: { key: string; label: string }[];
  range?: string;
  defaultRange?: string;
  onRangeChange?: (key: string) => void;
  /** What to draw: one view, or a function that gives the view for the picked source and range */
  data: LineChartView | ((pick: { source: string; range: string }) => LineChartView);
  /** Under the latest point. Defaults to "Now" */
  nowLabel?: string;
  /** Names the projection in the legend and the readout. Defaults to "Projected" */
  projectedLabel?: string;
  /** Heads the first column of the screen reader table, like "Hour" */
  pointName?: string;
  /** Which lines show. Leave it out to let the legend under the plot turn each on and off; one always stays on */
  visible?: LineChartLine[];
  defaultVisible?: LineChartLine[];
  onVisibleChange?: (lines: LineChartLine[]) => void;
  /** Writes a value in the readout. Defaults to whole numbers like 1,240 */
  format?: (n: number) => string;
  /** Writes the values on the left. Defaults to short numbers like 1.5k */
  formatAxis?: (n: number) => string;
  className?: string;
}

const AV = ['b', 'l', 'm', 'p', 't', 'k'];
const shortNum = (n: number) => n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n);
// the top of the scale: a round step that gives three or four bands above zero, with a little room over the highest value
const scaleOf = (m: number) => {
  const raw = m / 4 || 1, p = 10 ** Math.floor(Math.log10(raw)), s = [1, 2, 2.5, 5, 10].map(k => k * p).find(k => k >= raw) ?? raw;
  return { step: s, top: Math.max(s, Math.ceil(m * 1.04 / s) * s) };
};

/** One metric over a period against the period before: straight segments, a saturated line with a fading fill up to a ring at
    now, a dotted projection to the period's end, a dotted comparison, and a readout card that follows the pointer or the arrow keys. */
export function LineChart({ title, sources, source, defaultSource, onSourceChange, sourceLabel = 'Source', ranges, range, defaultRange, onRangeChange,
  data, nowLabel = 'Now', projectedLabel = 'Projected', pointName = 'Point', visible, defaultVisible = ['main', 'projected', 'compare'], onVisibleChange, format = formatCount, formatAxis = shortNum, className }: LineChartProps) {
  const [lines, setLines] = useControllable(visible, defaultVisible, onVisibleChange);
  const [src, setSrc] = useControllable(source, defaultSource ?? sources?.[0]?.key ?? '', onSourceChange);
  const [rng, setRng] = useControllable(range, defaultRange ?? ranges?.[0]?.key ?? '', onRangeChange);
  const view = typeof data === 'function' ? data({ source: src, range: rng }) : data;
  const { points, main, compare } = view, ticks = view.ticks ?? points, n = Math.max(1, points.length - 1);
  const now = Math.min(view.now ?? n, main.values.length - 1, n);
  // the projection: from now to the last point, given or carried forward along the comparison's shape
  const given = Array.isArray(view.projected) ? view.projected : null, base = compare?.values[now];
  const proj = points.map((_, j) => j < now || now >= n || view.projected === false ? null
    : given ? given[j - now] ?? null : base && compare ? main.values[now] * compare.values[j] / base : main.values[now]);
  const hasProj = proj.some((v, j) => j > now && v != null);
  const onA = lines.includes('main') || (!compare && !hasProj), onP = hasProj && lines.includes('projected'), onB = !!compare && lines.includes('compare');
  // the legend turns each line on and off; one always stays on
  const toggle = (l: LineChartLine) => { const st: Record<LineChartLine, boolean> = { main: onA, projected: onP, compare: onB };
    if (st[l] && !(Object.keys(st) as LineChartLine[]).some(k => k !== l && st[k])) return; setLines(st[l] ? lines.filter(x => x !== l) : [...lines, l]); };
  const { step, top } = scaleOf(Math.max(...main.values.slice(0, now + 1), ...(compare?.values ?? []), ...proj.filter((v): v is number => v != null)));
  const menu = usePopover();
  const pick = sources?.find(s => s.key === src) ?? sources?.[0];
  const markOf = (o: LineChartOption, i: number) => ({ text: o.mark ?? o.label.slice(0, 1), style: { ['--dm-mk' as string]: o.color ?? `var(--dm-av-${AV[i % AV.length]})`, ['--dm-mk-ink' as string]: o.ink ?? (o.color ? '#fff' : `var(--dm-av-${AV[i % AV.length]}-ink)`) } });

  // the plot's size, so the lines are drawn in pixels: sharp corners, even dots and dashes at any width
  const ch = useRef<HTMLDivElement>(null);
  const [box, setBox] = useState({ w: 0, h: 0 });
  useIsoLayoutEffect(() => {
    const el = ch.current; if (!el) return;
    const fit = () => setBox(b => (b.w === el.clientWidth && b.h === el.clientHeight ? b : { w: el.clientWidth, h: el.clientHeight }));
    fit(); const ro = new ResizeObserver(fit); ro.observe(el); return () => ro.disconnect();
  }, []);
  const W = box.w, H = box.h, xr = W - (now === n ? 6 : 0);
  const X = (i: number) => i / n * xr, Y = (v: number) => H - v / top * H;
  const line = (vs: number[]) => vs.map((v, i) => `${i ? 'L' : 'M'}${X(i).toFixed(1)} ${Y(v).toFixed(1)}`).join('');
  const A = main.values.slice(0, now + 1), P = proj.slice(now).filter((v): v is number => v != null);
  const pLine = P.map((v, j) => `${j ? 'L' : 'M'}${X(now + j).toFixed(1)} ${Y(v).toFixed(1)}`).join('');
  const grid = view.grid ?? [1, 2, 3, 4, 6, 12], k = grid.find(g => g * xr / n >= 40) ?? grid[grid.length - 1];
  const gl: number[] = []; for (let i = 0; i <= n; i += k) gl.push(Math.round(X(i)) + .5);

  // the lines draw in from the left, again whenever the source or the range changes
  const reduce = useReducedMotion();
  const [shown, setShown] = useState(0);
  const drawKey = `${src}|${rng}`;
  useEffect(() => {
    if (reduce) { setShown(1); return; }
    let raf = 0; const t0 = performance.now() + (shown === 0 ? 260 : 0);
    setShown(0);
    const f = (t: number) => { const p = Math.max(0, Math.min(1, (t - t0) / 1100)); setShown(p < .5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2); if (p < 1) raf = requestAnimationFrame(f); };
    raf = requestAnimationFrame(f); return () => cancelAnimationFrame(raf);
  }, [drawKey, reduce]); // eslint-disable-line react-hooks/exhaustive-deps

  // the point read: by the pointer, a finger or the arrow keys
  const [at, setAt] = useState<number | null>(null);
  const [said, setSaid] = useState('');
  const i = at == null ? null : Math.min(at, n);
  const idx = (e: PointerEvent<HTMLDivElement>) => { const b = e.currentTarget.getBoundingClientRect(); return Math.max(0, Math.min(n, Math.round((e.clientX - b.left) / (xr || 1) * n))); };
  // up to now a point reads the main series; after now, the projection
  const reading = (j: number) => j > now ? { on: onP, label: projectedLabel, value: proj[j] } : { on: onA, label: main.label, value: main.values[j] };
  const say = (j: number) => { const m = reading(j); setSaid(`${points[j]}: ` + [m.on && m.value != null && `${m.label} ${format(m.value)}`, onB && compare && `${compare.label} ${format(compare.values[j])}`].filter(Boolean).join(', ')); };
  const key = (e: KeyboardEvent<HTMLDivElement>) => {
    const from = i ?? now;
    const to = ({ ArrowLeft: from - 1, ArrowRight: from + 1, Home: 0, End: n } as Record<string, number>)[e.key];
    if (e.key === 'Escape' && i != null) { e.preventDefault(); setAt(null); return; }
    if (to == null) return;
    e.preventDefault(); const j = Math.max(0, Math.min(n, to)); setAt(j); say(j);
  };

  // the readout beside the guide on the side with room (or over the point on a plot too narrow for either), and the axis labels,
  // placed once they are measured
  const tt = useRef<HTMLDivElement>(null), ax = useRef<HTMLDivElement>(null);
  useIsoLayoutEffect(() => {
    const a = ax.current; if (!a || !W) return;
    const lab = (c: string) => a.querySelector<HTMLElement>(c);
    const near = (p: HTMLElement, q: HTMLElement) => p.offsetLeft < q.offsetLeft + q.offsetWidth + 6 && q.offsetLeft < p.offsetLeft + p.offsetWidth + 6;
    const put = (el: HTMLElement | null, x: number) => { if (el) el.style.left = Math.max(0, Math.min(xr - el.offsetWidth, x - el.offsetWidth / 2)) + 'px'; };
    const first = lab('.dm-lnx-a'), last = lab('.dm-lnx-z'), nw = lab('.dm-lnx-nw:not(.dm-lnx-z)'), tk = lab('.dm-lnx-tk');
    put(nw, X(now));
    // the first and last labels step aside for Now, and every label for the chip of the point read
    const hid = (l: HTMLElement) => l !== nw && !!nw && near(l, nw);
    if (tk && i != null) put(tk, X(i));
    [first, last, nw].forEach(l => l && l.classList.toggle('dm-lnx-off', hid(l) || (!!tk && i != null && near(l, tk))));
    const t = tt.current; if (!t || i == null) return;
    const m = reading(i), has = m.on && m.value != null, x = X(i), w = t.offsetWidth, h = t.offsetHeight, gap = 12, py = Y(has ? m.value ?? 0 : compare?.values[i] ?? 0);
    const side = x + gap + w <= W ? x + gap : x - gap - w >= 0 ? x - gap - w : null;
    t.style.left = (side ?? Math.max(0, Math.min(W - w, x - w / 2))) + 'px';
    t.style.top = (side != null ? Math.max(0, Math.min(H - h, py - h / 2)) : py - gap - h >= -8 ? py - gap - h : py + gap) + 'px';
  });

  const ids = useId().replace(/[^\w-]/g, '');
  const what = `${title}${pick ? ' on ' + pick.label : ''}`;
  return (
    <div data-dm="" className={cx('dm-lnx dm-panel', i != null && 'dm-on', !onA && 'dm-lnx-noa', !onP && 'dm-lnx-nop', !onB && 'dm-lnx-nob', className)}>
      <div className="dm-lnx-h">
        <div className="dm-lnx-tl">
          <span className="dm-lnx-t">{title}</span>
          {sources && pick && (
            <button type="button" className="dm-lnx-pk" {...menu.trigger} aria-label={`${sourceLabel}: ${pick.label}`}>
              {(() => { const m = markOf(pick, sources.indexOf(pick)); return <span className="dm-lnx-mk" style={m.style} aria-hidden="true">{m.text}</span>; })()}
              <span className="dm-lnx-pn">{pick.label}</span><Icon name="chev-d" size="xs" />
            </button>
          )}
        </div>
        {ranges && ranges.length > 1 && <Seg className="dm-lnx-rg" label="Range" value={rng} onChange={setRng} options={ranges.map(r => ({ value: r.key, label: r.label }))} />}
      </div>
      {sources && (
        <div {...menu.pop} className={cx(menu.pop.className, 'dm-lnx-pp')} role="menu" aria-label={sourceLabel}>
          {sources.map((o, j) => { const m = markOf(o, j); return (
            <button key={o.key} type="button" className="dm-mi" role="menuitemradio" aria-checked={o.key === src} onClick={() => { if (o.key !== src) setSrc(o.key); menu.closeSoon(); }}>
              <span className="dm-lnx-mk" style={m.style} aria-hidden="true">{m.text}</span><span>{o.label}</span><span className="dm-ck"><Icon name="check" size="xs" /></span>
            </button>
          ); })}
        </div>
      )}
      <div className="dm-lnx-pl">
        <div className="dm-lnx-y dm-num" aria-hidden="true">{Array.from({ length: top / step + 1 }, (_, j) => <span key={j}>{formatAxis(top - j * step)}</span>)}</div>
        <div className="dm-lnx-ch" ref={ch} tabIndex={0} role="group" aria-roledescription="line chart" aria-label={`${what}. The arrow keys read each point`}
          onPointerMove={e => setAt(idx(e))} onPointerDown={e => setAt(idx(e))}
          onPointerLeave={e => { if (e.pointerType !== 'touch' && !e.currentTarget.matches(':focus-visible')) setAt(null); }}
          onFocus={e => { if (e.currentTarget.matches(':focus-visible')) { setAt(now); say(now); } }} onBlur={() => setAt(null)} onKeyDown={key}>
          <svg className="dm-lnx-svg" viewBox={`0 0 ${W || 1} ${H || 1}`} aria-hidden="true">
            <defs>
              <linearGradient id={ids + 'g'} x1="0" x2="0" y1="0" y2="1">
                <stop offset="0" style={{ stopColor: 'var(--dm-lnx-line)', stopOpacity: 'var(--dm-lnx-fill)' }} />
                <stop offset="1" style={{ stopColor: 'var(--dm-lnx-line)', stopOpacity: 0 }} />
              </linearGradient>
              <linearGradient id={ids + 'p'} x1="0" x2="0" y1="0" y2="1">
                <stop offset="0" style={{ stopColor: 'var(--dm-lnx-line)', stopOpacity: 'var(--dm-lnx-pfill)' }} />
                <stop offset="1" style={{ stopColor: 'var(--dm-lnx-line)', stopOpacity: 0 }} />
              </linearGradient>
              <clipPath id={ids + 'c'}><rect x="-8" y="-8" height={H + 16} width={(W + 16) * shown} /></clipPath>
            </defs>
            {W > 0 && gl.map(x => <line key={x} className="dm-gl" x1={x} x2={x} y1="0" y2={H} />)}
            {W > 0 && (
              <g clipPath={`url(#${ids}c)`}>
                {compare && <path className="dm-cmp" d={line(compare.values)} />}
                {P.length > 1 && <path className="dm-par" d={`${pLine}L${X(now + P.length - 1).toFixed(1)} ${H}L${X(now).toFixed(1)} ${H}Z`} fill={`url(#${ids}p)`} />}
                <path className="dm-ar" d={`${line(A)}L${X(now).toFixed(1)} ${H}L0 ${H}Z`} fill={`url(#${ids}g)`} />
                {P.length > 1 && <path className="dm-prj" d={pLine} />}
                <path className="dm-ln" d={line(A)} />
              </g>
            )}
          </svg>
          <span className="dm-lnx-x" style={i != null ? { left: X(i) } : undefined} />
          {compare && <span className={cx('dm-lnx-pt', i != null && onB && 'dm-on')} style={{ color: 'var(--dm-lnx-cmp)', ...(i != null && { left: X(i), top: Y(compare.values[i]) }) }} />}
          {(() => { const m = i != null ? reading(i) : null; return <span className={cx('dm-lnx-pt', i != null && i !== now && m?.on && m.value != null && 'dm-on')} style={{ color: 'var(--dm-lnx-line)', ...(i != null && m?.value != null && { left: X(i), top: Y(m.value) }) }} />; })()}
          {W > 0 && <span className="dm-lnx-now" style={{ left: X(now), top: Y(A[now]), opacity: shown * (W + 16) - 8 >= X(now) ? 1 : 0 }} />}
          <div className="dm-lnx-tt" ref={tt} aria-hidden="true">
            <div className="dm-lnx-tt-h">{i != null && points[i]}</div>
            {(() => { const m = i != null ? reading(i) : null; return <div className={cx('dm-lnx-tt-r', i != null && i > now && 'dm-p')} hidden={!m?.on || m.value == null}><i /><span>{m?.label}</span><b className="dm-num">{m?.value != null && format(m.value)}</b></div>; })()}
            {compare && <div className="dm-lnx-tt-r dm-c" hidden={!onB}><i /><span>{compare.label}</span><b className="dm-num">{i != null && format(compare.values[i])}</b></div>}
          </div>
        </div>
        <div className="dm-lnx-ax dm-num" ref={ax} aria-hidden="true">
          <span className="dm-lnx-a">{ticks[0]}</span>
          <span className={cx('dm-lnx-z', now === n && 'dm-lnx-nw')}>{now === n ? nowLabel : ticks[n]}</span>
          {now < n && <span className="dm-lnx-nw">{nowLabel}</span>}
          <span className="dm-lnx-tk">{i != null && ticks[i]}</span>
        </div>
      </div>
      {(compare || hasProj) && (
        <div className="dm-lnx-lg">
          <button type="button" className="dm-lnx-k" aria-pressed={onA} onClick={() => toggle('main')}><i /><span>{main.label}</span></button>
          {hasProj && <button type="button" className="dm-lnx-k dm-p" aria-pressed={onP} onClick={() => toggle('projected')}><i /><span>{projectedLabel}</span></button>}
          {compare && <button type="button" className="dm-lnx-k dm-c" aria-pressed={onB} onClick={() => toggle('compare')}><i /><span>{compare.label}</span></button>}
        </div>
      )}
      <p className="dm-lnx-sr" aria-live="polite">{said}</p>
      <div className="dm-lnx-sr"><table>
        <caption>{what}</caption>
        <tbody>
          <tr><th scope="col">{pointName}</th><th scope="col">{main.label}</th>{hasProj && <th scope="col">{projectedLabel}</th>}{compare && <th scope="col">{compare.label}</th>}</tr>
          {points.map((p, j) => { const pv = proj[j]; return <tr key={j}><th scope="row">{p}</th><td>{j <= now ? format(main.values[j]) : ''}</td>{hasProj && <td>{j > now && pv != null ? format(pv) : ''}</td>}{compare && <td>{format(compare.values[j])}</td>}</tr>; })}
        </tbody>
      </table></div>
    </div>
  );
}
line-chart.cssReact · 127 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Line chart ---------- */
/* one metric over a period, against the period before (owner, 21 Nov): straight segments with sharp joins, a saturated line in the accent, and a fill that fades from the line's colour
   at the top to nothing at the bottom. A quiet head: the title, a picker for whose numbers they are, and the range switch, with
   a hairline under them. Under it the plot: the values on the left, dashed vertical gridlines and no horizontal ones, the period
   before as a dotted line in the chart palette's second colour across the whole period, and this period as a solid line up to
   now, with an open ring and "Now" under it, then projected to the period's end as a dotted line in its own colour over a
   fill at half strength, so the chart always runs full width (owner, 21 Nov: "I never seen charts that end mid way"). A legend under the plot names both lines and turns each on and off. Pointing at the plot, or the arrow keys on it, shows a dashed guide, a ring on each line and a readout card
   beside the guide on the side with room, and the point's name becomes a grey chip on the axis. The content sits 16px in from
   every edge; the picker's and the switch's hover boxes reach out round their words */
.dm-lnx{padding:var(--dm-s-4);display:flex;flex-direction:column;gap:var(--dm-s-4);--dm-row:color-mix(in srgb,var(--dm-fg) 5%,transparent);
  --dm-lnx-line:var(--dm-accent-mark,var(--dm-accent));--dm-lnx-cmp:var(--dm-c2);--dm-lnx-fill:.2;--dm-lnx-pfill:.1;--dm-lnx-grid:var(--dm-line);--dm-lnx-guide:color-mix(in srgb,var(--dm-fg) 38%,transparent)}
:root[data-theme="dark"] .dm-lnx{--dm-lnx-fill:.3;--dm-lnx-pfill:.15}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]) .dm-lnx{--dm-lnx-fill:.3;--dm-lnx-pfill:.15}}
.dm-lnx-h{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-2) var(--dm-s-3);flex-wrap:wrap;padding-bottom:var(--dm-s-4);border-bottom:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent)}
.dm-lnx-tl{display:flex;align-items:center;gap:6px;min-width:0;font-size:13.5px;line-height:20px}
.dm-lnx-t{color:var(--dm-muted);white-space:nowrap}
/* the picker: its mark and words in the text colour, no edge until hovered; its hover box reaches out round them */
.dm-lnx-pk{display:inline-flex;align-items:center;gap:6px;height:28px;margin:-4px -5px -4px 0;padding:0 5px 0 8px;border-radius:var(--dm-r-sm);color:var(--dm-fg);font-weight:500;white-space:nowrap;transition:background-color var(--dm-t-fast) var(--dm-ease)}
.dm-lnx-pk[aria-expanded="true"]{background:var(--dm-row)}
@media (hover:hover) and (pointer:fine){.dm-lnx-pk:hover{background:var(--dm-row)}}
.dm-lnx-pk .dm-i{color:var(--dm-muted);margin-left:-2px}
.dm-lnx-mk{width:18px;height:18px;flex:none;display:grid;place-items:center;border-radius:calc(5px * var(--dm-rk-s,var(--dm-rk)));font-size:10.5px;font-weight:500;line-height:1;background:var(--dm-mk,var(--dm-av-b));color:var(--dm-mk-ink,var(--dm-av-b-ink))}
.dm-pop.dm-lnx-pp{min-width:188px}
.dm-lnx-pp .dm-mi{gap:var(--dm-s-2)}
.dm-lnx-rg button{font-size:12px;height:26px;padding:0 9px}
/* on a narrow card the switch goes under the title, as wide as the content, its parts sharing the width */
.dm-lnx{container:lnx/inline-size}
@container lnx (max-width:375px){.dm-lnx-h{flex-direction:column;align-items:stretch}.dm-lnx-rg{display:flex}.dm-lnx-rg button{flex:1}.dm-lnx-pk{margin-top:0;margin-bottom:0}}
/* and on a phone the legend's three lines take two columns, so it is two rows whatever the range calls them, and switching the
   range never changes the card's height */
@container lnx (max-width:300px){.dm-lnx .dm-lnx-lg{display:grid;grid-template-columns:max-content max-content;gap:2px var(--dm-s-1);justify-content:start}}
/* the plot: the values in a column on the left, each centred on its height; the axis under the drawing */
.dm-lnx-pl{display:grid;grid-template-rows:auto auto;grid-template-columns:auto minmax(0,1fr);column-gap:var(--dm-s-3);row-gap:var(--dm-s-2)}
.dm-lnx-y{display:flex;flex-direction:column;justify-content:space-between;margin:-8px 0;font-size:12px;line-height:16px;color:var(--dm-muted);text-align:right;white-space:nowrap}
.dm-lnx-ch{position:relative;height:168px;touch-action:pan-y}
.dm-lnx-ch:focus-visible{outline-offset:6px}
.dm-lnx-svg{position:absolute;left:0;top:0;width:100%;height:100%;display:block;overflow:visible}
.dm-lnx-svg .dm-gl{stroke:var(--dm-lnx-grid);stroke-width:1;stroke-dasharray:3 4}
.dm-lnx-svg .dm-ln{fill:none;stroke:var(--dm-lnx-line);stroke-width:2;stroke-linejoin:miter;stroke-miterlimit:8;stroke-linecap:butt}
.dm-lnx-svg :is(.dm-cmp,.dm-prj){fill:none;stroke:var(--dm-lnx-cmp);stroke-width:2;stroke-linecap:round;stroke-dasharray:0 5}
.dm-lnx-svg .dm-prj{stroke:var(--dm-lnx-line)}
/* now: an open ring on the line's end, with a dot of the line's colour inside */
.dm-lnx-now{position:absolute;left:0;top:0;width:12px;height:12px;margin:-6px 0 0 -6px;border-radius:50%;background:radial-gradient(circle,var(--dm-lnx-line) 2px,var(--dm-surface) 2.6px);box-shadow:inset 0 0 0 2px var(--dm-lnx-line);pointer-events:none;transition:opacity var(--dm-t-fast) var(--dm-ease)}
/* the guide, the rings and the readout show while the plot is pointed at or has the keyboard's focus */
/* where the demo's pointer aims: an empty box centred on the point it reads */
.dm-lnx-aim{position:absolute;left:0;top:0;width:16px;height:16px;margin:-8px 0 0 -8px;pointer-events:none}
.dm-lnx-x{position:absolute;top:0;bottom:0;left:0;width:1px;margin-left:-.5px;background:repeating-linear-gradient(to bottom,var(--dm-lnx-guide) 0 3px,transparent 3px 7px);opacity:0;transition:opacity var(--dm-t-fast) var(--dm-ease);pointer-events:none}
.dm-lnx-pt{position:absolute;left:0;top:0;width:10px;height:10px;margin:-5px 0 0 -5px;border-radius:50%;background:var(--dm-surface);box-shadow:inset 0 0 0 2px currentColor;opacity:0;transition:opacity var(--dm-t-fast) var(--dm-ease);pointer-events:none}
.dm-lnx-tt{position:absolute;left:0;top:0;z-index:2;min-width:156px;border-radius:calc(10px * var(--dm-rk-m,var(--dm-rk)));background:var(--dm-raised);box-shadow:var(--dm-shadow-pop);font-size:12.5px;line-height:18px;white-space:nowrap;opacity:0;transform:translateY(4px);transition:opacity var(--dm-t-fast) var(--dm-ease),transform var(--dm-t) var(--dm-ease);pointer-events:none}
.dm-lnx-tt-h{padding:6px 10px;font-size:12px;color:var(--dm-muted);border-bottom:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent)}
.dm-lnx-tt-r{display:flex;align-items:center;gap:var(--dm-s-2);padding:6px 10px}
.dm-lnx-tt-r+.dm-lnx-tt-r{padding-top:0}
.dm-lnx-tt-r i{width:12px;height:2px;flex:none;border-radius:1px;background:var(--dm-lnx-line)}
.dm-lnx-tt-r.dm-c i{height:2px;background:radial-gradient(circle,var(--dm-lnx-cmp) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.dm-lnx-tt-r.dm-p i{background:radial-gradient(circle,var(--dm-lnx-line) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.dm-lnx-tt-r span{flex:1;color:var(--dm-fg2)}
.dm-lnx-tt-r b{font-weight:500;color:var(--dm-fg)}
.dm-lnx-tt-r[hidden]{display:none}
.dm-lnx.dm-on .dm-lnx-x,.dm-lnx.dm-on .dm-lnx-tt,.dm-lnx.dm-on .dm-lnx-pt.dm-on{opacity:1}
.dm-lnx.dm-on .dm-lnx-tt{transform:none}
/* the axis: the period's first point on the left, Now under its point in the accent's text colour, the last on the right; the
   point pointed at is a grey chip, and any label it would touch steps aside */
.dm-lnx-ax{grid-column:2;position:relative;height:20px;font-size:12px;line-height:20px;color:var(--dm-muted)}
.dm-lnx-ax span{position:absolute;top:0;left:0;white-space:nowrap;transition:opacity var(--dm-t-fast) var(--dm-ease)}
/* the last label ends on the plot's right edge (6px in when it is Now's own, so it sits under the ring) */
.dm-lnx-ax .dm-lnx-z:not([style]){left:auto;right:0}
.dm-lnx-ax .dm-lnx-z.dm-lnx-nw:not([style]){right:6px}
.dm-lnx-ax .dm-lnx-nw{color:var(--dm-accent-fg,var(--dm-accent))}
.dm-lnx-ax .dm-lnx-tk{padding:0 6px;border-radius:var(--dm-r-xs);background:var(--dm-chip);color:var(--dm-fg2);opacity:0}
.dm-lnx.dm-on .dm-lnx-ax .dm-lnx-tk{opacity:1}
.dm-lnx-ax :is(.dm-lnx-off,.dm-lnx-hid){opacity:0}
/* the legend: each line's swatch and name, a toggle; its words start on the content's edge and its hover reaches out round them.
   On this card the toggles' boxes sit on the content's 16px column instead, so nothing reaches nearer the card's edge than the
   rest of its content (owner, 21 Nov: insets measured in every style); a page that reuses the legend under a plot of its own
   keeps the hover reaching out */
.dm-lnx-lg{display:flex;flex-wrap:wrap;gap:var(--dm-s-1);margin:-8px -8px -5px}
.dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg{margin:-8px 0 0}
.dm-lnx-k{display:flex;align-items:center;gap:6px;height:26px;padding:0 8px;border-radius:var(--dm-r-pill);font-size:12px;color:var(--dm-muted);transition:color var(--dm-t-fast) var(--dm-ease),background-color var(--dm-t-fast) var(--dm-ease)}
@media (hover:hover) and (pointer:fine){.dm-lnx-k:hover{background:var(--dm-row)}}
.dm-lnx-k[aria-pressed="true"]{color:var(--dm-fg)}
.dm-lnx-k i{width:12px;height:2px;flex:none;border-radius:1px;background:var(--dm-lnx-line);transition:opacity var(--dm-t-fast) var(--dm-ease)}
.dm-lnx-k.dm-c i{background:radial-gradient(circle,var(--dm-lnx-cmp) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.dm-lnx-k.dm-p i{background:radial-gradient(circle,var(--dm-lnx-line) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.dm-lnx-k[aria-pressed="false"] i{opacity:.3}
.dm-lnx-svg :is(.dm-ln,.dm-ar,.dm-cmp,.dm-prj,.dm-par){transition:opacity var(--dm-t) var(--dm-ease)}
.dm-lnx.dm-lnx-noa .dm-lnx-svg :is(.dm-ln,.dm-ar),.dm-lnx.dm-lnx-nop .dm-lnx-svg :is(.dm-prj,.dm-par),.dm-lnx.dm-lnx-nob .dm-lnx-svg .dm-cmp{opacity:0}
.dm-lnx.dm-lnx-noa .dm-lnx-now{visibility:hidden}
.dm-lnx-sr{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
.dm-lnx-sr th{font-weight:400}
@media (prefers-reduced-motion:reduce){.dm-lnx :is(.dm-lnx-x,.dm-lnx-pt,.dm-lnx-tt,.dm-lnx-now,.dm-lnx-ax span){transition:none}}
/* Blueprint: square marks (the ring, the hover marks, the swatches) and square dots on the line before */
/* Studio: the project marks are monochrome, a solid ink tile like a logo, its letter in the ink's own text colour */
:root[data-style="studio"] .dm-lnx-mk,:root [data-style="studio"] .dm-lnx-mk,:root [data-style="studio"].dm-lnx-mk{background:var(--dm-ink);color:var(--dm-on-ink)}
/* Studio (owner, 21 Nov: Studio must read as Studio at a glance): the head and the legend sit on off-white strips that follow the
   card's corners, their controls on the content's 16px column and 16px from the strip's top and bottom (owner, 23 Nov; the title's words on
   the column, the switch ending on it). The picker's hover is a pill. The legend's toggles are flat pills: a line that is shown
   has the stronger neutral fill (Studio's selected state), one that is hidden none until pointed at, when it takes Studio's one
   hover fill. The readout is
   Studio's popover: its corners, its 6px inset and rows like a menu's, scaling and fading in over 220ms. The pointed-at tick is
   a pill. The strips belong to this card's own head (the title and the picker): a page that reuses the plot under a head of
   its own keeps its layout */
:root[data-style="studio"] .dm-lnx>.dm-lnx-h:has(>.dm-lnx-tl),:root [data-style="studio"] .dm-lnx>.dm-lnx-h:has(>.dm-lnx-tl),:root [data-style="studio"].dm-lnx>.dm-lnx-h:has(>.dm-lnx-tl){margin:calc(-1 * var(--dm-s-4)) calc(-1 * var(--dm-s-4)) 0;padding:var(--dm-strip-y) var(--dm-s-4);background:var(--dm-strip);border-bottom:1px solid var(--dm-line);border-radius:var(--dm-r-card) var(--dm-r-card) 0 0}
:root[data-style="studio"] .dm-lnx-pk,:root [data-style="studio"] .dm-lnx-pk,:root [data-style="studio"].dm-lnx-pk{border-radius:var(--dm-r-pill)}
@media (hover:hover) and (pointer:fine){:root[data-style="studio"] .dm-lnx-pk:hover,:root [data-style="studio"] .dm-lnx-pk:hover,:root [data-style="studio"].dm-lnx-pk:hover{background:var(--dm-row)}}
:root[data-style="studio"] .dm-lnx-pk[aria-expanded="true"],:root [data-style="studio"] .dm-lnx-pk[aria-expanded="true"],:root [data-style="studio"].dm-lnx-pk[aria-expanded="true"]{background:var(--dm-row-on)}
:root[data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg,:root [data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg,:root [data-style="studio"].dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg{margin:0 calc(-1 * var(--dm-s-4)) calc(-1 * var(--dm-s-4));padding:var(--dm-strip-y) var(--dm-s-4);gap:6px;background:var(--dm-strip);border-top:1px solid var(--dm-line);border-radius:0 0 var(--dm-r-card) var(--dm-r-card)}
:root[data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k,:root [data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k,:root [data-style="studio"].dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k{height:28px;padding:0 10px}
/* (on a phone its two columns share the width, the second ending on the content's right edge like the switch above) */
@container lnx (max-width:300px){:root[data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg,:root [data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg,:root [data-style="studio"].dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg{grid-template-columns:1fr 1fr}}
:root[data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k[aria-pressed="true"],:root [data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k[aria-pressed="true"],:root [data-style="studio"].dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k[aria-pressed="true"]{background:var(--dm-row-on)}
@media (hover:hover) and (pointer:fine){:root[data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k[aria-pressed="false"]:hover,:root [data-style="studio"] .dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k[aria-pressed="false"]:hover,:root [data-style="studio"].dm-lnx:has(>.dm-lnx-h>.dm-lnx-tl)>.dm-lnx-lg .dm-lnx-k[aria-pressed="false"]:hover{background:var(--dm-row)}}
:root[data-style="studio"] .dm-lnx-tt,:root [data-style="studio"] .dm-lnx-tt,:root [data-style="studio"].dm-lnx-tt{padding:6px;border-radius:calc(14px * var(--dm-rk-l,var(--dm-rk)));transform:scale(.96);transition:opacity var(--dm-t-fast) var(--dm-ease),transform var(--dm-t-fast) var(--dm-ease)}
:root[data-style="studio"] .dm-lnx.dm-on .dm-lnx-tt,:root [data-style="studio"] .dm-lnx.dm-on .dm-lnx-tt,:root [data-style="studio"].dm-lnx.dm-on .dm-lnx-tt{transform:none}
:root[data-style="studio"] .dm-lnx-tt-h,:root [data-style="studio"] .dm-lnx-tt-h,:root [data-style="studio"].dm-lnx-tt-h{padding:2px 8px 4px;border-bottom:0}
:root[data-style="studio"] .dm-lnx-tt-r,:root [data-style="studio"] .dm-lnx-tt-r,:root [data-style="studio"].dm-lnx-tt-r,:root[data-style="studio"] .dm-lnx-tt-r+.dm-lnx-tt-r,:root [data-style="studio"] .dm-lnx-tt-r+.dm-lnx-tt-r,:root [data-style="studio"].dm-lnx-tt-r+.dm-lnx-tt-r{padding:5px 8px;border-radius:var(--dm-r-in)}
:root[data-style="studio"] .dm-lnx-ax .dm-lnx-tk,:root [data-style="studio"] .dm-lnx-ax .dm-lnx-tk,:root [data-style="studio"].dm-lnx-ax .dm-lnx-tk{border-radius:var(--dm-r-pill)}
/* Studio dark's accent is white (owner, 21 Nov; Studio dark's tokens): the line, its projection, its rings and "Now" are white,
   so the area under them is a little fainter; the comparison keeps the palette's violet */
:root[data-style="studio"][data-theme="dark"] .dm-lnx,:root[data-theme="dark"] [data-style="studio"] .dm-lnx,:root[data-theme="dark"] [data-style="studio"].dm-lnx{--dm-lnx-fill:.16;--dm-lnx-pfill:.08}
@media (prefers-color-scheme:dark){:root[data-style="studio"]:not([data-theme="light"]) .dm-lnx,:root:not([data-theme="light"]) [data-style="studio"] .dm-lnx,:root:not([data-theme="light"]) [data-style="studio"].dm-lnx{--dm-lnx-fill:.16;--dm-lnx-pfill:.08}}
@media (prefers-reduced-motion:reduce){:root[data-style="studio"] .dm-lnx-tt,:root [data-style="studio"] .dm-lnx-tt,:root [data-style="studio"].dm-lnx-tt{transform:none}}
:root:not([data-style="soft"],[data-style="studio"]) .dm-lnx-svg :is(.dm-cmp,.dm-prj):not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){stroke-dasharray:2 3}
:root:not([data-style="soft"],[data-style="studio"]) .dm-lnx-now:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:linear-gradient(var(--dm-lnx-line),var(--dm-lnx-line)) center/4px 4px no-repeat,var(--dm-surface)}
:root:not([data-style="soft"],[data-style="studio"]) :is(.dm-lnx-tt-r,.dm-lnx-k).dm-c i:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:repeating-linear-gradient(90deg,var(--dm-lnx-cmp) 0 2px,transparent 2px 4px)}
:root:not([data-style="soft"],[data-style="studio"]) :is(.dm-lnx-tt-r,.dm-lnx-k).dm-p i:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:repeating-linear-gradient(90deg,var(--dm-lnx-line) 0 2px,transparent 2px 4px)}
LineChart.astroAstro · 38 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Line chart: Today so far and projected, against yesterday, with a range switch, a project picker, toggles and a readout.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change line-chart.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './line-chart.css';

export interface Props extends HTMLAttributes<'div'> {
  /** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
  'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', className]} data-c="line-chart" {...rest}>
  <div class="stage-in"><Fragment is:raw>
<div class="lnx panel">
  <div class="lnx-h">
    <div class="lnx-tl"><span class="lnx-t">Active editors</span><button class="lnx-pk" data-pop="#lnx-pp" aria-haspopup="menu" aria-expanded="false"><span class="lnx-mk" aria-hidden="true"></span><span class="lnx-pn"></span><svg class="i xs"><use href="#i-chev-d"/></svg></button></div>
    <div class="seg2 lnx-rg" role="group" aria-label="Range"><button aria-pressed="true" data-v="d">Day</button><button aria-pressed="false" data-v="w">Week</button><button aria-pressed="false" data-v="m">Month</button></div>
  </div>
  <div class="pop lnx-pp" id="lnx-pp" role="menu" aria-label="Project"></div>
  <div class="lnx-pl">
    <div class="lnx-y num" aria-hidden="true"></div>
    <div class="lnx-ch" tabindex="0" role="group" aria-roledescription="line chart"><svg class="lnx-svg" aria-hidden="true"></svg><span class="lnx-x"></span><span class="lnx-pt" style="color:var(--dm-lnx-cmp)"></span><span class="lnx-pt" style="color:var(--dm-lnx-line)"></span><span class="lnx-now"></span><span class="lnx-aim" aria-hidden="true"></span><div class="lnx-tt" aria-hidden="true"><div class="lnx-tt-h"></div><div class="lnx-tt-r"><i></i><span></span><b class="num"></b></div><div class="lnx-tt-r c"><i></i><span></span><b class="num"></b></div></div></div>
    <div class="lnx-ax num" aria-hidden="true"></div>
  </div>
  <div class="lnx-lg"><button class="lnx-k" aria-pressed="true" data-s="a"><i></i><span></span></button><button class="lnx-k p" aria-pressed="true" data-s="p"><i></i><span>Projected</span></button><button class="lnx-k c" aria-pressed="true" data-s="b"><i></i><span></span></button></div>
  <p class="lnx-sr" aria-live="polite"></p>
  <div class="lnx-sr"><table></table></div>
</div>
  </Fragment></div>
</div>
<script>
  import './line-chart.js';
</script>
line-chart.htmlHTML · 20 lines
<div class="card" data-c="line-chart">
  <div class="stage-in">
    <div class="lnx panel">
      <div class="lnx-h">
        <div class="lnx-tl"><span class="lnx-t">Active editors</span><button class="lnx-pk" data-pop="#lnx-pp" aria-haspopup="menu" aria-expanded="false"><span class="lnx-mk" aria-hidden="true"></span><span class="lnx-pn"></span><svg class="i xs"><use href="#i-chev-d"/></svg></button></div>
        <div class="seg2 lnx-rg" role="group" aria-label="Range"><button aria-pressed="true" data-v="d">Day</button><button aria-pressed="false" data-v="w">Week</button><button aria-pressed="false" data-v="m">Month</button></div>
      </div>
      <div class="pop lnx-pp" id="lnx-pp" role="menu" aria-label="Project"></div>
      <div class="lnx-pl">
        <div class="lnx-y num" aria-hidden="true"></div>
        <div class="lnx-ch" tabindex="0" role="group" aria-roledescription="line chart"><svg class="lnx-svg" aria-hidden="true"></svg><span class="lnx-x"></span><span class="lnx-pt" style="color:var(--dm-lnx-cmp)"></span><span class="lnx-pt" style="color:var(--dm-lnx-line)"></span><span class="lnx-now"></span><span class="lnx-aim" aria-hidden="true"></span><div class="lnx-tt" aria-hidden="true"><div class="lnx-tt-h"></div><div class="lnx-tt-r"><i></i><span></span><b class="num"></b></div><div class="lnx-tt-r c"><i></i><span></span><b class="num"></b></div></div></div>
        <div class="lnx-ax num" aria-hidden="true"></div>
      </div>
      <div class="lnx-lg"><button class="lnx-k" aria-pressed="true" data-s="a"><i></i><span></span></button><button class="lnx-k p" aria-pressed="true" data-s="p"><i></i><span>Projected</span></button><button class="lnx-k c" aria-pressed="true" data-s="b"><i></i><span></span></button></div>
      <p class="lnx-sr" aria-live="polite"></p>
      <div class="lnx-sr"><table></table></div>
    </div>
  </div>
</div>
line-chart.cssHTML · 126 lines
/* ---------- Line chart ---------- */
/* one metric over a period, against the period before (owner, 21 Nov): straight segments with sharp joins, a saturated line in the accent, and a fill that fades from the line's colour
   at the top to nothing at the bottom. A quiet head: the title, a picker for whose numbers they are, and the range switch, with
   a hairline under them. Under it the plot: the values on the left, dashed vertical gridlines and no horizontal ones, the period
   before as a dotted line in the chart palette's second colour across the whole period, and this period as a solid line up to
   now, with an open ring and "Now" under it, then projected to the period's end as a dotted line in its own colour over a
   fill at half strength, so the chart always runs full width (owner, 21 Nov: "I never seen charts that end mid way"). A legend under the plot names both lines and turns each on and off. Pointing at the plot, or the arrow keys on it, shows a dashed guide, a ring on each line and a readout card
   beside the guide on the side with room, and the point's name becomes a grey chip on the axis. The content sits 16px in from
   every edge; the picker's and the switch's hover boxes reach out round their words */
.lnx{padding:var(--dm-s-4);display:flex;flex-direction:column;gap:var(--dm-s-4);--dm-row:color-mix(in srgb,var(--dm-fg) 5%,transparent);
  --dm-lnx-line:var(--dm-accent-mark,var(--dm-accent));--dm-lnx-cmp:var(--dm-c2);--dm-lnx-fill:.2;--dm-lnx-pfill:.1;--dm-lnx-grid:var(--dm-line);--dm-lnx-guide:color-mix(in srgb,var(--dm-fg) 38%,transparent)}
:root[data-theme="dark"] .lnx{--dm-lnx-fill:.3;--dm-lnx-pfill:.15}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]) .lnx{--dm-lnx-fill:.3;--dm-lnx-pfill:.15}}
.lnx-h{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-2) var(--dm-s-3);flex-wrap:wrap;padding-bottom:var(--dm-s-4);border-bottom:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent)}
.lnx-tl{display:flex;align-items:center;gap:6px;min-width:0;font-size:13.5px;line-height:20px}
.lnx-t{color:var(--dm-muted);white-space:nowrap}
/* the picker: its mark and words in the text colour, no edge until hovered; its hover box reaches out round them */
.lnx-pk{display:inline-flex;align-items:center;gap:6px;height:28px;margin:-4px -5px -4px 0;padding:0 5px 0 8px;border-radius:var(--dm-r-sm);color:var(--dm-fg);font-weight:500;white-space:nowrap;transition:background-color var(--dm-t-fast) var(--dm-ease)}
.lnx-pk[aria-expanded="true"]{background:var(--dm-row)}
@media (hover:hover) and (pointer:fine){.lnx-pk:hover{background:var(--dm-row)}}
.lnx-pk .i{color:var(--dm-muted);margin-left:-2px}
.lnx-mk{width:18px;height:18px;flex:none;display:grid;place-items:center;border-radius:calc(5px * var(--dm-rk-s,var(--dm-rk)));font-size:10.5px;font-weight:500;line-height:1;background:var(--dm-mk,var(--dm-av-b));color:var(--dm-mk-ink,var(--dm-av-b-ink))}
.pop.lnx-pp{min-width:188px}
.lnx-pp .mi{gap:var(--dm-s-2)}
.lnx-rg button{font-size:12px;height:26px;padding:0 9px}
/* on a narrow card the switch goes under the title, as wide as the content, its parts sharing the width */
.lnx{container:lnx/inline-size}
@container lnx (max-width:375px){.lnx-h{flex-direction:column;align-items:stretch}.lnx-rg{display:flex}.lnx-rg button{flex:1}.lnx-pk{margin-top:0;margin-bottom:0}}
/* and on a phone the legend's three lines take two columns, so it is two rows whatever the range calls them, and switching the
   range never changes the card's height */
@container lnx (max-width:300px){.lnx .lnx-lg{display:grid;grid-template-columns:max-content max-content;gap:2px var(--dm-s-1);justify-content:start}}
/* the plot: the values in a column on the left, each centred on its height; the axis under the drawing */
.lnx-pl{display:grid;grid-template-rows:auto auto;grid-template-columns:auto minmax(0,1fr);column-gap:var(--dm-s-3);row-gap:var(--dm-s-2)}
.lnx-y{display:flex;flex-direction:column;justify-content:space-between;margin:-8px 0;font-size:12px;line-height:16px;color:var(--dm-muted);text-align:right;white-space:nowrap}
.lnx-ch{position:relative;height:168px;touch-action:pan-y}
.lnx-ch:focus-visible{outline-offset:6px}
.lnx-svg{position:absolute;left:0;top:0;width:100%;height:100%;display:block;overflow:visible}
.lnx-svg .gl{stroke:var(--dm-lnx-grid);stroke-width:1;stroke-dasharray:3 4}
.lnx-svg .ln{fill:none;stroke:var(--dm-lnx-line);stroke-width:2;stroke-linejoin:miter;stroke-miterlimit:8;stroke-linecap:butt}
.lnx-svg :is(.cmp,.prj){fill:none;stroke:var(--dm-lnx-cmp);stroke-width:2;stroke-linecap:round;stroke-dasharray:0 5}
.lnx-svg .prj{stroke:var(--dm-lnx-line)}
/* now: an open ring on the line's end, with a dot of the line's colour inside */
.lnx-now{position:absolute;left:0;top:0;width:12px;height:12px;margin:-6px 0 0 -6px;border-radius:50%;background:radial-gradient(circle,var(--dm-lnx-line) 2px,var(--dm-surface) 2.6px);box-shadow:inset 0 0 0 2px var(--dm-lnx-line);pointer-events:none;transition:opacity var(--dm-t-fast) var(--dm-ease)}
/* the guide, the rings and the readout show while the plot is pointed at or has the keyboard's focus */
/* where the demo's pointer aims: an empty box centred on the point it reads */
.lnx-aim{position:absolute;left:0;top:0;width:16px;height:16px;margin:-8px 0 0 -8px;pointer-events:none}
.lnx-x{position:absolute;top:0;bottom:0;left:0;width:1px;margin-left:-.5px;background:repeating-linear-gradient(to bottom,var(--dm-lnx-guide) 0 3px,transparent 3px 7px);opacity:0;transition:opacity var(--dm-t-fast) var(--dm-ease);pointer-events:none}
.lnx-pt{position:absolute;left:0;top:0;width:10px;height:10px;margin:-5px 0 0 -5px;border-radius:50%;background:var(--dm-surface);box-shadow:inset 0 0 0 2px currentColor;opacity:0;transition:opacity var(--dm-t-fast) var(--dm-ease);pointer-events:none}
.lnx-tt{position:absolute;left:0;top:0;z-index:2;min-width:156px;border-radius:calc(10px * var(--dm-rk-m,var(--dm-rk)));background:var(--dm-raised);box-shadow:var(--dm-shadow-pop);font-size:12.5px;line-height:18px;white-space:nowrap;opacity:0;transform:translateY(4px);transition:opacity var(--dm-t-fast) var(--dm-ease),transform var(--dm-t) var(--dm-ease);pointer-events:none}
.lnx-tt-h{padding:6px 10px;font-size:12px;color:var(--dm-muted);border-bottom:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent)}
.lnx-tt-r{display:flex;align-items:center;gap:var(--dm-s-2);padding:6px 10px}
.lnx-tt-r+.lnx-tt-r{padding-top:0}
.lnx-tt-r i{width:12px;height:2px;flex:none;border-radius:1px;background:var(--dm-lnx-line)}
.lnx-tt-r.c i{height:2px;background:radial-gradient(circle,var(--dm-lnx-cmp) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.lnx-tt-r.p i{background:radial-gradient(circle,var(--dm-lnx-line) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.lnx-tt-r span{flex:1;color:var(--dm-fg2)}
.lnx-tt-r b{font-weight:500;color:var(--dm-fg)}
.lnx-tt-r[hidden]{display:none}
.lnx.on .lnx-x,.lnx.on .lnx-tt,.lnx.on .lnx-pt.on{opacity:1}
.lnx.on .lnx-tt{transform:none}
/* the axis: the period's first point on the left, Now under its point in the accent's text colour, the last on the right; the
   point pointed at is a grey chip, and any label it would touch steps aside */
.lnx-ax{grid-column:2;position:relative;height:20px;font-size:12px;line-height:20px;color:var(--dm-muted)}
.lnx-ax span{position:absolute;top:0;left:0;white-space:nowrap;transition:opacity var(--dm-t-fast) var(--dm-ease)}
/* the last label ends on the plot's right edge (6px in when it is Now's own, so it sits under the ring) */
.lnx-ax .lnx-z:not([style]){left:auto;right:0}
.lnx-ax .lnx-z.lnx-nw:not([style]){right:6px}
.lnx-ax .lnx-nw{color:var(--dm-accent-fg,var(--dm-accent))}
.lnx-ax .lnx-tk{padding:0 6px;border-radius:var(--dm-r-xs);background:var(--dm-chip);color:var(--dm-fg2);opacity:0}
.lnx.on .lnx-ax .lnx-tk{opacity:1}
.lnx-ax :is(.lnx-off,.lnx-hid){opacity:0}
/* the legend: each line's swatch and name, a toggle; its words start on the content's edge and its hover reaches out round them.
   On this card the toggles' boxes sit on the content's 16px column instead, so nothing reaches nearer the card's edge than the
   rest of its content (owner, 21 Nov: insets measured in every style); a page that reuses the legend under a plot of its own
   keeps the hover reaching out */
.lnx-lg{display:flex;flex-wrap:wrap;gap:var(--dm-s-1);margin:-8px -8px -5px}
.lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg{margin:-8px 0 0}
.lnx-k{display:flex;align-items:center;gap:6px;height:26px;padding:0 8px;border-radius:var(--dm-r-pill);font-size:12px;color:var(--dm-muted);transition:color var(--dm-t-fast) var(--dm-ease),background-color var(--dm-t-fast) var(--dm-ease)}
@media (hover:hover) and (pointer:fine){.lnx-k:hover{background:var(--dm-row)}}
.lnx-k[aria-pressed="true"]{color:var(--dm-fg)}
.lnx-k i{width:12px;height:2px;flex:none;border-radius:1px;background:var(--dm-lnx-line);transition:opacity var(--dm-t-fast) var(--dm-ease)}
.lnx-k.c i{background:radial-gradient(circle,var(--dm-lnx-cmp) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.lnx-k.p i{background:radial-gradient(circle,var(--dm-lnx-line) .9px,transparent 1.1px) 0 50%/4px 2px repeat-x}
.lnx-k[aria-pressed="false"] i{opacity:.3}
.lnx-svg :is(.ln,.ar,.cmp,.prj,.par){transition:opacity var(--dm-t) var(--dm-ease)}
.lnx.lnx-noa .lnx-svg :is(.ln,.ar),.lnx.lnx-nop .lnx-svg :is(.prj,.par),.lnx.lnx-nob .lnx-svg .cmp{opacity:0}
.lnx.lnx-noa .lnx-now{visibility:hidden}
.lnx-sr{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
.lnx-sr th{font-weight:400}
@media (prefers-reduced-motion:reduce){.lnx :is(.lnx-x,.lnx-pt,.lnx-tt,.lnx-now,.lnx-ax span){transition:none}}
/* Blueprint: square marks (the ring, the hover marks, the swatches) and square dots on the line before */
/* Studio: the project marks are monochrome, a solid ink tile like a logo, its letter in the ink's own text colour */
:root[data-style="studio"] .lnx-mk,:root [data-style="studio"] .lnx-mk,:root [data-style="studio"].lnx-mk{background:var(--dm-ink);color:var(--dm-on-ink)}
/* Studio (owner, 21 Nov: Studio must read as Studio at a glance): the head and the legend sit on off-white strips that follow the
   card's corners, their controls on the content's 16px column and 16px from the strip's top and bottom (owner, 23 Nov; the title's words on
   the column, the switch ending on it). The picker's hover is a pill. The legend's toggles are flat pills: a line that is shown
   has the stronger neutral fill (Studio's selected state), one that is hidden none until pointed at, when it takes Studio's one
   hover fill. The readout is
   Studio's popover: its corners, its 6px inset and rows like a menu's, scaling and fading in over 220ms. The pointed-at tick is
   a pill. The strips belong to this card's own head (the title and the picker): a page that reuses the plot under a head of
   its own keeps its layout */
:root[data-style="studio"] .lnx>.lnx-h:has(>.lnx-tl),:root [data-style="studio"] .lnx>.lnx-h:has(>.lnx-tl),:root [data-style="studio"].lnx>.lnx-h:has(>.lnx-tl){margin:calc(-1 * var(--dm-s-4)) calc(-1 * var(--dm-s-4)) 0;padding:var(--dm-strip-y) var(--dm-s-4);background:var(--dm-strip);border-bottom:1px solid var(--dm-line);border-radius:var(--dm-r-card) var(--dm-r-card) 0 0}
:root[data-style="studio"] .lnx-pk,:root [data-style="studio"] .lnx-pk,:root [data-style="studio"].lnx-pk{border-radius:var(--dm-r-pill)}
@media (hover:hover) and (pointer:fine){:root[data-style="studio"] .lnx-pk:hover,:root [data-style="studio"] .lnx-pk:hover,:root [data-style="studio"].lnx-pk:hover{background:var(--dm-row)}}
:root[data-style="studio"] .lnx-pk[aria-expanded="true"],:root [data-style="studio"] .lnx-pk[aria-expanded="true"],:root [data-style="studio"].lnx-pk[aria-expanded="true"]{background:var(--dm-row-on)}
:root[data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg,:root [data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg,:root [data-style="studio"].lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg{margin:0 calc(-1 * var(--dm-s-4)) calc(-1 * var(--dm-s-4));padding:var(--dm-strip-y) var(--dm-s-4);gap:6px;background:var(--dm-strip);border-top:1px solid var(--dm-line);border-radius:0 0 var(--dm-r-card) var(--dm-r-card)}
:root[data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k,:root [data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k,:root [data-style="studio"].lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k{height:28px;padding:0 10px}
/* (on a phone its two columns share the width, the second ending on the content's right edge like the switch above) */
@container lnx (max-width:300px){:root[data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg,:root [data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg,:root [data-style="studio"].lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg{grid-template-columns:1fr 1fr}}
:root[data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k[aria-pressed="true"],:root [data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k[aria-pressed="true"],:root [data-style="studio"].lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k[aria-pressed="true"]{background:var(--dm-row-on)}
@media (hover:hover) and (pointer:fine){:root[data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k[aria-pressed="false"]:hover,:root [data-style="studio"] .lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k[aria-pressed="false"]:hover,:root [data-style="studio"].lnx:has(>.lnx-h>.lnx-tl)>.lnx-lg .lnx-k[aria-pressed="false"]:hover{background:var(--dm-row)}}
:root[data-style="studio"] .lnx-tt,:root [data-style="studio"] .lnx-tt,:root [data-style="studio"].lnx-tt{padding:6px;border-radius:calc(14px * var(--dm-rk-l,var(--dm-rk)));transform:scale(.96);transition:opacity var(--dm-t-fast) var(--dm-ease),transform var(--dm-t-fast) var(--dm-ease)}
:root[data-style="studio"] .lnx.on .lnx-tt,:root [data-style="studio"] .lnx.on .lnx-tt,:root [data-style="studio"].lnx.on .lnx-tt{transform:none}
:root[data-style="studio"] .lnx-tt-h,:root [data-style="studio"] .lnx-tt-h,:root [data-style="studio"].lnx-tt-h{padding:2px 8px 4px;border-bottom:0}
:root[data-style="studio"] .lnx-tt-r,:root [data-style="studio"] .lnx-tt-r,:root [data-style="studio"].lnx-tt-r,:root[data-style="studio"] .lnx-tt-r+.lnx-tt-r,:root [data-style="studio"] .lnx-tt-r+.lnx-tt-r,:root [data-style="studio"].lnx-tt-r+.lnx-tt-r{padding:5px 8px;border-radius:var(--dm-r-in)}
:root[data-style="studio"] .lnx-ax .lnx-tk,:root [data-style="studio"] .lnx-ax .lnx-tk,:root [data-style="studio"].lnx-ax .lnx-tk{border-radius:var(--dm-r-pill)}
/* Studio dark's accent is white (owner, 21 Nov; Studio dark's tokens): the line, its projection, its rings and "Now" are white,
   so the area under them is a little fainter; the comparison keeps the palette's violet */
:root[data-style="studio"][data-theme="dark"] .lnx,:root[data-theme="dark"] [data-style="studio"] .lnx,:root[data-theme="dark"] [data-style="studio"].lnx{--dm-lnx-fill:.16;--dm-lnx-pfill:.08}
@media (prefers-color-scheme:dark){:root[data-style="studio"]:not([data-theme="light"]) .lnx,:root:not([data-theme="light"]) [data-style="studio"] .lnx,:root:not([data-theme="light"]) [data-style="studio"].lnx{--dm-lnx-fill:.16;--dm-lnx-pfill:.08}}
@media (prefers-reduced-motion:reduce){:root[data-style="studio"] .lnx-tt,:root [data-style="studio"] .lnx-tt,:root [data-style="studio"].lnx-tt{transform:none}}
:root:not([data-style="soft"],[data-style="studio"]) .lnx-svg :is(.cmp,.prj):not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){stroke-dasharray:2 3}
:root:not([data-style="soft"],[data-style="studio"]) .lnx-now:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:linear-gradient(var(--dm-lnx-line),var(--dm-lnx-line)) center/4px 4px no-repeat,var(--dm-surface)}
:root:not([data-style="soft"],[data-style="studio"]) :is(.lnx-tt-r,.lnx-k).c i:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:repeating-linear-gradient(90deg,var(--dm-lnx-cmp) 0 2px,transparent 2px 4px)}
:root:not([data-style="soft"],[data-style="studio"]) :is(.lnx-tt-r,.lnx-k).p i:not(:where([data-style="soft"],[data-style="soft"] *,[data-style="studio"],[data-style="studio"] *)){background:repeating-linear-gradient(90deg,var(--dm-lnx-line) 0 2px,transparent 2px 4px)}
line-chart.jsHTML · 148 lines
DM.def('line-chart', (r, c) => {
  r.innerHTML = r.innerHTML.replace('{chev}', I('chev-d','xs'));
  const root = $('.lnx', r), ch = $('.lnx-ch', r), svg = $('.lnx-svg', r), yl = $('.lnx-y', r), ax = $('.lnx-ax', r), tt = $('.lnx-tt', r);
  const mark = $('.lnx-now', r), guide = $('.lnx-x', r), [pc, pm] = $$('.lnx-pt', r), pk = $('.lnx-pk', r), pp = $('.lnx-pp', r), live = $('p.lnx-sr', r), tab = $('.lnx-sr table', r);
  // the projects the picker offers: name, mark, the mark's colour, and how big each is next to the website
  const PJ = [['Website', 'W', 'b', 1], ['Mobile app', 'M', 'l', .58], ['Docs', 'D', 'm', .27]];
  // a small seeded wobble, so each project's numbers differ but are the same on every visit
  const wob = (s, i) => { const x = Math.sin(s * 91.7 + i * 12.9898) * 43758.5453; return x - Math.floor(x) - .5; };
  const HRS = Array.from({ length:24 }, (_, h) => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'));
  const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  // editors at work: an hour of today (it is 2pm on Thursday 19 November), a day of this week, a day of this month. November
  // starts on a Sunday and October on a Thursday, so their weekends fall on different days
  const RG = {
    d:{ pts:HRS, ax:HRS, now:14, a:'Today', b:'Yesterday', each:'Hour', what:'today against yesterday', grid:[1, 2, 3, 4, 6, 12],
      base:[110, 80, 64, 58, 62, 96, 210, 460, 820, 1120, 1290, 1360, 1180, 1260, 1330, 1250, 1130, 960, 720, 510, 360, 260, 190, 140], ka:1.05, kb:.93 },
    w:{ pts:DAYS, ax:DAYS.map(d => d.slice(0, 3)), now:3, a:'This week', b:'Last week', each:'Day', what:'this week against last week', grid:[1],
      base:[4380, 4720, 4610, 4890, 4420, 1680, 1240], ka:1.04, kb:.92 },
    m:{ pts:Array.from({ length:30 }, (_, d) => 'Nov ' + (d + 1)), ax:Array.from({ length:30 }, (_, d) => 'Nov ' + (d + 1)), now:18, a:'This month', b:'Last month', each:'Day', what:'this month against last month', grid:[1, 7, 14],
      base:Array.from({ length:30 }, (_, d) => d % 7 === 0 || d % 7 === 6 ? 1500 : 4500), baseB:Array.from({ length:30 }, (_, d) => (4 + d) % 7 === 0 || (4 + d) % 7 === 6 ? 1450 : 4400), ka:1.02, kb:.95 }
  };
  /* the rest of the period is projected from now: the latest value carried forward along the shape the period before took over
     the same points (the month along its own weekdays, as October's weekends fall on other dates) */
  const data = (p, k) => { const g = RG[k], [, , , sz] = PJ[p];
    const va = g.base.slice(0, g.now + 1).map((v, i) => Math.round(v * g.ka * sz * (1 + wob(p + 1, i) * .14)));
    const vb = (g.baseB || g.base).map((v, i) => Math.round(v * g.kb * sz * (1 + wob(p + 7, i) * .14)));
    const shape = g.baseB ? g.base.map((v, i) => v * (1 + wob(p + 13, i) * .06)) : vb;
    return { ...g, va, vb, vp:vb.map((_, i) => i < g.now ? null : Math.round(va[g.now] * shape[i] / shape[g.now])) }; };
  const fmt = n => n.toLocaleString('en-US');
  const kf = n => n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n);
  // the top of the scale: a round step that gives three or four bands above zero, with a little room over the highest value
  const scale = m => { const raw = m / 4, p = 10 ** Math.floor(Math.log10(raw || 1)), s = [1, 2, 2.5, 5, 10].map(k => k * p).find(k => k >= raw); return { s, top:Math.ceil(m * 1.04 / s) * s }; };
  const uid = 'lnx' + Math.random().toString(36).slice(2, 8);
  let pj = 0, rg = 'd', D = null, S = null, shown = 1, at = -1, clip = null;
  // which lines show: the legend turns each on and off, and one always stays on
  const on = { a:true, p:true, b:true }, keys = $$('.lnx-k', r);
  // where things go: the points spread over the plot's width, less the ring's half when the line ends on the last point
  const geo = () => { const W = ch.clientWidth, H = ch.clientHeight, n = D.pts.length - 1, xr = W - (D.now === n ? 6 : 0);
    return { W, H, n, xr, X:i => i / n * xr, Y:v => H - v / S.top * H }; };
  function draw(){
    if (!D || !ch.clientWidth) return;
    const { W, H, n, xr, X, Y } = geo(), A = D.va;
    const path = vs => vs.map((v, i) => `${i ? 'L' : 'M'}${X(i).toFixed(1)} ${Y(v).toFixed(1)}`).join('');
    // a gridline every few points, as many as fit about 40px apart
    const k = D.grid.find(g => g * xr / n >= 40) || D.grid[D.grid.length - 1];
    const gl = []; for (let i = 0; i <= n; i += k){ const x = Math.round(X(i)) + .5; gl.push(`<line class="gl" x1="${x}" x2="${x}" y1="0" y2="${H}"/>`); }
    svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
    const P = D.vp.slice(D.now), pPath = P.map((v, j) => `${j ? 'L' : 'M'}${X(D.now + j).toFixed(1)} ${Y(v).toFixed(1)}`).join('');
    svg.innerHTML = `<defs><linearGradient id="${uid}g" x1="0" x2="0" y1="0" y2="1"><stop offset="0" style="stop-color:var(--dm-lnx-line);stop-opacity:var(--dm-lnx-fill)"/><stop offset="1" style="stop-color:var(--dm-lnx-line);stop-opacity:0"/></linearGradient>`
      + `<linearGradient id="${uid}p" x1="0" x2="0" y1="0" y2="1"><stop offset="0" style="stop-color:var(--dm-lnx-line);stop-opacity:var(--dm-lnx-pfill)"/><stop offset="1" style="stop-color:var(--dm-lnx-line);stop-opacity:0"/></linearGradient>`
      + `<clipPath id="${uid}c"><rect x="-8" y="-8" height="${H + 16}" width="${(W + 16) * shown}"/></clipPath></defs>` + gl.join('')
      + `<g clip-path="url(#${uid}c)"><path class="cmp" d="${path(D.vb)}"/>`
      + (P.length > 1 ? `<path class="par" d="${pPath}L${X(n).toFixed(1)} ${H}L${X(D.now).toFixed(1)} ${H}Z" fill="url(#${uid}p)"/>` : '')
      + `<path class="ar" d="${path(A)}L${X(D.now).toFixed(1)} ${H}L0 ${H}Z" fill="url(#${uid}g)"/>${P.length > 1 ? `<path class="prj" d="${pPath}"/>` : ''}<path class="ln" d="${path(A)}"/></g>`;
    clip = $('rect', svg);
    mark.style.left = X(D.now) + 'px'; mark.style.top = Y(A[D.now]) + 'px'; mark.style.opacity = shown * (W + 16) - 8 >= X(D.now) ? 1 : 0;
    // the values on the left, top to bottom
    yl.innerHTML = Array.from({ length:S.top / S.s + 1 }, (_, j) => `<span>${kf(S.top - j * S.s)}</span>`).join('');
    // the axis: the first and last points, and Now under its own point (or the last point named Now when the line ends there)
    ax.innerHTML = `<span class="lnx-a">${D.ax[0]}</span><span class="lnx-z${D.now === n ? ' lnx-nw' : ''}">${D.now === n ? 'Now' : D.ax[n]}</span>${D.now < n ? '<span class="lnx-nw">Now</span>' : ''}<span class="lnx-tk"></span>`;
    const put = (el, x) => { const w = el.offsetWidth; el.style.left = Math.max(0, Math.min(xr - w, x - w / 2)) + 'px'; };
    const z = $('.lnx-z', ax);
    const nw = $('.lnx-nw:not(.lnx-z)', ax); if (nw){ put(nw, X(D.now)); [$('.lnx-a', ax), z].forEach(l => l.classList.toggle('lnx-hid', near(l, nw))); }
    if (at >= 0) show(at);
  }
  // two labels on the axis touch when their boxes come within 6px
  const near = (a, b) => { const p = a.offsetLeft, q = b.offsetLeft; return p < q + b.offsetWidth + 6 && q < p + a.offsetWidth + 6; };
  // a point's readout: the guide, a ring on each line, the card beside the guide on the side with room, and the point's chip
  function place(i){ const { X, Y } = geo(), x = X(i);
    [pm, pc].forEach(p => p.style.left = x + 'px');
    pm.style.top = Y(i <= D.now ? D.va[i] : D.vp[i]) + 'px'; pc.style.top = Y(D.vb[i]) + 'px'; }
  function show(i, say){
    if (!D) return; at = i; place(i);
    // up to now the reading is this period's own; after now it is the projection
    const { W, H, xr, X, Y } = geo(), x = X(i), ahead = i > D.now, has = ahead ? on.p : on.a, mv = ahead ? D.vp[i] : D.va[i], ml = ahead ? 'Projected' : D.a;
    root.classList.add('on'); guide.style.left = x + 'px';
    pm.classList.toggle('on', has && i !== D.now); pc.classList.toggle('on', on.b);
    $('.lnx-tt-h', tt).textContent = D.pts[i];
    const [ra, rb] = $$('.lnx-tt-r', tt); ra.hidden = !has; ra.classList.toggle('p', ahead);
    if (has){ $('span', ra).textContent = ml; $('b', ra).textContent = fmt(mv); }
    rb.hidden = !on.b; $('span', rb).textContent = D.b; $('b', rb).textContent = fmt(D.vb[i]);
    // beside the guide on the side with room; on a plot too narrow for either side, centred over the point and above it
    // (or under it when it sits high), so the card never covers the point it reads
    const w = tt.offsetWidth, h = tt.offsetHeight, gap = 12, py = Y(has ? mv : D.vb[i]), side = x + gap + w <= W ? x + gap : x - gap - w >= 0 ? x - gap - w : null;
    tt.style.left = (side ?? Math.max(0, Math.min(W - w, x - w / 2))) + 'px';
    tt.style.top = (side != null ? Math.max(0, Math.min(H - h, py - h / 2)) : py - gap - h >= -8 ? py - gap - h : py + gap) + 'px';
    const tk = $('.lnx-tk', ax); tk.textContent = D.ax[i]; const tw = tk.offsetWidth; tk.style.left = Math.max(0, Math.min(xr - tw, x - tw / 2)) + 'px';
    $$('span:not(.lnx-tk)', ax).forEach(l => l.classList.toggle('lnx-off', l.classList.contains('lnx-hid') || near(l, tk)));
    if (say) live.textContent = `${D.pts[i]}: ` + [has && `${ml} ${fmt(mv)}`, on.b && `${D.b} ${fmt(D.vb[i])}`].filter(Boolean).join(', ');
  }
  function hide(){ at = -1; root.classList.remove('on'); $$('span:not(.lnx-tk)', ax).forEach(l => l.classList.toggle('lnx-off', l.classList.contains('lnx-hid'))); }
  // a range or a project picked: the numbers change at once and the lines draw in again from the left
  let tok = 0;
  function load(){
    D = data(pj, rg); S = scale(Math.max(...D.va, ...D.vb, ...D.vp.filter(v => v != null)));
    const p = PJ[pj], mk = $('.lnx-mk', pk);
    mk.textContent = p[1]; mk.style.cssText = `--dm-mk:var(--dm-av-${p[2]});--dm-mk-ink:var(--dm-av-${p[2]}-ink)`; $('.lnx-pn', pk).textContent = p[0];
    pk.setAttribute('aria-label', 'Project: ' + p[0]);
    $$('.mi', pp).forEach((m, k) => m.setAttribute('aria-checked', k === pj));
    ch.setAttribute('aria-label', `Active editors on ${p[0]}, ${D.what}, the rest projected. The arrow keys read each ${D.each.toLowerCase()}`);
    tab.innerHTML = `<caption>Active editors on ${p[0]}, ${D.what}, the rest projected</caption><tr><th scope="col">${D.each}</th><th scope="col">${D.a}</th><th scope="col">Projected</th><th scope="col">${D.b}</th></tr>`
      + D.pts.map((t, i) => `<tr><th scope="row">${t}</th><td>${i <= D.now ? fmt(D.va[i]) : ''}</td><td>${i > D.now ? fmt(D.vp[i]) : ''}</td><td>${fmt(D.vb[i])}</td></tr>`).join('');
    $('span', keys[0]).textContent = D.a; $('span', keys[2]).textContent = D.b;
    if (at > D.pts.length - 1) at = D.now;
    draw();
  }
  function reveal(){
    const k = ++tok; shown = REDUCE ? 1 : 0; draw(); if (shown) return;
    tween(0, 1, 1100, t => { if (k !== tok) return; shown = t; if (!clip || !clip.isConnected) return; const { W, X } = geo(); clip.setAttribute('width', (W + 16) * t); mark.style.opacity = t * (W + 16) - 8 >= X(D.now) ? 1 : 0; }, t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
  }
  pp.innerHTML = PJ.map((p, k) => `<button class="mi" role="menuitemradio" aria-checked="${k === pj}" data-close data-k="${k}"><span class="lnx-mk" style="--dm-mk:var(--dm-av-${p[2]});--dm-mk-ink:var(--dm-av-${p[2]}-ink)" aria-hidden="true">${p[1]}</span><span>${p[0]}</span><span class="ck">${I('check','xs')}</span></button>`).join('');
  $$('.mi', pp).forEach(m => m.addEventListener('click', () => { const k = +m.dataset.k; if (k === pj) return; pj = k; load(); reveal(); }));
  seg($('.lnx-rg', r), v => { if (v === rg) return; rg = v; load(); reveal(); });
  keys.forEach(k => k.onclick = () => { const s = k.dataset.s; if (on[s] && !Object.keys(on).some(o => o !== s && on[o])) return; on[s] = !on[s];
    k.setAttribute('aria-pressed', on[s]); root.classList.toggle('lnx-no' + s, !on[s]); if (at >= 0) show(at); });
  // the pointer, a finger or the keyboard reads the nearest point
  const idx = e => { const b = ch.getBoundingClientRect(), { n, xr } = geo(); return Math.max(0, Math.min(n, Math.round((e.clientX - b.left) / xr * n))); };
  c.on(ch, 'pointermove', e => show(idx(e)));
  c.on(ch, 'pointerdown', e => show(idx(e)));
  c.on(ch, 'pointerleave', e => { if (e.pointerType !== 'touch' && !ch.matches(':focus-visible')) hide(); });
  c.on(ch, 'focus', () => { if (ch.matches(':focus-visible')) show(at < 0 ? D.now : at, true); });
  c.on(ch, 'blur', hide);
  c.on(ch, 'keydown', e => { const n = D.pts.length - 1, i = at < 0 ? D.now : at;
    const to = { ArrowLeft:i - 1, ArrowRight:i + 1, Home:0, End:n }[e.key];
    if (e.key === 'Escape' && at >= 0){ e.preventDefault(); hide(); return; }
    if (to == null) return; e.preventDefault(); show(Math.max(0, Math.min(n, to)), true); });
  const ro = new ResizeObserver(() => draw()); ro.observe(ch); c.offs.push(() => ro.disconnect());
  // the lines draw in once the chart has risen into view, so the draw is seen from its start
  shown = 0; load();
  c.later(260, reveal);
  // the demo reads a few points along today, switches to the week, then picks another project
  // a readout the demo left showing goes when the visitor takes over, unless they are reading the plot themselves
  c.taken(() => { if (!ch.matches(':hover,:focus-visible')) hide(); });
  c.story(async s => {
    // the demo's pointer goes to the point first, and only then does the readout move there
    const aim = $('.lnx-aim', r);
    const read = async i => { const { X, Y } = geo(); aim.style.left = X(i) + 'px'; aim.style.top = Y(i <= D.now ? D.va[i] : D.vp[i]) + 'px'; await s.point(aim, false); show(i); await s.beat(1.4); };
    await s.beat(4);
    // (the reading past Now is two points on, so on a phone its chip stays clear of the axis's last label)
    for (const i of [D.now - 6, D.now - 3, D.now, D.now + 2]) await read(i);
    hide(); s.away(); await s.beat(1);
    await s.tap($('.lnx-rg [data-v="w"]', r)); await s.beat(3);
    await read(D.now + 1); hide(); s.away(); await s.beat(1);
    await s.tap(pk); await s.beat(1.4);
    await s.tap($('.mi[data-k="1"]', pp)); await s.beat(3.5);
    await read(D.now); hide(); s.away(); await s.beat(1);
  });
});
06

Questions

What people ask about it.

How do I switch the data when someone picks a range or a source?
Pass data as a function: it gets { source, range } and returns the view to draw (points, main, compare and so on). Or control source and range yourself and pass the matching view.
Where does the projection come from?
From projected when you pass it: one value per point from now to the last. Otherwise the chart takes the value at now and follows the comparison's shape from there, so if yesterday fell by a third after 2pm, so does the projection. Pass projected: false to stop the line at now.
Can I leave out the comparison?
Yes. Without compare the chart draws the main line and its projection (held at the latest value unless you pass projected), and the readout has one row.
What if the period is over?
Leave out now, or set it to the last point. The line runs to the right edge with no projection, its ring sits on the last point and the axis ends with "Now" (or your nowLabel, like "Today").
Can I hide the picker or the range switch?
Leave out sources for no picker and ranges for no switch; the title stays.
07

More in Charts and tables

Lightweight charts and tables for dashboards and reports, drawn in plain SVG and HTML.

Health scoreAn account's health: a score ring, four factors that open, and the agent's next move.
Stat cardsFour headline numbers with sparklines and a period switch.