react-native-livechart 4.26.0 → 4.28.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 (142) 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/MultiSeriesDots.d.ts +1 -1
  9. package/dist/components/MultiSeriesDots.d.ts.map +1 -1
  10. package/dist/components/MultiSeriesValueLabels.d.ts +1 -1
  11. package/dist/components/MultiSeriesValueLabels.d.ts.map +1 -1
  12. package/dist/components/MultiSeriesValueLines.d.ts +1 -1
  13. package/dist/components/MultiSeriesValueLines.d.ts.map +1 -1
  14. package/dist/components/ReferenceLineOverlay.d.ts +4 -0
  15. package/dist/components/ReferenceLineOverlay.d.ts.map +1 -1
  16. package/dist/components/ReferenceValueBadge.d.ts +15 -0
  17. package/dist/components/ReferenceValueBadge.d.ts.map +1 -0
  18. package/dist/components/XAxisOverlay.d.ts +17 -0
  19. package/dist/components/XAxisOverlay.d.ts.map +1 -1
  20. package/dist/core/liveChartEngineTick.d.ts +4 -0
  21. package/dist/core/liveChartEngineTick.d.ts.map +1 -1
  22. package/dist/core/liveChartSeriesEngineTick.d.ts +15 -2
  23. package/dist/core/liveChartSeriesEngineTick.d.ts.map +1 -1
  24. package/dist/core/resolveConfig.d.ts +28 -1
  25. package/dist/core/resolveConfig.d.ts.map +1 -1
  26. package/dist/core/useLiveChartEngine.d.ts +9 -0
  27. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  28. package/dist/core/useLiveChartSeriesEngine.d.ts +18 -4
  29. package/dist/core/useLiveChartSeriesEngine.d.ts.map +1 -1
  30. package/dist/draw/grid.d.ts +6 -4
  31. package/dist/draw/grid.d.ts.map +1 -1
  32. package/dist/draw/line.d.ts +21 -3
  33. package/dist/draw/line.d.ts.map +1 -1
  34. package/dist/hooks/crosshairSeries.d.ts +2 -2
  35. package/dist/hooks/crosshairSeries.d.ts.map +1 -1
  36. package/dist/hooks/crosshairShared.d.ts +16 -1
  37. package/dist/hooks/crosshairShared.d.ts.map +1 -1
  38. package/dist/hooks/referenceBadgeFont.d.ts +5 -0
  39. package/dist/hooks/referenceBadgeFont.d.ts.map +1 -0
  40. package/dist/hooks/resolveChartLayout.d.ts +18 -2
  41. package/dist/hooks/resolveChartLayout.d.ts.map +1 -1
  42. package/dist/hooks/useBadge.d.ts +16 -1
  43. package/dist/hooks/useBadge.d.ts.map +1 -1
  44. package/dist/hooks/useChartSkiaFont.d.ts +1 -0
  45. package/dist/hooks/useChartSkiaFont.d.ts.map +1 -1
  46. package/dist/hooks/useCrosshair.d.ts +7 -2
  47. package/dist/hooks/useCrosshair.d.ts.map +1 -1
  48. package/dist/hooks/useCrosshairSeries.d.ts +6 -1
  49. package/dist/hooks/useCrosshairSeries.d.ts.map +1 -1
  50. package/dist/hooks/useLatestCallback.d.ts +6 -0
  51. package/dist/hooks/useLatestCallback.d.ts.map +1 -0
  52. package/dist/hooks/useMarkers.d.ts.map +1 -1
  53. package/dist/hooks/useMultiSeriesDegen.d.ts +1 -1
  54. package/dist/hooks/useMultiSeriesDegen.d.ts.map +1 -1
  55. package/dist/hooks/useMultiSeriesLinePaths.d.ts.map +1 -1
  56. package/dist/hooks/usePanScroll.d.ts +3 -1
  57. package/dist/hooks/usePanScroll.d.ts.map +1 -1
  58. package/dist/hooks/usePinchZoom.d.ts +7 -4
  59. package/dist/hooks/usePinchZoom.d.ts.map +1 -1
  60. package/dist/hooks/useReferenceDrag.d.ts +20 -5
  61. package/dist/hooks/useReferenceDrag.d.ts.map +1 -1
  62. package/dist/hooks/useReferenceLine.d.ts +24 -12
  63. package/dist/hooks/useReferenceLine.d.ts.map +1 -1
  64. package/dist/hooks/useReferenceLinePress.d.ts +4 -2
  65. package/dist/hooks/useReferenceLinePress.d.ts.map +1 -1
  66. package/dist/hooks/useReferenceTagStack.d.ts +31 -0
  67. package/dist/hooks/useReferenceTagStack.d.ts.map +1 -0
  68. package/dist/hooks/useScrubMarkers.d.ts +12 -0
  69. package/dist/hooks/useScrubMarkers.d.ts.map +1 -0
  70. package/dist/hooks/useXAxis.d.ts +1 -1
  71. package/dist/hooks/useXAxis.d.ts.map +1 -1
  72. package/dist/hooks/useYAxis.d.ts +1 -1
  73. package/dist/hooks/useYAxis.d.ts.map +1 -1
  74. package/dist/hooks/useYAxisLabelWidth.d.ts +6 -0
  75. package/dist/hooks/useYAxisLabelWidth.d.ts.map +1 -0
  76. package/dist/hooks/useYAxisScaleGesture.d.ts +34 -0
  77. package/dist/hooks/useYAxisScaleGesture.d.ts.map +1 -0
  78. package/dist/index.d.ts +1 -1
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/math/axisBadgeLayout.d.ts +16 -0
  81. package/dist/math/axisBadgeLayout.d.ts.map +1 -0
  82. package/dist/math/markers.d.ts +3 -0
  83. package/dist/math/markers.d.ts.map +1 -1
  84. package/dist/math/range.d.ts +1 -1
  85. package/dist/math/range.d.ts.map +1 -1
  86. package/dist/math/referenceLines.d.ts.map +1 -1
  87. package/dist/math/referenceTagStack.d.ts +36 -0
  88. package/dist/math/referenceTagStack.d.ts.map +1 -0
  89. package/dist/math/scrubMarkers.d.ts +12 -0
  90. package/dist/math/scrubMarkers.d.ts.map +1 -0
  91. package/dist/types.d.ts +262 -37
  92. package/dist/types.d.ts.map +1 -1
  93. package/package.json +1 -1
  94. package/src/components/CustomReferenceLineOverlay.tsx +50 -8
  95. package/src/components/CustomTooltipOverlay.tsx +5 -1
  96. package/src/components/LiveChart.tsx +580 -138
  97. package/src/components/LiveChartSeries.tsx +139 -19
  98. package/src/components/MultiSeriesDots.tsx +4 -2
  99. package/src/components/MultiSeriesValueLabels.tsx +4 -2
  100. package/src/components/MultiSeriesValueLines.tsx +4 -2
  101. package/src/components/ReferenceLineOverlay.tsx +62 -26
  102. package/src/components/ReferenceValueBadge.tsx +102 -0
  103. package/src/components/XAxisOverlay.tsx +104 -1
  104. package/src/core/liveChartEngineTick.ts +49 -4
  105. package/src/core/liveChartSeriesEngineTick.ts +107 -14
  106. package/src/core/resolveConfig.ts +103 -7
  107. package/src/core/useLiveChartEngine.ts +45 -9
  108. package/src/core/useLiveChartSeriesEngine.ts +47 -6
  109. package/src/draw/grid.ts +17 -13
  110. package/src/draw/line.ts +46 -5
  111. package/src/hooks/crosshairSeries.ts +37 -5
  112. package/src/hooks/crosshairShared.ts +56 -1
  113. package/src/hooks/referenceBadgeFont.ts +35 -0
  114. package/src/hooks/resolveChartLayout.ts +51 -3
  115. package/src/hooks/useBadge.ts +44 -5
  116. package/src/hooks/useChartSkiaFont.ts +1 -1
  117. package/src/hooks/useCrosshair.ts +444 -310
  118. package/src/hooks/useCrosshairSeries.ts +57 -20
  119. package/src/hooks/useLatestCallback.ts +15 -0
  120. package/src/hooks/useMarkers.ts +51 -39
  121. package/src/hooks/useMultiSeriesDegen.ts +10 -5
  122. package/src/hooks/useMultiSeriesLinePaths.ts +2 -0
  123. package/src/hooks/usePanScroll.ts +155 -127
  124. package/src/hooks/usePinchZoom.ts +94 -66
  125. package/src/hooks/useReferenceDrag.ts +409 -156
  126. package/src/hooks/useReferenceLine.ts +453 -277
  127. package/src/hooks/useReferenceLineGrouping.ts +1 -1
  128. package/src/hooks/useReferenceLinePress.ts +121 -53
  129. package/src/hooks/useReferenceTagStack.ts +81 -0
  130. package/src/hooks/useScrubMarkers.ts +79 -0
  131. package/src/hooks/useXAxis.ts +11 -2
  132. package/src/hooks/useYAxis.ts +1 -1
  133. package/src/hooks/useYAxisLabelWidth.ts +26 -0
  134. package/src/hooks/useYAxisScaleGesture.ts +263 -0
  135. package/src/index.ts +11 -0
  136. package/src/math/axisBadgeLayout.ts +37 -0
  137. package/src/math/markers.ts +28 -3
  138. package/src/math/range.ts +35 -0
  139. package/src/math/referenceLines.ts +5 -0
  140. package/src/math/referenceTagStack.ts +112 -0
  141. package/src/math/scrubMarkers.ts +55 -0
  142. package/src/types.ts +263 -37
@@ -10,7 +10,7 @@ import {
10
10
  type SharedValue,
11
11
  } from "react-native-reanimated";
12
12
  import { MS_PER_FRAME_60FPS, RETURN_TO_LIVE_MS } from "../constants";
13
- import type { LiveChartPoint, RangeAnimationConfig, SeriesConfig } from "../types";
13
+ import type { LiveChartPoint, SeriesRangeAnimationConfig, SeriesConfig } from "../types";
14
14
  import {
15
15
  tickLiveChartSeriesEngineFrame,
16
16
  type MultiEngineTickInput,
@@ -21,8 +21,9 @@ import type { ChartEngineScroll, MultiEngineState } from "./useLiveChartEngine";
21
21
  export interface MultiSeriesEngineConfig {
22
22
  series: SharedValue<SeriesConfig[]>;
23
23
  timeWindow: number;
24
+ historyStartTime?: number;
24
25
  smoothing: number;
25
- rangeAnimation?: RangeAnimationConfig;
26
+ rangeAnimation?: SeriesRangeAnimationConfig;
26
27
  /** Extra catch-up speed added to `smoothing` when a series tip lags. */
27
28
  adaptiveSpeedBoost?: number;
28
29
  exaggerate?: boolean;
@@ -30,9 +31,11 @@ export interface MultiSeriesEngineConfig {
30
31
  referenceValues?: number[];
31
32
  nonNegative?: boolean;
32
33
  maxValue?: number;
34
+ minRange?: number;
33
35
  /** Positive, finite live Y-range multiplier (1 = auto-fit); read each frame. */
34
36
  yRangeScale?: SharedValue<number>;
35
37
  nowOverride?: number;
38
+ presentationTime?: SharedValue<number | undefined>;
36
39
  windowBuffer?: number;
37
40
  paused?: boolean;
38
41
  /**
@@ -71,21 +74,29 @@ export interface MultiEngineFrameRefs {
71
74
  seriesOpacities: SharedValue<number[]>;
72
75
  displayMin: SharedValue<number>;
73
76
  displayMax: SharedValue<number>;
77
+ /** Persist untransformed fitted bounds even without a scratch container. */
78
+ fittedMinSV?: SharedValue<number | undefined>;
79
+ fittedMaxSV?: SharedValue<number | undefined>;
74
80
  displayWindow: SharedValue<number>;
75
81
  timestamp: SharedValue<number>;
76
82
  canvasWidth: SharedValue<number>;
77
83
  canvasHeight: SharedValue<number>;
78
84
  timeWindow: SharedValue<number>;
79
85
  smoothing: SharedValue<number>;
80
- rangeAnimationSV?: SharedValue<RangeAnimationConfig | undefined>;
86
+ rangeAnimationSV?: SharedValue<SeriesRangeAnimationConfig | undefined>;
81
87
  adaptiveSpeedBoostSV?: SharedValue<number | undefined>;
82
88
  exaggerateSV: SharedValue<boolean>;
83
89
  referenceValue: SharedValue<number | undefined>;
84
90
  referenceValues?: SharedValue<number[] | undefined>;
85
91
  nonNegativeSV?: SharedValue<boolean>;
86
92
  maxValueSV?: SharedValue<number | undefined>;
93
+ minRangeSV?: SharedValue<number | undefined>;
87
94
  yRangeScaleSV?: SharedValue<number>;
88
95
  nowOverrideSV?: SharedValue<number | undefined>;
96
+ presentationTimeSV?: SharedValue<number | undefined>;
97
+ historyStartTimeSV?: SharedValue<number | undefined>;
98
+ currentTimeSV?: SharedValue<number>;
99
+ fullHistoryWindowSV?: SharedValue<number | null>;
89
100
  windowBufferSV?: SharedValue<number>;
90
101
  pausedSV: SharedValue<boolean>;
91
102
  /** Pan-scroll right-edge override (null = follow live). Optional for callers/tests. */
@@ -217,6 +228,8 @@ export function applyLiveChartSeriesEngineFrame(
217
228
  };
218
229
  state.displayMin = sv.displayMin.value;
219
230
  state.displayMax = sv.displayMax.value;
231
+ state.fittedMin = sv.fittedMinSV?.value ?? state.fittedMin;
232
+ state.fittedMax = sv.fittedMaxSV?.value ?? state.fittedMax;
220
233
  state.displayWindow = sv.displayWindow.value;
221
234
  state.timestamp = sv.timestamp.value;
222
235
  state.liveEdge = sv.liveEdgeSV?.value ?? 0;
@@ -249,8 +262,11 @@ export function applyLiveChartSeriesEngineFrame(
249
262
  input.referenceValues = sv.referenceValues?.value;
250
263
  input.nonNegative = sv.nonNegativeSV?.value ?? false;
251
264
  input.maxValue = sv.maxValueSV?.value;
265
+ input.minRange = sv.minRangeSV?.value;
252
266
  input.yRangeScale = sv.yRangeScaleSV?.value ?? 1;
253
267
  input.nowOverride = sv.nowOverrideSV?.value;
268
+ input.presentationTime = sv.presentationTimeSV?.value;
269
+ input.historyStartTime = sv.historyStartTimeSV?.value;
254
270
  input.windowBuffer = sv.windowBufferSV?.value ?? 0;
255
271
  input.series = seriesSnap;
256
272
  input.nowSeconds = Date.now() / 1000;
@@ -264,9 +280,13 @@ export function applyLiveChartSeriesEngineFrame(
264
280
  tickLiveChartSeriesEngineFrame(state, input);
265
281
  sv.displayMin.value = state.displayMin;
266
282
  sv.displayMax.value = state.displayMax;
283
+ if (sv.fittedMinSV) sv.fittedMinSV.value = state.fittedMin;
284
+ if (sv.fittedMaxSV) sv.fittedMaxSV.value = state.fittedMax;
267
285
  sv.displayWindow.value = state.displayWindow;
268
286
  sv.timestamp.value = state.timestamp;
269
287
  if (sv.liveEdgeSV) sv.liveEdgeSV.value = state.liveEdge;
288
+ if (sv.currentTimeSV) sv.currentTimeSV.value = state.currentTime!;
289
+ if (sv.fullHistoryWindowSV) sv.fullHistoryWindowSV.value = state.fullHistoryWindow ?? null;
270
290
  sv.displaySeriesValues.value = state.displayValues;
271
291
  sv.seriesOpacities.value = state.opacities;
272
292
  sv.extremaMinValue.value = state.extremaMinValue;
@@ -298,11 +318,17 @@ export function applyLiveChartSeriesEngineFrame(
298
318
  */
299
319
  export function useLiveChartSeriesEngine(
300
320
  config: MultiSeriesEngineConfig,
301
- ): MultiEngineState & ChartEngineScroll {
321
+ ): MultiEngineState & ChartEngineScroll & {
322
+ currentTime: SharedValue<number>;
323
+ fullHistoryWindow: SharedValue<number | null>;
324
+ } {
302
325
  // Pinch-zoom window-width override (null = follow the configured window).
303
326
  // Declared first so `timeWindow` folds it in — see useLiveChartEngine.
304
327
  const viewWindow = useSharedValue<number | null>(null);
305
- const timeWindow = useDerivedValue(() => viewWindow.value ?? config.timeWindow);
328
+ const fullHistoryWindow = useSharedValue<number | null>(null);
329
+ const timeWindow = useDerivedValue(() => viewWindow.value ?? fullHistoryWindow.value ?? config.timeWindow);
330
+ const configuredTimeWindow = useDerivedValue(() => config.timeWindow);
331
+ const historyStartTimeSV = useDerivedValue(() => config.historyStartTime);
306
332
  const smoothing = useDerivedValue(() => config.smoothing);
307
333
  const rangeAnimationSV = useDerivedValue(() => config.rangeAnimation);
308
334
  const adaptiveSpeedBoostSV = useDerivedValue(() => config.adaptiveSpeedBoost);
@@ -311,6 +337,7 @@ export function useLiveChartSeriesEngine(
311
337
  const referenceValues = useDerivedValue(() => config.referenceValues);
312
338
  const nonNegativeSV = useDerivedValue(() => config.nonNegative ?? false);
313
339
  const maxValueSV = useDerivedValue(() => config.maxValue);
340
+ const minRangeSV = useDerivedValue(() => config.minRange);
314
341
  const nowOverrideSV = useDerivedValue(() => config.nowOverride);
315
342
  const windowBufferSV = useDerivedValue(() => config.windowBuffer ?? 0);
316
343
  const pausedSV = useDerivedValue(() => config.paused ?? false);
@@ -328,12 +355,16 @@ export function useLiveChartSeriesEngine(
328
355
 
329
356
  const displayMin = useSharedValue(0);
330
357
  const displayMax = useSharedValue(1);
358
+ const fittedMinSV = useSharedValue<number | undefined>(undefined);
359
+ const fittedMaxSV = useSharedValue<number | undefined>(undefined);
331
360
  const displayWindow = useSharedValue(config.timeWindow);
332
361
  const canvasWidth = useSharedValue(0);
333
362
  const canvasHeight = useSharedValue(0);
334
363
  // Seed once; overwritten by the frame callback on the first tick.
335
364
  const [initialTimestamp] = useState(() => Date.now() / 1000);
336
365
  const timestamp = useSharedValue(initialTimestamp);
366
+ const currentTime = useSharedValue(initialTimestamp);
367
+ const tipTime = useDerivedValue(() => Math.min(timestamp.value, currentTime.value));
337
368
 
338
369
  // Pan-scroll state (see useLiveChartEngine). Defaults to following live.
339
370
  const viewEnd = useSharedValue<number | null>(null);
@@ -386,11 +417,15 @@ export function useLiveChartSeriesEngine(
386
417
  seriesOpacities,
387
418
  displayMin,
388
419
  displayMax,
420
+ fittedMinSV,
421
+ fittedMaxSV,
389
422
  displayWindow,
390
423
  timestamp,
391
424
  canvasWidth,
392
425
  canvasHeight,
393
- timeWindow,
426
+ timeWindow: configuredTimeWindow,
427
+ historyStartTimeSV,
428
+ fullHistoryWindowSV: fullHistoryWindow,
394
429
  smoothing,
395
430
  rangeAnimationSV,
396
431
  adaptiveSpeedBoostSV,
@@ -399,8 +434,11 @@ export function useLiveChartSeriesEngine(
399
434
  referenceValues,
400
435
  nonNegativeSV,
401
436
  maxValueSV,
437
+ minRangeSV,
402
438
  yRangeScaleSV: config.yRangeScale,
403
439
  nowOverrideSV,
440
+ presentationTimeSV: config.presentationTime,
441
+ currentTimeSV: currentTime,
404
442
  windowBufferSV,
405
443
  pausedSV,
406
444
  viewEndSV: viewEnd,
@@ -468,6 +506,9 @@ export function useLiveChartSeriesEngine(
468
506
  viewEnd,
469
507
  viewWindow,
470
508
  liveEdge,
509
+ currentTime,
510
+ tipTime,
511
+ fullHistoryWindow,
471
512
  series: renderedSeries,
472
513
  displaySeriesValues,
473
514
  seriesOpacities,
package/src/draw/grid.ts CHANGED
@@ -17,10 +17,20 @@ export interface RightAnchoredYAxisColumnLayout {
17
17
  gridEndX: number;
18
18
  }
19
19
 
20
+ /** Width used by the painted right-anchored column, including fading entries. */
21
+ export function widestYAxisLabelWidth(entries: readonly YAxisEntry[], font: SkFont): number {
22
+ "worklet";
23
+ let width = 0;
24
+ for (let i = 0; i < entries.length; i++) {
25
+ width = Math.max(width, measureFontTextWidth(font, entries[i].label));
26
+ }
27
+ return width;
28
+ }
29
+
20
30
  /**
21
31
  * Measure the widest Y-axis label and anchor the shared left-aligned column to
22
- * a fixed canvas-edge margin. Shared by the axis and reference-line worklets so
23
- * their right edges cannot drift apart.
32
+ * a fixed canvas-edge margin. Shared by the axis, reference-line and live-badge
33
+ * worklets so their edges cannot drift apart.
24
34
  */
25
35
  export function rightAnchoredYAxisColumnLayout(
26
36
  canvasWidth: number,
@@ -30,13 +40,7 @@ export function rightAnchoredYAxisColumnLayout(
30
40
  gridEndGap = 0,
31
41
  ): RightAnchoredYAxisColumnLayout {
32
42
  "worklet";
33
- let maxTextW = 0;
34
- for (let i = 0; i < entries.length; i++) {
35
- maxTextW = Math.max(
36
- maxTextW,
37
- measureFontTextWidth(font, entries[i].label),
38
- );
39
- }
43
+ const maxTextW = widestYAxisLabelWidth(entries, font);
40
44
  const labelX = canvasWidth - labelRightMargin - maxTextW;
41
45
  return { labelX, gridEndX: labelX - gridEndGap };
42
46
  }
@@ -59,7 +63,7 @@ export function fixedGridEntries(
59
63
  padTop: number,
60
64
  count: number,
61
65
  minGap: number,
62
- formatValue: (v: number) => string,
66
+ formatValue: (v: number, tickStep?: number) => string,
63
67
  ): YAxisEntry[] {
64
68
  "worklet";
65
69
  // minGap floor: at most `floor(chartH / minGap)` gaps fit ⇒ that many + 1 labels.
@@ -73,7 +77,7 @@ export function fixedGridEntries(
73
77
  for (let i = 0; i < n; i++) {
74
78
  const y = padTop + i * stepPx;
75
79
  const val = displayMax - i * stepVal;
76
- entries.push({ y, label: formatValue(val), alpha: 1 });
80
+ entries.push({ y, label: formatValue(val, stepVal), alpha: 1 });
77
81
  }
78
82
  return entries;
79
83
  }
@@ -164,7 +168,7 @@ export function computeGridEntries(
164
168
  padBottom: number,
165
169
  prevInterval: number,
166
170
  labelAlphas: Record<number, number>,
167
- formatValue: (v: number) => string,
171
+ formatValue: (v: number, tickStep?: number) => string,
168
172
  dt: number,
169
173
  minGap = 36,
170
174
  grid: GridMetrics = GRID_METRICS_DEFAULTS,
@@ -299,7 +303,7 @@ export function computeGridEntries(
299
303
  const y = gridValueToY(val, displayMax, valRange, padTop, chartH);
300
304
  /* istanbul ignore next -- vertical clip; y stays in-band when val comes from tracked keys */
301
305
  if (y < padTop - 10 || y > canvasHeight - padBottom + 10) continue;
302
- entries.push({ y, label: formatValue(val), alpha });
306
+ entries.push({ y, label: formatValue(val, fine), alpha });
303
307
  }
304
308
 
305
309
  return { entries, interval };
package/src/draw/line.ts CHANGED
@@ -44,8 +44,10 @@ export function badgeTailAndCap(
44
44
  /**
45
45
  * Text left-edge X so the label is horizontally centered in the badge pill.
46
46
  * Uses the ASYMMETRIC layout: tail gap (`tl`) on the left, `BADGE_MARGIN_RIGHT` on
47
- * the right. Both `useBadge` and `GridOverlay` (when badge is shown) call this so
47
+ * the right. Both `useBadge` and `YAxisOverlay` (when badge is shown) call this so
48
48
  * the badge text and y-axis labels share the exact same horizontal position.
49
+ * With `yAxis.labelRightMargin` the labels use `rightAnchoredYAxisColumnLayout`
50
+ * instead, and so does the badge text with `badge.textAlign: "yAxisColumn"`.
49
51
  *
50
52
  * Layout: |dot| tl |PAD_X| text |PAD_X| BADGE_MARGIN_RIGHT |canvas edge
51
53
  * ↑ same x for grid labels and badge text
@@ -215,10 +217,44 @@ export function resolvePadding(
215
217
  };
216
218
  }
217
219
 
220
+ /**
221
+ * Clip rect for the series layers (line, fill, candles, gap bridges): the plot's
222
+ * vertical extent, so a zoomed-in `yRangeScale` can't draw over the time axis.
223
+ * Horizontally it reaches a canvas width past each edge so the left-edge entry
224
+ * and the degen shake stay unclipped.
225
+ */
226
+ export function seriesPlotClip(
227
+ padding: ChartPadding,
228
+ canvasWidth: number,
229
+ canvasHeight: number,
230
+ ): { x: number; y: number; width: number; height: number } {
231
+ "worklet";
232
+ return {
233
+ x: -canvasWidth,
234
+ y: padding.top,
235
+ width: canvasWidth * 3,
236
+ height: Math.max(0, canvasHeight - padding.top - padding.bottom),
237
+ };
238
+ }
239
+
240
+ /** Project a presented head, clamped to the viewport edge, into the plot. */
241
+ export function lineTipX(
242
+ viewportEnd: number,
243
+ windowSecs: number,
244
+ tipTime: number,
245
+ canvasWidth: number,
246
+ padding: ChartPadding,
247
+ ): number {
248
+ "worklet";
249
+ const chartW = canvasWidth - padding.left - padding.right;
250
+ if (windowSecs <= 0 || chartW <= 0) return -100;
251
+ return padding.left + ((Math.min(viewportEnd, tipTime) - (viewportEnd - windowSecs)) / windowSecs) * chartW;
252
+ }
253
+
218
254
  /**
219
255
  * Build screen-space points as a flat number array [x0, y0, x1, y1, ...].
220
256
  * Includes one point before the window for smooth left-edge entry,
221
- * and appends a live tip at (now, displayValue).
257
+ * and appends a live tip at (min(now, tipTime), displayValue).
222
258
  *
223
259
  * Flat layout avoids ~150 tuple object allocations per frame.
224
260
  *
@@ -241,6 +277,8 @@ export function buildLinePoints(
241
277
  padding: ChartPadding,
242
278
  out?: number[],
243
279
  omitTipBeyondData = false,
280
+ /** Optional presentation head; viewport end still determines the projection. */
281
+ tipTime = now,
244
282
  ): number[] {
245
283
  "worklet";
246
284
  const pts: number[] = out ?? [];
@@ -253,6 +291,8 @@ export function buildLinePoints(
253
291
  return pts;
254
292
 
255
293
  const winStart = now - windowSecs;
294
+ const head = Math.min(now, tipTime);
295
+ if (head < winStart || windowSecs <= 0) return pts;
256
296
 
257
297
  // Binary search for first point >= winStart
258
298
  let lo = 0;
@@ -269,10 +309,11 @@ export function buildLinePoints(
269
309
  let ehi = data.length;
270
310
  while (elo < ehi) {
271
311
  const emid = (elo + ehi) >> 1;
272
- if (data[emid].time <= now) elo = emid + 1;
312
+ if (data[emid].time <= head) elo = emid + 1;
273
313
  else ehi = emid;
274
314
  }
275
315
  const endIdx = elo;
316
+ if (endIdx <= startIdx) return pts;
276
317
 
277
318
  const xScale = chartW / windowSecs;
278
319
  const yScale = chartH / valRange;
@@ -350,14 +391,14 @@ export function buildLinePoints(
350
391
  if (
351
392
  omitTipBeyondData &&
352
393
  endIdx === data.length &&
353
- data[endIdx - 1].time < now
394
+ data[endIdx - 1].time < head
354
395
  ) {
355
396
  return pts;
356
397
  }
357
398
 
358
399
  // Live tip at current time with smoothed value
359
400
  pts.push(
360
- padding.left + chartW,
401
+ lineTipX(now, windowSecs, head, canvasWidth, padding),
361
402
  padding.top + ((displayMax - displayValue) / valRange) * chartH,
362
403
  );
363
404
 
@@ -15,21 +15,51 @@ const TOOLTIP_SIDE_GAP = 8;
15
15
  const TOOLTIP_STACK_GAP = 4;
16
16
  const TOOLTIP_TOP_GAP = 4;
17
17
 
18
- function valueAtTime(series: SeriesConfig, time: number): number | null {
18
+ function valueAtTime(
19
+ series: SeriesConfig,
20
+ time: number,
21
+ maxTime?: number,
22
+ tipValue?: number,
23
+ ): number | null {
19
24
  "worklet";
20
- return interpolateAtTime(series.data, time);
25
+ if (maxTime === undefined) return interpolateAtTime(series.data, time);
26
+ const points = series.data;
27
+ if (points.length === 0 || points[0].time > maxTime) return null;
28
+ const target = Math.min(time, maxTime);
29
+ if (target >= maxTime && tipValue !== undefined) return tipValue;
30
+ if (target <= points[0].time) return points[0].value;
31
+ let lo = 0;
32
+ let hi = points.length;
33
+ while (lo < hi) {
34
+ const mid = (lo + hi) >> 1;
35
+ if (points[mid].time <= target) lo = mid + 1;
36
+ else hi = mid;
37
+ }
38
+ const before = points[lo - 1];
39
+ const next = points[lo];
40
+ // Interpolate only through presented history and the synthetic endpoint,
41
+ // matching the line builder rather than blending toward a buffered sample.
42
+ const endTime = next && next.time <= maxTime ? next.time : maxTime;
43
+ const endValue = next && next.time <= maxTime
44
+ ? next.value
45
+ : (tipValue ?? before.value);
46
+ if (endTime <= before.time) return before.value;
47
+ return before.value + (endValue - before.value) *
48
+ ((target - before.time) / (endTime - before.time));
21
49
  }
22
50
 
23
51
  export function interpolateSeriesAtTime(
24
52
  series: SeriesConfig[],
25
53
  time: number,
54
+ maxTime?: number,
55
+ displaySeriesValues?: number[],
26
56
  ): { primary: number | null; seriesValues: ScrubSeriesValue[] } {
27
57
  "worklet";
28
58
  const seriesValues: ScrubSeriesValue[] = [];
29
59
  let primary: number | null = null;
30
60
  for (let i = 0; i < series.length; i++) {
31
61
  if (series[i].visible === false) continue;
32
- const v = valueAtTime(series[i], time);
62
+ const v = valueAtTime(series[i], time, maxTime, displaySeriesValues?.[i]);
33
63
  if (v === null) continue;
34
64
  seriesValues.push({
35
65
  id: series[i].id,
@@ -127,7 +157,7 @@ export function computePerSeriesTooltipLayout(
127
157
  if (item.visible === false || item.data.length === 0) continue;
128
158
  const value = pinned
129
159
  ? (displaySeriesValues[i] ?? item.value)
130
- : valueAtTime(item, activeTime);
160
+ : valueAtTime(item, activeTime, maxTime, displaySeriesValues[i]);
131
161
  if (value === null || !Number.isFinite(value)) continue;
132
162
 
133
163
  const label = truncateSeriesTooltipLabel(
@@ -300,8 +330,10 @@ export function deriveScrubValueSeries(
300
330
  scrubActive: boolean,
301
331
  scrubTime: number,
302
332
  series: SeriesConfig[],
333
+ maxTime?: number,
334
+ displaySeriesValues?: number[],
303
335
  ): number | null {
304
336
  "worklet";
305
337
  if (!scrubActive || scrubTime < 0) return null;
306
- return interpolateSeriesAtTime(series, scrubTime).primary;
338
+ return interpolateSeriesAtTime(series, scrubTime, maxTime, displaySeriesValues).primary;
307
339
  }
@@ -10,7 +10,7 @@ import {
10
10
  pickCandleGapAtTime,
11
11
  } from "../math/candleGaps";
12
12
  import { pickCandleAtTime } from "../math/pickCandle";
13
- import type { CandleGap, CandlePoint } from "../types";
13
+ import type { CandleGap, CandlePoint, Marker } from "../types";
14
14
 
15
15
  const TOOLTIP_PAD_X = 8;
16
16
  const TOOLTIP_PAD_Y = 6;
@@ -177,6 +177,7 @@ export const HIDDEN_TOOLTIP: TooltipLayout = {
177
177
  };
178
178
 
179
179
  export interface CrosshairState {
180
+ scrubMarkers: SharedValue<Marker[]>;
180
181
  scrubX: SharedValue<number>;
181
182
  scrubActive: SharedValue<boolean>;
182
183
  scrubTime: SharedValue<number>;
@@ -306,6 +307,60 @@ export function snapPrice(price: number, increment?: number): number {
306
307
  return Math.round(price / increment) * increment;
307
308
  }
308
309
 
310
+ /** What `Math.round(price / increment) * increment` can be off by at this price
311
+ * in double precision. */
312
+ function roundingNoise(increment: number, price: number): number {
313
+ "worklet";
314
+ return Math.max(increment * 1e-9, Math.abs(price) * 4 * Number.EPSILON);
315
+ }
316
+
317
+ /**
318
+ * {@link snapPrice} for a price inside `[min, max]` that should stay there: when
319
+ * rounding alone would leave the range, it rounds one `increment` inward instead
320
+ * (if that is still inside). A drag held at the plot's edge maps to exactly
321
+ * `max` / `min`, which plain rounding pushes just off the plot half the time.
322
+ */
323
+ export function snapPriceWithin(
324
+ price: number,
325
+ increment: number | undefined,
326
+ min: number,
327
+ max: number,
328
+ ): number {
329
+ "worklet";
330
+ const snapped = snapPrice(price, increment);
331
+ if (!increment || increment <= 0) return snapped;
332
+ // Past an edge by float noise alone (90.05 rounds to 90.05000000000001): the
333
+ // edge is that grid value, and it stays on the plot.
334
+ if (snapped > max) {
335
+ if (snapped - max <= roundingNoise(increment, max)) return max;
336
+ if (snapped - increment >= min) return snapped - increment;
337
+ } else if (snapped < min) {
338
+ if (min - snapped <= roundingNoise(increment, min)) return min;
339
+ if (snapped + increment <= max) return snapped + increment;
340
+ }
341
+ return snapped;
342
+ }
343
+
344
+ /**
345
+ * {@link snapPrice} that rounds away from the range instead of to the nearest
346
+ * increment: up for `side` `1`, down for `-1`, nearest for `0`. A drag past the
347
+ * plot's edge asks for a price beyond it, and a coarse `snap` rounded back
348
+ * inside would leave the range nothing to widen to.
349
+ */
350
+ export function snapPriceOutward(
351
+ price: number,
352
+ increment: number | undefined,
353
+ side: -1 | 0 | 1,
354
+ ): number {
355
+ "worklet";
356
+ const snapped = snapPrice(price, increment);
357
+ if (!increment || increment <= 0 || side === 0) return snapped;
358
+ const noise = roundingNoise(increment, price);
359
+ if (side > 0 && price - snapped > noise) return snapped + increment;
360
+ if (side < 0 && snapped - price > noise) return snapped - increment;
361
+ return snapped;
362
+ }
363
+
309
364
  /**
310
365
  * Maps a scrub X position to a window timestamp.
311
366
  * Returns -1 when inactive or when the canvas is not yet laid out.
@@ -0,0 +1,35 @@
1
+ import { matchFont, Skia, type SkFont } from "@shopify/react-native-skia";
2
+ import { resolveFontConfig } from "../core/resolveConfig";
3
+ import { MONO_FONT_FAMILY } from "../lib/monoFontFamily";
4
+ import type { BadgeStyleConfig, FontConfig } from "../types";
5
+ import { matchSystemFont } from "./useChartSkiaFont";
6
+
7
+ /** Resolve the same font for a rendered pill and its hit target, on the JS thread. */
8
+ export function referenceBadgeFont(
9
+ base: SkFont,
10
+ prop: FontConfig | undefined,
11
+ style: BadgeStyleConfig | undefined,
12
+ ): SkFont {
13
+ if (
14
+ style?.fontSize == null &&
15
+ style?.fontFamily == null &&
16
+ style?.fontWeight == null
17
+ )
18
+ return base;
19
+ const config = {
20
+ ...prop,
21
+ fontSize: style.fontSize ?? prop?.fontSize,
22
+ fontFamily: style.fontFamily ?? prop?.fontFamily,
23
+ fontWeight: style.fontWeight ?? prop?.fontWeight,
24
+ };
25
+ const { fontSize, fontFamily, fontWeight } = resolveFontConfig(
26
+ config,
27
+ MONO_FONT_FAMILY,
28
+ base.getSize(),
29
+ );
30
+ if (prop?.typeface)
31
+ return Skia.Font(base.getTypeface() ?? undefined, fontSize);
32
+ return prop?.fontManager
33
+ ? matchFont({ fontSize, fontFamily, fontWeight }, prop.fontManager)
34
+ : matchSystemFont(fontFamily, fontSize, fontWeight);
35
+ }
@@ -10,13 +10,19 @@ import {
10
10
  resolvePadding,
11
11
  type ChartPadding,
12
12
  } from "../draw/line";
13
- import type { BadgeMetrics, ChartInsets, LiveChartPalette } from "../types";
13
+ import type { BadgeMetrics, ChartInsets, LiveChartPalette, YAxisConfig } from "../types";
14
14
 
15
15
  export interface ChartLayoutConfig {
16
16
  palette: LiveChartPalette;
17
17
  lineWidthOverride?: number;
18
18
  insetsOverride?: ChartInsets;
19
19
  yAxis: boolean;
20
+ /** Explicit canvas-edge margin for a right-anchored tick column. */
21
+ labelRightMargin?: number;
22
+ /** Widest actual tick string measured on the UI thread; undefined uses a sample. */
23
+ yAxisLabelWidth?: number;
24
+ /** Outer dot/ring radius, before optional pulse/glow. */
25
+ dotRadius?: number;
20
26
  /** Float the y-axis over a full-width plot (no reserved right gutter). */
21
27
  yAxisFloat?: boolean;
22
28
  badge: boolean;
@@ -39,7 +45,7 @@ export interface ChartLayoutConfig {
39
45
  /** Skia font for measuring label width. When provided with formatValue + currentValue, padding auto-sizes. */
40
46
  font?: SkFont;
41
47
  /** Worklet formatter — called on JS thread here to measure label width */
42
- formatValue?: (v: number) => string;
48
+ formatValue?: (v: number, tickStep?: number) => string;
43
49
  /** Current value read from SharedValue on JS thread — used to produce a sample label for measurement */
44
50
  currentValue?: number;
45
51
  /**
@@ -65,11 +71,38 @@ export interface ChartLayoutConfig {
65
71
  multiSeriesMaxLabelWidth?: number;
66
72
  }
67
73
 
74
+ /** Only auto-size a gutter for a non-floating, right-anchored tick column. */
75
+ export function shouldMeasureYAxisLabels(
76
+ axis: Pick<YAxisConfig, "side" | "labelRightMargin" | "float"> | null | undefined,
77
+ rightInset: number | undefined,
78
+ floating = axis?.float ?? false,
79
+ ): boolean {
80
+ return axis?.side !== "left" && axis?.labelRightMargin != null &&
81
+ !floating && rightInset == null;
82
+ }
83
+
68
84
  export interface ChartLayoutResult {
69
85
  strokeWidth: number;
70
86
  padding: ChartPadding;
71
87
  }
72
88
 
89
+ /**
90
+ * Whether a live value should replace `sampled` (`0` = nothing sampled yet) as
91
+ * the `currentValue` the right gutter is measured from. Skips `0` and
92
+ * non-finite placeholders, then waits for a full order-of-magnitude move: the
93
+ * measured samples already span `v / 100` to `v * 10`, and ticks near a power
94
+ * of ten don't re-measure back and forth.
95
+ */
96
+ export function shouldResampleLayoutValue(
97
+ next: number,
98
+ sampled: number,
99
+ ): boolean {
100
+ "worklet";
101
+ if (next === 0 || !Number.isFinite(next)) return false;
102
+ if (sampled === 0) return true;
103
+ return Math.abs(Math.log10(Math.abs(next / sampled))) >= 1;
104
+ }
105
+
73
106
  /** Right inset (px) for a floating y-axis — just keeps the plot off the edge. */
74
107
  const FLOAT_AXIS_RIGHT_INSET = 6;
75
108
 
@@ -94,7 +127,7 @@ export function resolveChartLayout(
94
127
  (badgeUsesRightGutter || !config.badge || config.yAxis)
95
128
  ) {
96
129
  const v = config.currentValue;
97
- const samples = [v, v / 10, v / 100, v * 10].map(config.formatValue);
130
+ const samples = [v, v / 10, v / 100, v * 10].map(value => config.formatValue!(value));
98
131
  measuredYAxisLabelWidth = Math.max(
99
132
  ...samples.map((s) => measureFontTextWidth(config.font!, s)),
100
133
  );
@@ -151,6 +184,21 @@ export function resolveChartLayout(
151
184
  );
152
185
  }
153
186
 
187
+ // An edge-anchored column needs one label width and one radial clearance,
188
+ // unlike centered labels whose gutter reserves radial space on both sides.
189
+ if (config.yAxis && config.labelRightMargin != null && !config.yAxisFloat &&
190
+ config.insetsOverride?.right == null) {
191
+ const labelW = config.yAxisLabelWidth ??
192
+ ((measuredYAxisLabelWidth ?? 49) + (config.font?.getSize() ?? 12) / 2);
193
+ const dotR = config.dotRadius ?? config.multiSeriesDotRadius ?? 0;
194
+ const radialClearance = Math.max(dotR, dotEffectOutset) + 6;
195
+ const clearance = config.multiSeriesValueLabel
196
+ ? Math.max(radialClearance, dotR + 8 + (config.multiSeriesMaxLabelWidth ?? 0) + 8)
197
+ : radialClearance;
198
+ const axisPad = Math.ceil(config.labelRightMargin + labelW + clearance);
199
+ rightPad = badgeUsesRightGutter ? Math.max(rightPad, axisPad) : axisPad;
200
+ }
201
+
154
202
  // ── Left inset ───────────────────────────────────────────────────────────
155
203
  let leftPad: number;
156
204
  if (config.insetsOverride?.left != null) {