Skip to content

packages/core/src/features/viz/lib/bar-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 {
2   Group,
3   isSignal,
4   Rectangle,
5   resolveSignalValue,
6   useCanvasContext,
7 } from "@pibbl/core";
8 import type {
9   PibblEventHandlers,
10   PibblEventParticipationOptions,
11   PibblNode,
12   FillStyle,
13   SignalValue,
14   StrokeStyle,
15 } from "@pibbl/core";
16 import { withHooksForbidden } from "@pibbl/core/internal";
17 import { lookupScale } from "./scale-context.js";
18 import type { SignalStyle } from "@pibbl/core/internal";
19 import type { BandCategory, LineAccessor, ScaleId } from "./types.js";
20 import { useContinuousScale } from "./use-continuous-scale.js";
21 import { useBarScale } from "./use-bar-scale.js";
22 import { pointAccessor, pointData, finiteCoordinate } from "./point-data.js";
23 import { opacity, width } from "./paint.js";
24 /**
25  * A data property or callback that extracts a category, with nullish values treated as missing.
26  *
27  * @param datum - Datum whose category is being read.
28  * @param index - Zero-based index in the source data.
29  * @param data - Complete source data array.
30  * @returns The category, or null/undefined to indicate a missing category. See
31  * {@link BandCategory} .
32  *
33  * @see {@link BandCategory}
34  * @see {@link BarSeriesProps}
35  */
36 export type BarCategoryAccessor<D> =
37   | {
38       [K in keyof D]-?: D[K] extends BandCategory | null | undefined
39         ? K
40         : never;
41     }[keyof D]
42   | ((
43       datum: D,
44       index: number,
45       data: readonly D[],
46     ) => BandCategory | null | undefined);
47 import { barFill, type BarThresholdFill } from "./bar-fill.js";
48 export type { BarThresholdFill } from "./bar-fill.js";
49 /**
50  * Supported geometry and presentation properties for BarSeries.
51  *
52  * @see {@link FillStyle}
53  * @see {@link BarThresholdFill}
54  * @see {@link StrokeStyle}
55  * @see {@link BarStyleResolver}
56  */
57 export interface BarSeriesStyle {
58   /** Width allocated to one categorical band. See {@link BarSeriesStyle}. */
59   readonly bandwidth?: number | "auto";
60   /** Paint used for the interior. See {@link FillStyle}, {@link BarThresholdFill}. */
61   readonly fill?: FillStyle | BarThresholdFill;
62   /** Paint used for the outline. See {@link StrokeStyle}. */
63   readonly stroke?: StrokeStyle;
64   /** Width of the painted outline. See {@link BarSeriesStyle}. */
65   readonly strokeWidth?: number;
66   /** Opacity of the painted result. See {@link BarSeriesStyle}. */
67   readonly opacity?: number;
68   /** Cursor shown while this target owns pointer presentation. See {@link BarSeriesStyle}. */
69   readonly cursor?: string;
70 }
71 /**
72  * Computes bar styling from the datum, index, and source data.
73  *
74  * @param datum - Datum being styled.
75  * @param index - Zero-based index in the source data.
76  * @param data - Complete source data array.
77  * @returns Style for this datum's bar. See {@link BarSeriesStyle}.
78  *
79  * @see {@link BarSeriesStyle}
80  */
81 export type BarStyleResolver<D> = (
82   datum: D,
83   index: number,
84   data: readonly D[],
85 ) => BarSeriesStyle;
86 /**
87  * Shared data, category/value scales, orientation, filtering, and styling for bar variants.
88  *
89  * @see {@link BarCategoryAccessor}
90  * @see {@link BarSeriesStyle}
91  * @see {@link BarSeriesProps}
92  */
93 interface BarSeriesBaseProps<D> extends PibblEventHandlers, PibblEventParticipationOptions {
94   /**
95    * Application data supplied to the component or reported by the event. See {@link SignalValue}.
96    */
97   readonly data: SignalValue<readonly D[]>;
98   /** Optional committed bar capture; rendering alone performs no inspection searches. */
99   readonly inspection?: import("../inspection/bar.js").BarInspectionRef<D>;
100   /** Selects `"vertical"`, `"horizontal"` for orientation. See {@link BarSeriesBaseProps}. */
101   readonly orientation?: "vertical" | "horizontal";
102   /** Property or callback extracting a bar's discrete category. See {@link BarCategoryAccessor}. */
103   readonly category: BarCategoryAccessor<D>;
104   /** Band scale used to place categories. See {@link ScaleId}. */
105   readonly categoryScale: ScaleId;
106   /** Numeric scale used to map bar values. See {@link ScaleId}. */
107   readonly valueScale: ScaleId;
108   /**
109    * Selects the records that participate in the bar series. See {@link BarSeriesProps}.
110    * @param datum - Record to test.
111    * @param index - Zero-based index in the source array.
112    * @param data - Complete source data array.
113    * @returns Whether this record should contribute a bar.
114    */
115   readonly defined?: (datum: D, index: number, data: readonly D[]) => boolean;
116   /**
117    * Declared presentation and layout properties. See {@link SignalValue}, {@link SignalStyle},
118    * {@link BarSeriesStyle}, {@link BarStyleResolver}.
119    */
120   readonly style?: SignalValue<SignalStyle<BarSeriesStyle> | BarStyleResolver<D>>;
121 }
122 /**
123  * Authored inputs for BarSeries, including the declared data and presentation options.
124  *
125  * @see {@link LineAccessor}
126  * @see {@link SignalValue}
127  * @see {@link BarCategoryAccessor}
128  * @see {@link ScaleId}
129  * @see {@link BarSeries}
130  */
131 export type BarSeriesProps<D> = BarSeriesBaseProps<D> &
132   (
133     | {
134         /** Value associated with this sample, input, or result. See {@link LineAccessor}. */
135         readonly value: LineAccessor<D>;
136         /** Numeric value from which each ordinary bar starts. See {@link SignalValue}. */
137         readonly baseline?: SignalValue<number>;
138         /**
139          * Not accepted in this variant; use the alternative fields instead. See
140          * {@link BarSeriesProps}.
141          */
142         readonly valueStart?: never;
143         /**
144          * Not accepted in this variant; use the alternative fields instead. See
145          * {@link BarSeriesProps}.
146          */
147         readonly valueEnd?: never;
148       }
149     | {
150         /**
151          * Not accepted in this variant; use the alternative fields instead. See
152          * {@link BarSeriesProps}.
153          */
154         readonly value?: never;
155         /**
156          * Not accepted in this variant; use the alternative fields instead. See
157          * {@link BarSeriesProps}.
158          */
159         readonly baseline?: never;
160         /** Accessor for the beginning of a range bar. See {@link LineAccessor}. */
161         readonly valueStart: LineAccessor<D>;
162         /** Accessor for the end of a range bar. See {@link LineAccessor}. */
163         readonly valueEnd: LineAccessor<D>;
164       }
165   ) &
166   (
167     | {
168         /** Accessor identifying the subgroup of each bar. See {@link BarCategoryAccessor}. */
169         readonly group: BarCategoryAccessor<D>;
170         /** Band scale used to place subgroups within a category. See {@link ScaleId}. */
171         readonly groupScale: ScaleId;
172       }
173     | {
174         /** Accessor identifying the subgroup of each bar. See {@link BarSeriesProps}. */
175         readonly group?: never;
176         /**
177          * Not accepted in this variant; use the alternative fields instead. See
178          * {@link BarSeriesProps}.
179          */
180         readonly groupScale?: never;
181       }
182   );
183 /**
184  * Value bars in source order; rectangles supply ordinary paint and event geometry.
185  *
186  * @param props - Data, category and value accessors, scales, grouping, and styling. See
187  * {@link BarSeriesProps} .
188  * @returns Pibbl nodes drawing the bars.
189  *
190  * @see {@link BarSeriesProps}
191  */
192 export function BarSeries<D>({
193   data: input,
194   orientation = "vertical",
195   category: categoryInput,
196   value: valueInput,
197   valueStart,
198   valueEnd,
199   categoryScale,
200   valueScale,
201   baseline,
202   group,
203   groupScale,
204   defined,
205   style: styleInput,
206   pointerEvents,
207   inspection,
208   ...events
209 }: BarSeriesProps<D>) {
210   const categories = useBarScale(categoryScale).get();
211   const values = useContinuousScale(valueScale).get();
212   const groups = lookupScale(groupScale, "BarSeries groupScale")?.get();
213   if ((group === undefined) !== (groupScale === undefined))
214     throw new TypeError("BarSeries requires group and groupScale together.");
215   if (groups && groups.type !== "band")
216     throw new TypeError("BarSeries groupScale requires a band scale.");
217   const groupValue =
218     typeof group === "function"
219       ? group
220       : (datum: D) =>
221           group === undefined
222             ? undefined
223             : (datum[group] as BandCategory | null | undefined);
224   const slotWidth =
225     groups?.type === "band" ? groups.bandwidth : categories.bandwidth;
226   if (orientation !== "vertical" && orientation !== "horizontal")
227     throw new TypeError("BarSeries orientation must be vertical or horizontal.");
228   const data = pointData(resolveSignalValue(input), "BarSeries");
229   const category =
230     typeof categoryInput === "function"
231       ? categoryInput
232       : (datum: D) =>
233           datum[categoryInput] as BandCategory | null | undefined;
234   const ranged = valueStart !== undefined || valueEnd !== undefined;
235   if (
236     ranged
237       ? valueInput !== undefined ||
238         baseline !== undefined ||
239         valueStart === undefined ||
240         valueEnd === undefined
241       : valueInput === undefined
242   )
243     throw new TypeError(
244       "BarSeries requires either value with optional baseline, or both valueStart and valueEnd without value or baseline.",
245     );
246   const value = pointAccessor((ranged ? valueEnd : valueInput)!);
247   const startValue = ranged ? pointAccessor(valueStart!) : undefined;
248   const baselineValue = resolveSignalValue(baseline ?? 0);
249   const sharedBase = ranged ? undefined : values.map(baselineValue);
250   const specified = resolveSignalValue(styleInput);
251   const ctx = useCanvasContext();
252   function normalize(input: unknown, callback: boolean) {
253     if (!input || typeof input !== "object" || Array.isArray(input))
254       throw new TypeError("BarSeries style must be an object.");
255     if (
256       callback &&
257       Object.getPrototypeOf(input) !== Object.prototype &&
258       Object.getPrototypeOf(input) !== null
259     )
260       throw new TypeError(
261         "BarSeries datum style must be a plain synchronous object.",
262       );
263     const style: Record<string, unknown> = {};
264     for (const key of Object.keys(input)) {
265       if (
266         ![
267           "bandwidth",
268           "fill",
269           "stroke",
270           "strokeWidth",
271           "opacity",
272           "cursor",
273         ].includes(key)
274       )
275         throw new TypeError(`BarSeries: unsupported style field ${key}.`);
276       const value = (input as Record<string, unknown>)[key];
277       if (callback && isSignal(value))
278         throw new TypeError(
279           "BarSeries datum styles require plain values; read signals explicitly.",
280         );
281       style[key] = callback ? value : resolveSignalValue(value);
282     }
283     const resolved = style as BarSeriesStyle;
284     if (resolved.cursor !== undefined && typeof resolved.cursor !== "string")
285       throw new TypeError("BarSeries cursor must be a string.");
286     return {
287       bandwidth:
288         resolved.bandwidth === undefined || resolved.bandwidth === "auto"
289           ? slotWidth
290           : width(resolved.bandwidth, "BarSeries bandwidth"),
291       fill: barFill(ctx, resolved.fill ?? "#2563eb", (value) =>
292         values.map(value),
293         orientation,
294       ),
295       stroke: resolved.stroke,
296       strokeWidth: width(resolved.strokeWidth ?? 1, "BarSeries strokeWidth"),
297       alpha: opacity(resolved.opacity ?? 1, "BarSeries"),
298       cursor: resolved.cursor,
299     };
300   }
301   const shared =
302     typeof specified === "function"
303       ? undefined
304       : normalize(specified ?? {}, false);
305   const nodes: PibblNode[] = [];
306   const captured: import("../inspection/bar.js").CapturedBarMark<D>[] | undefined = inspection ? [] : undefined;
307   for (let i = 0; i < data.length; i++) {
308     const datum = data[i];
309     if (defined && !defined(datum, i, data)) continue;
310     const c = category(datum, i, data),
311       v = value(datum, i, data),
312       from = startValue ? startValue(datum, i, data) : baselineValue;
313     if (c == null || !finiteCoordinate(v) || !finiteCoordinate(from)) continue;
314     const categoryStart = categories.map(c);
315     const g = groups ? groupValue(datum, i, data) : undefined;
316     const offset = groups ? (g == null ? undefined : groups.map(g)) : 0;
317     if (categoryStart === undefined || offset === undefined || slotWidth === 0)
318       continue;
319     const start = categoryStart + offset;
320     const { bandwidth, fill, stroke, strokeWidth, alpha, cursor } =
321       shared ??
322       normalize(
323         withHooksForbidden("BarSeries style callback", () =>
324           (specified as BarStyleResolver<D>)(datum, i, data),
325         ),
326         true,
327       );
328     if (bandwidth === 0) continue;
329     const base = sharedBase ?? values.map(from);
330     const end = values.map(v);
331     const extent = Math.abs(end - base);
332     if (!Number.isFinite(extent))
333       throw new RangeError("BarSeries value extent must be finite.");
334     if (extent === 0) continue;
335     const vertical = orientation === "vertical";
336     const markFill = fill(from,v);
337     captured?.push(Object.freeze({datum,sourceIndex:i,category:c,group:g ?? undefined,valueStart:from,valueEnd:v,
338       boundsLocal:Object.freeze({x:vertical?start+(slotWidth-bandwidth)/2:Math.min(base,end),y:vertical?Math.min(base,end):start+(slotWidth-bandwidth)/2,width:vertical?bandwidth:extent,height:vertical?extent:bandwidth}),
339       fill:!!markFill,strokeWidthLocal:stroke?strokeWidth:0}));
340     nodes.push(
341       <Rectangle
342         key={i}
343         pointerEvents={pointerEvents}
344         style={{
345           left: vertical ? start + (slotWidth - bandwidth) / 2 : Math.min(base, end),
346           top: vertical ? Math.min(base, end) : start + (slotWidth - bandwidth) / 2,
347           width: vertical ? bandwidth : extent,
348           height: vertical ? extent : bandwidth,
349           fill: markFill,
350           stroke,
351           strokeWidth,
352           opacity: alpha,
353           cursor,
354         }}
355       />,
356     );
357   }
358   if (inspection) inspection.capture(captured!);
359   return <Group {...events}>{nodes}</Group>;
360 }
361 

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