packages/core/src/features/viz/lib/interval-band-series.tsx
This is the source snapshot used to build these API details. View this revision on GitHub.
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 { AreaSeriesStyle } from "./area-series.js";
15 import { opacity } from "./paint.js";
16 import type { LineAccessor, LineCoordinate, LineSeriesProps } from "./types.js";
17 import {
18 appendCurveForward,
19 appendCurveReverse,
20 curveGeometry,
21 resolveSeriesCurve,
22 validatePairedCurveGeometry,
23 } from "./curve-definition.js";
24 import { useContinuousScale } from "./use-continuous-scale.js";
25
26 /**
27 * Authored inputs for {@link IntervalBandSeries}.
28 *
29 * The data, horizontal coordinate, scales, and defined predicate use the same contract as
30 * {@link LineSeriesProps}. Each contiguous run of at least two observations draws its upper
31 * boundary forward and lower boundary backward.
32 *
33 * @see {@link AreaSeriesStyle}
34 * @see {@link LineSeriesProps}
35 */
36 export interface IntervalBandSeriesProps<D>
37 extends PibblEventHandlers, PibblEventParticipationOptions {
38 /** Application data supplied directly or through a signal. */
39 readonly data: LineSeriesProps<D>["data"];
40 /** Property key or callback extracting the horizontal coordinate. */
41 readonly x: LineAccessor<D>;
42 /** Property key or callback extracting the lower bound. */
43 readonly lower: LineAccessor<D>;
44 /** Property key or callback extracting the upper bound. */
45 readonly upper: LineAccessor<D>;
46 /** Continuous scale used to map horizontal data coordinates. */
47 readonly xScale: LineSeriesProps<D>["xScale"];
48 /** Continuous scale used to map both data bounds. */
49 readonly yScale: LineSeriesProps<D>["yScale"];
50 /** Selects records that participate in a matching-bounds run. */
51 readonly defined?: LineSeriesProps<D>["defined"];
52 /** Curve used to connect successive matching bounds. */
53 readonly curve?: LineSeriesProps<D>["curve"];
54 /** Shared band presentation. Individual datum styling is not supported. */
55 readonly style?: SignalValue<SignalStyle<AreaSeriesStyle>>;
56 }
57
58 function accessor<D>(
59 input: LineAccessor<D>,
60 ): (datum: D, index: number, data: readonly D[]) => LineCoordinate {
61 return typeof input === "function"
62 ? input
63 : (datum) => datum[input] as LineCoordinate;
64 }
65
66 function fill(value: unknown): FillStyle {
67 if (
68 typeof value === "string" ||
69 value instanceof CanvasGradient ||
70 value instanceof CanvasPattern
71 )
72 return value;
73 try {
74 validateTexturePaint(value as never);
75 return value as FillStyle;
76 } catch {
77 throw new TypeError("IntervalBandSeries: invalid fill.");
78 }
79 }
80
81 /**
82 * Draws a filled band between matching lower and upper observations.
83 *
84 * Missing, non-finite, and excluded coordinates split runs. A lower value above its upper
85 * value rejects the datum; equal bounds produce zero-area geometry. The component owns one
86 * ordinary {@link Path} target, so event participation follows standard Path defaults.
87 *
88 * @param props - Data, coordinate accessors, continuous scales, and presentation.
89 * @returns A Pibbl path node containing all drawable interval-band runs.
90 * @throws When data, presentation, or bounds are invalid.
91 *
92 * @see {@link IntervalBandSeriesProps}
93 */
94 export function IntervalBandSeries<D>({
95 data: dataInput,
96 x: xInput,
97 lower: lowerInput,
98 upper: upperInput,
99 xScale: xId,
100 yScale: yId,
101 defined,
102 curve,
103 style: styleInput,
104 ...eventProps
105 }: IntervalBandSeriesProps<D>) {
106 const xScale = useNumericPosition(xId);
107 const yScale = useContinuousScale(yId).get();
108 const curveDefinition = resolveSeriesCurve(curve);
109 const x = useInternalValueMemoSlot(
110 "vizIntervalBandXAccessor",
111 () => accessor(xInput),
112 [xInput],
113 );
114 const lower = useInternalValueMemoSlot(
115 "vizIntervalBandLowerAccessor",
116 () => accessor(lowerInput),
117 [lowerInput],
118 );
119 const upper = useInternalValueMemoSlot(
120 "vizIntervalBandUpperAccessor",
121 () => accessor(upperInput),
122 [upperInput],
123 );
124 const data = resolveSignalValue(dataInput);
125 if (!Array.isArray(data))
126 throw new TypeError(
127 "IntervalBandSeries data must be an array or a signal containing an array.",
128 );
129 const style = resolveSignalValue(styleInput) ?? {};
130 if (style === null || typeof style !== "object" || Array.isArray(style))
131 throw new TypeError("IntervalBandSeries: style must be an object.");
132 const bandFill = fill(resolveSignalValue(style.fill) ?? "#2563eb");
133 const alpha = opacity(
134 resolveSignalValue(style.opacity) ?? 0.2,
135 "IntervalBandSeries",
136 );
137 const cursor = resolveSignalValue(style.cursor);
138 if (cursor !== undefined && typeof cursor !== "string")
139 throw new TypeError("IntervalBandSeries: cursor must be a string.");
140
141 const path = new Path2D();
142 let run: (readonly [number, number, number])[] = [];
143 const closeRun = () => {
144 if (run.length >= 2) {
145 const upper = curveGeometry(
146 curveDefinition,
147 run.map(([x, _lower, value]) => [x, value] as const),
148 );
149 const lower = curveGeometry(
150 curveDefinition,
151 run.map(([x, value]) => [x, value] as const),
152 );
153 validatePairedCurveGeometry(upper, lower);
154 path.moveTo(upper.start[0], upper.start[1]);
155 appendCurveForward(path, upper);
156 appendCurveReverse(path, lower);
157 path.closePath();
158 }
159 run = [];
160 };
161 for (let i = 0; i < data.length; i++) {
162 const datum = data[i];
163 if (defined && !defined(datum, i, data)) {
164 closeRun();
165 continue;
166 }
167 const xv = x(datum, i, data);
168 const lowerValue = lower(datum, i, data);
169 const upperValue = upper(datum, i, data);
170 if (
171 typeof xv !== "number" ||
172 typeof lowerValue !== "number" ||
173 typeof upperValue !== "number" ||
174 !Number.isFinite(xv) ||
175 !Number.isFinite(lowerValue) ||
176 !Number.isFinite(upperValue)
177 ) {
178 closeRun();
179 continue;
180 }
181 if (lowerValue > upperValue)
182 throw new RangeError(
183 `IntervalBandSeries datum at index ${i} has lower bound above upper bound.`,
184 );
185 const point = [
186 xScale.map(xv),
187 yScale.map(lowerValue),
188 yScale.map(upperValue),
189 ] as const;
190 if (!point.every(Number.isFinite)) {
191 closeRun();
192 continue;
193 }
194 run.push(point);
195 }
196 closeRun();
197 return (
198 <Path
199 {...eventProps}
200 style={{ d: path, fill: bandFill, opacity: alpha, cursor }}
201 />
202 );
203 }
204
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.