Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions apps/storybook/stories/charts/Annotations.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
band,
errorBar,
referenceLine,
trendLine,
dot,
ChartGrid,
ChartAxis,
} from '@astryxdesign/charts';
Expand All @@ -17,14 +19,16 @@ import {
conversionTestData,
cpuUtilizationData,
latencyByConcurrencyData,
pageWeightLoadTimeData,
salesData,
signupForecastData,
} from './_data';

/**
* Annotations mark values on a chart: targets, ranges, events, uncertainty.
* Build them with `referenceLine()`, `band()` and `errorBar()`, the same
* factories you pass in `series`. They get no legend entry and no tooltip row.
* Build them with `referenceLine()`, `band()`, `errorBar()` and
* `trendLine()`, the same factories you pass in `series`. They get no legend
* entry and no tooltip row.
*
* `referenceLine({x})` takes a numeric `x`. It draws only on a numeric x axis;
* on a categorical x axis it draws nothing.
Expand Down Expand Up @@ -195,6 +199,60 @@ export const ErrorBars: StoryObj = {
),
};

// A least-squares fit of load time on page weight, computed here: the chart
// draws the values it is given and computes no fit itself.
const trendData = (() => {
const rows = [...pageWeightLoadTimeData].sort(
(a, b) => a.pageWeightKb - b.pageWeightKb,
);
const meanX = rows.reduce((s, d) => s + d.pageWeightKb, 0) / rows.length;
const meanY = rows.reduce((s, d) => s + d.loadTimeMs, 0) / rows.length;
let sxy = 0;
let sxx = 0;
for (const d of rows) {
sxy += (d.pageWeightKb - meanX) * (d.loadTimeMs - meanY);
sxx += (d.pageWeightKb - meanX) ** 2;
}
const slope = sxy / sxx;
return {
msPer100Kb: Math.round(slope * 100),
rows: rows.map(d => ({
...d,
trendMs: meanY + slope * (d.pageWeightKb - meanX),
})),
};
})();

/**
* A trend line draws a value for every x that you compute, here a straight
* least-squares fit, as a dashed annotation. It adds no legend item, tooltip
* row or table column. The subtitle, which is the chart's accessible
* description, states what it shows, rounded. The line joins rows in data
* order, so sort scatter rows by x. Unlike a `line()`, it also joins across
* rows with no value; draw two trend lines where a gap matters.
* Check: one straight dashed line runs through the dots from the lightest to
* the heaviest page, labelled "Trend" at its right end, and the tooltip on a
* dot has no trend row.
*/
export const TrendLine: StoryObj = {
render: () => (
<Chart
data={trendData.rows}
xKey="pageWeightKb"
title="Page load time by page weight"
subtitle={`Load time (ms) against page weight (KB), 60 pages. The dashed trend line shows load time rising about ${trendData.msPer100Kb} ms per 100 KB.`}
series={[
dot('loadTimeMs', {radius: 4, opacity: 0.7, label: 'Load time'}),
trendLine('trendMs', {label: 'Trend'}),
]}
tooltip
grid={<ChartGrid horizontal vertical />}
axes={axes}
height={360}
/>
),
};

/** Many marks at once: bars, reference range, confidence band, reference line, line, error bars. */
export const Layering: StoryObj = {
render: () => {
Expand Down
6 changes: 4 additions & 2 deletions docs/specs/AST-115-chart-value-format/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,10 @@ calendar: CalendarSystem) => string | null | undefined`. A format returns the
it as a read-only `formatValue`, and a custom series definition may set it
the same way. The format applies to every data key the series reads, so the
open, high, low, and close values of one candlestick read alike. Utility
marks (`band`, `errorBar`, `referenceLine`) take no format, because neither
the tooltip nor the data table shows them. The WebGL mark builders take no
marks, such as `band`, `errorBar`, `referenceLine`, and `trendLine`,
annotate the data rather than plot values a reader compares. They take no format,
because neither the tooltip nor the data table shows them. The WebGL mark
builders take no
format (DEC-7); a WebGL series that reads a data key shows that value with
FR8 and FR9.
- **FR3 — The chart declares how its x values read.** `Chart` accepts an
Expand Down
2 changes: 1 addition & 1 deletion docs/specs/components/Chart/Chart.spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ verified_by:
packages/charts/src/marks/marks.test.tsx,
apps/storybook/stories/charts/Chart.stories.tsx,
]
modules: []
modules: [module:Chart/trendLine]
families: []
design_specs: []
architecture:
Expand Down
194 changes: 194 additions & 0 deletions docs/specs/components/Chart/modules/trendLine.spec.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/charts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {Chart, bar, line} from '@astryxdesign/charts';
```

Marks are factory functions (`bar`, `line`, `area`, `dot`, `band`, `candlestick`,
`errorBar`, `referenceLine`, and WebGL variants) that return config objects passed
`errorBar`, `referenceLine`, `trendLine`, and WebGL variants) that return config objects passed
via the `series` prop. The chart root owns **one** x/y scale that every mark, axis,
and grid line reads, so they can never disagree. It consumes `@astryxdesign/core`
theme tokens directly (StyleX build mirrors `@astryxdesign/lab`).
Expand Down
2 changes: 2 additions & 0 deletions packages/charts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export {
candlestick,
errorBar,
referenceLine,
trendLine,
dotGL,
dotGLInteractive,
heatmapGL,
Expand All @@ -45,6 +46,7 @@ export type {
CandlestickOptions,
ErrorBarOptions,
ReferenceLineOptions,
TrendLineOptions,
DotGLOptions,
DotGLInteractiveOptions,
HeatmapGLOptions,
Expand Down
68 changes: 68 additions & 0 deletions packages/charts/src/marks/annotationLabel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file marks/annotationLabel.tsx
* @output The label badge that annotation marks draw beside their line, and
* the helpers that size and clamp it inside the plot
* @position Shared by `referenceLine()` and `trendLine()`
*/

// Badge dimensions — matches crosshair label style.
export const BADGE_H = 14;
const BADGE_RX = 3;
const LABEL_FONT_SIZE = 10;
// Rough per-glyph advance + horizontal padding for width estimation.
const LABEL_CHAR_W = 6.5;
const LABEL_PAD = 12;

export const clamp = (v: number, lo: number, hi: number): number =>
Math.max(lo, Math.min(v, hi));

/** Estimated badge width for a label (0 when there's no label). */
export function labelWidth(label: string | undefined): number {
return label ? label.length * LABEL_CHAR_W + LABEL_PAD : 0;
}

/**
* The label badge, positioned by its top-left corner so callers can clamp it
* into the plot uniformly regardless of orientation.
*/
export function AnnotationLabel({
x,
topY,
width,
color,
text,
}: {
x: number;
topY: number;
width: number;
color: string;
text: string;
}) {
return (
<g transform={`translate(${x},${topY})`} pointerEvents="none">
<rect
x={0}
y={0}
width={width}
height={BADGE_H}
rx={BADGE_RX}
fill="var(--color-background-popover)"
fillOpacity={0.85}
stroke={color}
strokeWidth={0.5}
/>
<text
x={width / 2}
y={BADGE_H / 2}
dy="0.35em"
textAnchor="middle"
fontSize={LABEL_FONT_SIZE}
fontWeight={500}
fill={color}>
{text}
</text>
</g>
);
}
1 change: 1 addition & 0 deletions packages/charts/src/marks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export {band, type BandOptions} from './band';
export {candlestick, type CandlestickOptions} from './candlestick';
export {errorBar, type ErrorBarOptions} from './errorBar';
export {referenceLine, type ReferenceLineOptions} from './referenceLine';
export {trendLine, type TrendLineOptions} from './trendLine';
export {dotGL, type DotGLOptions} from './dotGL';
export {
dotGLInteractive,
Expand Down
55 changes: 11 additions & 44 deletions packages/charts/src/marks/line.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,23 @@

/**
* @file marks/line.tsx
* @output Line series — self-contained resolve + render
* @output Line series — resolve + render through the shared line path helpers
*
* Missing / non-finite values become gaps (via d3's `.defined()`) instead of a
* misleading drop to the baseline, and per-point dots are only drawn where the
* point is finite.
*/

import {
line as d3Line,
curveLinear,
curveMonotoneX,
curveNatural,
curveStep,
} from 'd3-shape';
import type {SeriesDef, ResolvedPoint, ChartValueFormat} from '../types';
import type {SeriesDef, ChartValueFormat} from '../types';
import {seriesFill} from '../markColor';
import {xPixel} from '../utils';
import {
isFinitePoint,
linePath,
resolveLinePoints,
type CurveType,
} from './linePath';

const CURVES = {
linear: curveLinear,
monotone: curveMonotoneX,
natural: curveNatural,
step: curveStep,
} as const;
export type CurveType = keyof typeof CURVES;
export type {CurveType};

export interface LineOptions {
color?: string;
Expand All @@ -47,11 +39,6 @@ export interface LineOptions {
formatValue?: ChartValueFormat;
}

/** A point is drawable only when both of its plotted coordinates are finite. */
function isFinitePoint(p: ResolvedPoint): boolean {
return Number.isFinite(p.px) && Number.isFinite(p.py);
}

export function line(dataKey: string, options: LineOptions = {}): SeriesDef {
const color = options.color;
const curve = options.curve ?? 'linear';
Expand All @@ -73,34 +60,14 @@ export function line(dataKey: string, options: LineOptions = {}): SeriesDef {
layout: dots ? {xOverhang: dotRadius} : {},

resolve(ctx) {
const {data, xKey, xScale, yScale} = ctx;
const points: ResolvedPoint[] = [];
for (let i = 0; i < data.length; i++) {
const d = data[i];
const raw = d[dataKey];
const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN;
points.push({
px: xPixel(d, xKey, xScale),
py: yScale(v),
py0: yScale(0),
dataIndex: i,
});
}
return points;
return resolveLinePoints(ctx, dataKey);
},

render(resolved) {
if (resolved.length === 0) {
return null;
}
const curveFactory = CURVES[curve] ?? curveLinear;
const pathGen = d3Line<ResolvedPoint>()
.defined(isFinitePoint)
.x(d => d.px)
.y(d => d.py)
.curve(curveFactory);

const pathD = pathGen(resolved) ?? '';
const pathD = linePath(resolved, curve);
const strokeColor = seriesFill(seriesDef, color);
return (
<g>
Expand Down
69 changes: 69 additions & 0 deletions packages/charts/src/marks/linePath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file marks/linePath.ts
* @input A series context, one data key, and a curve name
* @output The per-row points and the SVG path of a line through one data key
* @position Shared by `line()` and `trendLine()`, so both place points and
* draw paths the same way
*/

import {
line as d3Line,
curveLinear,
curveMonotoneX,
curveNatural,
curveStep,
} from 'd3-shape';
import type {ResolvedPoint, SeriesContext} from '../types';
import {xPixel} from '../utils';

const CURVES = {
linear: curveLinear,
monotone: curveMonotoneX,
natural: curveNatural,
step: curveStep,
} as const;
export type CurveType = keyof typeof CURVES;

/** A point is drawable only when both of its plotted coordinates are finite. */
export function isFinitePoint(p: ResolvedPoint): boolean {
return Number.isFinite(p.px) && Number.isFinite(p.py);
}

/**
* One point per data row. A missing or non-finite value gets a non-finite
* `py`, so the path can skip it.
*/
export function resolveLinePoints(
ctx: SeriesContext,
dataKey: string,
): ResolvedPoint[] {
const {data, xKey, xScale, yScale} = ctx;
const points: ResolvedPoint[] = [];
for (let i = 0; i < data.length; i++) {
const d = data[i];
const raw = d[dataKey];
const v = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN;
points.push({
px: xPixel(d, xKey, xScale),
py: yScale(v),
py0: yScale(0),
dataIndex: i,
});
}
return points;
}

/**
* The SVG path through the drawable points, in data row order. A point that is
* not drawable starts a gap.
*/
export function linePath(points: ResolvedPoint[], curve: CurveType): string {
const pathGen = d3Line<ResolvedPoint>()
.defined(isFinitePoint)
.x(d => d.px)
.y(d => d.py)
.curve(CURVES[curve] ?? curveLinear);
return pathGen(points) ?? '';
}
Loading
Loading