react-native-livechart 4.29.0 → 4.30.1

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 (50) hide show
  1. package/dist/components/LiveChart.d.ts.map +1 -1
  2. package/dist/components/LiveChartSeries.d.ts.map +1 -1
  3. package/dist/components/ResetButtonOverlay.d.ts +25 -0
  4. package/dist/components/ResetButtonOverlay.d.ts.map +1 -0
  5. package/dist/core/gestureRangeOwnership.d.ts +13 -0
  6. package/dist/core/gestureRangeOwnership.d.ts.map +1 -0
  7. package/dist/core/liveChartEngineTick.d.ts +30 -0
  8. package/dist/core/liveChartEngineTick.d.ts.map +1 -1
  9. package/dist/core/resolveConfig.d.ts +35 -1
  10. package/dist/core/resolveConfig.d.ts.map +1 -1
  11. package/dist/core/useLiveChartEngine.d.ts +34 -3
  12. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  13. package/dist/hooks/crosshairShared.d.ts +2 -2
  14. package/dist/hooks/crosshairShared.d.ts.map +1 -1
  15. package/dist/hooks/resetButtonLayout.d.ts +24 -0
  16. package/dist/hooks/resetButtonLayout.d.ts.map +1 -0
  17. package/dist/hooks/resetView.d.ts +31 -0
  18. package/dist/hooks/resetView.d.ts.map +1 -0
  19. package/dist/hooks/useCrosshair.d.ts +3 -1
  20. package/dist/hooks/useCrosshair.d.ts.map +1 -1
  21. package/dist/hooks/useLiveDot.d.ts +6 -2
  22. package/dist/hooks/useLiveDot.d.ts.map +1 -1
  23. package/dist/hooks/usePanScroll.d.ts +39 -3
  24. package/dist/hooks/usePanScroll.d.ts.map +1 -1
  25. package/dist/hooks/useResetButton.d.ts +41 -0
  26. package/dist/hooks/useResetButton.d.ts.map +1 -0
  27. package/dist/hooks/useYAxisScaleGesture.d.ts +14 -1
  28. package/dist/hooks/useYAxisScaleGesture.d.ts.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/types.d.ts +138 -5
  32. package/dist/types.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/src/components/LiveChart.tsx +67 -6
  35. package/src/components/LiveChartSeries.tsx +6 -1
  36. package/src/components/ResetButtonOverlay.tsx +129 -0
  37. package/src/core/gestureRangeOwnership.ts +46 -0
  38. package/src/core/liveChartEngineTick.ts +84 -4
  39. package/src/core/resolveConfig.ts +76 -0
  40. package/src/core/useLiveChartEngine.ts +191 -22
  41. package/src/hooks/crosshairShared.ts +2 -2
  42. package/src/hooks/resetButtonLayout.ts +80 -0
  43. package/src/hooks/resetView.ts +92 -0
  44. package/src/hooks/useCrosshair.ts +50 -19
  45. package/src/hooks/useLiveDot.ts +41 -4
  46. package/src/hooks/usePanScroll.ts +177 -5
  47. package/src/hooks/useResetButton.ts +181 -0
  48. package/src/hooks/useYAxisScaleGesture.ts +70 -13
  49. package/src/index.ts +3 -0
  50. package/src/types.ts +141 -5
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * @see https://github.com/benjitaylor/liveline
7
7
  */
8
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
8
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
9
9
  import {
10
10
  cancelAnimation,
11
11
  Easing,
@@ -16,11 +16,13 @@ import {
16
16
  withTiming,
17
17
  type SharedValue,
18
18
  } from "react-native-reanimated";
19
+ import { scheduleOnUI } from "react-native-worklets";
19
20
  import { useDemandFrameLoop } from "../hooks/useDemandFrameLoop";
20
21
  import { MS_PER_FRAME_60FPS, RETURN_TO_LIVE_MS } from "../constants";
21
22
  import type {
22
23
  CandleGap,
23
24
  CandlePoint,
25
+ ChartScale,
24
26
  LiveChartFrameStats,
25
27
  LiveChartPoint,
26
28
  RangeAnimationConfig,
@@ -40,6 +42,7 @@ import {
40
42
 
41
43
  import { useHistoryRevision } from "./useHistoryRevision";
42
44
  import type { ResolvedViewportConfig } from "./resolveConfig";
45
+ import { useGestureRangeOwnership, writeGestureRange } from "./gestureRangeOwnership";
43
46
 
44
47
  export interface EngineConfig {
45
48
  /** External scroll/zoom values adopted in place of private gesture state. */
@@ -209,6 +212,28 @@ export interface ChartEngineEdge {
209
212
  edgeValue: SharedValue<number>;
210
213
  }
211
214
 
215
+ /** Price-range state shared by the price-pan / axis-scale gestures and the reset button. */
216
+ export interface ChartEngineRange {
217
+ /** Explicit price bounds: the app's `viewport.range` when supplied, else private state. */
218
+ viewRange: SharedValue<Pick<ChartScale, "min" | "max"> | null>;
219
+ /**
220
+ * True while {@link viewRange} was written by a gesture, which keeps it
221
+ * applied while following live. An app write or replacement viewport gives
222
+ * ownership back to the app. Resets, axis double-taps and framing changes
223
+ * clear only gesture-owned bounds.
224
+ */
225
+ viewRangeGestureOwned: SharedValue<boolean>;
226
+ /** Fitted Y bounds the eased display range pursues, before a range override. */
227
+ fitMin: SharedValue<number>;
228
+ fitMax: SharedValue<number>;
229
+ }
230
+
231
+ /** "Return to live" glide state (see `EngineTickInput.returnT`). */
232
+ export interface ChartEngineReturnToLive {
233
+ returnT: SharedValue<number>;
234
+ returnFrom: SharedValue<number>;
235
+ }
236
+
212
237
  export interface SingleEngineState
213
238
  extends ChartEngineLayout,
214
239
  ChartEngineExtrema {
@@ -269,6 +294,11 @@ export interface EngineFrameRefs {
269
294
  yRangeScaleSV?: SharedValue<number>;
270
295
  /** External price bounds read in the same frame as end/window. */
271
296
  viewRangeSV?: ResolvedViewportConfig["range"];
297
+ /** Honor `viewRangeSV` while following live (a gesture-owned range). */
298
+ viewRangeFollowsLiveSV?: SharedValue<boolean>;
299
+ /** Fitted bounds written back each frame (see `EngineTickMutable.fitMin`). */
300
+ fitMinSV?: SharedValue<number>;
301
+ fitMaxSV?: SharedValue<number>;
272
302
  nowOverrideSV?: SharedValue<number | undefined>;
273
303
  windowBufferSV?: SharedValue<number>;
274
304
  pausedSV: SharedValue<boolean>;
@@ -289,7 +319,7 @@ export interface EngineFrameRefs {
289
319
  /** Receives the smoothed right-edge value each frame. Optional for callers/tests. */
290
320
  edgeValueSV?: SharedValue<number>;
291
321
  /**
292
- * One-shot "snap the framing this frame" flag (set by the `snapKey` effect).
322
+ * One-shot "snap the framing this frame" flag (set by the `snapKey` reaction).
293
323
  * Consumed and cleared by {@link applyLiveChartEngineFrame} after the tick.
294
324
  * Optional for callers/tests.
295
325
  */
@@ -330,6 +360,10 @@ export function makeEngineFrameScratch(): EngineFrameScratch {
330
360
  extremaMaxValue: NaN,
331
361
  extremaMinTime: NaN,
332
362
  extremaMaxTime: NaN,
363
+ fitMin: 0,
364
+ fitMax: 1,
365
+ adjustedViewRangeMin: NaN,
366
+ adjustedViewRangeMax: NaN,
333
367
  lastCanvasWidth: undefined,
334
368
  lastCanvasHeight: undefined,
335
369
  },
@@ -347,6 +381,21 @@ export function makeEngineFrameScratch(): EngineFrameScratch {
347
381
  };
348
382
  }
349
383
 
384
+ /**
385
+ * Drop a gesture-written price range so the next frame lands on the fit (a
386
+ * `snapKey` or `mode` change re-frames the chart). An app-written range,
387
+ * which the app owns, is left alone.
388
+ */
389
+ export function clearGestureOwnedRange(
390
+ viewRange: SharedValue<Pick<ChartScale, "min" | "max"> | null>,
391
+ viewRangeGestureOwned: SharedValue<boolean>,
392
+ ): void {
393
+ "worklet";
394
+ if (!viewRangeGestureOwned.get()) return;
395
+ viewRange.set(null);
396
+ viewRangeGestureOwned.set(false);
397
+ }
398
+
350
399
  /**
351
400
  * Shared between the `useFrameCallback` worklet and unit tests.
352
401
  * Mutates shared values from a snapshot tick (`tickLiveChartEngineFrame`).
@@ -373,6 +422,10 @@ export function applyLiveChartEngineFrame(
373
422
  extremaMaxValue: NaN,
374
423
  extremaMinTime: NaN,
375
424
  extremaMaxTime: NaN,
425
+ fitMin: 0,
426
+ fitMax: 1,
427
+ adjustedViewRangeMin: NaN,
428
+ adjustedViewRangeMax: NaN,
376
429
  lastCanvasWidth: undefined,
377
430
  lastCanvasHeight: undefined,
378
431
  };
@@ -387,6 +440,8 @@ export function applyLiveChartEngineFrame(
387
440
  state.extremaMaxValue = sv.extremaMaxValue.value;
388
441
  state.extremaMinTime = sv.extremaMinTime.value;
389
442
  state.extremaMaxTime = sv.extremaMaxTime.value;
443
+ state.fitMin = sv.fitMinSV?.value ?? state.fitMin;
444
+ state.fitMax = sv.fitMaxSV?.value ?? state.fitMax;
390
445
 
391
446
  const input: EngineTickInput = scratch?.input ?? {
392
447
  dt,
@@ -418,6 +473,7 @@ export function applyLiveChartEngineFrame(
418
473
  input.minRange = sv.minRangeSV?.value;
419
474
  input.yRangeScale = sv.yRangeScaleSV?.value ?? 1;
420
475
  input.viewRange = sv.viewRangeSV?.value;
476
+ input.viewRangeFollowsLive = sv.viewRangeFollowsLiveSV?.value ?? false;
421
477
  input.nowOverride = sv.nowOverrideSV?.value;
422
478
  input.windowBuffer = sv.windowBufferSV?.value ?? 0;
423
479
  input.targetValue = sv.value.value;
@@ -455,6 +511,25 @@ export function applyLiveChartEngineFrame(
455
511
  sv.extremaMaxValue.value = state.extremaMaxValue;
456
512
  sv.extremaMinTime.value = state.extremaMinTime;
457
513
  sv.extremaMaxTime.value = state.extremaMaxTime;
514
+ if (sv.fitMinSV && state.fitMin !== undefined) sv.fitMinSV.value = state.fitMin;
515
+ if (sv.fitMaxSV && state.fitMax !== undefined) sv.fitMaxSV.value = state.fitMax;
516
+ // A gesture-owned range the tick had to clamp is written back, so the next
517
+ // gesture frame continues from the clamped bounds instead of drifting past them.
518
+ const adjustedMin = state.adjustedViewRangeMin;
519
+ const adjustedMax = state.adjustedViewRangeMax;
520
+ if (
521
+ sv.viewRangeSV &&
522
+ sv.viewRangeFollowsLiveSV?.value === true &&
523
+ adjustedMin !== undefined &&
524
+ adjustedMax !== undefined &&
525
+ Number.isFinite(adjustedMin) &&
526
+ Number.isFinite(adjustedMax)
527
+ ) {
528
+ writeGestureRange(sv.viewRangeSV, sv.viewRangeFollowsLiveSV, {
529
+ min: adjustedMin,
530
+ max: adjustedMax,
531
+ });
532
+ }
458
533
  // Clear the one-shot snap so the next frame eases normally again — but only
459
534
  // once a real (measured) frame consumed it. The tick early-returns on a
460
535
  // zero-size canvas (before applying the snap), so keep the flag pending until
@@ -471,7 +546,11 @@ export function applyLiveChartEngineFrame(
471
546
 
472
547
  export function useLiveChartEngine(
473
548
  config: EngineConfig,
474
- ): SingleEngineState & ChartEngineScroll & ChartEngineEdge & { wake: () => void } {
549
+ ): SingleEngineState &
550
+ ChartEngineScroll &
551
+ ChartEngineEdge &
552
+ ChartEngineRange &
553
+ ChartEngineReturnToLive & { wake: () => void } {
475
554
  const {
476
555
  viewport,
477
556
  data,
@@ -520,7 +599,26 @@ export function useLiveChartEngine(
520
599
  const internalViewWindow = useSharedValue<number | null>(null);
521
600
  const viewWindow = viewport?.window ?? internalViewWindow;
522
601
  const hasViewport = viewport != null;
523
- const viewRange = viewport?.range;
602
+ // Explicit price bounds. The price-pan / axis-scale gestures write these (the
603
+ // app's `viewport.range` when supplied, else private state) and mark them
604
+ // gesture-owned so the tick keeps applying them while following live.
605
+ const internalViewRange = useSharedValue<Pick<ChartScale, "min" | "max"> | null>(null);
606
+ const viewRange = viewport?.range ?? internalViewRange;
607
+ const viewRangeGestureOwned = useGestureRangeOwnership(viewRange);
608
+ const fitMin = useSharedValue(0);
609
+ const fitMax = useSharedValue(1);
610
+ const clearGestureRange = useCallback(
611
+ () => scheduleOnUI(clearGestureOwnedRange, viewRange, viewRangeGestureOwned),
612
+ [viewRange, viewRangeGestureOwned],
613
+ );
614
+ // A mode switch (line ↔ candle) re-frames the price range like a `snapKey`
615
+ // change does below, so a panned window from the other mode doesn't linger.
616
+ const lastMode = useRef(mode);
617
+ useEffect(() => {
618
+ if (mode === lastMode.current) return;
619
+ lastMode.current = mode;
620
+ clearGestureRange();
621
+ }, [mode, clearGestureRange]);
524
622
  const windowSmoothing = viewport?.windowSmoothing ?? true;
525
623
  const viewWindowSmoothingSV = useDerivedValue(() => windowSmoothing);
526
624
  // A change to the `timeWindow` prop (a range / timeframe selector) is an explicit
@@ -641,23 +739,16 @@ export function useLiveChartEngine(
641
739
 
642
740
  // High-frequency data reads directly from the caller's shared values —
643
741
  // no useDerivedValue bridging, no closure serialization per tick.
644
- // One-shot "snap the framing" flag. The effect below flips it to `true` when
645
- // `snapKey` changes; the next frame consumes it (bypassing `smoothing` for the
646
- // window / range / value) and clears it, so a timeframe / dataset switch lands
647
- // in one frame while live ticks stay smoothed. See `snapKey`.
742
+ // One-shot "snap the framing" flag. The selection reaction below consumes it
743
+ // after the UI-thread config is current, bypassing smoothing for that update
744
+ // while ordinary live ticks keep their smoothing. See `snapKey`.
648
745
  const snapSV = useSharedValue(false);
649
- // Compare against the previous key (not a "first render" flag) so React 18
650
- // StrictMode's double-invoked mount effect can't fire a spurious snap.
651
- const lastSnapKey = useRef(snapKey);
652
- // Layout effect, not passive: a passive effect runs after the commit has
653
- // painted, so the frame between them draws the new data/candleWidth against
654
- // the OLD framing (a one-frame squeeze on a timeframe switch). Flipping the
655
- // flag before paint lets the first frame with the new props consume the snap.
656
- useLayoutEffect(() => {
657
- if (snapKey === lastSnapKey.current) return;
658
- lastSnapKey.current = snapKey;
659
- snapSV.set(true);
660
- }, [snapKey, snapSV]);
746
+ // Comparing keys avoids a spurious mount snap during StrictMode replay.
747
+ const lastSnapKey = useSharedValue(snapKey);
748
+ const snapConfiguration = useDerivedValue(() => ({
749
+ key: snapKey,
750
+ configuredWindow: configuredTimeWindow,
751
+ }));
661
752
 
662
753
  // Static charts run zero per-frame loops. `isStaticSV` gates both the
663
754
  // frame-callback autostart and the one-shot settle reaction below.
@@ -700,6 +791,9 @@ export function useLiveChartEngine(
700
791
  minRangeSV,
701
792
  yRangeScaleSV: yRangeScale,
702
793
  viewRangeSV: viewRange,
794
+ viewRangeFollowsLiveSV: viewRangeGestureOwned,
795
+ fitMinSV: fitMin,
796
+ fitMaxSV: fitMax,
703
797
  nowOverrideSV,
704
798
  windowBufferSV,
705
799
  pausedSV,
@@ -772,6 +866,9 @@ export function useLiveChartEngine(
772
866
  viewWindow,
773
867
  viewWindowSmoothingSV,
774
868
  viewRange,
869
+ viewRangeGestureOwned,
870
+ fitMin,
871
+ fitMax,
775
872
  windowBufferSV,
776
873
  yRangeScale,
777
874
  ],
@@ -783,6 +880,72 @@ export function useLiveChartEngine(
783
880
  frameScratchRef.current = makeEngineFrameScratch();
784
881
  }
785
882
 
883
+ // Settle before the path mappers observe new series/config; waiting for the
884
+ // next frame callback lets those paths combine new data with the old scale.
885
+ useAnimatedReaction(
886
+ () => ({
887
+ configuration: snapConfiguration.get(),
888
+ effectiveWindow: timeWindow.get(),
889
+ windowOverride: viewWindow.get(),
890
+ // Config mappers can be re-registered after this reaction. Reading their
891
+ // values here keeps the snap downstream of the complete framing update.
892
+ framingInputs: [
893
+ viewEnd.get(),
894
+ viewRange.get(),
895
+ modeSV.get(),
896
+ nowOverrideSV.get(),
897
+ windowBufferSV.get(),
898
+ smoothing.get(),
899
+ rangeAnimationSV.get(),
900
+ adaptiveSpeedBoostSV.get(),
901
+ exaggerateSV.get(),
902
+ maxValueSV.get(),
903
+ minRangeSV.get(),
904
+ nonNegativeSV.get(),
905
+ yRangeScale?.get(),
906
+ referenceValue.get(),
907
+ referenceValues.get(),
908
+ thresholdRangePoints.get(),
909
+ thresholdRangeExtendToStart.get(),
910
+ thresholdRangeExtendToNow.get(),
911
+ pausedSV.get(),
912
+ allowFutureViewEndSV.get(),
913
+ viewWindowSmoothingSV.get(),
914
+ candleGapsSV.get(),
915
+ candleGapBridgeNoTradesSV.get(),
916
+ candleGapBridgeUnavailableSV.get(),
917
+ candleGapBridgeUnknownSV.get(),
918
+ ],
919
+ }),
920
+ ({ configuration, effectiveWindow, windowOverride }) => {
921
+ if (configuration.key === lastSnapKey.get()) {
922
+ return;
923
+ }
924
+ const expectedWindow = windowOverride ?? configuration.configuredWindow;
925
+ if (effectiveWindow !== expectedWindow) {
926
+ return;
927
+ }
928
+ lastSnapKey.set(configuration.key);
929
+ // The new framing lands on the fit, not on a window panned for the old data.
930
+ clearGestureOwnedRange(viewRange, viewRangeGestureOwned);
931
+ snapSV.set(true);
932
+ applyLiveChartEngineFrame(
933
+ { timeSincePreviousFrame: MS_PER_FRAME_60FPS },
934
+ frameRefs,
935
+ frameScratchRef.current!,
936
+ );
937
+ },
938
+ // Keep this mapper ahead of path consumers across React config changes.
939
+ [snapConfiguration, timeWindow, viewWindow, viewEnd, viewRange, viewRangeGestureOwned, modeSV,
940
+ nowOverrideSV, windowBufferSV, smoothing, maxValueSV, minRangeSV,
941
+ nonNegativeSV, yRangeScale, referenceValue, referenceValues,
942
+ rangeAnimationSV, adaptiveSpeedBoostSV, exaggerateSV,
943
+ thresholdRangePoints, thresholdRangeExtendToStart, thresholdRangeExtendToNow,
944
+ pausedSV, allowFutureViewEndSV, viewWindowSmoothingSV, candleGapsSV,
945
+ candleGapBridgeNoTradesSV, candleGapBridgeUnavailableSV, candleGapBridgeUnknownSV,
946
+ lastSnapKey, snapSV, frameRefs, frameScratchRef],
947
+ );
948
+
786
949
  const tickFrame = useCallback((dt: number): boolean => {
787
950
  "worklet";
788
951
  if (isFrameLoopActive?.get() === false) return false;
@@ -825,14 +988,14 @@ export function useLiveChartEngine(
825
988
  exaggerateSV.get(), referenceValue.get(), referenceValues.get(), thresholdRangePoints.get(),
826
989
  thresholdRangeExtendToStart.get(), thresholdRangeExtendToNow.get(), nonNegativeSV.get(),
827
990
  maxValueSV.get(), minRangeSV.get(), yRangeScale?.get(), nowOverrideSV.get(), windowBufferSV.get(), pausedSV.get(),
828
- viewEnd.get(), viewWindow.get(), viewRange?.get(), viewWindowSmoothingSV.get(), allowFutureViewEndSV.get(), returnT.get(), returnFrom.get(),
991
+ viewEnd.get(), viewWindow.get(), viewRange.get(), viewRangeGestureOwned.get(), viewWindowSmoothingSV.get(), allowFutureViewEndSV.get(), returnT.get(), returnFrom.get(),
829
992
  snapSV.get(), modeSV.get(), candleGapsSV.get(), candleGapBridgeNoTradesSV.get(),
830
993
  candleGapBridgeUnavailableSV.get(), candleGapBridgeUnknownSV.get(), isFrameLoopActive?.get(),
831
994
  keepAwake?.get(), wakeSignal?.get()];
832
995
  }, [pointHistory, candleHistory, data, value, candles, liveCandle, canvasWidth, canvasHeight, timeWindow, smoothing, rangeAnimationSV,
833
996
  adaptiveSpeedBoostSV, exaggerateSV, referenceValue, referenceValues, thresholdRangePoints,
834
997
  thresholdRangeExtendToStart, thresholdRangeExtendToNow, nonNegativeSV, maxValueSV, minRangeSV, yRangeScale,
835
- nowOverrideSV, windowBufferSV, pausedSV, viewEnd, viewWindow, viewRange, viewWindowSmoothingSV, allowFutureViewEndSV, returnT,
998
+ nowOverrideSV, windowBufferSV, pausedSV, viewEnd, viewWindow, viewRange, viewRangeGestureOwned, viewWindowSmoothingSV, allowFutureViewEndSV, returnT,
836
999
  returnFrom, snapSV, modeSV, candleGapsSV, candleGapBridgeNoTradesSV, candleGapBridgeUnavailableSV,
837
1000
  candleGapBridgeUnknownSV, isFrameLoopActive, keepAwake, wakeSignal]);
838
1001
 
@@ -956,6 +1119,12 @@ export function useLiveChartEngine(
956
1119
  timestamp,
957
1120
  viewEnd,
958
1121
  viewWindow,
1122
+ viewRange,
1123
+ viewRangeGestureOwned,
1124
+ fitMin,
1125
+ fitMax,
1126
+ returnT,
1127
+ returnFrom,
959
1128
  liveEdge,
960
1129
  edgeValue,
961
1130
  extremaMinValue,
@@ -178,8 +178,8 @@ export const HIDDEN_TOOLTIP: TooltipLayout = {
178
178
 
179
179
  export interface CrosshairState {
180
180
  scrubMarkers: SharedValue<Marker[]>;
181
- scrubX: SharedValue<number>;
182
- scrubActive: SharedValue<boolean>;
181
+ scrubX: SharedValue<number> | DerivedValue<number>;
182
+ scrubActive: SharedValue<boolean> | DerivedValue<boolean>;
183
183
  scrubTime: SharedValue<number>;
184
184
  scrubValue: SharedValue<number | null>;
185
185
  crosshairOpacity: SharedValue<number>;
@@ -0,0 +1,80 @@
1
+ import type { ChartPadding } from "../draw/line";
2
+
3
+ /** Where the reset button sits inside the plot rect. */
4
+ export type ResetButtonPlacement = "bottom-center" | "bottom-right";
5
+
6
+ /** Canvas-px rect of the rendered reset button. */
7
+ export interface ResetButtonRect {
8
+ x: number;
9
+ y: number;
10
+ width: number;
11
+ height: number;
12
+ }
13
+
14
+ /**
15
+ * Position of the reset button inside the plot, from the measured button size.
16
+ * Shared by the overlay's layout and the tap hit-test so both agree.
17
+ */
18
+ export function resetButtonRect(
19
+ canvasWidth: number,
20
+ canvasHeight: number,
21
+ padding: ChartPadding,
22
+ placement: ResetButtonPlacement,
23
+ margin: number,
24
+ width: number,
25
+ height: number,
26
+ ): ResetButtonRect {
27
+ "worklet";
28
+ const plotLeft = padding.left;
29
+ const plotRight = canvasWidth - padding.right;
30
+ const plotBottom = canvasHeight - padding.bottom;
31
+ const x =
32
+ placement === "bottom-right"
33
+ ? plotRight - margin - width
34
+ : (plotLeft + plotRight) / 2 - width / 2;
35
+ return { x, y: plotBottom - margin - height, width, height };
36
+ }
37
+
38
+ /** Whether a canvas-px touch lands on the button. */
39
+ export function isResetButtonHit(
40
+ x: number,
41
+ y: number,
42
+ rect: ResetButtonRect,
43
+ ): boolean {
44
+ "worklet";
45
+ return (
46
+ rect.width > 0 &&
47
+ rect.height > 0 &&
48
+ x >= rect.x &&
49
+ x <= rect.x + rect.width &&
50
+ y >= rect.y &&
51
+ y <= rect.y + rect.height
52
+ );
53
+ }
54
+
55
+ /** `yRangeScale` this close to 1 counts as fitted (it eases back to exactly 1). */
56
+ const Y_RANGE_SCALE_EPSILON = 1e-3;
57
+
58
+ /**
59
+ * True while any of the enabled manual states moves the view off the fitted
60
+ * live view: a window scrolled back in time, a pinched width, a scaled price
61
+ * axis or a gesture-owned price range.
62
+ */
63
+ export function isViewOffFitted(
64
+ viewEnd: number | null,
65
+ viewWindow: number | null,
66
+ yRangeScale: number,
67
+ hasGestureRange: boolean,
68
+ showTimeScroll: boolean,
69
+ showZoom: boolean,
70
+ showYScale: boolean,
71
+ showPriceScroll: boolean,
72
+ ): boolean {
73
+ "worklet";
74
+ return (
75
+ (showTimeScroll && viewEnd !== null) ||
76
+ (showZoom && viewWindow !== null) ||
77
+ (showYScale && Math.abs(yRangeScale - 1) > Y_RANGE_SCALE_EPSILON) ||
78
+ (showPriceScroll && hasGestureRange)
79
+ );
80
+ }
@@ -0,0 +1,92 @@
1
+ import {
2
+ cancelAnimation,
3
+ Easing,
4
+ withTiming,
5
+ type SharedValue,
6
+ } from "react-native-reanimated";
7
+
8
+ import type { ChartScale } from "../types";
9
+
10
+ /** Duration (ms) of the eased `yRangeScale` → 1 when no price pan is active. */
11
+ export const Y_RANGE_SCALE_RESET_MS = 240;
12
+
13
+ /** The subset of {@link ResetViewRefs} a chart without price panning resets. */
14
+ export type ResetSeriesViewRefs = Pick<
15
+ ResetViewRefs,
16
+ "viewEnd" | "viewWindow" | "yRangeScale"
17
+ >;
18
+
19
+ /**
20
+ * `LiveChartSeries` counterpart of {@link resetChartView}: clear the pinch
21
+ * window and frozen edge (as `resetZoom()`) and ease `yRangeScale` back to 1.
22
+ */
23
+ export function resetSeriesView(refs: ResetSeriesViewRefs): void {
24
+ "worklet";
25
+ const { viewEnd, viewWindow, yRangeScale } = refs;
26
+ cancelAnimation(viewWindow);
27
+ cancelAnimation(viewEnd);
28
+ viewWindow.set(null);
29
+ viewEnd.set(null);
30
+ cancelAnimation(yRangeScale);
31
+ yRangeScale.set(withTiming(1, { duration: Y_RANGE_SCALE_RESET_MS }));
32
+ }
33
+
34
+ /** Engine SharedValues a reset writes. */
35
+ export interface ResetViewRefs {
36
+ viewEnd: SharedValue<number | null>;
37
+ viewWindow: SharedValue<number | null>;
38
+ viewRange: SharedValue<Pick<ChartScale, "min" | "max"> | null>;
39
+ viewRangeGestureOwned: SharedValue<boolean>;
40
+ yRangeScale: SharedValue<number>;
41
+ returnT: SharedValue<number>;
42
+ returnFrom: SharedValue<number>;
43
+ /** "Return to live" glide duration in ms; `0` snaps. */
44
+ returnToLiveMs: number;
45
+ }
46
+
47
+ /**
48
+ * Return the chart to its fitted live view on the UI thread: clear the pinch
49
+ * window, glide the right edge back to live (the `timeScroll.returnToLive`
50
+ * timing, see #164), drop a gesture-owned price range and land `yRangeScale`
51
+ * on 1. Safe to call when the view is already fitted.
52
+ */
53
+ export function resetChartView(refs: ResetViewRefs): void {
54
+ "worklet";
55
+ const {
56
+ viewEnd,
57
+ viewWindow,
58
+ viewRange,
59
+ viewRangeGestureOwned,
60
+ yRangeScale,
61
+ returnT,
62
+ returnFrom,
63
+ returnToLiveMs,
64
+ } = refs;
65
+ cancelAnimation(viewWindow);
66
+ viewWindow.set(null);
67
+ const frozenEnd = viewEnd.get();
68
+ cancelAnimation(viewEnd);
69
+ viewEnd.set(null);
70
+ if (frozenEnd != null && returnToLiveMs > 0) {
71
+ returnFrom.set(frozenEnd);
72
+ returnT.set(0);
73
+ returnT.set(
74
+ withTiming(1, {
75
+ duration: returnToLiveMs,
76
+ easing: Easing.out(Easing.cubic),
77
+ }),
78
+ );
79
+ }
80
+ cancelAnimation(yRangeScale);
81
+ if (viewRangeGestureOwned.get()) {
82
+ // Land the scale in one step: the tick snaps the range while the scale is
83
+ // moving, which would jump the panned window onto the scaled fit before
84
+ // easing. With the scale parked, the display range eases from the panned
85
+ // window to the fit instead.
86
+ viewRange.set(null);
87
+ viewRangeGestureOwned.set(false);
88
+ yRangeScale.set(1);
89
+ } else {
90
+ yRangeScale.set(withTiming(1, { duration: Y_RANGE_SCALE_RESET_MS }));
91
+ }
92
+ }