Components
Chart
How a number is drawn: White bars per day under a total, and lines over time in the brand's series order (White, #A3A3A3, #4D4D4D, then the spectrum from Magenta to Blue). Axes from 0 on #363636 hairlines; pointing reads a value.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add chart<script type="module" src="/spyglass-ds/elements/bar-chart.js"></script>Searches, October
24,440
Usage
Searches per day, creatives found per category, spend over a flight. Every chart has a caption; every series is named in the legend.
Never
- Series colors out of order, or spectrum colors before the neutrals
- Color alone to tell series apart: the third series is dashed and every series is in the legend
- An axis that starts above 0
- Bars that regrow on every hover: they rise once
lib/chart.ts holds the series colors (CHART_COLORS, ten in order) and the axis helpers both flavors use; draw your own charts with them so the order stays the brand's.
Props
The web component takes the same as attributes or properties (<spyglass-bar-chart>); title is heading there.
<BarChart>
| Prop | Type | Default |
|---|---|---|
points | DayPoint[] One value per day: [{ day (ISO), value }]. | |
label | string The caption: what the bars count. | |
height | number The bars' height in px. | 160 |
focus | number[] Indexes lit from outside, the rest quiet. | |
note | string What the caption says while nothing is pointed at. |
<LineChart>
| Prop | Type | Default |
|---|---|---|
title | string The caption: what the lines count. | |
series | LineSeries[] [{ label, points: [{ t (ms), v }] }], ten at most. | |
format | (value: number) => string A value as written in the crosshair. | String |
formatAxis | (value: number) => string An axis figure as written. | compactNumber |
formatTime | (t: number) => string How a time reads under the plot and in the crosshair. | day |
bare | boolean No card, inside one already. |
Examples
The same example in React and as web components; both render identically.
import { BarChart } from '@/react/components/ui/BarChart'
import { formatNumber, type DayPoint } from '@/lib/chart'
// A month of searches on a #262626 card: the total in Funnel Display, the bars per day under it. Point at a bar to
// read it. Sample data.
const days = Array.from({ length: 30 }, (_, i) => `2026-10-${String(i + 2).padStart(2, '0')}`)
const points: DayPoint[] = days.map((day, i) => ({ day, value: Math.round(1800 * (0.2 + (((i * 7) % 23) / 23) ** 2 * 0.8)) }))
const total = points.reduce((a, p) => a + p.value, 0)
export default function Searches() {
return (
<div className="flex w-full max-w-150 flex-col gap-6 rounded-container bg-surface-raised p-6 max-sm:p-4">
<div className="flex flex-col gap-2">
<p className="type-label text-fg-muted">Searches, October</p>
<p className="type-heading-1 tabular-nums">{formatNumber(total)}</p>
</div>
<BarChart points={points} label="Searches per day" height={140} />
</div>
)
}<!-- A month of searches on a #262626 card: the total in Funnel Display, the bars per day under it. Point at a bar to
read it. Sample data. -->
<div class="flex w-full max-w-150 flex-col gap-6 rounded-container bg-surface-raised p-6 max-sm:p-4">
<div class="flex flex-col gap-2">
<p class="type-label text-fg-muted">Searches, October</p>
<p id="searches-total" class="type-heading-1 tabular-nums"></p>
</div>
<spyglass-bar-chart id="searches-chart" label="Searches per day" height="140"></spyglass-bar-chart>
</div>
<script type="module">
const days = Array.from({ length: 30 }, (_, i) => `2026-10-${String(i + 2).padStart(2, '0')}`)
const points = days.map((day, i) => ({ day, value: Math.round(1800 * (0.2 + (((i * 7) % 23) / 23) ** 2 * 0.8)) }))
document.getElementById('searches-total').textContent = new Intl.NumberFormat('en-US').format(points.reduce((a, p) => a + p.value, 0))
document.getElementById('searches-chart').points = points
</script>'use client'
import { LineChart, type LineSeries } from '@/react/components/ui/LineChart'
// New creatives found per day by category over two weeks: six series in the brand's order, the neutrals first, then
// the spectrum. Point at the plot to read a day. Sample data.
const day = (i: number) => Date.UTC(2026, 10, 2 + i)
const categories = ['Skincare', 'Snacks', 'Fitness', 'Beverages', 'Apparel', 'Home']
const series: LineSeries[] = categories.map((label, k) => ({
label,
points: Array.from({ length: 14 }, (_, i) => ({ t: day(i), v: Math.round(120 - k * 16 + ((i * (k + 3) * 7) % 11) * 4 + i * (3 - k * 0.4)) })),
}))
const count = (v: number) => `${Math.round(v)} creatives`
export default function Categories() {
return (
<div className="w-full max-w-238">
<LineChart title="New creatives per day" series={series} format={count} />
</div>
)
}<!-- New creatives found per day by category over two weeks: six series in the brand's order, the neutrals first, then
the spectrum. Point at the plot to read a day. Sample data. -->
<div class="w-full max-w-238">
<spyglass-line-chart id="categories-chart" heading="New creatives per day"></spyglass-line-chart>
</div>
<script type="module">
const day = (i) => Date.UTC(2026, 10, 2 + i)
const categories = ['Skincare', 'Snacks', 'Fitness', 'Beverages', 'Apparel', 'Home']
const chart = document.getElementById('categories-chart')
chart.format = (v) => `${Math.round(v)} creatives`
chart.series = categories.map((label, k) => ({
label,
points: Array.from({ length: 14 }, (_, i) => ({ t: day(i), v: Math.round(120 - k * 16 + ((i * (k + 3) * 7) % 11) * 4 + i * (3 - k * 0.4)) })),
}))
</script>Source
'use client'
import { useState, type CSSProperties } from 'react'
import { type DayPoint, compactNumber, dayMarks, formatDay, formatNumber, niceTicks } from '@/lib/chart'
import { cn } from '@/react/lib/cn'
// A White bar per day on the Black ground. The axis starts at 0 and ends on a round number in about four steps; grid
// lines are #363636 hairlines; axis figures are DM Sans 12px muted in tabular figures. A day with any activity keeps a
// visible bar. Pointing at a bar names its day and value in the caption and quiets the others to #4D4D4D. The bars
// rise from the axis once (360ms, ease-out, staggered over 120ms), then only their color changes; with reduced motion
// they are simply there. `focus`: bars lit from outside, the rest quiet; `note`: what the caption says meanwhile.
export interface BarChartProps {
/** One value per day: [{ day (ISO), value }]. */
points: DayPoint[]
/** The caption: what the bars count. */
label: string
/** The bars' height in px. */
height?: number
/** Indexes lit from outside, the rest quiet. */
focus?: number[]
/** What the caption says while nothing is pointed at. */
note?: string
}
export function BarChart({ points, label, height = 160, focus, note }: BarChartProps) {
const ticks = niceTicks(points.map(p => p.value))
const top = ticks[ticks.length - 1]!
const marks = dayMarks(points)
const [hover, setHover] = useState<number | null>(null)
const shown = hover === null ? null : points[hover] ?? null
const peak = formatNumber(Math.max(0, ...points.map(p => p.value)))
return (
<figure data-ds="bar-chart" className="flex min-w-0 flex-col gap-3">
<style href="ds-bar-chart" precedence="ds">{css}</style>
<figcaption className="flex h-5 items-baseline justify-between gap-4">
<span className="type-label text-fg-muted">{label}</span>
{shown
? <span className="type-caption text-fg-muted tabular-nums">{`${formatDay(shown.day, true)} `}<span className="font-medium text-fg">{formatNumber(shown.value)}</span></span>
: note ? <span className="type-caption text-fg-muted">{note}</span> : null}
</figcaption>
{!points.length
? <p className="flex items-center justify-center type-ui text-fg-muted" style={{ height: `${height}px` }}>No activity yet.</p>
: (
<div className="grid grid-cols-[40px_minmax(0,1fr)] gap-x-2">
<div className="relative" style={{ height: `${height}px` }} aria-hidden="true">
{ticks.map(t => <span key={t} className="absolute right-0 -translate-y-1/2 type-caption text-fg-muted tabular-nums" style={{ top: `${(1 - t / top) * 100}%` }}>{compactNumber(t)}</span>)}
</div>
<div className="relative" style={{ height: `${height}px` }} role="img" aria-label={`${label}: ${points.length} days, peak ${peak}`} onPointerLeave={() => setHover(null)}>
{ticks.map(t => <div key={t} className="pointer-events-none absolute inset-x-0 border-t border-data-grid" style={{ top: `${(1 - t / top) * 100}%` }} />)}
<div className="absolute inset-0 flex items-end">
{points.map((p, i) => (
<div key={p.day} className="flex h-full flex-1 items-end" onPointerEnter={() => setHover(i)}>
<div
className="ds-bar mx-auto w-[70%] rounded-t-ds-sm bg-data-3 data-lit:bg-data-1"
data-lit={hover === i || (hover === null && (!focus || focus.includes(i))) || undefined}
style={{ height: p.value > 0 ? `max(2px, ${(p.value / top) * 100}%)` : '0', '--i': (i * 120) / points.length } as CSSProperties}
/>
</div>
))}
</div>
</div>
<div />
<div className="relative mt-2 h-4" aria-hidden="true">
{marks.map((m, i) => (
<span
key={m.text}
className={cn('absolute whitespace-nowrap type-caption text-fg-muted tabular-nums', i === 0 ? 'left-0' : i === marks.length - 1 ? 'right-0' : '-translate-x-1/2')}
style={i === 0 || i === marks.length - 1 ? {} : { left: m.left }}
>{m.text}</span>
))}
</div>
</div>
)}
</figure>
)
}
export default BarChart
const css = `
.ds-bar { transform-origin: bottom; animation: ds-bar-in var(--ds-duration-entrance) var(--ds-easing-out) both; animation-delay: calc(var(--i, 0) * 1ms); transition: background-color var(--ds-duration-glide) var(--ds-easing-standard); }
@keyframes ds-bar-in { from { transform: scaleY(0.02); } }
@media (prefers-reduced-motion: reduce) { .ds-bar { animation: none; } }
`'use client'
import { useState, type PointerEvent } from 'react'
import { type LineSeries, PLOT, compactNumber, lineLayout } from '@/lib/chart'
import { cn } from '@/react/lib/cn'
// Lines over time: one axis from 0 on #363636 hairlines, 2px lines in the brand's series order (White, #A3A3A3,
// #4D4D4D dashed, then the spectrum: Magenta, Red, Orange, Yellow, Green, Cyan, Blue), the first series shading the
// area under it, a legend when there is more than one, and a crosshair with the values under the pointer on the
// #262626 overlay panel. Ten series at most. On a #262626 card by default; `bare` drops the card, for a chart already
// inside one. `format` writes a value (axis figures use the compact form unless `formatAxis` is given).
export type { LineSeries }
export interface LineChartProps {
/** The caption: what the lines count. */
title: string
/** [{ label, points: [{ t (ms), v }] }], ten at most. */
series: LineSeries[]
/** A value as written in the crosshair. */
format?: (value: number) => string
/** An axis figure as written. */
formatAxis?: (value: number) => string
/** How a time reads under the plot and in the crosshair. */
formatTime?: (t: number) => string
/** No card, inside one already. */
bare?: boolean
}
const day = (t: number) => new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
export function LineChart({ title, series, format = String, formatAxis = compactNumber, formatTime = day, bare }: LineChartProps) {
const { lines, paths, span, ticks, max, x, nearest, valuesAt } = lineLayout(series)
const [hover, setHover] = useState<number | null>(null)
function move(event: PointerEvent<HTMLDivElement>) {
const box = event.currentTarget.getBoundingClientRect()
setHover(nearest((event.clientX - box.left) / box.width))
}
const hovered = hover === null ? null : { left: `${(x(hover) / PLOT.w) * 100}%`, right: x(hover) > PLOT.w * 0.6, time: formatTime(hover), values: valuesAt(hover) }
return (
<figure data-ds="line-chart" className={cn('flex min-w-0 flex-col gap-4', !bare && 'rounded-container bg-surface-raised p-6 max-sm:p-4')}>
<figcaption className="flex min-h-5 flex-wrap items-baseline justify-between gap-x-4 gap-y-2">
<span className="type-label text-fg-muted">{title}</span>
{lines.length > 1 && (
<span className="flex flex-wrap gap-x-4 gap-y-1 type-caption text-fg-muted">
{paths.map(p => (
<span key={p.label} className="inline-flex items-center gap-1.5">
<svg width="16" height="4" aria-hidden="true"><line x1="0" y1="2" x2="16" y2="2" stroke={p.color} strokeWidth="2" strokeDasharray={p.dash || undefined} /></svg>
{p.label}
</span>
))}
</span>
)}
</figcaption>
{!lines.length
? <p className="type-ui text-fg-muted">No data in this range.</p>
: (
<div className="flex gap-2">
<div className="relative h-40 w-10 shrink-0" aria-hidden="true">
{ticks.map(t => <span key={t} className="absolute right-0 -translate-y-1/2 whitespace-nowrap type-caption text-fg-muted tabular-nums" style={{ top: `${(1 - t / max) * 100}%` }}>{formatAxis(t)}</span>)}
</div>
<div className="min-w-0 flex-1">
<div className="relative h-40 touch-none" role="img" aria-label={`${title}: ${paths.map(p => `${p.label} last ${format(p.last.v)}`).join(', ')}`} onPointerMove={move} onPointerLeave={() => setHover(null)}>
<svg className="absolute inset-0 h-full w-full overflow-visible" viewBox={`0 0 ${PLOT.w} ${PLOT.h}`} preserveAspectRatio="none" aria-hidden="true">
{ticks.map(t => <line key={t} x1="0" y1={PLOT.h - (t / max) * PLOT.h} x2={PLOT.w} y2={PLOT.h - (t / max) * PLOT.h} stroke="var(--ds-color-data-grid)" strokeWidth="1" vectorEffect="non-scaling-stroke" />)}
{paths.filter(q => q.area).map(p => <path key={`${p.label}-area`} d={p.area} fill={p.color} fillOpacity="0.08" />)}
{paths.map(p => <path key={p.label} d={p.d} fill="none" stroke={p.color} strokeWidth="2" strokeDasharray={p.dash || undefined} strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />)}
</svg>
{hovered && (
<>
<div className="pointer-events-none absolute inset-y-0 w-px bg-edge-strong" style={{ left: hovered.left }} />
<div className="pointer-events-none absolute top-0 z-10 flex flex-col gap-1 rounded-control border border-edge bg-surface-raised px-3 py-2 type-caption" style={hovered.right ? { right: `calc(100% - ${hovered.left} + 8px)` } : { left: `calc(${hovered.left} + 8px)` }}>
<p className="text-fg-muted tabular-nums">{hovered.time}</p>
{hovered.values.map(v => (
<p key={v.label} className="flex items-center gap-2 whitespace-nowrap tabular-nums">
<span className="inline-block h-0.5 w-3" style={{ background: v.color }} />
{lines.length > 1 && <span className="text-fg-muted">{v.label}</span>}
<span className="ml-auto font-medium text-fg">{v.value === undefined ? 'None' : format(v.value)}</span>
</p>
))}
</div>
</>
)}
</div>
<div className="mt-2 flex justify-between type-caption text-fg-muted tabular-nums">
<span>{formatTime(span.from)}</span>
<span>{formatTime(span.to)}</span>
</div>
</div>
</div>
)}
</figure>
)
}
export default LineChart// What the charts share, in both flavors: the series colors, numbers in en-US, an axis that ends on a round number in
// about four steps, and the days under the bars. Framework-free.
/**
* The series colors in order: the neutrals first (White, #A3A3A3, #4D4D4D), then the spectrum in the order the brand
* always shows it (Magenta, Red, Orange, Yellow, Green, Cyan, Blue). Ten series at most; the third is dashed, so a
* dim gray line still reads, and every series is named in the legend.
*/
export const CHART_COLORS = [
'var(--ds-color-data-1)',
'var(--ds-color-data-2)',
'var(--ds-color-data-3)',
'var(--ds-color-magenta)',
'var(--ds-color-red)',
'var(--ds-color-orange)',
'var(--ds-color-yellow)',
'var(--ds-color-green)',
'var(--ds-color-cyan)',
'var(--ds-color-blue)',
] as const
/** Each series' dash pattern (SVG stroke-dasharray), by the same index. */
export const CHART_DASH = ['', '', '5 4', '', '', '', '', '', '', '']
export type DayPoint = { day: string, value: number }
export type LineSeries = { label: string, points: Array<{ t: number, v: number }> }
const whole = new Intl.NumberFormat('en-US')
const compact = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 })
/** 186402 -> "186,402". */
export const formatNumber = (n: number) => whole.format(n)
/** 186402 -> "186.4K", for axis labels. */
export const compactNumber = (n: number) => compact.format(n)
/** The axis: a step of 1, 2, 2.5 or 5 times a power of ten that covers the largest value in four. Starts at 0. */
export function niceTicks(values: number[]) {
const max = Math.max(0, ...values)
if (max === 0) return [0, 1]
const raw = max / 4
const power = 10 ** Math.floor(Math.log10(raw))
const step = ([1, 2, 2.5, 5, 10].find((m) => m * power >= raw) ?? 10) * power
return Array.from({ length: Math.ceil(max / step) + 1 }, (_, i) => i * step)
}
/** "Oct 2", or "Oct 2, 2026" with the year, from an ISO day. */
export const formatDay = (value: string, year = false) => new Date(`${value}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', ...(year ? { year: 'numeric' } : {}), timeZone: 'UTC' })
/** Four dates under n bars: the first, the last and two between, each with its center as a share of the width. */
export function dayMarks(points: DayPoint[]) {
const n = points.length
if (!n) return []
return [...new Set([0, Math.round((n - 1) / 3), Math.round((2 * (n - 1)) / 3), n - 1])].map((i) => ({ left: `${((i + 0.5) / n) * 100}%`, text: formatDay(points[i]!.day) }))
}
/** The plot's drawing box for lines (an SVG viewBox, stretched to the plot). */
export const PLOT = { w: 600, h: 160 }
/** Lines over time laid out in PLOT: paths, the shaded area under the first, the axis top and the hovered values. */
export function lineLayout(series: LineSeries[]) {
const lines = series.slice(0, CHART_COLORS.length).filter((s) => s.points.length)
const times = [...new Set(lines.flatMap((s) => s.points.map((p) => p.t)))].sort((a, b) => a - b)
const span = { from: times[0] ?? 0, to: times[times.length - 1] ?? 1 }
const ticks = niceTicks(lines.flatMap((s) => s.points.map((p) => p.v)))
const max = ticks[ticks.length - 1]!
const x = (t: number) => (span.to === span.from ? PLOT.w / 2 : ((t - span.from) / (span.to - span.from)) * PLOT.w)
const y = (v: number) => PLOT.h - (v / max) * PLOT.h
const paths = lines.map((s, i) => ({
label: s.label,
color: CHART_COLORS[i]!,
dash: CHART_DASH[i]!,
d: s.points.map((p, j) => `${j ? 'L' : 'M'}${x(p.t).toFixed(1)},${y(p.v).toFixed(1)}`).join(''),
area: i ? '' : `M${x(s.points[0]!.t).toFixed(1)},${PLOT.h}${s.points.map((p) => `L${x(p.t).toFixed(1)},${y(p.v).toFixed(1)}`).join('')}L${x(s.points[s.points.length - 1]!.t).toFixed(1)},${PLOT.h}Z`,
last: s.points[s.points.length - 1]!,
}))
/** The time nearest a share (0 to 1) of the width. */
const nearest = (share: number) => {
const t = span.from + share * (span.to - span.from)
let best: number | null = null
for (const c of times) if (best === null || Math.abs(c - t) < Math.abs(best - t)) best = c
return best
}
const valuesAt = (t: number) => lines.map((s, i) => ({ label: s.label, color: CHART_COLORS[i]!, value: s.points.find((p) => p.t === t)?.v }))
return { lines, paths, span, ticks, max, x, nearest, valuesAt }
}// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]
export function cn(...values: ClassValue[]): string {
const out: string[] = []
for (const v of values) {
if (!v) continue
if (Array.isArray(v)) {
const s = cn(...v)
if (s) out.push(s)
}
else out.push(v)
}
return out.join(' ')
}import { html, nothing } from 'lit'
import { repeat } from 'lit/directives/repeat.js'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define } from '@/elements/lib/element'
import { type DayPoint, compactNumber, dayMarks, formatDay, formatNumber, niceTicks } from '@/lib/chart'
import styles from 'virtual:tw'
// BarChart.tsx as <spyglass-bar-chart>: a White bar per day on the Black ground. The axis starts at 0 and ends on a
// round number in about four steps; grid lines are #363636 hairlines; axis figures are DM Sans 12px muted in tabular
// figures. Pointing at a bar names its day and value in the caption and quiets the others to #4D4D4D. The bars rise
// from the axis once, then only their color changes. `focus` (React's `focus`; the property is `lit`, as `focus` is
// HTMLElement's own method): bars lit from outside; `note`: what the caption says meanwhile. `points` is a property
// (or a JSON attribute).
/** @summary A White bar per day, with its axis, grid and dates. */
export class BarChart extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { points: { type: Array }, label: {}, height: { type: Number }, lit: { type: Array, attribute: 'focus' }, note: {}, hover: { state: true } }
/** One value per day: [{ day (ISO), value }]. */
points: DayPoint[] = []
/** The caption: what the bars count. */
label = ''
/** The bars' height in px. */
height = 160
/** Indexes lit from outside, the rest quiet (the focus attribute). */
lit?: number[]
/** What the caption says while nothing is pointed at. */
note?: string
private hover: number | null = null
render() {
const points = this.points ?? []
const ticks = niceTicks(points.map((p) => p.value))
const top = ticks[ticks.length - 1]!
const n = points.length
const marks = dayMarks(points)
const shown = this.hover === null ? null : points[this.hover] ?? null
const peak = formatNumber(Math.max(0, ...points.map((p) => p.value)))
const h = `height: ${this.height}px`
const body = !n
? html`<p class="flex items-center justify-center type-ui text-fg-muted" style=${h}>No activity yet.</p>`
: html`<div class="grid grid-cols-[40px_minmax(0,1fr)] gap-x-2">
<div class="relative" style=${h} aria-hidden="true">${ticks.map((t) => html`<span class="absolute right-0 -translate-y-1/2 type-caption text-fg-muted tabular-nums" style=${`top: ${(1 - t / top) * 100}%`}>${compactNumber(t)}</span>`)}</div>
<div class="relative" style=${h} role="img" aria-label=${`${this.label}: ${n} days, peak ${peak}`} @pointerleave=${() => { this.hover = null }}>
${ticks.map((t) => html`<div class="pointer-events-none absolute inset-x-0 border-t border-data-grid" style=${`top: ${(1 - t / top) * 100}%`}></div>`)}
<div class="absolute inset-0 flex items-end">${repeat(points, (p) => p.day, (p, i) => html`<div class="flex h-full flex-1 items-end" @pointerenter=${() => { this.hover = i }}><div class="ds-bar mx-auto w-[70%] rounded-t-ds-sm bg-data-3 data-lit:bg-data-1" data-lit=${ifDefined(this.hover === i || (this.hover === null && (!this.lit || this.lit.includes(i))) ? 'true' : undefined)} style=${`height: ${p.value > 0 ? `max(2px, ${(p.value / top) * 100}%)` : '0'}; --i: ${(i * 120) / n}`}></div></div>`)}</div>
</div>
<div></div>
<div class="relative mt-2 h-4" aria-hidden="true">${marks.map((m, i) => html`<span class=${['absolute whitespace-nowrap type-caption text-fg-muted tabular-nums', i === 0 ? 'left-0' : i === marks.length - 1 ? 'right-0' : '-translate-x-1/2'].join(' ')} style=${ifDefined(i === 0 || i === marks.length - 1 ? undefined : `left: ${m.left}`)}>${m.text}</span>`)}</div>
</div>`
return html`<figure data-ds="bar-chart" class="flex min-w-0 flex-col gap-3">
<figcaption class="flex h-5 items-baseline justify-between gap-4">
<span class="type-label text-fg-muted">${this.label}</span>
${shown ? html`<span class="type-caption text-fg-muted tabular-nums">${`${formatDay(shown.day, true)} `}<span class="font-medium text-fg">${formatNumber(shown.value)}</span></span>` : this.note ? html`<span class="type-caption text-fg-muted">${this.note}</span>` : nothing}
</figcaption>
${body}
</figure>`
}
}
define('bar-chart', BarChart)/* BarChart.tsx's styles: a bar rises from the axis once, then only its color changes. */
.ds-bar { transform-origin: bottom; animation: ds-bar-in var(--ds-duration-entrance) var(--ds-easing-out) both; animation-delay: calc(var(--i, 0) * 1ms); transition: background-color var(--ds-duration-glide) var(--ds-easing-standard); }
@keyframes ds-bar-in { from { transform: scaleY(0.02); } }
@media (prefers-reduced-motion: reduce) { .ds-bar { animation: none; } }import { html, nothing, svg } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define } from '@/elements/lib/element'
import { type LineSeries, PLOT, compactNumber, lineLayout } from '@/lib/chart'
import styles from 'virtual:tw'
// LineChart.tsx as <spyglass-line-chart>: lines over time: one axis from 0 on #363636 hairlines, 2px lines in the
// brand's series order (White, #A3A3A3, #4D4D4D dashed, then the spectrum: Magenta, Red, Orange, Yellow, Green, Cyan,
// Blue), the first series shading the area under it, a legend when there is more than one, and a crosshair with the
// values under the pointer on the #262626 overlay panel. Ten series at most. On a #262626 card by default; `bare`
// drops the card. React's `title` is `heading`; `series`, `format`, `formatAxis` and `formatTime` are properties.
export type { LineSeries }
const day = (t: number) => new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
/** @summary Lines over time, with a legend and a crosshair. */
export class LineChart extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { heading: {}, series: { type: Array }, format: { attribute: false }, formatAxis: { attribute: false }, formatTime: { attribute: false }, bare: { type: Boolean }, hover: { state: true } }
/** The caption (React's `title`; `title` is HTML's tooltip attribute). */
heading = ''
/** [{ label, points: [{ t (ms), v }] }], ten at most. */
series: LineSeries[] = []
/** A value as written in the crosshair (a property: a function). */
format: (value: number) => string = String
/** An axis figure as written (a property: a function). */
formatAxis: (value: number) => string = compactNumber
/** How a time reads (a property: a function). */
formatTime: (t: number) => string = day
/** No card, inside one already. */
bare = false
private hover: number | null = null
private move(event: PointerEvent) {
const box = (event.currentTarget as HTMLElement).getBoundingClientRect()
this.hover = lineLayout(this.series ?? []).nearest((event.clientX - box.left) / box.width)
}
render() {
const { lines, paths, span, ticks, max, x, valuesAt } = lineLayout(this.series ?? [])
const format = this.format
const hover = this.hover
const hovered = hover === null ? null : { left: `${(x(hover) / PLOT.w) * 100}%`, right: x(hover) > PLOT.w * 0.6, time: this.formatTime(hover), values: valuesAt(hover) }
const legend = lines.length > 1
? html`<span class="flex flex-wrap gap-x-4 gap-y-1 type-caption text-fg-muted">${paths.map((p) => html`<span class="inline-flex items-center gap-1.5"><svg width="16" height="4" aria-hidden="true">${svg`<line x1="0" y1="2" x2="16" y2="2" stroke=${p.color} stroke-width="2" stroke-dasharray=${ifDefined(p.dash || undefined)}></line>`}</svg>${p.label}</span>`)}</span>`
: nothing
const body = !lines.length
? html`<p class="type-ui text-fg-muted">No data in this range.</p>`
: html`<div class="flex gap-2">
<div class="relative h-40 w-10 shrink-0" aria-hidden="true">${ticks.map((t) => html`<span class="absolute right-0 -translate-y-1/2 whitespace-nowrap type-caption text-fg-muted tabular-nums" style=${`top: ${(1 - t / max) * 100}%`}>${this.formatAxis(t)}</span>`)}</div>
<div class="min-w-0 flex-1">
<div class="relative h-40 touch-none" role="img" aria-label=${`${this.heading}: ${paths.map((p) => `${p.label} last ${format(p.last.v)}`).join(', ')}`} @pointermove=${this.move} @pointerleave=${() => { this.hover = null }}>
<svg class="absolute inset-0 h-full w-full overflow-visible" viewBox=${`0 0 ${PLOT.w} ${PLOT.h}`} preserveAspectRatio="none" aria-hidden="true">
${ticks.map((t) => svg`<line x1="0" y1=${PLOT.h - (t / max) * PLOT.h} x2=${PLOT.w} y2=${PLOT.h - (t / max) * PLOT.h} stroke="var(--ds-color-data-grid)" stroke-width="1" vector-effect="non-scaling-stroke"></line>`)}
${paths.filter((q) => q.area).map((p) => svg`<path d=${p.area} fill=${p.color} fill-opacity="0.08"></path>`)}
${paths.map((p) => svg`<path d=${p.d} fill="none" stroke=${p.color} stroke-width="2" stroke-dasharray=${ifDefined(p.dash || undefined)} stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"></path>`)}
</svg>
${hovered
? html`<div class="pointer-events-none absolute inset-y-0 w-px bg-edge-strong" style=${`left: ${hovered.left}`}></div><div class="pointer-events-none absolute top-0 z-10 flex flex-col gap-1 rounded-control border border-edge bg-surface-raised px-3 py-2 type-caption" style=${hovered.right ? `right: calc(100% - ${hovered.left} + 8px)` : `left: calc(${hovered.left} + 8px)`}><p class="text-fg-muted tabular-nums">${hovered.time}</p>${hovered.values.map((v) => html`<p class="flex items-center gap-2 whitespace-nowrap tabular-nums"><span class="inline-block h-0.5 w-3" style=${`background: ${v.color}`}></span>${lines.length > 1 ? html`<span class="text-fg-muted">${v.label}</span>` : nothing}<span class="ml-auto font-medium text-fg">${v.value === undefined ? 'None' : format(v.value)}</span></p>`)}</div>`
: nothing}
</div>
<div class="mt-2 flex justify-between type-caption text-fg-muted tabular-nums"><span>${this.formatTime(span.from)}</span><span>${this.formatTime(span.to)}</span></div>
</div>
</div>`
return html`<figure data-ds="line-chart" class=${this.bare ? 'flex min-w-0 flex-col gap-4' : 'flex min-w-0 flex-col gap-4 rounded-container bg-surface-raised p-6 max-sm:p-4'}>
<figcaption class="flex min-h-5 flex-wrap items-baseline justify-between gap-x-4 gap-y-2"><span class="type-label text-fg-muted">${this.heading}</span>${legend}</figcaption>
${body}
</figure>`
}
}
define('line-chart', LineChart)Reference: Derived from the guidelines: Black ground, White primary, the neutral spectrum for the first series and the seven spectrum colors in their fixed order after them, DM Sans figures and capital labels at 6%, the #262626 card fill. shadcn's chart for the parts (caption, legend, tooltip)..