react-native-livechart 4.28.2 → 4.30.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 (65) hide show
  1. package/README.md +1 -1
  2. package/dist/components/LiveChart.d.ts.map +1 -1
  3. package/dist/components/LiveChartSeries.d.ts.map +1 -1
  4. package/dist/components/LoadingOverlay.d.ts +6 -1
  5. package/dist/components/LoadingOverlay.d.ts.map +1 -1
  6. package/dist/components/ResetButtonOverlay.d.ts +25 -0
  7. package/dist/components/ResetButtonOverlay.d.ts.map +1 -0
  8. package/dist/constants.d.ts +6 -0
  9. package/dist/constants.d.ts.map +1 -1
  10. package/dist/core/gestureRangeOwnership.d.ts +13 -0
  11. package/dist/core/gestureRangeOwnership.d.ts.map +1 -0
  12. package/dist/core/liveChartEngineTick.d.ts +33 -1
  13. package/dist/core/liveChartEngineTick.d.ts.map +1 -1
  14. package/dist/core/resolveConfig.d.ts +39 -2
  15. package/dist/core/resolveConfig.d.ts.map +1 -1
  16. package/dist/core/useLiveChartEngine.d.ts +35 -2
  17. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  18. package/dist/draw/line.d.ts.map +1 -1
  19. package/dist/hooks/resetButtonLayout.d.ts +24 -0
  20. package/dist/hooks/resetButtonLayout.d.ts.map +1 -0
  21. package/dist/hooks/resetView.d.ts +31 -0
  22. package/dist/hooks/resetView.d.ts.map +1 -0
  23. package/dist/hooks/useBadge.d.ts.map +1 -1
  24. package/dist/hooks/useChartPaths.d.ts +3 -1
  25. package/dist/hooks/useChartPaths.d.ts.map +1 -1
  26. package/dist/hooks/useDemandFrameLoop.d.ts.map +1 -1
  27. package/dist/hooks/useLiveDot.d.ts +5 -2
  28. package/dist/hooks/useLiveDot.d.ts.map +1 -1
  29. package/dist/hooks/usePanScroll.d.ts +39 -3
  30. package/dist/hooks/usePanScroll.d.ts.map +1 -1
  31. package/dist/hooks/useReferenceLine.d.ts.map +1 -1
  32. package/dist/hooks/useResetButton.d.ts +41 -0
  33. package/dist/hooks/useResetButton.d.ts.map +1 -0
  34. package/dist/hooks/useYAxisScaleGesture.d.ts +14 -1
  35. package/dist/hooks/useYAxisScaleGesture.d.ts.map +1 -1
  36. package/dist/index.d.ts +1 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/math/squiggly.d.ts +12 -0
  39. package/dist/math/squiggly.d.ts.map +1 -1
  40. package/dist/types.d.ts +167 -11
  41. package/dist/types.d.ts.map +1 -1
  42. package/package.json +2 -2
  43. package/src/components/LiveChart.tsx +75 -4
  44. package/src/components/LiveChartSeries.tsx +9 -1
  45. package/src/components/LoadingOverlay.tsx +44 -6
  46. package/src/components/ResetButtonOverlay.tsx +129 -0
  47. package/src/constants.ts +7 -0
  48. package/src/core/gestureRangeOwnership.ts +46 -0
  49. package/src/core/liveChartEngineTick.ts +103 -2
  50. package/src/core/resolveConfig.ts +88 -2
  51. package/src/core/useLiveChartEngine.ts +122 -4
  52. package/src/draw/line.ts +13 -5
  53. package/src/hooks/resetButtonLayout.ts +80 -0
  54. package/src/hooks/resetView.ts +92 -0
  55. package/src/hooks/useBadge.ts +18 -5
  56. package/src/hooks/useChartPaths.ts +6 -4
  57. package/src/hooks/useDemandFrameLoop.ts +7 -2
  58. package/src/hooks/useLiveDot.ts +26 -11
  59. package/src/hooks/usePanScroll.ts +177 -5
  60. package/src/hooks/useReferenceLine.ts +4 -1
  61. package/src/hooks/useResetButton.ts +181 -0
  62. package/src/hooks/useYAxisScaleGesture.ts +70 -13
  63. package/src/index.ts +3 -0
  64. package/src/math/squiggly.ts +27 -0
  65. package/src/types.ts +170 -11
@@ -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 {
@@ -267,6 +292,13 @@ export interface EngineFrameRefs {
267
292
  maxValueSV?: SharedValue<number | undefined>;
268
293
  minRangeSV?: SharedValue<number | undefined>;
269
294
  yRangeScaleSV?: SharedValue<number>;
295
+ /** External price bounds read in the same frame as end/window. */
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>;
270
302
  nowOverrideSV?: SharedValue<number | undefined>;
271
303
  windowBufferSV?: SharedValue<number>;
272
304
  pausedSV: SharedValue<boolean>;
@@ -328,6 +360,10 @@ export function makeEngineFrameScratch(): EngineFrameScratch {
328
360
  extremaMaxValue: NaN,
329
361
  extremaMinTime: NaN,
330
362
  extremaMaxTime: NaN,
363
+ fitMin: 0,
364
+ fitMax: 1,
365
+ adjustedViewRangeMin: NaN,
366
+ adjustedViewRangeMax: NaN,
331
367
  lastCanvasWidth: undefined,
332
368
  lastCanvasHeight: undefined,
333
369
  },
@@ -345,6 +381,21 @@ export function makeEngineFrameScratch(): EngineFrameScratch {
345
381
  };
346
382
  }
347
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
+
348
399
  /**
349
400
  * Shared between the `useFrameCallback` worklet and unit tests.
350
401
  * Mutates shared values from a snapshot tick (`tickLiveChartEngineFrame`).
@@ -371,6 +422,10 @@ export function applyLiveChartEngineFrame(
371
422
  extremaMaxValue: NaN,
372
423
  extremaMinTime: NaN,
373
424
  extremaMaxTime: NaN,
425
+ fitMin: 0,
426
+ fitMax: 1,
427
+ adjustedViewRangeMin: NaN,
428
+ adjustedViewRangeMax: NaN,
374
429
  lastCanvasWidth: undefined,
375
430
  lastCanvasHeight: undefined,
376
431
  };
@@ -385,6 +440,8 @@ export function applyLiveChartEngineFrame(
385
440
  state.extremaMaxValue = sv.extremaMaxValue.value;
386
441
  state.extremaMinTime = sv.extremaMinTime.value;
387
442
  state.extremaMaxTime = sv.extremaMaxTime.value;
443
+ state.fitMin = sv.fitMinSV?.value ?? state.fitMin;
444
+ state.fitMax = sv.fitMaxSV?.value ?? state.fitMax;
388
445
 
389
446
  const input: EngineTickInput = scratch?.input ?? {
390
447
  dt,
@@ -415,6 +472,8 @@ export function applyLiveChartEngineFrame(
415
472
  input.maxValue = sv.maxValueSV?.value;
416
473
  input.minRange = sv.minRangeSV?.value;
417
474
  input.yRangeScale = sv.yRangeScaleSV?.value ?? 1;
475
+ input.viewRange = sv.viewRangeSV?.value;
476
+ input.viewRangeFollowsLive = sv.viewRangeFollowsLiveSV?.value ?? false;
418
477
  input.nowOverride = sv.nowOverrideSV?.value;
419
478
  input.windowBuffer = sv.windowBufferSV?.value ?? 0;
420
479
  input.targetValue = sv.value.value;
@@ -452,6 +511,25 @@ export function applyLiveChartEngineFrame(
452
511
  sv.extremaMaxValue.value = state.extremaMaxValue;
453
512
  sv.extremaMinTime.value = state.extremaMinTime;
454
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
+ }
455
533
  // Clear the one-shot snap so the next frame eases normally again — but only
456
534
  // once a real (measured) frame consumed it. The tick early-returns on a
457
535
  // zero-size canvas (before applying the snap), so keep the flag pending until
@@ -468,7 +546,11 @@ export function applyLiveChartEngineFrame(
468
546
 
469
547
  export function useLiveChartEngine(
470
548
  config: EngineConfig,
471
- ): SingleEngineState & ChartEngineScroll & ChartEngineEdge & { wake: () => void } {
549
+ ): SingleEngineState &
550
+ ChartEngineScroll &
551
+ ChartEngineEdge &
552
+ ChartEngineRange &
553
+ ChartEngineReturnToLive & { wake: () => void } {
472
554
  const {
473
555
  viewport,
474
556
  data,
@@ -517,6 +599,26 @@ export function useLiveChartEngine(
517
599
  const internalViewWindow = useSharedValue<number | null>(null);
518
600
  const viewWindow = viewport?.window ?? internalViewWindow;
519
601
  const hasViewport = viewport != null;
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]);
520
622
  const windowSmoothing = viewport?.windowSmoothing ?? true;
521
623
  const viewWindowSmoothingSV = useDerivedValue(() => windowSmoothing);
522
624
  // A change to the `timeWindow` prop (a range / timeframe selector) is an explicit
@@ -653,7 +755,9 @@ export function useLiveChartEngine(
653
755
  if (snapKey === lastSnapKey.current) return;
654
756
  lastSnapKey.current = snapKey;
655
757
  snapSV.set(true);
656
- }, [snapKey, snapSV]);
758
+ // The new framing lands on the fit, not on a window panned for the old data.
759
+ clearGestureRange();
760
+ }, [snapKey, snapSV, clearGestureRange]);
657
761
 
658
762
  // Static charts run zero per-frame loops. `isStaticSV` gates both the
659
763
  // frame-callback autostart and the one-shot settle reaction below.
@@ -695,6 +799,10 @@ export function useLiveChartEngine(
695
799
  maxValueSV,
696
800
  minRangeSV,
697
801
  yRangeScaleSV: yRangeScale,
802
+ viewRangeSV: viewRange,
803
+ viewRangeFollowsLiveSV: viewRangeGestureOwned,
804
+ fitMinSV: fitMin,
805
+ fitMaxSV: fitMax,
698
806
  nowOverrideSV,
699
807
  windowBufferSV,
700
808
  pausedSV,
@@ -766,6 +874,10 @@ export function useLiveChartEngine(
766
874
  viewEnd,
767
875
  viewWindow,
768
876
  viewWindowSmoothingSV,
877
+ viewRange,
878
+ viewRangeGestureOwned,
879
+ fitMin,
880
+ fitMax,
769
881
  windowBufferSV,
770
882
  yRangeScale,
771
883
  ],
@@ -819,14 +931,14 @@ export function useLiveChartEngine(
819
931
  exaggerateSV.get(), referenceValue.get(), referenceValues.get(), thresholdRangePoints.get(),
820
932
  thresholdRangeExtendToStart.get(), thresholdRangeExtendToNow.get(), nonNegativeSV.get(),
821
933
  maxValueSV.get(), minRangeSV.get(), yRangeScale?.get(), nowOverrideSV.get(), windowBufferSV.get(), pausedSV.get(),
822
- viewEnd.get(), viewWindow.get(), viewWindowSmoothingSV.get(), allowFutureViewEndSV.get(), returnT.get(), returnFrom.get(),
934
+ viewEnd.get(), viewWindow.get(), viewRange.get(), viewRangeGestureOwned.get(), viewWindowSmoothingSV.get(), allowFutureViewEndSV.get(), returnT.get(), returnFrom.get(),
823
935
  snapSV.get(), modeSV.get(), candleGapsSV.get(), candleGapBridgeNoTradesSV.get(),
824
936
  candleGapBridgeUnavailableSV.get(), candleGapBridgeUnknownSV.get(), isFrameLoopActive?.get(),
825
937
  keepAwake?.get(), wakeSignal?.get()];
826
938
  }, [pointHistory, candleHistory, data, value, candles, liveCandle, canvasWidth, canvasHeight, timeWindow, smoothing, rangeAnimationSV,
827
939
  adaptiveSpeedBoostSV, exaggerateSV, referenceValue, referenceValues, thresholdRangePoints,
828
940
  thresholdRangeExtendToStart, thresholdRangeExtendToNow, nonNegativeSV, maxValueSV, minRangeSV, yRangeScale,
829
- nowOverrideSV, windowBufferSV, pausedSV, viewEnd, viewWindow, viewWindowSmoothingSV, allowFutureViewEndSV, returnT,
941
+ nowOverrideSV, windowBufferSV, pausedSV, viewEnd, viewWindow, viewRange, viewRangeGestureOwned, viewWindowSmoothingSV, allowFutureViewEndSV, returnT,
830
942
  returnFrom, snapSV, modeSV, candleGapsSV, candleGapBridgeNoTradesSV, candleGapBridgeUnavailableSV,
831
943
  candleGapBridgeUnknownSV, isFrameLoopActive, keepAwake, wakeSignal]);
832
944
 
@@ -950,6 +1062,12 @@ export function useLiveChartEngine(
950
1062
  timestamp,
951
1063
  viewEnd,
952
1064
  viewWindow,
1065
+ viewRange,
1066
+ viewRangeGestureOwned,
1067
+ fitMin,
1068
+ fitMax,
1069
+ returnT,
1070
+ returnFrom,
953
1071
  liveEdge,
954
1072
  edgeValue,
955
1073
  extremaMinValue,
package/src/draw/line.ts CHANGED
@@ -388,16 +388,24 @@ export function buildLinePoints(
388
388
  padding.top + (displayMax - (b === tailIdx ? liveTailValue! : data[b].value)) * yScale,
389
389
  );
390
390
  }
391
+ // Min/max reduction can omit the newest sample when it is not an extremum.
392
+ // Preserve its position so a line without a synthetic tip meets its live dot.
393
+ const lastIdx = endIdx - 1;
394
+ if (b !== lastIdx) {
395
+ pts.push(
396
+ padding.left + (data[lastIdx].time - winStart) * xScale,
397
+ padding.top + (displayMax - (lastIdx === tailIdx ? liveTailValue! : data[lastIdx].value)) * yScale,
398
+ );
399
+ }
391
400
  }
392
401
 
393
- // A scrolled-back / overscrolled window can end after the last data point;
394
- // the synthetic tip would then fabricate a flat segment from that point to
395
- // the right edge. Callers pass `omitTipBeyondData` to end the line at the
396
- // last real point instead.
402
+ // Without more recorded data at the head, a synthetic tip would extend the
403
+ // line into future space or overwrite the endpoint's price at the same time.
404
+ // Callers pass `omitTipBeyondData` to end at the last real point instead.
397
405
  if (
398
406
  omitTipBeyondData &&
399
407
  endIdx === data.length &&
400
- data[endIdx - 1].time < head
408
+ data[endIdx - 1].time <= head
401
409
  ) {
402
410
  return pts;
403
411
  }
@@ -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
+ }
@@ -177,16 +177,29 @@ export function useBadge(
177
177
  badgeMetrics,
178
178
  );
179
179
  // textAlign "yAxisColumn": the range the value may take inside the
180
- // pill's horizontal padding. When it doesn't fit there, it stays centered.
181
- const minTextX = bodyLeft + badgeMetrics.padX;
182
- const maxTextX = bodyRight - badgeMetrics.padX - textW;
180
+ // pill's horizontal padding. A tail-less pill keeps `padX` on both
181
+ // sides. Next to the tail, whose taper already keeps the value off the
182
+ // outline, a pill too narrow for both paddings gives up the left one
183
+ // first, then the right one, so the value never jumps as the pill
184
+ // narrows. When the paddings kept don't fit, it stays centered.
185
+ const spare = pillW - textW;
186
+ const padLeft = showTail
187
+ ? Math.min(badgeMetrics.padX, Math.max(spare - badgeMetrics.padX, 0))
188
+ : badgeMetrics.padX;
189
+ const padRight = showTail
190
+ ? Math.min(badgeMetrics.padX, Math.max(spare, 0))
191
+ : badgeMetrics.padX;
192
+ const minTextX = bodyLeft + padLeft;
193
+ const maxTextX = bodyRight - padRight - textW;
183
194
  if (
184
195
  yAxisEntries !== undefined &&
185
196
  labelRightMargin !== undefined &&
186
- minTextX <= maxTextX
197
+ // minTextX <= maxTextX, tested on `spare`: where the two bounds meet
198
+ // (a narrow tailed pill), a rounding error must not flip to centered.
199
+ padLeft <= spare - padRight
187
200
  ) {
188
201
  // Start at the labels' shared left X; a value wider than every label
189
- // ends at the column's right edge instead. Kept inside the padding, so
202
+ // ends at the column's right edge instead. Kept inside that range, so
190
203
  // the alignment gives way where the two disagree.
191
204
  const { labelX } = rightAnchoredYAxisColumnLayout(
192
205
  w,
@@ -64,6 +64,8 @@ export function useChartPaths(
64
64
  simplifyTolerance = 0,
65
65
  /** Explicit empty intervals that split line and fill geometry. */
66
66
  lineGaps: CandleGap[] = [],
67
+ /** Controlled or buffered viewports must not fabricate prices in future space. */
68
+ shouldOmitTipBeyondData = false,
67
69
  ) {
68
70
  const lineBuilder = usePathBuilder();
69
71
  const fillBuilder = usePathBuilder();
@@ -148,10 +150,10 @@ export function useChartPaths(
148
150
  engine.canvasHeight.get(),
149
151
  padding,
150
152
  simplify > 0 ? cache.rawPts : buf,
151
- // Only a live-following chart may extend the line to the right edge; a
152
- // parked (scrolled-back / overscrolled) window ends at its last real
153
- // point rather than fabricating a flat line into dataless space.
154
- engine.viewEnd.get() != null,
153
+ // Only an unbuffered live-following chart may extend to the right edge;
154
+ // controlled or parked windows end at their last real point rather than
155
+ // fabricating a flat line into dataless space.
156
+ shouldOmitTipBeyondData || engine.viewEnd.get() != null,
155
157
  );
156
158
  const chartWidth = canvasWidth - padding.left - padding.right;
157
159
  const absoluteXOffset =
@@ -2,6 +2,8 @@ import { useCallback, useEffect } from "react";
2
2
  import { useAnimatedReaction, useSharedValue } from "react-native-reanimated";
3
3
  import { scheduleOnUI } from "react-native-worklets";
4
4
 
5
+ import { MAX_FRAME_DELTA_MS } from "../constants";
6
+
5
7
  /** Wait through several unchanged frames, rather than mistaking one quiet frame for rest. */
6
8
  export const IDLE_SETTLE_MS = 160;
7
9
 
@@ -10,7 +12,7 @@ function noReaction() { "worklet"; }
10
12
 
11
13
  export function nextQuietTime(previous: number, changed: boolean, dt: number): number {
12
14
  "worklet";
13
- return changed ? 0 : previous + Math.min(Math.max(dt, 0), 34);
15
+ return changed ? 0 : previous + Math.min(Math.max(dt, 0), MAX_FRAME_DELTA_MS);
14
16
  }
15
17
 
16
18
  /**
@@ -41,7 +43,10 @@ export function useDemandFrameLoop(
41
43
  "worklet";
42
44
  if (!mounted.get() || generation.get() !== token) return;
43
45
  // Resuming never integrates the entire sleeping interval as a single frame.
44
- const dt = previous === null ? 1000 / 60 : Math.min(timestamp - previous, 34);
46
+ const dt =
47
+ previous === null
48
+ ? 1000 / 60
49
+ : Math.min(timestamp - previous, MAX_FRAME_DELTA_MS);
45
50
  previous = timestamp;
46
51
  const quiet = nextQuietTime(quietTime.get(), tick(dt), dt);
47
52
  quietTime.set(quiet);
@@ -7,7 +7,7 @@ import type { ChartPadding } from "../draw/line";
7
7
 
8
8
  /**
9
9
  * Derive the live dot position (right edge of the chart, mapped to current value).
10
- * Returns `{ dotX, dotY }` as shared values. Coordinates are set to `-100`
10
+ * Returns `{ dotX, dotY, indicatorValue }` as shared values. Coordinates are set to `-100`
11
11
  * (off-screen sentinel) when canvas dimensions are unavailable.
12
12
  *
13
13
  * With `followViewEdge` + `edgeValue`, the dot (and the value line that shares
@@ -26,15 +26,34 @@ export function useLiveDot(
26
26
  edgeValue?: SharedValue<number>,
27
27
  followViewEdge = false,
28
28
  trackWhileParked = false,
29
+ /** Keep the dot on recorded geometry when the viewport includes future space. */
30
+ shouldOmitTipBeyondData = false,
29
31
  ) {
32
+ // A line with no synthetic tip ends at its recorded price. Share that value
33
+ // with the badge so its text, the value line, and the dot stay aligned even
34
+ // while the engine's live value is still easing toward a new tick.
35
+ const indicatorValue = useDerivedValue(() => {
36
+ if (followViewEdge && edgeValue) return edgeValue.value;
37
+ if (shouldOmitTipBeyondData) {
38
+ const data = engine.data.value;
39
+ const last = data[data.length - 1];
40
+ if (last && last.time <= engine.timestamp.value) return last.value;
41
+ }
42
+ return engine.displayValue.value;
43
+ });
44
+
30
45
  const dotX = useDerivedValue(() => {
31
46
  const w = engine.canvasWidth.value;
32
47
  if (w === 0) return -100;
33
48
  const right = w - padding.right;
34
- // While parked (scrolled back / overscrolled) the live point is not at the
35
- // plot edge — track its real x so a pan doesn't lose the dot, and hide it
36
- // only once the point leaves the window.
37
- if (trackWhileParked && !followViewEdge && engine.viewEnd.value != null) {
49
+ // Buffered or parked windows can put the last point before the plot edge.
50
+ // Track its real x so a pan doesn't lose the dot, and hide it only once
51
+ // the point leaves the window.
52
+ if (
53
+ !followViewEdge &&
54
+ (shouldOmitTipBeyondData ||
55
+ (trackWhileParked && engine.viewEnd.value != null))
56
+ ) {
38
57
  const data = engine.data.value;
39
58
  const last = data[data.length - 1];
40
59
  const win = engine.displayWindow.value;
@@ -56,12 +75,8 @@ export function useLiveDot(
56
75
  const dMax = engine.displayMax.value;
57
76
  const valRange = dMax - dMin;
58
77
  if (valRange === 0) return padding.top + chartH / 2;
59
- const v =
60
- followViewEdge && edgeValue
61
- ? edgeValue.value
62
- : engine.displayValue.value;
63
- return padding.top + ((dMax - v) / valRange) * chartH;
78
+ return padding.top + ((dMax - indicatorValue.value) / valRange) * chartH;
64
79
  });
65
80
 
66
- return { dotX, dotY } as const;
81
+ return { dotX, dotY, indicatorValue } as const;
67
82
  }