react-native-livechart 4.28.1 → 4.29.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 (53) 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/SeriesToggleChips.d.ts +7 -5
  7. package/dist/components/SeriesToggleChips.d.ts.map +1 -1
  8. package/dist/constants.d.ts +6 -0
  9. package/dist/constants.d.ts.map +1 -1
  10. package/dist/core/liveChartEngineTick.d.ts +3 -1
  11. package/dist/core/liveChartEngineTick.d.ts.map +1 -1
  12. package/dist/core/resolveConfig.d.ts +4 -1
  13. package/dist/core/resolveConfig.d.ts.map +1 -1
  14. package/dist/core/useLiveChartEngine.d.ts +2 -0
  15. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  16. package/dist/core/useLiveChartSeriesEngine.d.ts +20 -15
  17. package/dist/core/useLiveChartSeriesEngine.d.ts.map +1 -1
  18. package/dist/draw/line.d.ts.map +1 -1
  19. package/dist/hooks/useBadge.d.ts.map +1 -1
  20. package/dist/hooks/useChartPaths.d.ts +3 -1
  21. package/dist/hooks/useChartPaths.d.ts.map +1 -1
  22. package/dist/hooks/useDemandFrameLoop.d.ts.map +1 -1
  23. package/dist/hooks/useLiveDot.d.ts +5 -2
  24. package/dist/hooks/useLiveDot.d.ts.map +1 -1
  25. package/dist/hooks/useMultiSeriesDegen.d.ts +7 -1
  26. package/dist/hooks/useMultiSeriesDegen.d.ts.map +1 -1
  27. package/dist/hooks/useReferenceLine.d.ts.map +1 -1
  28. package/dist/hooks/useSeriesPresentation.d.ts +13 -0
  29. package/dist/hooks/useSeriesPresentation.d.ts.map +1 -0
  30. package/dist/math/squiggly.d.ts +12 -0
  31. package/dist/math/squiggly.d.ts.map +1 -1
  32. package/dist/types.d.ts +48 -12
  33. package/dist/types.d.ts.map +1 -1
  34. package/package.json +2 -2
  35. package/src/components/LiveChart.tsx +14 -2
  36. package/src/components/LiveChartSeries.tsx +48 -103
  37. package/src/components/LoadingOverlay.tsx +44 -6
  38. package/src/components/SeriesToggleChips.tsx +14 -37
  39. package/src/constants.ts +7 -0
  40. package/src/core/liveChartEngineTick.ts +23 -2
  41. package/src/core/resolveConfig.ts +12 -2
  42. package/src/core/useLiveChartEngine.ts +8 -2
  43. package/src/core/useLiveChartSeriesEngine.ts +56 -37
  44. package/src/draw/line.ts +13 -5
  45. package/src/hooks/useBadge.ts +18 -5
  46. package/src/hooks/useChartPaths.ts +6 -4
  47. package/src/hooks/useDemandFrameLoop.ts +7 -2
  48. package/src/hooks/useLiveDot.ts +26 -11
  49. package/src/hooks/useMultiSeriesDegen.ts +17 -8
  50. package/src/hooks/useReferenceLine.ts +4 -1
  51. package/src/hooks/useSeriesPresentation.ts +133 -0
  52. package/src/math/squiggly.ts +27 -0
  53. package/src/types.ts +48 -12
@@ -20,6 +20,7 @@ import { scheduleOnRN } from "react-native-worklets";
20
20
  import {
21
21
  BADGE_METRICS_DEFAULTS,
22
22
  EMPTY_STATE_METRICS_DEFAULTS,
23
+ MS_PER_FRAME_60FPS,
23
24
  } from "../constants";
24
25
  import {
25
26
  badgeTailAndCap,
@@ -32,7 +33,12 @@ import {
32
33
  type ReanimatedPathBuilder,
33
34
  } from "../hooks/usePathBuilder";
34
35
  import { drawSpline } from "../math/spline";
35
- import { buildSquigglyPts, squiggleClockSeconds } from "../math/squiggly";
36
+ import {
37
+ buildSquigglyPts,
38
+ squiggleClockSeconds,
39
+ squiggleFrozen,
40
+ squiggleShownMsAfterFrame,
41
+ } from "../math/squiggly";
36
42
  import type {
37
43
  BadgeMetrics,
38
44
  EmptyStateMetrics,
@@ -77,6 +83,7 @@ export function LoadingOverlay({
77
83
  lineStrokeWidth,
78
84
  waveAmplitude = 14,
79
85
  waveSpeed = 1,
86
+ waveFreezeAfterMs,
80
87
  opaqueCanvas = false,
81
88
  }: {
82
89
  engine: ChartEngineLayout;
@@ -97,6 +104,11 @@ export function LoadingOverlay({
97
104
  waveAmplitude?: number;
98
105
  /** Breathing-wave speed multiplier. */
99
106
  waveSpeed?: number;
107
+ /**
108
+ * Animated time (ms) per showing of the loading / empty shell before the
109
+ * squiggle freezes (`LoadingConfig.freezeAfterMs`). Omit → no limit.
110
+ */
111
+ waveFreezeAfterMs?: number;
100
112
  /** Paint the owned background instead of erasing destination alpha. */
101
113
  opaqueCanvas?: boolean;
102
114
  /** Mirror the badge prop so labels align with GridOverlay's label positions. */
@@ -141,23 +153,49 @@ export function LoadingOverlay({
141
153
  // the engine clock between data updates, which froze the loading line with it
142
154
  // (the pulse clock in DotOverlay has the same fix). Ticks only while the shell
143
155
  // shows (loading, empty, or mid-reveal) on a chart whose frame loops run: never
144
- // on a `static` chart, while `isFrameLoopActive` is off, or at wave speed 0.
156
+ // on a `static` chart, while `isFrameLoopActive` is off, at wave speed 0, or
157
+ // once the shell has used up `freezeAfterMs`.
145
158
  const squiggleClock = useSharedValue(squiggleClockSeconds());
146
- /* istanbul ignore next -- frame-callback worklet runs on the UI thread, not in Jest */
147
- const squiggleFrames = useFrameCallback(() => {
159
+ // `freezeAfterMs`: the time the squiggle has animated in this showing of the
160
+ // loading / empty shell, in frames drawn (only counted with a limit). The
161
+ // reveal doesn't count: it is bounded by its own duration, and its morph
162
+ // phases its wave on the wall clock, so a shell frozen through it would show
163
+ // two waves out of step.
164
+ const squiggleShownMs = useSharedValue(0);
165
+ const squiggleFrames = useFrameCallback((frame) => {
148
166
  if (isFrameLoopActive?.get() === false) return;
149
- squiggleClock.value = squiggleClockSeconds();
167
+ if (waveFreezeAfterMs !== undefined && (isLoading.get() || isEmpty.value)) {
168
+ const shown = squiggleShownMsAfterFrame(
169
+ squiggleShownMs.get(),
170
+ frame.timeSincePreviousFrame ?? MS_PER_FRAME_60FPS,
171
+ );
172
+ squiggleShownMs.set(shown);
173
+ // Out of time: freeze. The reaction below stops this callback.
174
+ if (squiggleFrozen(shown, waveFreezeAfterMs)) return;
175
+ }
176
+ squiggleClock.set(squiggleClockSeconds());
150
177
  }, false);
151
178
  const setSquiggleTicking = useCallback(
152
179
  (on: boolean) => squiggleFrames.setActive(on),
153
180
  [squiggleFrames],
154
181
  );
182
+ // Each time the shell appears (on mount, or after data has shown), the
183
+ // squiggle gets the whole `freezeAfterMs` again. Loading and the empty state
184
+ // that follows it share one.
185
+ useAnimatedReaction(
186
+ () => isLoading.get() || isEmpty.value,
187
+ (shown, previous) => {
188
+ if (shown && shown !== previous) squiggleShownMs.set(0);
189
+ },
190
+ );
155
191
  useAnimatedReaction(
156
192
  () =>
157
193
  !isStatic &&
158
194
  waveSpeed !== 0 &&
159
195
  isFrameLoopActive?.get() !== false &&
160
- (isLoading.get() || isEmpty.value || morphT.get() < 1),
196
+ (isLoading.get() || isEmpty.value
197
+ ? !squiggleFrozen(squiggleShownMs.get(), waveFreezeAfterMs)
198
+ : morphT.get() < 1),
161
199
  (ticking, previous) => {
162
200
  if (ticking === previous) return;
163
201
  // Start from now, not from wherever the clock stopped when the shell last hid:
@@ -1,11 +1,9 @@
1
- import { useState } from "react";
2
1
  import { Pressable, StyleSheet, Text, View } from "react-native";
3
- import { useAnimatedReaction, type SharedValue } from "react-native-reanimated";
4
- import { scheduleOnRN } from "react-native-worklets";
2
+ import type { SharedValue } from "react-native-reanimated";
5
3
  import { MONO_FONT_FAMILY } from "../lib/monoFontFamily";
6
4
  import type { ResolvedLegendConfig } from "../core/resolveConfig";
7
5
  import type { LiveChartPalette, SeriesConfig } from "../types";
8
- import { seriesMetaSig } from "./seriesMetaSig";
6
+ import { useSeriesPresentation } from "../hooks/useSeriesPresentation";
9
7
 
10
8
  export interface SeriesToggleChipsProps {
11
9
  series: SharedValue<SeriesConfig[]>;
@@ -40,39 +38,18 @@ function legendColorDefaults(palette: LiveChartPalette | undefined) {
40
38
  };
41
39
  }
42
40
 
43
- /**
44
- * Mirrors `series` into React state when id/label/color/visibility changes (not on every data tick).
45
- */
46
- export function SeriesToggleChips({
47
- series,
48
- legend,
49
- palette,
50
- onSeriesToggle,
51
- }: SeriesToggleChipsProps) {
52
- // Seed from the current series at mount; the reaction below keeps it in sync.
53
- const [snapshot, setSnapshot] = useState<SeriesConfig[]>(() =>
54
- series.get().slice(),
55
- );
56
-
57
- // Read the `series` prop from closure rather than a SharedValue passed
58
- // through `scheduleOnRN`: the handle serialized across the worklet→JS
59
- // boundary exposes the native `.value` accessor but NOT the `.get()` method,
60
- // so calling `.get()` on it throws ("sv.get is not a function").
61
- const pullSnapshot = () => {
62
- setSnapshot(series.get().slice());
63
- };
64
-
65
- useAnimatedReaction(
66
- () => seriesMetaSig(series.get()),
67
- /* istanbul ignore next -- Reanimated reaction; snapshot seeded at mount, pulled here on change */
68
- (sig, prev) => {
69
- if (sig !== prev) {
70
- scheduleOnRN(pullSnapshot);
71
- }
72
- },
73
- [series, pullSnapshot],
74
- );
41
+ /** Standalone wrapper; LiveChartSeries shares its controller snapshot instead. */
42
+ export function SeriesToggleChips(props: SeriesToggleChipsProps) {
43
+ const { snapshot, refresh } = useSeriesPresentation(props.series);
44
+ return <SeriesToggleChipsView {...props} snapshot={snapshot} onSnapshotChange={refresh} />;
45
+ }
75
46
 
47
+ export function SeriesToggleChipsView({
48
+ series, legend, palette, onSeriesToggle, snapshot, onSnapshotChange,
49
+ }: SeriesToggleChipsProps & {
50
+ snapshot: SeriesConfig[];
51
+ onSnapshotChange: () => void;
52
+ }) {
76
53
  if (!legend.visible) return null;
77
54
 
78
55
  const toggle = (id: string) => {
@@ -86,7 +63,7 @@ export function SeriesToggleChips({
86
63
  i === idx ? { ...s, visible: nextVisible } : s,
87
64
  );
88
65
  series.set(next);
89
- setSnapshot(next);
66
+ onSnapshotChange();
90
67
  onSeriesToggle?.(id, nextVisible);
91
68
  };
92
69
 
package/src/constants.ts CHANGED
@@ -9,6 +9,13 @@ import type {
9
9
  /** Milliseconds per frame at 60 fps — baseline for frame-rate-independent lerp. */
10
10
  export const MS_PER_FRAME_60FPS = 16.67;
11
11
 
12
+ /**
13
+ * Longest frame delta (ms) that time counted in frames takes from one frame —
14
+ * about two 60fps frames — so the first frame back from the background, or
15
+ * after a stall, counts as one frame rather than the time away.
16
+ */
17
+ export const MAX_FRAME_DELTA_MS = 34;
18
+
12
19
  /**
13
20
  * Initial size of the Y-axis label pool. The pool grows when the dynamic
14
21
  * (nice-interval) grid produces more labels (a tall plot or a small `minGap`);
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  CandleGap,
3
3
  CandlePoint,
4
+ ChartScale,
4
5
  LiveChartPoint,
5
6
  RangeAnimationConfig,
6
7
  } from "../types";
@@ -92,6 +93,8 @@ export interface EngineTickInput {
92
93
  minRange?: number;
93
94
  /** Positive, finite Y-range multiplier around the fitted midpoint (1 = auto-fit). */
94
95
  yRangeScale?: number;
96
+ /** Explicit finite price bounds for a freely positioned external viewport. */
97
+ viewRange?: Pick<ChartScale, "min" | "max"> | null;
95
98
  targetValue: number;
96
99
  points: LiveChartPoint[];
97
100
  /** Internal notification revision for the selected history; omit to disable reuse. */
@@ -218,6 +221,17 @@ export function tickLiveChartEngineFrame(
218
221
  const timestampSecondsPerPixel =
219
222
  Math.min(state.displayWindow, targetWindow) / input.canvasWidth;
220
223
  const viewEnd = input.viewEnd;
224
+ const requestedRange = input.viewRange;
225
+ const viewRange =
226
+ viewEnd != null &&
227
+ Number.isFinite(viewEnd) &&
228
+ requestedRange &&
229
+ Number.isFinite(requestedRange.min) &&
230
+ Number.isFinite(requestedRange.max) &&
231
+ requestedRange.min < requestedRange.max &&
232
+ Number.isFinite(requestedRange.max - requestedRange.min)
233
+ ? requestedRange
234
+ : undefined;
221
235
  // First time of the visible series' data — the floor a frozen edge must stay
222
236
  // at or above. `-Infinity` when there's no data to bound against, so the freeze
223
237
  // still works (we can't strand a plot we have no time bounds for).
@@ -235,10 +249,11 @@ export function tickLiveChartEngineFrame(
235
249
  // time-scroll is disabled the hook clears `viewEnd` (and kicks off the glide
236
250
  // below), so a stale edge can't keep the window frozen. See #164. With
237
251
  // `allowFutureViewEnd` (timeScroll.overscroll) an edge parked past live is
238
- // honored too — the data-overlap strand-guard stays in both modes.
252
+ // honored too. Valid explicit price bounds let external editors position
253
+ // before the first sample as well, without an empty auto-fit to resolve.
239
254
  const scrolledBack =
240
255
  viewEnd != null &&
241
- viewEnd >= firstDataTime &&
256
+ (viewRange !== undefined || viewEnd >= firstDataTime) &&
242
257
  (viewEnd < liveEdge || input.allowFutureViewEnd === true);
243
258
  const canvasChanged =
244
259
  state.lastCanvasWidth !== input.canvasWidth ||
@@ -560,6 +575,12 @@ export function tickLiveChartEngineFrame(
560
575
  }
561
576
  }
562
577
 
578
+ // Explicit bounds keep a gesture's price coordinates stable, even in empty space.
579
+ if (viewRange) {
580
+ state.displayMin = viewRange.min;
581
+ state.displayMax = viewRange.max;
582
+ }
583
+
563
584
  // Edge value: the price at the visible window's right edge. Following live →
564
585
  // track the live value (badge unchanged). Scrolled back → track the last
565
586
  // visible point/candle close, lerped so a `followViewEdge` badge glides to the
@@ -779,6 +779,7 @@ export function resolveViewport(
779
779
  return {
780
780
  end: prop.end,
781
781
  window: prop.window,
782
+ range: prop.range,
782
783
  windowSmoothing: prop.windowSmoothing ?? VIEWPORT_DEFAULTS.windowSmoothing,
783
784
  };
784
785
  }
@@ -1134,6 +1135,8 @@ export interface ResolvedLoadingConfig {
1134
1135
  speed: number;
1135
1136
  /** Draw the skeleton Y-axis label placeholders. */
1136
1137
  axisLabels: boolean;
1138
+ /** undefined → never frozen: the squiggle animates while the shell shows */
1139
+ freezeAfterMs: number | undefined;
1137
1140
  }
1138
1141
 
1139
1142
  const LOADING_DEFAULTS: ResolvedLoadingConfig = {
@@ -1142,18 +1145,25 @@ const LOADING_DEFAULTS: ResolvedLoadingConfig = {
1142
1145
  amplitude: LOADING_WAVE_AMPLITUDE,
1143
1146
  speed: LOADING_WAVE_SPEED,
1144
1147
  axisLabels: true,
1148
+ freezeAfterMs: undefined,
1145
1149
  };
1146
1150
 
1147
1151
  /**
1148
1152
  * Resolves the `loading` prop to a fully-typed config or null (not loading).
1149
1153
  * `true` → defaults (loading on, built-in look), object → merged with defaults
1150
1154
  * (loading on, restyled), `false` / omitted → null. So a non-null result is the
1151
- * "is loading" flag and carries the resolved styling.
1155
+ * "is loading" flag and carries the resolved styling. A `freezeAfterMs` of
1156
+ * `NaN` or `Infinity` resolves to `undefined`: no limit, and no frame counting.
1152
1157
  */
1153
1158
  export function resolveLoading(
1154
1159
  prop: boolean | LoadingConfig | undefined,
1155
1160
  ): ResolvedLoadingConfig | null {
1156
- return resolveToggle(prop, LOADING_DEFAULTS, false);
1161
+ const resolved = resolveToggle(prop, LOADING_DEFAULTS, false);
1162
+ if (resolved === null) return null;
1163
+ const { freezeAfterMs } = resolved;
1164
+ return Number.isNaN(freezeAfterMs) || freezeAfterMs === Infinity
1165
+ ? { ...resolved, freezeAfterMs: undefined }
1166
+ : resolved;
1157
1167
  }
1158
1168
 
1159
1169
  const SCRUB_ACTION_DEFAULTS: ResolvedScrubActionConfig = {
@@ -267,6 +267,8 @@ export interface EngineFrameRefs {
267
267
  maxValueSV?: SharedValue<number | undefined>;
268
268
  minRangeSV?: SharedValue<number | undefined>;
269
269
  yRangeScaleSV?: SharedValue<number>;
270
+ /** External price bounds read in the same frame as end/window. */
271
+ viewRangeSV?: ResolvedViewportConfig["range"];
270
272
  nowOverrideSV?: SharedValue<number | undefined>;
271
273
  windowBufferSV?: SharedValue<number>;
272
274
  pausedSV: SharedValue<boolean>;
@@ -415,6 +417,7 @@ export function applyLiveChartEngineFrame(
415
417
  input.maxValue = sv.maxValueSV?.value;
416
418
  input.minRange = sv.minRangeSV?.value;
417
419
  input.yRangeScale = sv.yRangeScaleSV?.value ?? 1;
420
+ input.viewRange = sv.viewRangeSV?.value;
418
421
  input.nowOverride = sv.nowOverrideSV?.value;
419
422
  input.windowBuffer = sv.windowBufferSV?.value ?? 0;
420
423
  input.targetValue = sv.value.value;
@@ -517,6 +520,7 @@ export function useLiveChartEngine(
517
520
  const internalViewWindow = useSharedValue<number | null>(null);
518
521
  const viewWindow = viewport?.window ?? internalViewWindow;
519
522
  const hasViewport = viewport != null;
523
+ const viewRange = viewport?.range;
520
524
  const windowSmoothing = viewport?.windowSmoothing ?? true;
521
525
  const viewWindowSmoothingSV = useDerivedValue(() => windowSmoothing);
522
526
  // A change to the `timeWindow` prop (a range / timeframe selector) is an explicit
@@ -695,6 +699,7 @@ export function useLiveChartEngine(
695
699
  maxValueSV,
696
700
  minRangeSV,
697
701
  yRangeScaleSV: yRangeScale,
702
+ viewRangeSV: viewRange,
698
703
  nowOverrideSV,
699
704
  windowBufferSV,
700
705
  pausedSV,
@@ -766,6 +771,7 @@ export function useLiveChartEngine(
766
771
  viewEnd,
767
772
  viewWindow,
768
773
  viewWindowSmoothingSV,
774
+ viewRange,
769
775
  windowBufferSV,
770
776
  yRangeScale,
771
777
  ],
@@ -819,14 +825,14 @@ export function useLiveChartEngine(
819
825
  exaggerateSV.get(), referenceValue.get(), referenceValues.get(), thresholdRangePoints.get(),
820
826
  thresholdRangeExtendToStart.get(), thresholdRangeExtendToNow.get(), nonNegativeSV.get(),
821
827
  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(),
828
+ viewEnd.get(), viewWindow.get(), viewRange?.get(), viewWindowSmoothingSV.get(), allowFutureViewEndSV.get(), returnT.get(), returnFrom.get(),
823
829
  snapSV.get(), modeSV.get(), candleGapsSV.get(), candleGapBridgeNoTradesSV.get(),
824
830
  candleGapBridgeUnavailableSV.get(), candleGapBridgeUnknownSV.get(), isFrameLoopActive?.get(),
825
831
  keepAwake?.get(), wakeSignal?.get()];
826
832
  }, [pointHistory, candleHistory, data, value, candles, liveCandle, canvasWidth, canvasHeight, timeWindow, smoothing, rangeAnimationSV,
827
833
  adaptiveSpeedBoostSV, exaggerateSV, referenceValue, referenceValues, thresholdRangePoints,
828
834
  thresholdRangeExtendToStart, thresholdRangeExtendToNow, nonNegativeSV, maxValueSV, minRangeSV, yRangeScale,
829
- nowOverrideSV, windowBufferSV, pausedSV, viewEnd, viewWindow, viewWindowSmoothingSV, allowFutureViewEndSV, returnT,
835
+ nowOverrideSV, windowBufferSV, pausedSV, viewEnd, viewWindow, viewRange, viewWindowSmoothingSV, allowFutureViewEndSV, returnT,
830
836
  returnFrom, snapSV, modeSV, candleGapsSV, candleGapBridgeNoTradesSV, candleGapBridgeUnavailableSV,
831
837
  candleGapBridgeUnknownSV, isFrameLoopActive, keepAwake, wakeSignal]);
832
838
 
@@ -66,6 +66,9 @@ export interface MultiSeriesEngineConfig {
66
66
  snapKey?: string | number;
67
67
  }
68
68
 
69
+ /** Constant React props copied with the frame worklet; no mapper/SharedValue is needed. */
70
+ type FrameParameter<T> = Pick<SharedValue<T>, "value">;
71
+
69
72
  export interface MultiEngineFrameRefs {
70
73
  series: SharedValue<SeriesConfig[]>;
71
74
  /** Drawing input published with this frame's range/tips. Optional for standalone callers. */
@@ -82,28 +85,28 @@ export interface MultiEngineFrameRefs {
82
85
  timestamp: SharedValue<number>;
83
86
  canvasWidth: SharedValue<number>;
84
87
  canvasHeight: SharedValue<number>;
85
- timeWindow: SharedValue<number>;
86
- smoothing: SharedValue<number>;
87
- rangeAnimationSV?: SharedValue<SeriesRangeAnimationConfig | undefined>;
88
- adaptiveSpeedBoostSV?: SharedValue<number | undefined>;
89
- exaggerateSV: SharedValue<boolean>;
90
- referenceValue: SharedValue<number | undefined>;
91
- referenceValues?: SharedValue<number[] | undefined>;
92
- nonNegativeSV?: SharedValue<boolean>;
93
- maxValueSV?: SharedValue<number | undefined>;
94
- minRangeSV?: SharedValue<number | undefined>;
88
+ timeWindow: FrameParameter<number>;
89
+ smoothing: FrameParameter<number>;
90
+ rangeAnimationSV?: FrameParameter<SeriesRangeAnimationConfig | undefined>;
91
+ adaptiveSpeedBoostSV?: FrameParameter<number | undefined>;
92
+ exaggerateSV: FrameParameter<boolean>;
93
+ referenceValue: FrameParameter<number | undefined>;
94
+ referenceValues?: FrameParameter<number[] | undefined>;
95
+ nonNegativeSV?: FrameParameter<boolean>;
96
+ maxValueSV?: FrameParameter<number | undefined>;
97
+ minRangeSV?: FrameParameter<number | undefined>;
95
98
  yRangeScaleSV?: SharedValue<number>;
96
- nowOverrideSV?: SharedValue<number | undefined>;
99
+ nowOverrideSV?: FrameParameter<number | undefined>;
97
100
  presentationTimeSV?: SharedValue<number | undefined>;
98
- historyStartTimeSV?: SharedValue<number | undefined>;
101
+ historyStartTimeSV?: FrameParameter<number | undefined>;
99
102
  currentTimeSV?: SharedValue<number>;
100
103
  fullHistoryWindowSV?: SharedValue<number | null>;
101
- windowBufferSV?: SharedValue<number>;
102
- pausedSV: SharedValue<boolean>;
104
+ windowBufferSV?: FrameParameter<number>;
105
+ pausedSV: FrameParameter<boolean>;
103
106
  /** Pan-scroll right-edge override (null = follow live). Optional for callers/tests. */
104
107
  viewEndSV?: SharedValue<number | null>;
105
108
  /** Honor a `viewEnd` past the live edge (timeScroll.overscroll). Optional. */
106
- allowFutureViewEndSV?: SharedValue<boolean>;
109
+ allowFutureViewEndSV?: FrameParameter<boolean>;
107
110
  /** "Return to live" glide progress (0→1); the right edge eases to live. Optional. */
108
111
  returnTSV?: SharedValue<number>;
109
112
  /** Frozen right-edge time the return glide starts from. Optional. */
@@ -118,6 +121,8 @@ export interface MultiEngineFrameRefs {
118
121
  * tick. Optional for callers/tests.
119
122
  */
120
123
  snapSV?: SharedValue<boolean>;
124
+ /** Wait for measured, visible data before fitting the initial range. */
125
+ initialFitPendingSV?: SharedValue<boolean>;
121
126
  extremaMinValue: SharedValue<number>;
122
127
  extremaMaxValue: SharedValue<number>;
123
128
  extremaMinTime: SharedValue<number>;
@@ -198,6 +203,16 @@ export function applyLiveChartSeriesEngineFrame(
198
203
  // and clear it below so only this frame snaps (live ticks stay smoothed).
199
204
  const snap = sv.snapSV?.value ?? false;
200
205
  const seriesSnap = sv.series.value;
206
+ let initialFit = false;
207
+ if (sv.initialFitPendingSV?.value && sv.canvasWidth.value > 0 && sv.canvasHeight.value > 0) {
208
+ for (let i = 0; i < seriesSnap.length; i++) {
209
+ const s = seriesSnap[i];
210
+ if (s.visible !== false && s.data.length > 0 && Number.isFinite(s.value)) {
211
+ initialFit = true;
212
+ break;
213
+ }
214
+ }
215
+ }
201
216
  const curDv = sv.displaySeriesValues.value;
202
217
  const curOp = sv.seriesOpacities.value;
203
218
  let displayValues: number[];
@@ -272,7 +287,7 @@ export function applyLiveChartSeriesEngineFrame(
272
287
  input.series = seriesSnap;
273
288
  input.nowSeconds = Date.now() / 1000;
274
289
  input.paused = sv.pausedSV.value;
275
- input.snap = snap;
290
+ input.snap = snap || initialFit;
276
291
  input.viewEnd = sv.viewEndSV?.value;
277
292
  input.allowFutureViewEnd = sv.allowFutureViewEndSV?.value ?? false;
278
293
  input.returnT = sv.returnTSV?.value;
@@ -306,6 +321,7 @@ export function applyLiveChartSeriesEngineFrame(
306
321
  }
307
322
  sv.renderedSeries.value = rendered;
308
323
  }
324
+ if (initialFit && sv.initialFitPendingSV) sv.initialFitPendingSV.value = false;
309
325
  // Clear the one-shot snap so the next frame eases normally again — but only
310
326
  // once a real (measured) frame consumed it (the tick early-returns on a
311
327
  // zero-size canvas before applying the snap). See applyLiveChartEngineFrame.
@@ -329,31 +345,30 @@ export function useLiveChartSeriesEngine(
329
345
  const viewWindow = useSharedValue<number | null>(null);
330
346
  const fullHistoryWindow = useSharedValue<number | null>(null);
331
347
  const timeWindow = useDerivedValue(() => viewWindow.value ?? fullHistoryWindow.value ?? config.timeWindow);
332
- const configuredTimeWindow = useDerivedValue(() => config.timeWindow);
333
- const historyStartTimeSV = useDerivedValue(() => config.historyStartTime);
334
- const smoothing = useDerivedValue(() => config.smoothing);
335
- const rangeAnimationSV = useDerivedValue(() => config.rangeAnimation);
336
- const adaptiveSpeedBoostSV = useDerivedValue(() => config.adaptiveSpeedBoost);
337
- const exaggerateSV = useDerivedValue(() => config.exaggerate ?? false);
338
- const referenceValue = useDerivedValue(() => config.referenceValue);
339
- const referenceValues = useDerivedValue(() => config.referenceValues);
340
- const nonNegativeSV = useDerivedValue(() => config.nonNegative ?? false);
341
- const maxValueSV = useDerivedValue(() => config.maxValue);
342
- const minRangeSV = useDerivedValue(() => config.minRange);
343
- const nowOverrideSV = useDerivedValue(() => config.nowOverride);
344
- const windowBufferSV = useDerivedValue(() => config.windowBuffer ?? 0);
345
- const pausedSV = useDerivedValue(() => config.paused ?? false);
348
+ // These are React props, not UI-thread signals. The registered frame and
349
+ // return-to-live worklets capture a fresh snapshot when props change. Keeping
350
+ // them as plain values avoids one native mutable and mapper per parameter.
351
+ const configuredTimeWindow = { value: config.timeWindow };
352
+ const historyStartTimeSV = { value: config.historyStartTime };
353
+ const smoothing = { value: config.smoothing };
354
+ const rangeAnimationSV = { value: config.rangeAnimation };
355
+ const adaptiveSpeedBoostSV = { value: config.adaptiveSpeedBoost };
356
+ const exaggerateSV = { value: config.exaggerate ?? false };
357
+ const referenceValue = { value: config.referenceValue };
358
+ const referenceValues = { value: config.referenceValues };
359
+ const nonNegativeSV = { value: config.nonNegative ?? false };
360
+ const maxValueSV = { value: config.maxValue };
361
+ const minRangeSV = { value: config.minRange };
362
+ const nowOverrideSV = { value: config.nowOverride };
363
+ const windowBufferSV = { value: config.windowBuffer ?? 0 };
364
+ const pausedSV = { value: config.paused ?? false };
346
365
  // Whether time-scroll is active — drives the return-to-live reaction below.
347
366
  // Defaults to enabled (legacy behavior).
348
- const scrollEnabledSV = useDerivedValue(() => config.scrollEnabled ?? true);
367
+ const scrollEnabledSV = { value: config.scrollEnabled ?? true };
349
368
  // Honor a viewEnd parked past the live edge (timeScroll.overscroll).
350
- const allowFutureViewEndSV = useDerivedValue(
351
- () => config.allowFutureViewEnd ?? false,
352
- );
369
+ const allowFutureViewEndSV = { value: config.allowFutureViewEnd ?? false };
353
370
  // Return-to-live glide duration (ms); 0 = instant snap. Read by the reaction.
354
- const returnToLiveMsSV = useDerivedValue(
355
- () => config.returnToLiveMs ?? RETURN_TO_LIVE_MS,
356
- );
371
+ const returnToLiveMsSV = { value: config.returnToLiveMs ?? RETURN_TO_LIVE_MS };
357
372
 
358
373
  const displayMin = useSharedValue(0);
359
374
  const displayMax = useSharedValue(1);
@@ -394,6 +409,9 @@ export function useLiveChartSeriesEngine(
394
409
  // One-shot "snap the framing" flag — flipped by the effect when `snapKey`
395
410
  // changes, consumed + cleared by the next frame (mirrors useLiveChartEngine).
396
411
  const snapSV = useSharedValue(false);
412
+ // A placeholder 0–1 range must not delay the first visible chart when
413
+ // expansion animation is enabled. Consume this only after data and size arrive.
414
+ const initialFitPendingSV = useSharedValue(true);
397
415
  const lastSnapKey = useRef(config.snapKey);
398
416
  // Layout effect so the snap flag lands before the commit paints — a passive
399
417
  // effect leaves one frame of new data in the old framing (mirrors useLiveChartEngine).
@@ -452,6 +470,7 @@ export function useLiveChartSeriesEngine(
452
470
  viewWindowSV: viewWindow,
453
471
  liveEdgeSV: liveEdge,
454
472
  snapSV,
473
+ initialFitPendingSV,
455
474
  extremaMinValue,
456
475
  extremaMaxValue,
457
476
  extremaMinTime,
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
  }
@@ -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);