Skip to content

Commit 255be16

Browse files
committed
feat(charts): add a trendLine utility mark
trendLine(dataKey, options) draws an annotation through one value per data row: a fitted trend, a moving average, a forecast or a target path that the caller computes. It places and joins points as line() does, on numeric and categorical x, and a missing value starts a gap. It is dashed by default and can carry a label badge at its last point inside the plot. It is a utility mark: it adds no tooltip row, row label or hover dot, no derived legend item, no palette slot, no data-table column, no name in the default accessible name and no pointer point. Its values widen the y domain, so the line stays visible unless the chart fixes yDomain. The default stroke and label use the secondary text color. line() and trendLine() share one private point and path helper, and referenceLine() and trendLine() share one private label badge; line() and referenceLine() render the same output as before. The new module:Chart/trendLine draft record contracts the mark (DEC-1), the draft component:Chart record lists it, and spec:AST-115 FR2 now describes utility marks by their role and names trendLine among them. An Annotations story shows a scatter with a trend line.
1 parent 200a36f commit 255be16

13 files changed

Lines changed: 951 additions & 112 deletions

File tree

‎apps/storybook/stories/charts/Annotations.stories.tsx‎

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
band,
99
errorBar,
1010
referenceLine,
11+
trendLine,
12+
dot,
1113
ChartGrid,
1214
ChartAxis,
1315
} from '@astryxdesign/charts';
@@ -17,14 +19,16 @@ import {
1719
conversionTestData,
1820
cpuUtilizationData,
1921
latencyByConcurrencyData,
22+
pageWeightLoadTimeData,
2023
salesData,
2124
signupForecastData,
2225
} from './_data';
2326

2427
/**
2528
* Annotations mark values on a chart: targets, ranges, events, uncertainty.
26-
* Build them with `referenceLine()`, `band()` and `errorBar()`, the same
27-
* factories you pass in `series`. They get no legend entry and no tooltip row.
29+
* Build them with `referenceLine()`, `band()`, `errorBar()` and
30+
* `trendLine()`, the same factories you pass in `series`. They get no legend
31+
* entry and no tooltip row.
2832
*
2933
* `referenceLine({x})` takes a numeric `x`. It draws only on a numeric x axis;
3034
* on a categorical x axis it draws nothing.
@@ -195,6 +199,58 @@ export const ErrorBars: StoryObj = {
195199
),
196200
};
197201

202+
// A least-squares fit of load time on page weight, computed here: the chart
203+
// draws the values it is given and computes no fit itself.
204+
const trendData = (() => {
205+
const rows = [...pageWeightLoadTimeData].sort(
206+
(a, b) => a.pageWeightKb - b.pageWeightKb,
207+
);
208+
const meanX = rows.reduce((s, d) => s + d.pageWeightKb, 0) / rows.length;
209+
const meanY = rows.reduce((s, d) => s + d.loadTimeMs, 0) / rows.length;
210+
let sxy = 0;
211+
let sxx = 0;
212+
for (const d of rows) {
213+
sxy += (d.pageWeightKb - meanX) * (d.loadTimeMs - meanY);
214+
sxx += (d.pageWeightKb - meanX) ** 2;
215+
}
216+
const slope = sxy / sxx;
217+
return {
218+
msPer100Kb: Math.round(slope * 100),
219+
rows: rows.map(d => ({
220+
...d,
221+
trendMs: Math.round(meanY + slope * (d.pageWeightKb - meanX)),
222+
})),
223+
};
224+
})();
225+
226+
/**
227+
* A trend line draws a value for every x that you compute, here a straight
228+
* least-squares fit, as a dashed annotation. It adds no legend item, tooltip
229+
* row or table column, and the subtitle states what it shows for screen
230+
* readers. Sort scatter rows by x, because the line joins rows in data order.
231+
* Check: one straight dashed line runs through the dots from the lightest to
232+
* the heaviest page, labelled "Trend" at its right end, and hovering a dot
233+
* shows only that page's load time.
234+
*/
235+
export const TrendLine: StoryObj = {
236+
render: () => (
237+
<Chart
238+
data={trendData.rows}
239+
xKey="pageWeightKb"
240+
title="Page load time by page weight"
241+
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.`}
242+
series={[
243+
dot('loadTimeMs', {radius: 4, opacity: 0.7, label: 'Load time'}),
244+
trendLine('trendMs', {label: 'Trend'}),
245+
]}
246+
tooltip
247+
grid={<ChartGrid horizontal vertical />}
248+
axes={axes}
249+
height={360}
250+
/>
251+
),
252+
};
253+
198254
/** Many marks at once: bars, reference range, confidence band, reference line, line, error bars. */
199255
export const Layering: StoryObj = {
200256
render: () => {

‎docs/specs/AST-115-chart-value-format/spec.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,9 @@ calendar: CalendarSystem) => string | null | undefined`. A format returns the
101101
it as a read-only `formatValue`, and a custom series definition may set it
102102
the same way. The format applies to every data key the series reads, so the
103103
open, high, low, and close values of one candlestick read alike. Utility
104-
marks (`band`, `errorBar`, `referenceLine`) take no format, because neither
105-
the tooltip nor the data table shows them. The WebGL mark builders take no
104+
marks, which annotate the data rather than plot values a reader compares,
105+
take no format, because neither the tooltip nor the data table shows them.
106+
`band`, `errorBar`, `referenceLine`, and `trendLine` are utility marks. The WebGL mark builders take no
106107
format (DEC-7); a WebGL series that reads a data key shows that value with
107108
FR8 and FR9.
108109
- **FR3 — The chart declares how its x values read.** `Chart` accepts an

‎docs/specs/components/Chart/Chart.spec.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ verified_by:
1616
packages/charts/src/marks/marks.test.tsx,
1717
apps/storybook/stories/charts/Chart.stories.tsx,
1818
]
19-
modules: []
19+
modules: [module:Chart/trendLine]
2020
families: []
2121
design_specs: []
2222
architecture:
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
---
2+
schema_version: 3
3+
template_version: 4
4+
kind: module
5+
id: module:Chart/trendLine
6+
authority: draft
7+
archive_reason: null
8+
superseded_by: null
9+
approved_by: null
10+
approved_at: null
11+
owners: [marie-lucas]
12+
review_triggers: [public-api, behavior, theming, accessibility]
13+
verified_by:
14+
[
15+
packages/charts/src/marks/trendLine.test.tsx,
16+
packages/charts/src/marks/marks.test.tsx,
17+
apps/storybook/stories/charts/Annotations.stories.tsx,
18+
]
19+
parent_component: component:Chart
20+
references: [spec:AST-002, spec:AST-115/FR2]
21+
---
22+
23+
# Trend line module contract
24+
25+
<!-- path-applicability:v1 -->
26+
27+
```json
28+
{
29+
"paths": [
30+
"packages/charts/src/marks/trendLine.tsx",
31+
"packages/charts/src/marks/linePath.ts",
32+
"packages/charts/src/marks/annotationLabel.tsx"
33+
]
34+
}
35+
```
36+
37+
## Contract at a glance
38+
39+
| Area | Contract |
40+
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
41+
| Public contract | `trendLine(dataKey, options?)` builds a series definition. `TrendLineOptions` takes `color`, `curve`, `strokeWidth`, `strokeDasharray` and `label`. |
42+
| Behavior | The mark draws one point per data row from `data[dataKey]`, placed and joined as `line()` places and joins them, dashed by default. A missing value starts a gap. Its values widen the y domain. It is an annotation, not a compared series. |
43+
| End-user impact | People reading a chart see a trend, a moving average, a forecast or a target path as a dashed annotation. The tooltip, the legend and the hidden data table show only the compared series, and series colors do not shift. |
44+
| Builder impact | Optional. A caller computes the values and passes the key. The caller states what the trend shows in the chart's `subtitle`. |
45+
| Compatibility/readiness | Additive. Existing marks and charts are unchanged. |
46+
| Review checks | Reject a trend line that adds a tooltip row, a row label, a hover dot, a derived legend item, a palette slot, a data-table column, a name in the default accessible name or a pointer point; a value format option; a badge outside the plot. |
47+
| Governing rules | DEC-1 (pending owner approval); `spec:AST-115` FR2 (utility marks take no format); `spec:AST-002`. |
48+
49+
This table is a review projection; the body below is authoritative.
50+
51+
## Intent
52+
53+
Charts often show a line that annotates the data rather than plotting values a
54+
reader compares: a fitted trend, a moving average, a forecast or a target
55+
path. Drawn with `line()`, such a line takes a palette color, a legend item, a
56+
tooltip row and a table column, and it reads as one more data series. This
57+
module draws it as an annotation that the caller supplies one value per x for.
58+
59+
This record contracts the trend line mark. Computing the values, such as a
60+
fit, is outside it.
61+
62+
## Compatibility and migration
63+
64+
- Released default preserved: `yes`; no existing mark or chart changes
65+
- Compatibility class: additive
66+
- Migration decision: none; a caller who draws a trend with `line()` can keep
67+
it
68+
69+
Consumer migration instructions belong in consumer docs and release notes.
70+
71+
## Ownership boundary
72+
73+
**Owns**
74+
75+
- The `trendLine()` builder, its options and their defaults.
76+
- How the mark places points, joins them and leaves gaps (FR1, FR2).
77+
- Its exclusion from data-series surfaces (FR3) and its y-domain effect (FR4).
78+
- Its label badge (FR5).
79+
80+
**Does not own / non-goals**
81+
82+
- Point placement on the x axis and the path builder that `line()` also uses —
83+
owned by `line()` and `component:Chart`; this module reuses them.
84+
- Which surfaces skip utility marks, and the order of layout and paint — owned
85+
by `component:Chart`.
86+
- Computing values, such as a fitted line, its extent or its confidence
87+
interval — uncontracted.
88+
- Value text for the trend in the tooltip, the table or an accessible
89+
description — uncontracted; `spec:AST-115` FR2 gives utility marks no format.
90+
- `referenceLine`, `band` and `errorBar` — uncontracted here.
91+
92+
## Public API and concepts
93+
94+
| Concept | Closed values or states | Meaning | Default | Owner | Stability |
95+
| ----------------- | ----------------------------------------------- | ------------------------------------------------------------ | ----------------------------- | ------------------------ | ------------ |
96+
| `dataKey` | a key of the chart's data rows | the value of the trend at each row's x | required | `module:Chart/trendLine` | experimental |
97+
| `color` | a CSS color | the stroke and the label color; it takes no palette slot | `var(--color-text-secondary)` | `module:Chart/trendLine` | experimental |
98+
| `curve` | `'linear'`, `'monotone'`, `'natural'`, `'step'` | how points join, as on `line()` | `'linear'` | `line()` | experimental |
99+
| `strokeWidth` | a finite number, at least 0 | the stroke width | `1.5` | `module:Chart/trendLine` | experimental |
100+
| `strokeDasharray` | an SVG dash pattern | the dash pattern | `'6 3'` | `module:Chart/trendLine` | experimental |
101+
| `label` | a string | the text of a badge at the line's last point inside the plot | none | `module:Chart/trendLine` | experimental |
102+
103+
## Behavioral contract
104+
105+
| ID | Invariant | Basis | Draft review state |
106+
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ------------------ |
107+
| FR1 | The mark MUST draw one point per data row, in data order, at the row's x as `line()` places it (a band center on a categorical x, the scale position on a numeric x) and at `data[dataKey]` on the y scale. Points join by `curve`, as on `line()`. | DEC-1 | human decision |
108+
| FR2 | A row whose value is missing or not a finite number MUST start a gap: the path does not join the points on either side of it. When no row has a finite value, the mark draws nothing. | DEC-1 | human decision |
109+
| FR3 | The mark MUST add no tooltip row, row label or hover dot, no derived legend item, no palette slot, no data-table column and no name in the chart's default accessible name. It MUST give the pointer no candidate point. An explicit `legend.items` list can still show it. | DEC-1; `spec:AST-115` FR2 | human decision |
110+
| FR4 | The mark's values MUST widen the y domain, like a series value. Its layout adds no x inset, stack or baseline. A chart with an explicit `yDomain` keeps that domain, and the plot clips the line. | DEC-1 | human decision |
111+
| FR5 | With `label`, the mark MUST draw one badge that ends at the last drawn point inside the plot and sits above it, kept inside the plot. When no drawn point is inside the plot, it draws no badge. | DEC-1 | human decision |
112+
| FR6 | The mark MUST take no value format. | `spec:AST-115` FR2 | settled |
113+
114+
## Accessibility contract
115+
116+
- **AR1 — The meaning goes in the chart description.** The mark exposes no
117+
values to assistive technology. Its documentation and examples state what the
118+
trend shows in the chart's `subtitle`, which the chart exposes as the image
119+
description. A label drawn inside the chart image is not that description.
120+
121+
## Design relationships
122+
123+
| Anatomy or state | Design requirement | Representation authority | Module contract |
124+
| ---------------- | ------------------------------------------------------------------ | ------------------------ | --------------- |
125+
| trend stroke | an annotation reads as distinct from data without relying on color | unsettled | FR1; DD1 |
126+
| label badge | label text meets text contrast in light and dark | unsettled | FR5 |
127+
128+
### Design decisions
129+
130+
<!-- design-decisions:v1 -->
131+
132+
| ID | Decision | Intent or reason | Applies to | Allowed variation |
133+
| --- | ---------------------------- | ----------------------------------------------------------------------------------- | ------------ | ------------------------------------- |
134+
| DD1 | The default stroke is dashed | A dash marks the line as an annotation in every color mode and without color vision | trend stroke | the dash pattern and the stroke width |
135+
136+
## Parent and system relationships
137+
138+
- `component:Chart` owns layout, palette assignment, the surfaces that skip
139+
utility marks, and the render pass.
140+
- `line()` owns point placement and joining; this module reuses them.
141+
142+
## Verification map
143+
144+
| Contract | Verification | Representative states | Mutation or failure expectation |
145+
| -------- | ------------------------------------------ | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
146+
| FR1 | `trendLine.test.tsx` | numeric x with an explicit y domain; categorical x; a monotone curve | points placed off the band centers or the scale positions fail |
147+
| FR2 | `trendLine.test.tsx` | a missing middle value; no finite value | a path joined across the gap, or an empty path element, fails |
148+
| FR3 | `trendLine.test.tsx` | legend, palette order, table columns, accessible name, tooltip card, pointer points | removing the mark from the utility marks, or resolving points, fails |
149+
| FR4 | `trendLine.test.tsx` | trend values above the data | a mark that reads no data key fails |
150+
| FR5 | `trendLine.test.tsx`; real-browser capture | a label at the line end; every point outside the plot; no label; light and dark | a badge at the first point, or a badge with no visible point, fails |
151+
| FR6 | `trendLine.test.tsx` type assertion | `TrendLineOptions` | adding `formatValue` fails the type check |
152+
153+
## Decision log
154+
155+
### DEC-1 — A trend line is a utility mark that reads one value per x
156+
157+
**Reference:** `module:Chart/trendLine/DEC-1`
158+
**Decider:** `marie-lucas`, `2026-12-01`
159+
160+
A trend line takes a data key and draws its value at every x, as `line()`
161+
does. What makes it a trend line is its dashed styling, its label and that the
162+
chart treats it as an annotation rather than a compared series. One value per
163+
x covers fitted trends, moving averages, forecasts and target paths, and a
164+
caller computes the values in whatever way fits the product. Its values widen
165+
the y domain, so the line stays visible unless the caller fixes the domain.
166+
167+
Rejected: `line()` with a dash option, because the line would still take a palette color, a legend item, a tooltip row and a table column.
168+
Rejected: two endpoints only, because a moving average, a forecast or a curved fit needs a value at every x.
169+
170+
## Open questions
171+
172+
- **OQ1 — Missing values.** Does a trend line join across a missing value
173+
instead of leaving a gap, so that values on two distant rows draw one
174+
straight segment? (`human-api`)
175+
176+
## Content boundary
177+
178+
This record does not duplicate consumer signatures or examples, layout, the
179+
render pass, current audit results or implementation steps. It links to their
180+
canonical owners.

‎packages/charts/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ export {
3131
candlestick,
3232
errorBar,
3333
referenceLine,
34+
trendLine,
3435
dotGL,
3536
dotGLInteractive,
3637
heatmapGL,
@@ -45,6 +46,7 @@ export type {
4546
CandlestickOptions,
4647
ErrorBarOptions,
4748
ReferenceLineOptions,
49+
TrendLineOptions,
4850
DotGLOptions,
4951
DotGLInteractiveOptions,
5052
HeatmapGLOptions,

0 commit comments

Comments
 (0)