Skip to content

packages/core/src/features/viz/lib/area-series.tsx

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import { useNumericPosition } from "./series-position.js";
2 import { Path, resolveSignalValue } from "@pibbl/core";
3 import type {
4   FillStyle,
5   PibblEventHandlers,
6   PibblEventParticipationOptions,
7   SignalValue,
8 } from "@pibbl/core";
9 import {
10   useInternalValueMemoSlot,
11   validateTexturePaint,
12 } from "@pibbl/core/internal";
13 import type { SignalStyle } from "@pibbl/core/internal";
14 import type { LineAccessor, LineCoordinate, LineSeriesProps } from "./types.js";
15 import {
16   appendCurveForward,
17   curveGeometry,
18   resolveSeriesCurve,
19 } from "./curve-definition.js";
20 import { opacity } from "./paint.js";
21 import { useContinuousScale } from "./use-continuous-scale.js";
22 
23 /**
24  * Presentation properties for an {@link AreaSeries}.
25  *
26  * @see {@link FillStyle}
27  * @see {@link AreaSeriesProps}
28  */
29 export interface AreaSeriesStyle {
30   /** Paint used for the area interior. */
31   readonly fill?: FillStyle;
32   /** Opacity of the painted area, from zero through one. */
33   readonly opacity?: number;
34   /** Cursor shown while the area target owns pointer presentation. */
35   readonly cursor?: string;
36 }
37 
38 /**
39  * Authored inputs for {@link AreaSeries}.
40  *
41  * The data, coordinate accessors, scales, and defined predicate use the same
42  * contract as {@link LineSeriesProps}. Each contiguous run of at least two
43  * valid observations is closed to `baseline` in data space.
44  *
45  * @see {@link LineSeriesProps}
46  * @see {@link AreaSeriesStyle}
47  */
48 export interface AreaSeriesProps<D>
49   extends PibblEventHandlers, PibblEventParticipationOptions {
50   /** Application data supplied directly or through a signal. */
51   readonly data: LineSeriesProps<D>["data"];
52   /** Property key or callback extracting the horizontal coordinate. */
53   readonly x: LineAccessor<D>;
54   /** Property key or callback extracting the vertical coordinate. */
55   readonly y: LineAccessor<D>;
56   /** Continuous scale used to map horizontal data coordinates. */
57   readonly xScale: LineSeriesProps<D>["xScale"];
58   /** Continuous scale used to map vertical data coordinates and baseline. */
59   readonly yScale: LineSeriesProps<D>["yScale"];
60   /** Selects records that participate in an observed run. */
61   readonly defined?: LineSeriesProps<D>["defined"];
62   /** Curve used to connect successive observed samples. */
63   readonly curve?: LineSeriesProps<D>["curve"];
64   /** Finite data-space value to which each observed run closes. */
65   readonly baseline: SignalValue<number>;
66   /** Shared area presentation. Individual datum styling is not supported. */
67   readonly style?: SignalValue<SignalStyle<AreaSeriesStyle>>;
68 }
69 
70 function accessor<D>(
71   input: LineAccessor<D>,
72 ): (datum: D, index: number, data: readonly D[]) => LineCoordinate {
73   return typeof input === "function"
74     ? input
75     : (datum) => datum[input] as LineCoordinate;
76 }
77 
78 function fill(value: unknown): FillStyle {
79   if (
80     typeof value === "string" ||
81     value instanceof CanvasGradient ||
82     value instanceof CanvasPattern
83   )
84     return value;
85   try {
86     validateTexturePaint(value as never);
87     return value as FillStyle;
88   } catch {
89     throw new TypeError("AreaSeries: invalid fill.");
90   }
91 }
92 
93 /**
94  * Draws each contiguous observed run as a filled polygon closed to an explicit baseline.
95  *
96  * Missing, non-finite, and excluded coordinates split runs. A lone observation has no area.
97  * The component owns one ordinary {@link Path} target, so event participation follows the
98  * standard Path defaults; callers may wrap it in `Clip` when clipping is needed.
99  *
100  * @param props - Data, coordinate accessors, continuous scales, baseline, and presentation.
101  * @returns A Pibbl path node containing all drawable area runs.
102  * @throws When `data` is not an array, the baseline is not finite, or presentation is invalid.
103  *
104  * @see {@link AreaSeriesProps}
105  */
106 export function AreaSeries<D>({
107   data: dataInput,
108   x: xInput,
109   y: yInput,
110   xScale: xId,
111   yScale: yId,
112   baseline: baselineInput,
113   defined,
114   curve,
115   style: styleInput,
116   ...eventProps
117 }: AreaSeriesProps<D>) {
118   const xScale = useNumericPosition(xId);
119   const yScale = useContinuousScale(yId).get();
120   const curveDefinition = resolveSeriesCurve(curve);
121   const x = useInternalValueMemoSlot(
122     "vizAreaXAccessor",
123     () => accessor(xInput),
124     [xInput],
125   );
126   const y = useInternalValueMemoSlot(
127     "vizAreaYAccessor",
128     () => accessor(yInput),
129     [yInput],
130   );
131   const data = resolveSignalValue(dataInput);
132   if (!Array.isArray(data))
133     throw new TypeError(
134       "AreaSeries data must be an array or a signal containing an array.",
135     );
136   const baseline = resolveSignalValue(baselineInput);
137   if (typeof baseline !== "number" || !Number.isFinite(baseline))
138     throw new RangeError("AreaSeries baseline must be finite.");
139   const baselineY = yScale.map(baseline);
140   if (!Number.isFinite(baselineY))
141     throw new RangeError(
142       "AreaSeries baseline must map to a finite coordinate.",
143     );
144   const style = resolveSignalValue(styleInput) ?? {};
145   if (style === null || typeof style !== "object" || Array.isArray(style))
146     throw new TypeError("AreaSeries: style must be an object.");
147   const areaFill = fill(resolveSignalValue(style.fill) ?? "#2563eb");
148   const alpha = opacity(resolveSignalValue(style.opacity) ?? 0.2, "AreaSeries");
149   const cursor = resolveSignalValue(style.cursor);
150   if (cursor !== undefined && typeof cursor !== "string")
151     throw new TypeError("AreaSeries: cursor must be a string.");
152 
153   const path = new Path2D();
154   let run: (readonly [number, number])[] = [];
155   const closeRun = () => {
156     if (run.length >= 2) {
157       const first = run[0];
158       const last = run[run.length - 1];
159       const geometry = curveGeometry(curveDefinition, run);
160       path.moveTo(geometry.start[0], geometry.start[1]);
161       appendCurveForward(path, geometry);
162       path.lineTo(last[0], baselineY);
163       path.lineTo(first[0], baselineY);
164       path.closePath();
165     }
166     run = [];
167   };
168   for (let i = 0; i < data.length; i++) {
169     const datum = data[i];
170     if (defined && !defined(datum, i, data)) {
171       closeRun();
172       continue;
173     }
174     const xv = x(datum, i, data);
175     const yv = y(datum, i, data);
176     if (
177       typeof xv !== "number" ||
178       typeof yv !== "number" ||
179       !Number.isFinite(xv) ||
180       !Number.isFinite(yv)
181     ) {
182       closeRun();
183       continue;
184     }
185     const point = [xScale.map(xv), yScale.map(yv)] as const;
186     if (!Number.isFinite(point[0]) || !Number.isFinite(point[1])) {
187       closeRun();
188       continue;
189     }
190     run.push(point);
191   }
192   closeRun();
193   return (
194     <Path
195       {...eventProps}
196       style={{ d: path, fill: areaFill, opacity: alpha, cursor }}
197     />
198   );
199 }
200 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.