panelui-native 0.86.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1143 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * PyramidChart — two series mirrored about a centre line, drawn and animated on
5
+ * the UI thread.
6
+ *
7
+ * ```tsx
8
+ * <PyramidChart data={penguins} xDataKey="species">
9
+ * <PyramidChart.Grid />
10
+ * <PyramidChart.Bar dataKey="male" side="start" />
11
+ * <PyramidChart.Bar dataKey="female" side="end" />
12
+ * <PyramidChart.XAxis />
13
+ * <PyramidChart.YAxis />
14
+ * <PyramidChart.Tooltip />
15
+ * </PyramidChart>
16
+ * ```
17
+ *
18
+ * ## The two wings share one scale
19
+ *
20
+ * This is the whole contract, and everything else here follows from it. The
21
+ * domain is derived from the larger of the two series' extents and used by
22
+ * both, so a bar twice as long as the one facing it means twice as much.
23
+ * Scaling each side to its own maximum produces a chart whose halves cannot be
24
+ * compared — which is the only thing a pyramid is for.
25
+ *
26
+ * For the same reason the centre is zero and stays there. There is no `yDomain`
27
+ * that starts anywhere else, because a wing cropped at its base is a length
28
+ * that lies.
29
+ *
30
+ * ## Lengths, not signed values
31
+ *
32
+ * Which side a series is on comes from `side`, not from the sign of its
33
+ * numbers, so a value is a distance outward from the centre. A negative one has
34
+ * no direction left to grow in and is drawn as nothing; it still appears in the
35
+ * readout, so a data error shows up as a gap rather than as a bar pointing the
36
+ * wrong way.
37
+ *
38
+ * ## Where the category names go
39
+ *
40
+ * `labelPlacement="above"`, the default, gives each row a line of its own over
41
+ * its pair of bars. That leaves the two wings meeting in the middle with
42
+ * nothing standing between them, and puts the name where it is read before the
43
+ * lengths it belongs to rather than beside them.
44
+ *
45
+ * `"center"` puts the names in a gutter between the wings instead — taken off
46
+ * the bars rather than off the edges, so both wings stay equal — and `"start"`
47
+ * puts them down the left, for a chart with room to spare on that side.
48
+ *
49
+ * ## Every series is one path
50
+ *
51
+ * A `Bar` draws all its rectangles as subpaths of a single animated path, split
52
+ * in two so the row under the finger keeps full ink while the rest fade. Thirty
53
+ * rows is two animated props a frame rather than thirty.
54
+ */
55
+ import { Children, createContext, forwardRef, isValidElement, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
56
+ import { StyleSheet, View } from 'react-native';
57
+ import { Gesture, GestureDetector } from 'react-native-gesture-handler';
58
+ import Animated, { Easing, cancelAnimation, runOnJS, useAnimatedProps, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated';
59
+ import Svg, { Defs, G, Line as SvgLine, LinearGradient, Path, Stop } from 'react-native-svg';
60
+ import { useCSSVariable } from 'uniwind';
61
+ import { ChartAccessibilityData } from "../../primitives/chart-accessibility.js";
62
+ import { Text } from "../../primitives/text.js";
63
+ import { barPath, columnValues, compactNumber, niceDomain, useSeriesColor } from "../../utils/chart.js";
64
+ import { cn } from "../../utils/cn.js";
65
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
66
+ const AnimatedPath = Animated.createAnimatedComponent(Path);
67
+ const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
68
+
69
+ /** Room left around the plot for the value labels along the bottom. */
70
+ const PADDING = {
71
+ top: 6,
72
+ right: 10,
73
+ bottom: 22,
74
+ left: 10
75
+ };
76
+
77
+ /** Left gutter reserved for the category names when they sit at the start. */
78
+ const CATEGORY_GUTTER = 68;
79
+
80
+ /**
81
+ * Middle gutter reserved for them when they sit between the wings. Taken off
82
+ * the bars rather than off the edges, so the two wings stay equal.
83
+ */
84
+ const CENTRE_GUTTER = 72;
85
+
86
+ /** Width the readout is laid out at, so it can be clamped inside the plot. */
87
+ const LABEL_WIDTH = 132;
88
+
89
+ /**
90
+ * Box each value label is centred in. Narrow, because the outermost tick on
91
+ * each wing sits on the plot's own edge — a box centred there hangs half its
92
+ * width off the side of the chart, and the number is cropped away.
93
+ */
94
+ const AXIS_LABEL_WIDTH = 56;
95
+
96
+ /** Line height of an `xs` label, for centring one on the tick it names. */
97
+ const AXIS_LABEL_HEIGHT = 16;
98
+
99
+ /**
100
+ * Steps the value axis is rounded out to. Four rather than the two labels each
101
+ * wing draws, so the halfway label lands on a round number too.
102
+ */
103
+ const DOMAIN_STEPS = 4;
104
+
105
+ /**
106
+ * Height taken off the top of every band for the name sitting over it. An `xs`
107
+ * line plus the air that keeps it off the bar it belongs to.
108
+ */
109
+ const LABEL_ROW = 20;
110
+
111
+ /** Which wing a series grows into. */
112
+
113
+ /** Where the category names sit. */
114
+
115
+ const PyramidChartContext = /*#__PURE__*/createContext(null);
116
+ function useChart(component) {
117
+ const context = useContext(PyramidChartContext);
118
+ if (!context) {
119
+ throw new Error(`${component} must be used within a <PyramidChart>`);
120
+ }
121
+ return context;
122
+ }
123
+
124
+ /**
125
+ * The row under the finger, for something rendered *inside* the chart. A
126
+ * readout in the card's header is outside this provider — use
127
+ * `onActiveIndexChange` for that.
128
+ */
129
+ export function usePyramidChart() {
130
+ const {
131
+ data,
132
+ activeIndexJS,
133
+ xDataKey
134
+ } = useChart('usePyramidChart');
135
+ return {
136
+ activeIndex: activeIndexJS,
137
+ activePoint: activeIndexJS >= 0 ? data[activeIndexJS] ?? null : null,
138
+ xDataKey
139
+ };
140
+ }
141
+
142
+ /** Imperative handle: re-run the grow-out, for a "replay" control. */
143
+
144
+ function partition(children) {
145
+ const svg = [];
146
+ const overlay = [];
147
+ const header = [];
148
+ Children.forEach(children, (child, index) => {
149
+ if (! /*#__PURE__*/isValidElement(child)) return;
150
+ const layer = child.type.layer ?? 'svg';
151
+ const slot = /*#__PURE__*/_jsx(ChildSlot, {
152
+ children: child
153
+ }, index);
154
+ (layer === 'header' ? header : layer === 'overlay' ? overlay : svg).push(slot);
155
+ });
156
+ return {
157
+ svg,
158
+ overlay,
159
+ header
160
+ };
161
+ }
162
+ function ChildSlot({
163
+ children
164
+ }) {
165
+ return /*#__PURE__*/_jsx(_Fragment, {
166
+ children: children
167
+ });
168
+ }
169
+ const PyramidChartRoot = /*#__PURE__*/forwardRef(function PyramidChartRoot({
170
+ className,
171
+ data,
172
+ xDataKey = 'name',
173
+ status = 'ready',
174
+ aspectRatio = 1.2,
175
+ animationDuration = 700,
176
+ domainDuration = 500,
177
+ maxValue,
178
+ labelPlacement = 'above',
179
+ barGap = 0.25,
180
+ barWidth,
181
+ cornerRadius = 4,
182
+ minBarLength = 0,
183
+ fadedOpacity = 0.3,
184
+ onActiveIndexChange,
185
+ accessible,
186
+ accessibilityLabel,
187
+ accessibilityHint,
188
+ accessibilityLabelForDatum,
189
+ onAccessibilityDatumPress,
190
+ children,
191
+ ...props
192
+ }, ref) {
193
+ const [size, setSize] = useState({
194
+ width: 0,
195
+ height: 0
196
+ });
197
+ const [series, setSeries] = useState([]);
198
+ const [activeIndexJS, setActiveIndexJS] = useState(-1);
199
+ const reveal = useSharedValue(0);
200
+ const domainMax = useSharedValue(0);
201
+ const activeIndex = useSharedValue(-1);
202
+ const reducedMotion = useReducedMotion();
203
+ const registerSeries = useMemo(() => next => setSeries(current => {
204
+ const existing = current.find(entry => entry.key === next.key);
205
+ if (existing?.color === next.color && existing.side === next.side) return current;
206
+ return [...current.filter(entry => entry.key !== next.key), next];
207
+ }), []);
208
+ const unregisterSeries = useMemo(() => key => setSeries(current => current.filter(entry => entry.key !== key)), []);
209
+
210
+ /*
211
+ * Whether the category names are asking for room. It has to be known before
212
+ * the plot is laid out, and only the root sees the children early enough to
213
+ * ask — the axis itself renders into a box that has already been decided.
214
+ */
215
+ const hasYAxis = useMemo(() => {
216
+ let found = false;
217
+ Children.forEach(children, child => {
218
+ if (/*#__PURE__*/isValidElement(child) && child.type.axis === 'y') {
219
+ found = true;
220
+ }
221
+ });
222
+ return found;
223
+ }, [children]);
224
+
225
+ /*
226
+ * Three places a name can go, and each takes its room from somewhere
227
+ * different: `above` off the top of every band, `center` out of the middle
228
+ * of the plot, `start` off the left edge.
229
+ */
230
+ const gutter = hasYAxis && labelPlacement === 'center' ? CENTRE_GUTTER : 0;
231
+ const labelInset = hasYAxis && labelPlacement === 'above' ? LABEL_ROW : 0;
232
+ const pad = {
233
+ ...PADDING,
234
+ left: hasYAxis && labelPlacement === 'start' ? CATEGORY_GUTTER : PADDING.left
235
+ };
236
+ const plot = {
237
+ left: pad.left,
238
+ top: pad.top,
239
+ width: Math.max(size.width - pad.left - pad.right, 0),
240
+ height: Math.max(size.height - pad.top - pad.bottom, 0)
241
+ };
242
+ const seriesKeys = series.map(entry => entry.key).join('|');
243
+ const extentMax = useMemo(() => {
244
+ if (maxValue !== undefined && maxValue > 0) return maxValue;
245
+ const keys = seriesKeys ? seriesKeys.split('|') : [];
246
+ let max = 0;
247
+ /*
248
+ * One number for both wings. Taking a maximum per side is what makes a
249
+ * pyramid whose halves cannot be compared, so the largest value anywhere
250
+ * in either series sets the scale for all of them.
251
+ */
252
+ for (const row of data) {
253
+ for (const key of keys) {
254
+ const value = row[key];
255
+ if (typeof value !== 'number' || Number.isNaN(value)) continue;
256
+ if (value > max) max = value;
257
+ }
258
+ }
259
+ /*
260
+ * Rounded out to a step a reader can divide in their head, rather than
261
+ * padded by a fraction. A tenth added to 73 ends the axis at 80.3 and
262
+ * labels the wings 40.2 and 80.3 — numbers that are true and that nobody
263
+ * was looking for. The centre is left exactly where it is: rounding it
264
+ * would lift the bars off their own baseline.
265
+ *
266
+ * Four steps, not two, so the halfway label the axis draws by default is
267
+ * a round number as well as the end one.
268
+ */
269
+ return max === 0 ? 1 : niceDomain(0, max, DOMAIN_STEPS)[1];
270
+ }, [data, maxValue, seriesKeys]);
271
+ const loading = status === 'loading';
272
+ useEffect(() => {
273
+ if (loading) return;
274
+ const first = domainMax.value === 0;
275
+ if (first || reducedMotion) {
276
+ domainMax.value = extentMax;
277
+ return;
278
+ }
279
+ domainMax.value = withTiming(extentMax, {
280
+ duration: domainDuration
281
+ });
282
+ }, [extentMax, loading, reducedMotion, domainDuration, domainMax]);
283
+ const revealed = useRef(false);
284
+ const playReveal = useMemo(() => () => {
285
+ if (reducedMotion) {
286
+ reveal.value = 1;
287
+ return;
288
+ }
289
+ reveal.value = 0;
290
+ reveal.value = withTiming(1, {
291
+ duration: animationDuration,
292
+ easing: Easing.out(Easing.cubic)
293
+ });
294
+ }, [reducedMotion, animationDuration, reveal]);
295
+ useEffect(() => {
296
+ /*
297
+ * Going back to `loading` arms the reveal again. Without this a chart
298
+ * that is refetched comes back fully drawn on the frame the data lands,
299
+ * which reads as the loading state having been for nothing.
300
+ */
301
+ if (loading) {
302
+ revealed.current = false;
303
+ reveal.value = 0;
304
+ return;
305
+ }
306
+ if (revealed.current || plot.width <= 0 || !data.length) return;
307
+ revealed.current = true;
308
+ playReveal();
309
+ }, [loading, plot.width, data.length, playReveal, reveal]);
310
+ useImperativeHandle(ref, () => ({
311
+ replay: playReveal
312
+ }), [playReveal]);
313
+ const handleActiveIndex = useMemo(() => index => {
314
+ setActiveIndexJS(index);
315
+ onActiveIndexChange?.(index, index >= 0 ? data[index] ?? null : null);
316
+ }, [onActiveIndexChange, data]);
317
+ const onLayout = event => {
318
+ const {
319
+ width,
320
+ height
321
+ } = event.nativeEvent.layout;
322
+ setSize(current => Math.abs(current.width - width) < 1 && Math.abs(current.height - height) < 1 ? current : {
323
+ width,
324
+ height
325
+ });
326
+ props.onLayout?.(event);
327
+ };
328
+ const context = useMemo(() => ({
329
+ data,
330
+ xDataKey,
331
+ plot,
332
+ status,
333
+ gutter,
334
+ labelInset,
335
+ labelPlacement,
336
+ barGap,
337
+ barWidth,
338
+ cornerRadius,
339
+ minBarLength,
340
+ fadedOpacity,
341
+ series,
342
+ registerSeries,
343
+ unregisterSeries,
344
+ domainMax,
345
+ extentMax,
346
+ reveal,
347
+ activeIndex,
348
+ activeIndexJS,
349
+ setActiveIndexJS: handleActiveIndex
350
+ }),
351
+ // `plot` is rebuilt every render from `size`, so it is compared by value.
352
+ // eslint-disable-next-line react-hooks/exhaustive-deps
353
+ [data, xDataKey, plot.width, plot.height, plot.left, plot.top, status, gutter, labelInset, labelPlacement, barGap, barWidth, cornerRadius, minBarLength, fadedOpacity, series, registerSeries, unregisterSeries, domainMax, extentMax, reveal, activeIndex, activeIndexJS, handleActiveIndex]);
354
+ const {
355
+ svg,
356
+ overlay,
357
+ header
358
+ } = partition(children);
359
+
360
+ /*
361
+ * Two views, because the header is not part of the plot. `aspectRatio` and
362
+ * the layout measurement belong to the drawing area alone — measured on the
363
+ * outer view they would take in the header too, and the plot would lose as
364
+ * much height as the readout took while still claiming the shape asked for.
365
+ */
366
+ return /*#__PURE__*/_jsx(PyramidChartContext.Provider, {
367
+ value: context,
368
+ children: /*#__PURE__*/_jsxs(View, {
369
+ ...props,
370
+ style: props.style,
371
+ className: cn('w-full', className),
372
+ children: [header, /*#__PURE__*/_jsx(ChartAccessibilityData, {
373
+ chart: "Pyramid chart",
374
+ data: data,
375
+ disabled: accessible === false || loading,
376
+ accessibilityLabel: accessibilityLabel,
377
+ accessibilityHint: accessibilityHint,
378
+ accessibilityLabelForDatum: accessibilityLabelForDatum,
379
+ onAccessibilityDatumPress: onAccessibilityDatumPress,
380
+ valueOf: datum => [[xDataKey, datum[xDataKey]], ...series.map(entry => [entry.key, datum[entry.key]])]
381
+ }), /*#__PURE__*/_jsx(View, {
382
+ onLayout: onLayout,
383
+ style: {
384
+ aspectRatio
385
+ },
386
+ className: "w-full",
387
+ accessibilityElementsHidden: true,
388
+ importantForAccessibility: "no-hide-descendants",
389
+ children: plot.width > 0 ? /*#__PURE__*/_jsxs(_Fragment, {
390
+ children: [/*#__PURE__*/_jsx(Svg, {
391
+ width: "100%",
392
+ height: "100%",
393
+ style: StyleSheet.absoluteFill,
394
+ children: svg
395
+ }), overlay]
396
+ }) : null
397
+ })]
398
+ })
399
+ });
400
+ });
401
+ PyramidChartRoot.displayName = 'PyramidChart';
402
+
403
+ /**
404
+ * Where the centre line is, and how much room one wing has. Every part needs
405
+ * both and none of them should work it out twice.
406
+ */
407
+ function geometry(plot, gutter) {
408
+ 'worklet';
409
+
410
+ const centre = plot.left + plot.width / 2;
411
+ return {
412
+ centre,
413
+ /** The inner edge of the start wing — where a left-growing bar begins. */
414
+ innerStart: centre - gutter / 2,
415
+ /** The inner edge of the end wing. */
416
+ innerEnd: centre + gutter / 2,
417
+ wing: Math.max((plot.width - gutter) / 2, 0)
418
+ };
419
+ }
420
+
421
+ /* -------------------------------------------------------------------------- */
422
+ /* SVG layer */
423
+ /* -------------------------------------------------------------------------- */
424
+
425
+ /**
426
+ * Lines up the value axis, mirrored, so a bar can be read against a number
427
+ * rather than only against the bar facing it.
428
+ *
429
+ * The centre line is drawn solid and undashed where the others are dashed: it
430
+ * is not a tick, it is the zero both wings are measured from.
431
+ */
432
+ function PyramidChartGrid({
433
+ columns = 2,
434
+ color,
435
+ dashArray = '4,6',
436
+ opacity = 1,
437
+ centreLine = true
438
+ }) {
439
+ const {
440
+ plot,
441
+ gutter
442
+ } = useChart('PyramidChart.Grid');
443
+ const token = useCSSVariable('--color-border');
444
+ const stroke = color ?? (typeof token === 'string' ? token : 'rgba(0,0,0,0.1)');
445
+ const {
446
+ innerStart,
447
+ innerEnd,
448
+ wing,
449
+ centre
450
+ } = geometry(plot, gutter);
451
+ const ticks = Array.from({
452
+ length: columns
453
+ }, (_unused, index) => (index + 1) / columns);
454
+ return /*#__PURE__*/_jsxs(G, {
455
+ opacity: opacity,
456
+ children: [ticks.map(fraction => /*#__PURE__*/_jsxs(G, {
457
+ children: [/*#__PURE__*/_jsx(SvgLine, {
458
+ x1: innerStart - wing * fraction,
459
+ x2: innerStart - wing * fraction,
460
+ y1: plot.top,
461
+ y2: plot.top + plot.height,
462
+ stroke: stroke,
463
+ strokeDasharray: dashArray,
464
+ strokeWidth: 1
465
+ }), /*#__PURE__*/_jsx(SvgLine, {
466
+ x1: innerEnd + wing * fraction,
467
+ x2: innerEnd + wing * fraction,
468
+ y1: plot.top,
469
+ y2: plot.top + plot.height,
470
+ stroke: stroke,
471
+ strokeDasharray: dashArray,
472
+ strokeWidth: 1
473
+ })]
474
+ }, fraction)), centreLine ? /*#__PURE__*/_jsx(SvgLine, {
475
+ x1: centre,
476
+ x2: centre,
477
+ y1: plot.top,
478
+ y2: plot.top + plot.height,
479
+ stroke: stroke,
480
+ strokeWidth: 1
481
+ }) : null]
482
+ });
483
+ }
484
+ PyramidChartGrid.displayName = 'PyramidChart.Grid';
485
+ PyramidChartGrid.layer = 'svg';
486
+ /**
487
+ * One wing.
488
+ *
489
+ * Drawn as two paths rather than one rectangle per row: the row under the
490
+ * finger, and everything else. That is the fewest animated props that can still
491
+ * dim the rest — one path could not, since a path has one opacity, and a view
492
+ * per bar would be one animated prop per bar for the same picture.
493
+ */
494
+ function PyramidChartBar({
495
+ dataKey,
496
+ side = 'end',
497
+ color,
498
+ colorIndex,
499
+ cornerRadius
500
+ }) {
501
+ const {
502
+ data,
503
+ plot,
504
+ status,
505
+ gutter,
506
+ labelInset,
507
+ barGap,
508
+ barWidth,
509
+ cornerRadius: chartRadius,
510
+ minBarLength,
511
+ fadedOpacity,
512
+ registerSeries,
513
+ unregisterSeries,
514
+ domainMax,
515
+ reveal,
516
+ activeIndex
517
+ } = useChart('PyramidChart.Bar');
518
+ const index = colorIndex ?? (side === 'start' ? 2 : 1);
519
+ const fill = useSeriesColor(color, index);
520
+ const radius = cornerRadius ?? chartRadius;
521
+ useEffect(() => {
522
+ registerSeries({
523
+ key: dataKey,
524
+ color: fill,
525
+ side
526
+ });
527
+ return () => unregisterSeries(dataKey);
528
+ }, [dataKey, fill, side, registerSeries, unregisterSeries]);
529
+ const values = useMemo(() => columnValues(data, dataKey), [data, dataKey]);
530
+ const loading = status === 'loading';
531
+ const total = data.length;
532
+ const towards = side === 'start' ? 'left' : 'right';
533
+
534
+ /*
535
+ * Both paths come out of one builder, filtered by whether the row is the
536
+ * active one. Two passes over the data a frame is still cheaper than the
537
+ * bookkeeping needed to build both at once, and it keeps the geometry in
538
+ * exactly one place.
539
+ */
540
+ const build = wantActive => () => {
541
+ 'worklet';
542
+
543
+ if (!total || plot.width <= 0) {
544
+ return {
545
+ d: '',
546
+ opacity: 1
547
+ };
548
+ }
549
+ const {
550
+ innerStart,
551
+ innerEnd,
552
+ wing
553
+ } = geometry(plot, gutter);
554
+ const band = plot.height / total;
555
+ // What is left of a band once the name over it has taken its line.
556
+ const usable = Math.max(band - labelInset, 0);
557
+ const thickness = Math.min(barWidth ?? usable * (1 - barGap), usable * (1 - barGap));
558
+ const max = domainMax.value || 1;
559
+ const grow = reveal.value;
560
+ const active = activeIndex.value;
561
+ let d = '';
562
+ for (let i = 0; i < total; i++) {
563
+ if (i === active !== wantActive) continue;
564
+ const value = values[i];
565
+ if (value === null || value === undefined) continue;
566
+
567
+ /*
568
+ * Staggered by row, but every bar still finishes inside the one duration:
569
+ * the window each gets is what is left after the stagger, so a chart of
570
+ * twenty rows does not take twenty times as long to arrive.
571
+ */
572
+ const start = total > 1 ? i / total * 0.45 : 0;
573
+ const eased = Math.max(0, Math.min(1, (grow - start) / 0.55));
574
+ // A length, so a negative number has no direction left to grow in. It is
575
+ // still in the readout; it just cannot be drawn.
576
+ const shown = loading ? 0 : Math.max(value, 0) * eased;
577
+ let length = shown / max * wing;
578
+ if (minBarLength > 0 && shown > 0 && length < minBarLength) length = minBarLength;
579
+ if (length <= 0) continue;
580
+ const lead = plot.top + i * band + labelInset + (usable - thickness) / 2;
581
+ d += side === 'start' ? barPath(innerStart - length, lead, length, thickness, radius, towards) : barPath(innerEnd, lead, length, thickness, radius, towards);
582
+ }
583
+
584
+ // Dimming only happens while something *is* active; with nothing under the
585
+ // finger every bar is at full ink, which is the resting state.
586
+ const dim = !wantActive && active >= 0 ? fadedOpacity : 1;
587
+ return {
588
+ d,
589
+ opacity: dim
590
+ };
591
+ };
592
+ const restProps = useAnimatedProps(build(false));
593
+ const activeProps = useAnimatedProps(build(true));
594
+ return /*#__PURE__*/_jsxs(G, {
595
+ children: [/*#__PURE__*/_jsx(AnimatedPath, {
596
+ animatedProps: restProps,
597
+ fill: fill
598
+ }), /*#__PURE__*/_jsx(AnimatedPath, {
599
+ animatedProps: activeProps,
600
+ fill: fill
601
+ })]
602
+ });
603
+ }
604
+ PyramidChartBar.displayName = 'PyramidChart.Bar';
605
+ PyramidChartBar.layer = 'svg';
606
+
607
+ /** How much of one wing a placeholder bar takes. */
608
+ const SKELETON_LENGTH = 0.35;
609
+
610
+ /** Rows to draw when there is no data yet to count them from. */
611
+ const SKELETON_ROWS = 5;
612
+ /**
613
+ * The loading state: equal stubs either side of the centre, with a highlight
614
+ * travelling across them.
615
+ *
616
+ * Equal on purpose. Placeholder wings of differing lengths are a distribution
617
+ * the reader has no way to tell from the real one until it changes under them,
618
+ * so these say only how many rows there will be and where the centre is.
619
+ */
620
+ function PyramidChartSkeleton({
621
+ rows,
622
+ duration = 1400,
623
+ color
624
+ }) {
625
+ const {
626
+ plot,
627
+ status,
628
+ gutter,
629
+ labelInset,
630
+ data,
631
+ barGap,
632
+ barWidth,
633
+ cornerRadius
634
+ } = useChart('PyramidChart.Skeleton');
635
+ const token = useCSSVariable('--color-skeleton');
636
+ const base = color ?? (typeof token === 'string' ? token : 'rgba(128,128,128,0.2)');
637
+ const highlight = useSeriesColor(undefined, 1);
638
+ const sweep = useSharedValue(0);
639
+ const reducedMotion = useReducedMotion();
640
+ const loading = status === 'loading';
641
+ useEffect(() => {
642
+ if (!loading || reducedMotion) {
643
+ cancelAnimation(sweep);
644
+ sweep.value = 0;
645
+ return;
646
+ }
647
+ sweep.value = 0;
648
+ sweep.value = withRepeat(withTiming(1, {
649
+ duration,
650
+ easing: Easing.linear
651
+ }), -1, false);
652
+ return () => cancelAnimation(sweep);
653
+ }, [loading, reducedMotion, duration, sweep]);
654
+
655
+ // The band travels by moving the gradient's own endpoints, so the whole
656
+ // effect is two numbers changing on the UI thread.
657
+ const animatedProps = useAnimatedProps(() => ({
658
+ x1: `${(sweep.value * 1.4 - 0.4) * 100}%`,
659
+ x2: `${(sweep.value * 1.4 - 0.4 + 0.4) * 100}%`
660
+ }));
661
+ const total = Math.max(1, rows ?? (data.length || SKELETON_ROWS));
662
+ const d = useMemo(() => {
663
+ if (plot.width <= 0 || plot.height <= 0) return '';
664
+ const {
665
+ innerStart,
666
+ innerEnd,
667
+ wing
668
+ } = geometry(plot, gutter);
669
+ const band = plot.height / total;
670
+ const usable = Math.max(band - labelInset, 0);
671
+ const thickness = Math.min(barWidth ?? usable * (1 - barGap), usable * (1 - barGap));
672
+ const length = wing * SKELETON_LENGTH;
673
+ let path = '';
674
+ for (let i = 0; i < total; i += 1) {
675
+ const lead = plot.top + i * band + labelInset + (usable - thickness) / 2;
676
+ path += barPath(innerStart - length, lead, length, thickness, cornerRadius, 'left');
677
+ path += barPath(innerEnd, lead, length, thickness, cornerRadius, 'right');
678
+ }
679
+ return path;
680
+ }, [plot, gutter, labelInset, total, barGap, barWidth, cornerRadius]);
681
+ if (!loading || !d) return null;
682
+ const gradientId = 'panelui-pyramid-skeleton';
683
+ return /*#__PURE__*/_jsxs(G, {
684
+ children: [/*#__PURE__*/_jsx(Defs, {
685
+ children: /*#__PURE__*/_jsxs(AnimatedLinearGradient, {
686
+ id: gradientId,
687
+ animatedProps: animatedProps,
688
+ y1: "0",
689
+ y2: "0",
690
+ children: [/*#__PURE__*/_jsx(Stop, {
691
+ offset: "0",
692
+ stopColor: base
693
+ }), /*#__PURE__*/_jsx(Stop, {
694
+ offset: "0.5",
695
+ stopColor: highlight,
696
+ stopOpacity: 0.55
697
+ }), /*#__PURE__*/_jsx(Stop, {
698
+ offset: "1",
699
+ stopColor: base
700
+ })]
701
+ })
702
+ }), /*#__PURE__*/_jsx(Path, {
703
+ d: d,
704
+ fill: `url(#${gradientId})`
705
+ })]
706
+ });
707
+ }
708
+ PyramidChartSkeleton.displayName = 'PyramidChart.Skeleton';
709
+ PyramidChartSkeleton.layer = 'svg';
710
+
711
+ /* -------------------------------------------------------------------------- */
712
+ /* Overlay layer */
713
+ /* -------------------------------------------------------------------------- */
714
+
715
+ /**
716
+ * The value labels along the bottom, mirrored either side of a zero in the
717
+ * middle — the same magnitudes twice, because both wings are read outward from
718
+ * the centre rather than along one continuous axis.
719
+ *
720
+ * Real text rather than SVG text, so the labels follow the theme's font and the
721
+ * platform's text scaling. SVG text does neither.
722
+ */
723
+ function PyramidChartXAxis({
724
+ ticks = 2,
725
+ format,
726
+ className
727
+ }) {
728
+ const {
729
+ plot,
730
+ gutter,
731
+ extentMax
732
+ } = useChart('PyramidChart.XAxis');
733
+ const {
734
+ innerStart,
735
+ innerEnd,
736
+ wing,
737
+ centre
738
+ } = geometry(plot, gutter);
739
+ const fmt = format ?? compactNumber;
740
+ const labels = useMemo(() => {
741
+ const out = [{
742
+ key: 'centre',
743
+ text: fmt(0),
744
+ x: centre
745
+ }];
746
+ for (let index = 1; index <= ticks; index += 1) {
747
+ const fraction = index / ticks;
748
+ const text = fmt(extentMax * fraction);
749
+ out.push({
750
+ key: `start-${index}`,
751
+ text,
752
+ x: innerStart - wing * fraction
753
+ });
754
+ out.push({
755
+ key: `end-${index}`,
756
+ text,
757
+ x: innerEnd + wing * fraction
758
+ });
759
+ }
760
+ return out;
761
+ }, [ticks, fmt, extentMax, innerStart, innerEnd, wing, centre]);
762
+ if (wing <= 0) return null;
763
+ return /*#__PURE__*/_jsx(View, {
764
+ style: {
765
+ position: 'absolute',
766
+ inset: 0,
767
+ pointerEvents: 'none'
768
+ },
769
+ className: cn(className),
770
+ children: labels.map(label => /*#__PURE__*/_jsx(Text, {
771
+ size: "xs",
772
+ muted: true,
773
+ numberOfLines: 1,
774
+ style: {
775
+ position: 'absolute',
776
+ bottom: 0,
777
+ // Centred on its tick, then held inside the chart. The outermost
778
+ // tick of each wing is on the plot's own edge, so a box centred
779
+ // there would hang half its width off the side and lose the number.
780
+ left: Math.max(0, Math.min(label.x - AXIS_LABEL_WIDTH / 2, plot.left + plot.width + PADDING.right - AXIS_LABEL_WIDTH)),
781
+ width: AXIS_LABEL_WIDTH,
782
+ textAlign: 'center'
783
+ },
784
+ children: label.text
785
+ }, label.key))
786
+ });
787
+ }
788
+ PyramidChartXAxis.displayName = 'PyramidChart.XAxis';
789
+ PyramidChartXAxis.layer = 'overlay';
790
+ /**
791
+ * The category names, one per row.
792
+ *
793
+ * `above` puts each name on its own line over the pair of bars it belongs to,
794
+ * which leaves the two wings meeting in the middle — the name is read first and
795
+ * the bars are then read outward from a centre nothing is standing in.
796
+ *
797
+ * One box per band rather than a spaced column, in every placement: a row owns
798
+ * a *band*, so names spread evenly would be half a band out at the top and
799
+ * bottom.
800
+ */
801
+ function PyramidChartYAxis({
802
+ format,
803
+ className
804
+ }) {
805
+ const {
806
+ data,
807
+ xDataKey,
808
+ plot,
809
+ gutter,
810
+ labelInset,
811
+ labelPlacement
812
+ } = useChart('PyramidChart.YAxis');
813
+ const {
814
+ centre
815
+ } = geometry(plot, gutter);
816
+ if (!data.length) return null;
817
+ const label = (datum, index) => format ? format(datum, index) : String(datum[xDataKey] ?? '');
818
+ if (labelPlacement === 'above') {
819
+ const band = plot.height / data.length;
820
+ return /*#__PURE__*/_jsx(View, {
821
+ pointerEvents: "none",
822
+ style: {
823
+ position: 'absolute',
824
+ inset: 0
825
+ },
826
+ className: cn(className),
827
+ children: data.map((datum, index) => /*#__PURE__*/_jsx(View, {
828
+ style: {
829
+ position: 'absolute',
830
+ left: plot.left,
831
+ width: plot.width,
832
+ top: plot.top + index * band,
833
+ height: labelInset
834
+ },
835
+ className: "justify-center",
836
+ children: /*#__PURE__*/_jsx(Text, {
837
+ size: "xs",
838
+ muted: true,
839
+ numberOfLines: 1,
840
+ style: {
841
+ textAlign: 'center'
842
+ },
843
+ children: label(datum, index)
844
+ })
845
+ }, index))
846
+ });
847
+ }
848
+ const centred = labelPlacement === 'center';
849
+ return /*#__PURE__*/_jsx(View, {
850
+ pointerEvents: "none",
851
+ style: {
852
+ position: 'absolute',
853
+ left: centred ? centre - CENTRE_GUTTER / 2 : 0,
854
+ top: plot.top,
855
+ height: plot.height,
856
+ width: centred ? CENTRE_GUTTER : Math.max(plot.left - 8, 0)
857
+ },
858
+ className: cn(centred ? 'items-center' : 'items-end', className),
859
+ children: data.map((datum, index) => /*#__PURE__*/_jsx(View, {
860
+ className: "flex-1 justify-center",
861
+ children: /*#__PURE__*/_jsx(Text, {
862
+ size: "xs",
863
+ muted: true,
864
+ numberOfLines: 1,
865
+ children: label(datum, index)
866
+ })
867
+ }, index))
868
+ });
869
+ }
870
+ PyramidChartYAxis.displayName = 'PyramidChart.YAxis';
871
+ PyramidChartYAxis.layer = 'overlay';
872
+ // Read by the root, which has to leave room for the names before it lays the
873
+ // plot out — a name drawn over a bar is unreadable, and makes the bar it is
874
+ // drawn over unreadable too.
875
+ PyramidChartYAxis.axis = 'y';
876
+ /**
877
+ * The readout, and the gesture that drives it.
878
+ *
879
+ * There is no crosshair. A bar is already the thing being pointed at, so
880
+ * highlighting its row and dimming the rest says the same thing without drawing
881
+ * a line through the chart.
882
+ *
883
+ * The hit area is the whole plot. A readout you have to land on the bar to
884
+ * summon is a readout nobody finds.
885
+ */
886
+ function PyramidChartTooltip({
887
+ formatValue,
888
+ formatX,
889
+ className
890
+ }) {
891
+ const {
892
+ data,
893
+ xDataKey,
894
+ plot,
895
+ series,
896
+ activeIndex,
897
+ activeIndexJS,
898
+ setActiveIndexJS,
899
+ status
900
+ } = useChart('PyramidChart.Tooltip');
901
+ const total = data.length;
902
+ const top = plot.top;
903
+ const height = plot.height;
904
+
905
+ /*
906
+ * The readout's own height, measured rather than assumed. It has to be
907
+ * clamped inside the plot, and how tall it is depends on how many series are
908
+ * listed in it — a constant would either let a three-series readout hang off
909
+ * the bottom or reserve room a one-series readout never uses.
910
+ */
911
+ const labelHeight = useSharedValue(0);
912
+
913
+ /*
914
+ * Declared inside the memo, next to its callers: a worklet may only call
915
+ * another worklet, and the rule is enforced by crashing rather than warning.
916
+ */
917
+ const pan = useMemo(() => {
918
+ const resolve = y => {
919
+ 'worklet';
920
+
921
+ if (!total) return;
922
+ const offset = (y - top) / (height || 1);
923
+ // Bands, not points: the finger is inside whichever row it lands on,
924
+ // which is a floor rather than a round to the nearest centre.
925
+ const next = Math.max(0, Math.min(total - 1, Math.floor(offset * total)));
926
+ if (next === activeIndex.value) return;
927
+ activeIndex.value = next;
928
+ runOnJS(setActiveIndexJS)(next);
929
+ };
930
+ return Gesture.Pan().minDistance(0).onBegin(event => {
931
+ 'worklet';
932
+
933
+ resolve(event.y);
934
+ }).onUpdate(event => {
935
+ 'worklet';
936
+
937
+ resolve(event.y);
938
+ }).onFinalize(() => {
939
+ 'worklet';
940
+
941
+ activeIndex.value = -1;
942
+ runOnJS(setActiveIndexJS)(-1);
943
+ });
944
+ }, [total, top, height, activeIndex, setActiveIndexJS]);
945
+
946
+ /*
947
+ * The readout slides down to the row it is describing and sits centred over
948
+ * the plot. Held at the top instead it would name the row under the finger
949
+ * while covering the first one, which is the row a reader checks it against.
950
+ */
951
+ const labelStyle = useAnimatedStyle(() => {
952
+ const index = activeIndex.value;
953
+ if (index < 0 || !total) return {
954
+ opacity: 0
955
+ };
956
+ const band = plot.height / total;
957
+ const centre = plot.top + band * (index + 0.5);
958
+ const x = plot.left + plot.width / 2 - LABEL_WIDTH / 2;
959
+
960
+ // Until the first measurement lands the height is zero, which clamps to the
961
+ // top of the plot — the same place it used to sit, rather than a jump from
962
+ // somewhere it never was.
963
+ const tall = labelHeight.value;
964
+ const y = Math.min(plot.top + Math.max(plot.height - tall, 0), Math.max(plot.top, centre - tall / 2));
965
+ return {
966
+ opacity: 1,
967
+ transform: [{
968
+ translateX: x
969
+ }, {
970
+ translateY: y
971
+ }]
972
+ };
973
+ });
974
+ const active = activeIndexJS >= 0 ? data[activeIndexJS] : null;
975
+ const fmtValue = formatValue ?? (value => compactNumber(value));
976
+ const fmtX = formatX ?? (datum => String(datum[xDataKey] ?? ''));
977
+ if (status === 'loading') return null;
978
+ return /*#__PURE__*/_jsx(GestureDetector, {
979
+ gesture: pan,
980
+ children: /*#__PURE__*/_jsx(View, {
981
+ style: StyleSheet.absoluteFill,
982
+ children: /*#__PURE__*/_jsx(Animated.View, {
983
+ pointerEvents: "none",
984
+ style: [{
985
+ position: 'absolute',
986
+ left: 0,
987
+ top: 0,
988
+ width: LABEL_WIDTH
989
+ }, labelStyle],
990
+ children: active ? /*#__PURE__*/_jsxs(View, {
991
+ onLayout: event => {
992
+ labelHeight.value = event.nativeEvent.layout.height;
993
+ },
994
+ className: cn('rounded-xl border border-border bg-popover px-2.5 py-1.5 shadow-lg', className),
995
+ children: [/*#__PURE__*/_jsx(Text, {
996
+ size: "xs",
997
+ muted: true,
998
+ numberOfLines: 1,
999
+ children: fmtX(active)
1000
+ }), series.map(entry => {
1001
+ const value = active[entry.key];
1002
+ if (typeof value !== 'number') return null;
1003
+ return /*#__PURE__*/_jsxs(View, {
1004
+ className: "flex-row items-center gap-1.5",
1005
+ children: [/*#__PURE__*/_jsx(View, {
1006
+ style: {
1007
+ width: 6,
1008
+ height: 6,
1009
+ borderRadius: 3,
1010
+ backgroundColor: entry.color
1011
+ }
1012
+ }), /*#__PURE__*/_jsx(Text, {
1013
+ size: "xs",
1014
+ weight: "medium",
1015
+ children: fmtValue(value, entry.key)
1016
+ })]
1017
+ }, entry.key);
1018
+ })]
1019
+ }) : null
1020
+ })
1021
+ })
1022
+ });
1023
+ }
1024
+ PyramidChartTooltip.displayName = 'PyramidChart.Tooltip';
1025
+ PyramidChartTooltip.layer = 'overlay';
1026
+ /** One series' colour and name. Shared by the legend and the header. */
1027
+ function SeriesSwatch({
1028
+ color,
1029
+ label
1030
+ }) {
1031
+ return /*#__PURE__*/_jsxs(View, {
1032
+ className: "flex-row items-center gap-1.5",
1033
+ children: [/*#__PURE__*/_jsx(View, {
1034
+ style: {
1035
+ backgroundColor: color
1036
+ },
1037
+ className: "h-2 w-2 rounded-full"
1038
+ }), /*#__PURE__*/_jsx(Text, {
1039
+ size: "xs",
1040
+ muted: true,
1041
+ children: label
1042
+ })]
1043
+ });
1044
+ }
1045
+
1046
+ /** A swatch and a name per series, in the order the series were declared. */
1047
+ function PyramidChartLegend({
1048
+ className,
1049
+ labels,
1050
+ ...props
1051
+ }) {
1052
+ const {
1053
+ series
1054
+ } = useChart('PyramidChart.Legend');
1055
+ if (!series.length) return null;
1056
+ return /*#__PURE__*/_jsx(View, {
1057
+ ...props,
1058
+ style: [{
1059
+ pointerEvents: 'none'
1060
+ }, props.style],
1061
+ className: cn('absolute right-2 top-1 flex-row gap-3', className),
1062
+ children: series.map(entry => /*#__PURE__*/_jsx(SeriesSwatch, {
1063
+ color: entry.color,
1064
+ label: labels?.[entry.key] ?? entry.key
1065
+ }, entry.key))
1066
+ });
1067
+ }
1068
+ PyramidChartLegend.displayName = 'PyramidChart.Legend';
1069
+ PyramidChartLegend.layer = 'overlay';
1070
+
1071
+ /* -------------------------------------------------------------------------- */
1072
+ /* Header layer */
1073
+ /* -------------------------------------------------------------------------- */
1074
+
1075
+ /**
1076
+ * The strip above the plot: what the chart is of, what it currently reads, and
1077
+ * what the two colours mean.
1078
+ *
1079
+ * It belongs to the chart rather than to the card around it because it is about
1080
+ * the *plot* — the number changes as a finger moves down the rows, and the
1081
+ * legend is the series list the chart itself is holding.
1082
+ *
1083
+ * The value is not derived here. A readout that follows the finger belongs to
1084
+ * whoever owns the data — take it from `onActiveIndexChange` and pass the
1085
+ * formatted string down.
1086
+ */
1087
+ function PyramidChartHeader({
1088
+ className,
1089
+ title,
1090
+ value,
1091
+ caption,
1092
+ labels,
1093
+ legend = false,
1094
+ children,
1095
+ ...props
1096
+ }) {
1097
+ const {
1098
+ series
1099
+ } = useChart('PyramidChart.Header');
1100
+ const trailing = children ?? (legend && series.length ? /*#__PURE__*/_jsx(View, {
1101
+ className: "flex-row flex-wrap items-center justify-end gap-x-3 gap-y-1",
1102
+ children: series.map(entry => /*#__PURE__*/_jsx(SeriesSwatch, {
1103
+ color: entry.color,
1104
+ label: labels?.[entry.key] ?? entry.key
1105
+ }, entry.key))
1106
+ }) : null);
1107
+ return /*#__PURE__*/_jsxs(View, {
1108
+ ...props,
1109
+ className: cn('flex-row items-start justify-between gap-3 pb-3', className),
1110
+ children: [/*#__PURE__*/_jsxs(View, {
1111
+ className: "flex-1 gap-0.5",
1112
+ children: [title ? /*#__PURE__*/_jsx(Text, {
1113
+ size: "xs",
1114
+ muted: true,
1115
+ children: title
1116
+ }) : null, value ? /*#__PURE__*/_jsx(Text, {
1117
+ size: "xl",
1118
+ weight: "bold",
1119
+ children: value
1120
+ }) : null, caption ? /*#__PURE__*/_jsx(Text, {
1121
+ size: "xs",
1122
+ muted: true,
1123
+ children: caption
1124
+ }) : null]
1125
+ }), trailing ? /*#__PURE__*/_jsx(View, {
1126
+ className: "shrink pt-1",
1127
+ children: trailing
1128
+ }) : null]
1129
+ });
1130
+ }
1131
+ PyramidChartHeader.displayName = 'PyramidChart.Header';
1132
+ PyramidChartHeader.layer = 'header';
1133
+ export const PyramidChart = Object.assign(PyramidChartRoot, {
1134
+ Header: PyramidChartHeader,
1135
+ Grid: PyramidChartGrid,
1136
+ Bar: PyramidChartBar,
1137
+ Skeleton: PyramidChartSkeleton,
1138
+ XAxis: PyramidChartXAxis,
1139
+ YAxis: PyramidChartYAxis,
1140
+ Tooltip: PyramidChartTooltip,
1141
+ Legend: PyramidChartLegend
1142
+ });
1143
+ //# sourceMappingURL=index.js.map