react-native-livechart 4.25.0 → 4.27.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.
Files changed (125) hide show
  1. package/dist/components/CustomReferenceLineOverlay.d.ts +8 -1
  2. package/dist/components/CustomReferenceLineOverlay.d.ts.map +1 -1
  3. package/dist/components/CustomTooltipOverlay.d.ts +3 -2
  4. package/dist/components/CustomTooltipOverlay.d.ts.map +1 -1
  5. package/dist/components/LiveChart.d.ts +1 -1
  6. package/dist/components/LiveChart.d.ts.map +1 -1
  7. package/dist/components/LiveChartSeries.d.ts.map +1 -1
  8. package/dist/components/ReferenceLineOverlay.d.ts +4 -0
  9. package/dist/components/ReferenceLineOverlay.d.ts.map +1 -1
  10. package/dist/components/ReferenceValueBadge.d.ts +15 -0
  11. package/dist/components/ReferenceValueBadge.d.ts.map +1 -0
  12. package/dist/components/XAxisOverlay.d.ts +17 -0
  13. package/dist/components/XAxisOverlay.d.ts.map +1 -1
  14. package/dist/core/liveChartEngineTick.d.ts +6 -1
  15. package/dist/core/liveChartEngineTick.d.ts.map +1 -1
  16. package/dist/core/liveChartSeriesEngineTick.d.ts +4 -1
  17. package/dist/core/liveChartSeriesEngineTick.d.ts.map +1 -1
  18. package/dist/core/resolveConfig.d.ts +28 -1
  19. package/dist/core/resolveConfig.d.ts.map +1 -1
  20. package/dist/core/useLiveChartEngine.d.ts +10 -1
  21. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  22. package/dist/core/useLiveChartSeriesEngine.d.ts +5 -1
  23. package/dist/core/useLiveChartSeriesEngine.d.ts.map +1 -1
  24. package/dist/draw/grid.d.ts +2 -2
  25. package/dist/draw/line.d.ts +15 -1
  26. package/dist/draw/line.d.ts.map +1 -1
  27. package/dist/hooks/crosshairShared.d.ts +24 -1
  28. package/dist/hooks/crosshairShared.d.ts.map +1 -1
  29. package/dist/hooks/referenceBadgeFont.d.ts +5 -0
  30. package/dist/hooks/referenceBadgeFont.d.ts.map +1 -0
  31. package/dist/hooks/resolveChartLayout.d.ts +8 -0
  32. package/dist/hooks/resolveChartLayout.d.ts.map +1 -1
  33. package/dist/hooks/useBadge.d.ts +16 -1
  34. package/dist/hooks/useBadge.d.ts.map +1 -1
  35. package/dist/hooks/useChartSkiaFont.d.ts +1 -0
  36. package/dist/hooks/useChartSkiaFont.d.ts.map +1 -1
  37. package/dist/hooks/useCrosshair.d.ts +7 -2
  38. package/dist/hooks/useCrosshair.d.ts.map +1 -1
  39. package/dist/hooks/useCrosshairSeries.d.ts +4 -1
  40. package/dist/hooks/useCrosshairSeries.d.ts.map +1 -1
  41. package/dist/hooks/useLatestCallback.d.ts +6 -0
  42. package/dist/hooks/useLatestCallback.d.ts.map +1 -0
  43. package/dist/hooks/useMarkers.d.ts.map +1 -1
  44. package/dist/hooks/usePanScroll.d.ts +3 -1
  45. package/dist/hooks/usePanScroll.d.ts.map +1 -1
  46. package/dist/hooks/usePinchZoom.d.ts.map +1 -1
  47. package/dist/hooks/useReferenceDrag.d.ts +23 -7
  48. package/dist/hooks/useReferenceDrag.d.ts.map +1 -1
  49. package/dist/hooks/useReferenceLine.d.ts +24 -12
  50. package/dist/hooks/useReferenceLine.d.ts.map +1 -1
  51. package/dist/hooks/useReferenceLineGrouping.d.ts +19 -0
  52. package/dist/hooks/useReferenceLineGrouping.d.ts.map +1 -0
  53. package/dist/hooks/useReferenceLinePress.d.ts +4 -2
  54. package/dist/hooks/useReferenceLinePress.d.ts.map +1 -1
  55. package/dist/hooks/useReferenceTagStack.d.ts +31 -0
  56. package/dist/hooks/useReferenceTagStack.d.ts.map +1 -0
  57. package/dist/hooks/useScrubMarkers.d.ts +12 -0
  58. package/dist/hooks/useScrubMarkers.d.ts.map +1 -0
  59. package/dist/hooks/useXAxis.d.ts +1 -1
  60. package/dist/hooks/useXAxis.d.ts.map +1 -1
  61. package/dist/hooks/useYAxisScaleGesture.d.ts +34 -0
  62. package/dist/hooks/useYAxisScaleGesture.d.ts.map +1 -0
  63. package/dist/index.d.ts +1 -1
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/math/axisBadgeLayout.d.ts +16 -0
  66. package/dist/math/axisBadgeLayout.d.ts.map +1 -0
  67. package/dist/math/markers.d.ts +3 -0
  68. package/dist/math/markers.d.ts.map +1 -1
  69. package/dist/math/range.d.ts +1 -1
  70. package/dist/math/range.d.ts.map +1 -1
  71. package/dist/math/rangeAnimation.d.ts +4 -0
  72. package/dist/math/rangeAnimation.d.ts.map +1 -0
  73. package/dist/math/referenceDrag.d.ts +17 -5
  74. package/dist/math/referenceDrag.d.ts.map +1 -1
  75. package/dist/math/referenceGroup.d.ts +2 -2
  76. package/dist/math/referenceTagStack.d.ts +36 -0
  77. package/dist/math/referenceTagStack.d.ts.map +1 -0
  78. package/dist/math/scrubMarkers.d.ts +12 -0
  79. package/dist/math/scrubMarkers.d.ts.map +1 -0
  80. package/dist/types.d.ts +240 -30
  81. package/dist/types.d.ts.map +1 -1
  82. package/package.json +1 -1
  83. package/src/components/CustomReferenceLineOverlay.tsx +50 -8
  84. package/src/components/CustomTooltipOverlay.tsx +5 -1
  85. package/src/components/LiveChart.tsx +563 -200
  86. package/src/components/LiveChartSeries.tsx +117 -13
  87. package/src/components/ReferenceLineOverlay.tsx +62 -26
  88. package/src/components/ReferenceValueBadge.tsx +102 -0
  89. package/src/components/XAxisOverlay.tsx +104 -1
  90. package/src/core/liveChartEngineTick.ts +66 -10
  91. package/src/core/liveChartSeriesEngineTick.ts +55 -5
  92. package/src/core/resolveConfig.ts +95 -2
  93. package/src/core/useLiveChartEngine.ts +53 -11
  94. package/src/core/useLiveChartSeriesEngine.ts +11 -1
  95. package/src/draw/grid.ts +2 -2
  96. package/src/draw/line.ts +23 -1
  97. package/src/hooks/crosshairShared.ts +85 -1
  98. package/src/hooks/referenceBadgeFont.ts +35 -0
  99. package/src/hooks/resolveChartLayout.ts +17 -0
  100. package/src/hooks/useBadge.ts +44 -5
  101. package/src/hooks/useChartSkiaFont.ts +1 -1
  102. package/src/hooks/useCrosshair.ts +446 -300
  103. package/src/hooks/useCrosshairSeries.ts +29 -10
  104. package/src/hooks/useLatestCallback.ts +15 -0
  105. package/src/hooks/useMarkers.ts +51 -39
  106. package/src/hooks/usePanScroll.ts +155 -127
  107. package/src/hooks/usePinchZoom.ts +84 -63
  108. package/src/hooks/useReferenceDrag.ts +395 -146
  109. package/src/hooks/useReferenceLine.ts +453 -277
  110. package/src/hooks/useReferenceLineGrouping.ts +72 -0
  111. package/src/hooks/useReferenceLinePress.ts +121 -53
  112. package/src/hooks/useReferenceTagStack.ts +81 -0
  113. package/src/hooks/useScrubMarkers.ts +79 -0
  114. package/src/hooks/useXAxis.ts +11 -2
  115. package/src/hooks/useYAxisScaleGesture.ts +263 -0
  116. package/src/index.ts +11 -0
  117. package/src/math/axisBadgeLayout.ts +37 -0
  118. package/src/math/markers.ts +28 -3
  119. package/src/math/range.ts +35 -0
  120. package/src/math/rangeAnimation.ts +28 -0
  121. package/src/math/referenceDrag.ts +21 -4
  122. package/src/math/referenceGroup.ts +2 -2
  123. package/src/math/referenceTagStack.ts +112 -0
  124. package/src/math/scrubMarkers.ts +55 -0
  125. package/src/types.ts +246 -30
@@ -0,0 +1,263 @@
1
+ import type { SkFont } from "@shopify/react-native-skia";
2
+ import { useMemo } from "react";
3
+ import {
4
+ Gesture,
5
+ type ComposedGesture,
6
+ type GestureType,
7
+ } from "react-native-gesture-handler";
8
+ import {
9
+ cancelAnimation,
10
+ useSharedValue,
11
+ withTiming,
12
+ type SharedValue,
13
+ } from "react-native-reanimated";
14
+ import type { ResolvedYAxisConfig } from "../core/resolveConfig";
15
+ import type { ChartEngineLayout } from "../core/useLiveChartEngine";
16
+ import { rightAnchoredYAxisColumnLayout, type YAxisEntry } from "../draw/grid";
17
+ import type { ChartPadding } from "../draw/line";
18
+
19
+ /** Preserve private scale state across gesture/axis toggles on a mounted chart. */
20
+ export function useYAxisScaleValue(external?: SharedValue<number>) {
21
+ const internal = useSharedValue(1);
22
+ return external ?? internal;
23
+ }
24
+
25
+ /** The reserved gutter, or the actual measured price column when it floats. */
26
+ export function isYAxisScaleHit(
27
+ x: number,
28
+ y: number,
29
+ width: number,
30
+ height: number,
31
+ padding: ChartPadding,
32
+ side: "left" | "right",
33
+ floating: boolean,
34
+ labelRightMargin: number | undefined,
35
+ entries: readonly YAxisEntry[],
36
+ font: SkFont,
37
+ ): boolean {
38
+ "worklet";
39
+ if (
40
+ width <= 0 ||
41
+ height <= 0 ||
42
+ x < 0 ||
43
+ x > width ||
44
+ y < padding.top ||
45
+ y >= height - padding.bottom
46
+ )
47
+ return false;
48
+ if (side === "left") return x < padding.left;
49
+ let left = width - padding.right;
50
+ if (floating || labelRightMargin !== undefined) {
51
+ // Matches YAxisOverlay: floating labels sit 6px off the canvas edge.
52
+ const column = rightAnchoredYAxisColumnLayout(
53
+ width,
54
+ entries,
55
+ font,
56
+ labelRightMargin ?? 6,
57
+ );
58
+ left = Math.min(left, column.labelX);
59
+ }
60
+ return x >= Math.max(padding.left, left);
61
+ }
62
+
63
+ /** Log-space clamping avoids overflow even for very large drag translations. */
64
+ export function draggedYAxisScale(
65
+ start: number,
66
+ dy: number,
67
+ distance: number,
68
+ min: number,
69
+ max: number,
70
+ ): number {
71
+ "worklet";
72
+ const validStart = Number.isFinite(start) && start > 0 ? start : 1;
73
+ const logScale =
74
+ Math.log(Math.max(min, Math.min(max, validStart))) + dy / distance;
75
+ return Math.max(
76
+ min,
77
+ Math.min(
78
+ max,
79
+ Math.exp(Math.max(Math.log(min), Math.min(Math.log(max), logScale))),
80
+ ),
81
+ );
82
+ }
83
+
84
+ type Options = {
85
+ engine: Pick<ChartEngineLayout, "canvasWidth" | "canvasHeight"> & {
86
+ wake?: () => void;
87
+ };
88
+ padding: ChartPadding;
89
+ axis: ResolvedYAxisConfig | null;
90
+ floating?: boolean;
91
+ entries: SharedValue<YAxisEntry[]> | null;
92
+ font: SkFont;
93
+ scale: SharedValue<number>;
94
+ /** Existing plot gesture graph, including pinch. */
95
+ gesture: GestureType | ComposedGesture;
96
+ /** Interactive chart overlays retain their normal tap/drag behavior. */
97
+ deferHit?: (x: number, y: number) => boolean;
98
+ onStart?: () => void;
99
+ active?: SharedValue<boolean>;
100
+ };
101
+
102
+ /** Owns gutter touches at touch-down; fails immediately everywhere else. */
103
+ export function useYAxisScaleGesture({
104
+ engine,
105
+ padding,
106
+ axis,
107
+ floating = false,
108
+ entries,
109
+ font,
110
+ scale,
111
+ gesture,
112
+ deferHit,
113
+ onStart,
114
+ active,
115
+ }: Options) {
116
+ const startScale = useSharedValue(1);
117
+ const startY = useSharedValue(0);
118
+ const armed = useSharedValue(false);
119
+ const { canvasWidth, canvasHeight, wake } = engine;
120
+ const { left, right, top, bottom } = padding;
121
+ const side = axis?.side ?? "right";
122
+ const labelRightMargin = axis?.labelRightMargin;
123
+ const config = axis?.scaleGesture;
124
+ const enabled = config != null;
125
+ const minScale = config?.minScale ?? 0.25;
126
+ const maxScale = config?.maxScale ?? 10;
127
+ const dragDistance = config?.dragDistance ?? 160;
128
+ const doubleTapReset = config?.doubleTapReset ?? true;
129
+
130
+ const axisGesture = useMemo(() => {
131
+ if (!enabled) return null;
132
+ const hit = (x: number, y: number) => {
133
+ "worklet";
134
+ return (
135
+ isYAxisScaleHit(
136
+ x,
137
+ y,
138
+ canvasWidth.get(),
139
+ canvasHeight.get(),
140
+ { left, right, top, bottom },
141
+ side,
142
+ floating,
143
+ labelRightMargin,
144
+ entries?.get() ?? [],
145
+ font,
146
+ ) && !deferHit?.(x, y)
147
+ );
148
+ };
149
+ const pan = Gesture.Manual()
150
+ .onTouchesDown((event, manager) => {
151
+ "worklet";
152
+ const touch = event.allTouches[0];
153
+ if (event.numberOfTouches !== 1 || !touch || !hit(touch.x, touch.y)) {
154
+ armed.set(false);
155
+ manager.fail();
156
+ return;
157
+ }
158
+ // A Manual recognizer owns the entire down→up lifecycle. A Pan with
159
+ // manualActivation can overwrite activation while beginning its native
160
+ // recognition, so it cannot reliably claim a gutter touch on down.
161
+ // Claim before a parent ScrollView or chart scrub can activate.
162
+ // Exclusive below gives this pair priority over the entire plot graph.
163
+ // Native touch moves can arrive before the ACTIVE/onStart event. Seed
164
+ // the drag here so the first move cannot reuse a previous drag's scale.
165
+ cancelAnimation(scale);
166
+ startScale.set(scale.get());
167
+ startY.set(touch.y);
168
+ armed.set(true);
169
+ active?.set(true);
170
+ manager.begin();
171
+ manager.activate();
172
+ })
173
+ .onStart(() => {
174
+ "worklet";
175
+ wake?.();
176
+ active?.set(true);
177
+ onStart?.();
178
+ })
179
+ .onTouchesMove((event) => {
180
+ "worklet";
181
+ const touch = event.allTouches[0];
182
+ if (!armed.get() || !touch) return;
183
+ scale.set(
184
+ draggedYAxisScale(
185
+ startScale.get(),
186
+ touch.y - startY.get(),
187
+ dragDistance,
188
+ minScale,
189
+ maxScale,
190
+ ),
191
+ );
192
+ })
193
+ .onTouchesUp((_event, manager) => {
194
+ "worklet";
195
+ if (armed.get()) {
196
+ armed.set(false);
197
+ manager.end();
198
+ }
199
+ })
200
+ .onTouchesCancelled((_event, manager) => {
201
+ "worklet";
202
+ armed.set(false);
203
+ manager.fail();
204
+ })
205
+ .onFinalize(() => {
206
+ "worklet";
207
+ armed.set(false);
208
+ active?.set(false);
209
+ });
210
+ const reset = Gesture.Tap()
211
+ .enabled(doubleTapReset)
212
+ .numberOfTaps(2)
213
+ .maxDistance(16)
214
+ .onTouchesDown((event, manager) => {
215
+ "worklet";
216
+ const touch = event.allTouches[0];
217
+ if (event.numberOfTouches !== 1 || !touch || !hit(touch.x, touch.y))
218
+ manager.fail();
219
+ })
220
+ .onEnd((_event, success) => {
221
+ "worklet";
222
+ if (!success) return;
223
+ wake?.();
224
+ cancelAnimation(scale);
225
+ scale.set(
226
+ withTiming(Math.max(minScale, Math.min(maxScale, 1)), {
227
+ duration: 240,
228
+ }),
229
+ );
230
+ onStart?.();
231
+ });
232
+ return Gesture.Simultaneous(pan, reset);
233
+ }, [
234
+ enabled,
235
+ canvasWidth,
236
+ canvasHeight,
237
+ left,
238
+ right,
239
+ top,
240
+ bottom,
241
+ side,
242
+ floating,
243
+ labelRightMargin,
244
+ entries,
245
+ font,
246
+ deferHit,
247
+ scale,
248
+ startScale,
249
+ startY,
250
+ armed,
251
+ wake,
252
+ onStart,
253
+ active,
254
+ minScale,
255
+ maxScale,
256
+ dragDistance,
257
+ doubleTapReset,
258
+ ]);
259
+ return useMemo(
260
+ () => (axisGesture ? Gesture.Exclusive(axisGesture, gesture) : gesture),
261
+ [axisGesture, gesture],
262
+ );
263
+ }
package/src/index.ts CHANGED
@@ -61,9 +61,12 @@ export type {
61
61
  ChartPlotRect,
62
62
  ChartScale,
63
63
  ChartSegment,
64
+ ChartViewportControl,
64
65
  DegenOptions,
65
66
  DegenShakePayload,
67
+ DotConfig,
66
68
  DotGlowConfig,
69
+ DotRingConfig,
67
70
  EmptyStateMetrics,
68
71
  FontConfig,
69
72
  FontWeight,
@@ -74,6 +77,7 @@ export type {
74
77
  LegendConfig,
75
78
  LegendStyle,
76
79
  LineConfig,
80
+ LineStyleConfig,
77
81
  LiveChartCoreProps,
78
82
  LiveChartFrameStats,
79
83
  LiveChartHandle,
@@ -97,14 +101,17 @@ export type {
97
101
  MultiSeriesDotConfig,
98
102
  PerSeriesTooltipConfig,
99
103
  PulseConfig,
104
+ RangeAnimationConfig,
100
105
  ReferenceLine,
101
106
  ReferenceLineBadgeConfig,
107
+ ReferenceLineValueBadgeConfig,
102
108
  ReferenceLineGroupingConfig,
103
109
  ReferenceLineRenderProps,
104
110
  ReturnToLiveConfig,
105
111
  ScrubActionConfig,
106
112
  ScrubActionPoint,
107
113
  ScrubConfig,
114
+ ScrubMarkerConfig,
108
115
  ScrubPoint,
109
116
  ScrubPointCore,
110
117
  ScrubPointMulti,
@@ -116,14 +123,18 @@ export type {
116
123
  ThemeMode,
117
124
  ThresholdConfig,
118
125
  ThresholdBadgeRenderProps,
126
+ ThresholdFillConfig,
119
127
  ThresholdLineConfig,
128
+ TimeScrollConfig,
120
129
  TooltipRenderProps,
121
130
  TradeEvent,
122
131
  TransitionConfig,
123
132
  ValueLineConfig,
133
+ ViewportConfig,
124
134
  VisibleRange,
125
135
  VolumeConfig,
126
136
  XAxisConfig,
127
137
  YAxisConfig,
138
+ YAxisScaleGestureConfig,
128
139
  ZoomConfig,
129
140
  } from "./types";
@@ -0,0 +1,37 @@
1
+ import { BADGE_METRICS_DEFAULTS } from "../constants";
2
+ import { badgeTailAndCap } from "../draw/line";
3
+ import type { BadgeMetrics } from "../types";
4
+
5
+ /** Horizontal price-column geometry, independent of the value's vertical position. */
6
+ export interface AxisBadgeConfig {
7
+ float?: boolean;
8
+ alignTextWithYAxis?: boolean;
9
+ showTail?: boolean;
10
+ fontSize?: number;
11
+ metrics?: BadgeMetrics;
12
+ offsetX?: number;
13
+ }
14
+
15
+ export function axisBadgeBounds(
16
+ width: number,
17
+ paddingRight: number,
18
+ textWidth: number,
19
+ fontSize: number,
20
+ config?: AxisBadgeConfig,
21
+ ) {
22
+ "worklet";
23
+ const metrics = config?.metrics ?? BADGE_METRICS_DEFAULTS;
24
+ const right = width - metrics.marginEdge + (config?.offsetX ?? 0);
25
+ const left = config?.float
26
+ ? right - textWidth - 2 * metrics.padX
27
+ : width -
28
+ paddingRight +
29
+ metrics.dotGap +
30
+ badgeTailAndCap(
31
+ config?.fontSize ?? fontSize,
32
+ config?.showTail ?? true,
33
+ metrics,
34
+ ) +
35
+ (config?.offsetX ?? 0);
36
+ return { left, right, textX: (left + right - textWidth) / 2 };
37
+ }
@@ -6,6 +6,9 @@ import { splineValueAtTime } from "./spline";
6
6
  export interface ProjectedMarker {
7
7
  x: number;
8
8
  y: number;
9
+ /** The anchor is on the plot: across within `EDGE_SLOP` of it, up and down
10
+ * within `CULL_MARGIN`. Only visible markers are drawn, clustered, or
11
+ * hit-tested. */
9
12
  visible: boolean;
10
13
  /** Collapsed cluster member that the representative stands in for — not drawn,
11
14
  * not hit-tested. Set by the cluster pass; `false` outside `markerCluster`. */
@@ -41,9 +44,25 @@ export interface ProjectMarkersOpts {
41
44
  lineLinear?: boolean;
42
45
  }
43
46
 
44
- /** How far off-chart (px) a marker may sit before it is culled. */
47
+ /**
48
+ * How far above / below the plot (px) a marker's anchor may sit before it is
49
+ * culled. Vertical only: across, the anchor must stay on the plot (see
50
+ * {@link EDGE_SLOP}).
51
+ */
45
52
  const CULL_MARGIN = 24;
46
53
 
54
+ /**
55
+ * Slack (px) past the plot's left / right edge before a marker is culled.
56
+ * `LiveChart`'s engine moves its right edge in half-pixel steps
57
+ * (`advanceTimestampByPixel`), so it can trail its target by up to half a
58
+ * pixel: a marker stamped with the current time sits just past the edge until
59
+ * the next step (on a wide window, for seconds), and after a `nowOverride`
60
+ * change the edge can rest just short of the new time indefinitely, so a
61
+ * marker at `nowOverride` would otherwise never show. Also absorbs float
62
+ * rounding of a marker exactly on an edge.
63
+ */
64
+ const EDGE_SLOP = 0.5;
65
+
47
66
  /**
48
67
  * Project one marker (given its primitive anchor fields) into `target`,
49
68
  * without allocation. Primitives only, so per-glyph worklet closures don't
@@ -115,9 +134,15 @@ function projectInto(
115
134
  const y = chartTop + ((opts.displayMax - v) / valRange) * chartH;
116
135
  target.x = x;
117
136
  target.y = y;
137
+ // Across, a marker shows only while its anchor is on the plot: it disappears
138
+ // at the plot's left / right edge instead of sliding on over a y-axis gutter
139
+ // (either side) or the left inset. A glyph anchored just inside an edge still
140
+ // overhangs it by up to half its width. Up and down keep CULL_MARGIN: a
141
+ // marker's value can sit just outside the fitted Y range, or lead it while
142
+ // the range eases out.
118
143
  target.visible =
119
- x >= chartLeft - CULL_MARGIN &&
120
- x <= chartRight + CULL_MARGIN &&
144
+ x >= chartLeft - EDGE_SLOP &&
145
+ x <= chartRight + EDGE_SLOP &&
121
146
  y >= chartTop - CULL_MARGIN &&
122
147
  y <= chartBottom + CULL_MARGIN;
123
148
  }
package/src/math/range.ts CHANGED
@@ -11,6 +11,7 @@ export function computeRange(
11
11
  exaggerate?: boolean,
12
12
  nonNegative?: boolean,
13
13
  maxValue?: number,
14
+ floorRange?: number,
14
15
  ): { min: number; max: number } {
15
16
  "worklet";
16
17
  let targetMin = Infinity;
@@ -47,6 +48,40 @@ export function computeRange(
47
48
  targetMax += margin;
48
49
  }
49
50
 
51
+ // Compare the bounded fit: a clamp can shrink an otherwise wider range.
52
+ // Slide a widened fit off either bound; both hard bounds win if the floor
53
+ // cannot fit between them. Mirrors the fitted range used by both engines.
54
+ if (floorRange !== undefined && floorRange > 0 && Number.isFinite(floorRange)) {
55
+ const boundedMin = nonNegative && targetMin < 0 ? 0 : targetMin;
56
+ const boundedMax =
57
+ maxValue !== undefined && targetMax > maxValue ? maxValue : targetMax;
58
+ if (floorRange > boundedMax - boundedMin) {
59
+ // Halve before adding so large finite prices cannot overflow the midpoint.
60
+ const mid = targetMin / 2 + targetMax / 2;
61
+ let nextMin = mid - floorRange / 2;
62
+ let nextMax = mid + floorRange / 2;
63
+ if (nonNegative && nextMin < 0) {
64
+ nextMax -= nextMin;
65
+ nextMin = 0;
66
+ }
67
+ if (maxValue !== undefined && nextMax > maxValue) {
68
+ nextMin -= nextMax - maxValue;
69
+ nextMax = maxValue;
70
+ }
71
+ if (nonNegative && nextMin < 0) nextMin = 0;
72
+ // Ignore a floor that would overflow or round the bounds onto each other.
73
+ if (
74
+ Number.isFinite(nextMin) &&
75
+ Number.isFinite(nextMax) &&
76
+ nextMin < nextMax &&
77
+ Number.isFinite(nextMax - nextMin)
78
+ ) {
79
+ targetMin = nextMin;
80
+ targetMax = nextMax;
81
+ }
82
+ }
83
+ }
84
+
50
85
  if (nonNegative && targetMin < 0) targetMin = 0;
51
86
  if (maxValue !== undefined && targetMax > maxValue) targetMax = maxValue;
52
87
 
@@ -0,0 +1,28 @@
1
+ import type { RangeAnimationConfig } from "../types";
2
+
3
+ // Worklet closures capture local functions when the caller is initialized.
4
+ function resolveSpeed(smoothing: number, speed: number | undefined): number {
5
+ "worklet";
6
+ return speed === undefined || !Number.isFinite(speed)
7
+ ? smoothing
8
+ : Math.max(0, Math.min(1, speed));
9
+ }
10
+
11
+ /** Select per-bound easing while preserving immediate expansion and reduced motion. */
12
+ export function rangeAnimationSpeed(
13
+ smoothing: number,
14
+ config: RangeAnimationConfig | undefined,
15
+ expanding: boolean,
16
+ disjoint = false,
17
+ ): number {
18
+ "worklet";
19
+ if (smoothing >= 1 || (expanding && !config?.animateExpansion)) return 1;
20
+ const speed = resolveSpeed(
21
+ smoothing,
22
+ expanding ? config?.expansionSmoothing : config?.contractionSmoothing,
23
+ );
24
+ // Until the ranges overlap, contraction must not outrun the expanding bound.
25
+ return !expanding && disjoint && config?.animateExpansion
26
+ ? Math.min(speed, resolveSpeed(smoothing, config.expansionSmoothing))
27
+ : speed;
28
+ }
@@ -17,16 +17,29 @@ export function clampToBounds(
17
17
  return Math.min(hi, Math.max(lo, value));
18
18
  }
19
19
 
20
+ /**
21
+ * Where a touch may grab each line: the touch `x` and, index-aligned with the
22
+ * chart's `referenceLines`, each line's `grabRange` (`[from, to]`, canvas px) —
23
+ * `null` / `undefined` for a line grabbed anywhere along it.
24
+ */
25
+ export interface GrabRangeProbe {
26
+ x: number;
27
+ ranges: readonly (readonly [number, number] | null | undefined)[];
28
+ }
29
+
20
30
  /**
21
31
  * Index of the draggable line whose handle-Y is nearest the touch `y`, within
22
32
  * `slop` px — or `-1` when none is in reach. `handleYs` is index-aligned with the
23
- * chart's `referenceLines`; entries `< 0` (not draggable / off-screen / not laid
24
- * out) are skipped. Ties favor the later (topmost-drawn) line.
33
+ * chart's `referenceLines`; entries `< 0` (not draggable / not laid out) are
34
+ * skipped; off-screen lines pin to the nearest plot edge. Ties favor the later
35
+ * (topmost-drawn) line. With `grab`, a line
36
+ * whose `grabRange` does not contain the touch `x` is skipped too.
25
37
  */
26
38
  export function nearestDraggableIndex(
27
39
  handleYs: number[],
28
40
  y: number,
29
41
  slop: number,
42
+ grab?: GrabRangeProbe,
30
43
  ): number {
31
44
  "worklet";
32
45
  let best = -1;
@@ -34,6 +47,8 @@ export function nearestDraggableIndex(
34
47
  for (let i = 0; i < handleYs.length; i++) {
35
48
  const hy = handleYs[i];
36
49
  if (hy < 0) continue;
50
+ const range = grab?.ranges[i];
51
+ if (range && (grab.x < range[0] || grab.x > range[1])) continue;
37
52
  const d = Math.abs(hy - y);
38
53
  if (d <= bestDist) {
39
54
  bestDist = d;
@@ -49,17 +64,19 @@ export function nearestDraggableIndex(
49
64
  * or already dragging) owns the touch outright, wherever the asking gesture says
50
65
  * the finger is: the scrub pan can activate mid-drag and asks with its
51
66
  * touch-DOWN point, which a longer drag has carried the line away from. With no
52
- * line grabbed, it is the geometric reach test around the handles.
67
+ * line grabbed, it is the geometric reach test around the handles (and, with
68
+ * `grab`, inside each line's `grabRange`).
53
69
  */
54
70
  export function referenceDragOwnsTouch(
55
71
  dragIndex: number,
56
72
  handleYs: number[],
57
73
  y: number,
58
74
  slop: number,
75
+ grab?: GrabRangeProbe,
59
76
  ): boolean {
60
77
  "worklet";
61
78
  if (dragIndex >= 0) return true;
62
- return nearestDraggableIndex(handleYs, y, slop) >= 0;
79
+ return nearestDraggableIndex(handleYs, y, slop, grab) >= 0;
63
80
  }
64
81
 
65
82
  /**
@@ -26,8 +26,8 @@ export interface ReferenceGrouping {
26
26
 
27
27
  /**
28
28
  * Single-linkage cluster of reference-line handle Ys: lines whose sorted Y gaps are
29
- * all `<= radius` chain into one group. Entries `< 0` (not a Form-A line / off the
30
- * canvas) are ignored. Returns which lines are collapsed (`hidden`) plus a centroid
29
+ * all `<= radius` chain into one group. Entries `< 0` (not a Form-A line / not laid
30
+ * out) are ignored. Returns which lines are collapsed (`hidden`) plus a centroid
31
31
  * + count per multi-line cluster. A non-positive `radius` disables grouping.
32
32
  */
33
33
  export function groupReferenceLines(
@@ -0,0 +1,112 @@
1
+ /** Screen rectangles shared by reference-tag drawing and interaction. */
2
+ export interface TagRect { x: number; y: number; w: number; h: number }
3
+ export interface ReferenceTag extends TagRect {
4
+ index: number;
5
+ lineId?: string;
6
+ key: string;
7
+ kind: "name" | "value" | "custom";
8
+ /** Original projected price Y; displacement never changes the price. */
9
+ lineY: number;
10
+ }
11
+ export interface StackedReferenceTag extends ReferenceTag { offsetY: number }
12
+ export interface ReferenceTagStack {
13
+ offsets: number[];
14
+ valueOffsets: number[];
15
+ tags: StackedReferenceTag[];
16
+ }
17
+ export const EMPTY_TAG_STACK: ReferenceTagStack = { offsets: [], valueOffsets: [], tags: [] };
18
+
19
+ export function overlapsX(a: TagRect, b: TagRect): boolean {
20
+ "worklet";
21
+ return a.x < b.x + b.w && b.x < a.x + a.w;
22
+ }
23
+
24
+ /** Fit an ordered column without changing its order. Null means it cannot fit. */
25
+ function pack(tags: ReferenceTag[], top: number, bottom: number, radius: number): number[] | null {
26
+ "worklet";
27
+ if (!tags.length) return [];
28
+ const ys: number[] = [];
29
+ for (let i = 0; i < tags.length; i++) {
30
+ const t = tags[i];
31
+ const min = i === 0 ? top + t.h / 2 : ys[i - 1] + Math.max(radius, (tags[i - 1].h + t.h) / 2 + 2);
32
+ ys.push(Math.max(min, t.y + t.h / 2));
33
+ }
34
+ ys[ys.length - 1] = Math.min(ys[ys.length - 1], bottom - tags[tags.length - 1].h / 2);
35
+ for (let i = ys.length - 2; i >= 0; i--)
36
+ ys[i] = Math.min(ys[i], ys[i + 1] - Math.max(radius, (tags[i].h + tags[i + 1].h) / 2 + 2));
37
+ return ys[0] >= top + tags[0].h / 2 - 0.001 ? ys : null;
38
+ }
39
+
40
+ /**
41
+ * Pack only horizontally intersecting columns. Opposite edges stay independent.
42
+ * A fixed value-badge obstacle divides a column into above/below slots; choose
43
+ * the feasible split with the smallest total squared displacement. If there is
44
+ * physically insufficient height, retain every tag in bounds with best-effort
45
+ * spacing rather than hiding levels or moving their prices.
46
+ */
47
+ export function stackReferenceTags(
48
+ input: ReferenceTag[], top: number, bottom: number, radius = 18, obstacle: TagRect | null = null,
49
+ ): ReferenceTagStack {
50
+ "worklet";
51
+ const result: ReferenceTagStack = { offsets: [], valueOffsets: [], tags: [] };
52
+ if (!Number.isFinite(top) || !Number.isFinite(bottom) || bottom <= top) return result;
53
+ const tags = input.filter(t => [t.x, t.y, t.w, t.h, t.lineY].every(v => Number.isFinite(v)) && t.w > 0 && t.h > 0);
54
+ const separation = Number.isFinite(radius) && radius >= 0 ? radius : 18;
55
+ const visited: boolean[] = [];
56
+ for (let first = 0; first < tags.length; first++) {
57
+ if (visited[first]) continue;
58
+ const component = [tags[first]];
59
+ visited[first] = true;
60
+ for (let j = 0; j < component.length; j++) {
61
+ for (let k = 0; k < tags.length; k++) {
62
+ if (!visited[k] && overlapsX(component[j], tags[k])) {
63
+ visited[k] = true;
64
+ component.push(tags[k]);
65
+ }
66
+ }
67
+ }
68
+ component.sort((a, b) => (a.y + a.h / 2) - (b.y + b.h / 2) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
69
+ const blocked = obstacle && obstacle.h > 0 && obstacle.y < bottom && obstacle.y + obstacle.h > top && component.some(t => overlapsX(t, obstacle));
70
+ let positions: number[] | null = null;
71
+ if (blocked && obstacle) {
72
+ let bestCost = Infinity;
73
+ for (let split = 0; split <= component.length; split++) {
74
+ const above = pack(component.slice(0, split), top, Math.min(bottom, obstacle.y - 2), separation);
75
+ const below = pack(component.slice(split), Math.max(top, obstacle.y + obstacle.h + 2), bottom, separation);
76
+ if (!above || !below) continue;
77
+ const candidate = above.concat(below);
78
+ let cost = 0;
79
+ for (let j = 0; j < candidate.length; j++) cost += (candidate[j] - component[j].y - component[j].h / 2) ** 2;
80
+ if (cost < bestCost) { positions = candidate; bestCost = cost; }
81
+ }
82
+ } else positions = pack(component, top, bottom, separation);
83
+ if (!positions) {
84
+ // Crowded charts cannot guarantee separation. Keep stable price ordering
85
+ // and bounded centers; never silently collapse or discard a reference.
86
+ positions = component.map((t, i) => {
87
+ const half = Math.min(t.h / 2, (bottom - top) / 2);
88
+ return Math.max(top + half, Math.min(bottom - half,
89
+ component.length === 1 ? t.y + t.h / 2 : top + half + (bottom - top - 2 * half) * i / (component.length - 1)));
90
+ });
91
+ }
92
+ for (let j = 0; j < component.length; j++) {
93
+ const tag = component[j];
94
+ const offsetY = positions[j] - tag.y - tag.h / 2;
95
+ if (tag.kind === "value") result.valueOffsets[tag.index] = offsetY;
96
+ else result.offsets[tag.index] = offsetY;
97
+ result.tags.push({ ...tag, y: tag.y + offsetY, offsetY });
98
+ }
99
+ }
100
+ return result;
101
+ }
102
+
103
+ /** Exact rectangles beat inflated targets when adjacent tags have a small gap. */
104
+ export function stackedTagAt(tags: StackedReferenceTag[], x: number, y: number): StackedReferenceTag | null {
105
+ "worklet";
106
+ let hit: StackedReferenceTag | null = null;
107
+ for (let i = tags.length - 1; i >= 0; i--) {
108
+ const t = tags[i];
109
+ if ((!hit || t.index > hit.index) && x >= t.x && x <= t.x + t.w && y >= t.y && y <= t.y + t.h) hit = t;
110
+ }
111
+ return hit;
112
+ }