react-native-livechart 4.26.0 → 4.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/components/CustomReferenceLineOverlay.d.ts +8 -1
  2. package/dist/components/CustomReferenceLineOverlay.d.ts.map +1 -1
  3. package/dist/components/CustomTooltipOverlay.d.ts +3 -2
  4. package/dist/components/CustomTooltipOverlay.d.ts.map +1 -1
  5. package/dist/components/LiveChart.d.ts +1 -1
  6. package/dist/components/LiveChart.d.ts.map +1 -1
  7. package/dist/components/LiveChartSeries.d.ts.map +1 -1
  8. package/dist/components/ReferenceLineOverlay.d.ts +4 -0
  9. package/dist/components/ReferenceLineOverlay.d.ts.map +1 -1
  10. package/dist/components/ReferenceValueBadge.d.ts +15 -0
  11. package/dist/components/ReferenceValueBadge.d.ts.map +1 -0
  12. package/dist/components/XAxisOverlay.d.ts +17 -0
  13. package/dist/components/XAxisOverlay.d.ts.map +1 -1
  14. package/dist/core/liveChartEngineTick.d.ts +4 -0
  15. package/dist/core/liveChartEngineTick.d.ts.map +1 -1
  16. package/dist/core/liveChartSeriesEngineTick.d.ts +2 -0
  17. package/dist/core/liveChartSeriesEngineTick.d.ts.map +1 -1
  18. package/dist/core/resolveConfig.d.ts +28 -1
  19. package/dist/core/resolveConfig.d.ts.map +1 -1
  20. package/dist/core/useLiveChartEngine.d.ts +7 -0
  21. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  22. package/dist/core/useLiveChartSeriesEngine.d.ts +2 -0
  23. package/dist/core/useLiveChartSeriesEngine.d.ts.map +1 -1
  24. package/dist/draw/grid.d.ts +2 -2
  25. package/dist/draw/line.d.ts +15 -1
  26. package/dist/draw/line.d.ts.map +1 -1
  27. package/dist/hooks/crosshairShared.d.ts +16 -1
  28. package/dist/hooks/crosshairShared.d.ts.map +1 -1
  29. package/dist/hooks/referenceBadgeFont.d.ts +5 -0
  30. package/dist/hooks/referenceBadgeFont.d.ts.map +1 -0
  31. package/dist/hooks/resolveChartLayout.d.ts +8 -0
  32. package/dist/hooks/resolveChartLayout.d.ts.map +1 -1
  33. package/dist/hooks/useBadge.d.ts +16 -1
  34. package/dist/hooks/useBadge.d.ts.map +1 -1
  35. package/dist/hooks/useChartSkiaFont.d.ts +1 -0
  36. package/dist/hooks/useChartSkiaFont.d.ts.map +1 -1
  37. package/dist/hooks/useCrosshair.d.ts +7 -2
  38. package/dist/hooks/useCrosshair.d.ts.map +1 -1
  39. package/dist/hooks/useCrosshairSeries.d.ts +4 -1
  40. package/dist/hooks/useCrosshairSeries.d.ts.map +1 -1
  41. package/dist/hooks/useLatestCallback.d.ts +6 -0
  42. package/dist/hooks/useLatestCallback.d.ts.map +1 -0
  43. package/dist/hooks/useMarkers.d.ts.map +1 -1
  44. package/dist/hooks/usePanScroll.d.ts +3 -1
  45. package/dist/hooks/usePanScroll.d.ts.map +1 -1
  46. package/dist/hooks/usePinchZoom.d.ts.map +1 -1
  47. package/dist/hooks/useReferenceDrag.d.ts +20 -5
  48. package/dist/hooks/useReferenceDrag.d.ts.map +1 -1
  49. package/dist/hooks/useReferenceLine.d.ts +24 -12
  50. package/dist/hooks/useReferenceLine.d.ts.map +1 -1
  51. package/dist/hooks/useReferenceLinePress.d.ts +4 -2
  52. package/dist/hooks/useReferenceLinePress.d.ts.map +1 -1
  53. package/dist/hooks/useReferenceTagStack.d.ts +31 -0
  54. package/dist/hooks/useReferenceTagStack.d.ts.map +1 -0
  55. package/dist/hooks/useScrubMarkers.d.ts +12 -0
  56. package/dist/hooks/useScrubMarkers.d.ts.map +1 -0
  57. package/dist/hooks/useXAxis.d.ts +1 -1
  58. package/dist/hooks/useXAxis.d.ts.map +1 -1
  59. package/dist/hooks/useYAxisScaleGesture.d.ts +34 -0
  60. package/dist/hooks/useYAxisScaleGesture.d.ts.map +1 -0
  61. package/dist/index.d.ts +1 -1
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/math/axisBadgeLayout.d.ts +16 -0
  64. package/dist/math/axisBadgeLayout.d.ts.map +1 -0
  65. package/dist/math/markers.d.ts +3 -0
  66. package/dist/math/markers.d.ts.map +1 -1
  67. package/dist/math/range.d.ts +1 -1
  68. package/dist/math/range.d.ts.map +1 -1
  69. package/dist/math/referenceTagStack.d.ts +36 -0
  70. package/dist/math/referenceTagStack.d.ts.map +1 -0
  71. package/dist/math/scrubMarkers.d.ts +12 -0
  72. package/dist/math/scrubMarkers.d.ts.map +1 -0
  73. package/dist/types.d.ts +202 -32
  74. package/dist/types.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/components/CustomReferenceLineOverlay.tsx +50 -8
  77. package/src/components/CustomTooltipOverlay.tsx +5 -1
  78. package/src/components/LiveChart.tsx +560 -138
  79. package/src/components/LiveChartSeries.tsx +113 -13
  80. package/src/components/ReferenceLineOverlay.tsx +62 -26
  81. package/src/components/ReferenceValueBadge.tsx +102 -0
  82. package/src/components/XAxisOverlay.tsx +104 -1
  83. package/src/core/liveChartEngineTick.ts +49 -4
  84. package/src/core/liveChartSeriesEngineTick.ts +37 -0
  85. package/src/core/resolveConfig.ts +95 -2
  86. package/src/core/useLiveChartEngine.ts +43 -9
  87. package/src/core/useLiveChartSeriesEngine.ts +5 -0
  88. package/src/draw/grid.ts +2 -2
  89. package/src/draw/line.ts +23 -1
  90. package/src/hooks/crosshairShared.ts +56 -1
  91. package/src/hooks/referenceBadgeFont.ts +35 -0
  92. package/src/hooks/resolveChartLayout.ts +17 -0
  93. package/src/hooks/useBadge.ts +44 -5
  94. package/src/hooks/useChartSkiaFont.ts +1 -1
  95. package/src/hooks/useCrosshair.ts +444 -310
  96. package/src/hooks/useCrosshairSeries.ts +29 -10
  97. package/src/hooks/useLatestCallback.ts +15 -0
  98. package/src/hooks/useMarkers.ts +51 -39
  99. package/src/hooks/usePanScroll.ts +155 -127
  100. package/src/hooks/usePinchZoom.ts +84 -63
  101. package/src/hooks/useReferenceDrag.ts +390 -155
  102. package/src/hooks/useReferenceLine.ts +453 -277
  103. package/src/hooks/useReferenceLineGrouping.ts +1 -1
  104. package/src/hooks/useReferenceLinePress.ts +121 -53
  105. package/src/hooks/useReferenceTagStack.ts +81 -0
  106. package/src/hooks/useScrubMarkers.ts +79 -0
  107. package/src/hooks/useXAxis.ts +11 -2
  108. package/src/hooks/useYAxisScaleGesture.ts +263 -0
  109. package/src/index.ts +10 -0
  110. package/src/math/axisBadgeLayout.ts +37 -0
  111. package/src/math/markers.ts +28 -3
  112. package/src/math/range.ts +35 -0
  113. package/src/math/referenceTagStack.ts +112 -0
  114. package/src/math/scrubMarkers.ts +55 -0
  115. package/src/types.ts +207 -32
@@ -28,7 +28,7 @@ export function useReferenceLineGrouping({
28
28
  offAxisCustom: boolean[];
29
29
  dragValues: SharedValue<number[]>;
30
30
  }) {
31
- const hasOffAxisBadge = lines.map((line) => Boolean(line.badge || line.offAxisBadge));
31
+ const hasOffAxisBadge = lines.map((line) => Boolean(line.badge || line.offAxisBadge || line.valueBadge));
32
32
  const result = useDerivedValue<ReferenceGrouping>(() => {
33
33
  if (radius == null) return EMPTY_GROUPING;
34
34
  const canvasHeight = engine.canvasHeight.get();
@@ -1,3 +1,5 @@
1
+ import type { ReferenceTagStack } from "../math/referenceTagStack";
2
+ import { useMemo } from "react";
1
3
  import type { SkFont } from "@shopify/react-native-skia";
2
4
  import { Gesture } from "react-native-gesture-handler";
3
5
  import { useDerivedValue, type SharedValue } from "react-native-reanimated";
@@ -5,13 +7,19 @@ import { scheduleOnRN } from "react-native-worklets";
5
7
 
6
8
  import type { ChartEngineLayout } from "../core/useLiveChartEngine";
7
9
  import type { ChartPadding } from "../draw/line";
8
- import type { ReferenceLine } from "../types";
10
+ import type { AxisBadgeConfig } from "../math/axisBadgeLayout";
11
+ import { referenceBadgeFont } from "./referenceBadgeFont";
12
+ import { resolveReferenceBadge } from "../math/referenceLines";
13
+ import type { FontConfig, ReferenceLine } from "../types";
9
14
  import { pointInRect } from "./crosshairShared";
10
15
  import {
11
- computeReferenceBadgeRect,
16
+ computeReferenceLineLayout,
17
+ referenceBadgeRect,
12
18
  type ReferenceBadgeRect,
13
19
  } from "./useReferenceLine";
14
20
 
21
+ import { useLatestCallback } from "./useLatestCallback";
22
+
15
23
  /**
16
24
  * Builds a tap gesture that hit-tests a chart's reference-line **badges** (the
17
25
  * pill tags for working orders / alerts / targets) and fires `onPress(line,
@@ -36,71 +44,131 @@ export function useReferenceLinePress(
36
44
  /** Per-line live value overrides (dragged values) so a draggable line's hit-rect
37
45
  * tracks the drag, index-aligned with `lines`. */
38
46
  dragValues?: SharedValue<number[]>,
47
+ valueAxis?: AxisBadgeConfig,
48
+ fontProp?: FontConfig,
49
+ groupHidden?: SharedValue<boolean[]>,
50
+ custom?: boolean[],
51
+ offAxisCustom?: boolean[],
52
+ tagStack?: SharedValue<ReferenceTagStack>,
39
53
  ): {
40
54
  tapGesture: ReturnType<typeof Gesture.Tap>;
41
55
  hitTest: (x: number, y: number) => boolean;
42
56
  } {
43
- // Per-frame badge hit-rects, index-aligned with `lines` (null = no pressable
44
- // badge / off-screen / not laid out). Recomputed on the UI thread.
57
+ const fonts = useMemo(
58
+ () =>
59
+ lines.map((line) => ({
60
+ name: referenceBadgeFont(
61
+ font,
62
+ fontProp,
63
+ resolveReferenceBadge(line) ?? undefined,
64
+ ),
65
+ value: referenceBadgeFont(
66
+ font,
67
+ fontProp,
68
+ typeof line.valueBadge === "object" ? line.valueBadge : undefined,
69
+ ),
70
+ })),
71
+ [lines, font, fontProp],
72
+ );
45
73
  /* istanbul ignore next -- worklet runs on the UI thread, not in Jest */
46
- const rects = useDerivedValue<(ReferenceBadgeRect | null)[]>(() => {
74
+ const rects = useDerivedValue<(ReferenceBadgeRect | null)[][]>(() => {
47
75
  if (!active || lines.length === 0) return [];
48
- const w = engine.canvasWidth.value;
49
- const h = engine.canvasHeight.value;
50
- const dMin = engine.displayMin.value;
51
- const dMax = engine.displayMax.value;
52
- const out: (ReferenceBadgeRect | null)[] = [];
53
- const dv = dragValues?.value;
76
+ if (tagStack) {
77
+ const out: ReferenceBadgeRect[][] = [];
78
+ for (let i = 0; i < lines.length; i++) out.push([]);
79
+ for (const tag of tagStack.get().tags) {
80
+ if (lines[tag.index] && lines[tag.index].id === tag.lineId && tag.kind !== "custom" && (tag.kind === "value" || resolveReferenceBadge(lines[tag.index]))) {
81
+ out[tag.index]?.push(tag);
82
+ }
83
+ }
84
+ return out;
85
+ }
86
+ const out: (ReferenceBadgeRect | null)[][] = [];
54
87
  for (let i = 0; i < lines.length; i++) {
55
- out.push(
56
- computeReferenceBadgeRect(
57
- lines[i],
58
- w,
59
- h,
60
- padding,
61
- dMin,
62
- dMax,
63
- font,
64
- formatValue,
65
- dv ? dv[i] : undefined,
66
- ),
88
+ if (custom?.[i] || groupHidden?.get()[i]) {
89
+ out.push([]);
90
+ continue;
91
+ }
92
+ const layout = computeReferenceLineLayout(
93
+ engine.canvasWidth.get(),
94
+ engine.canvasHeight.get(),
95
+ padding,
96
+ lines[i],
97
+ formatValue,
98
+ fonts[i].name,
99
+ engine.displayMin.get(),
100
+ engine.displayMax.get(),
101
+ 0,
102
+ 1,
103
+ dragValues?.get()[i],
104
+ undefined,
105
+ undefined,
106
+ 0,
107
+ font,
108
+ fonts[i].value,
109
+ valueAxis,
67
110
  );
111
+ if (offAxisCustom?.[i] && layout.offAxis) {
112
+ out.push([]);
113
+ continue;
114
+ }
115
+ out.push([
116
+ referenceBadgeRect(layout, fonts[i].name, lines[i]),
117
+ layout.valueBadge,
118
+ ]);
68
119
  }
69
120
  return out;
70
121
  });
71
122
 
72
- // Topmost badge under (x, y), or -1. Last drawn = last in the array = topmost.
73
- /* istanbul ignore next -- worklet, runs on the UI thread */
74
- const indexAt = (x: number, y: number): number => {
75
- "worklet";
76
- const rs = rects.value;
77
- for (let i = rs.length - 1; i >= 0; i--) {
78
- const r = rs[i];
79
- if (r && pointInRect(x, y, r, hitSlop)) return i;
80
- }
81
- return -1;
82
- };
83
-
84
- /* istanbul ignore next -- worklet, runs on the UI thread */
85
- const hitTest = (x: number, y: number): boolean => {
86
- "worklet";
87
- return indexAt(x, y) >= 0;
88
- };
123
+ const emitPress = useLatestCallback(
124
+ (index: number, id: string | undefined) => {
125
+ const line = lines[index];
126
+ // A queued tap must not target a replacement at the same array index.
127
+ if (line && line.id === id) onPress?.(line, index);
128
+ },
129
+ );
130
+ const lineIds = useDerivedValue(() => {
131
+ const ids: (string | undefined)[] = [];
132
+ for (const line of lines) ids.push(line.id);
133
+ return ids;
134
+ });
89
135
 
90
- /* istanbul ignore next -- runs only via scheduleOnRN from the UI-thread tap */
91
- function emitPress(index: number) {
92
- onPress?.(lines[index], index);
93
- }
136
+ return useMemo(() => {
137
+ // Topmost badge under (x, y), or -1. Last drawn = last in the array = topmost.
138
+ /* istanbul ignore next -- worklet, runs on the UI thread */
139
+ const indexAt = (x: number, y: number): number => {
140
+ "worklet";
141
+ const rs = rects.get();
142
+ // Exact pill hits win over neighboring expanded touch targets.
143
+ if (tagStack) {
144
+ for (let i = rs.length - 1; i >= 0; i--) {
145
+ for (const r of rs[i]) if (r && pointInRect(x, y, r, 0)) return i;
146
+ }
147
+ }
148
+ for (let i = rs.length - 1; i >= 0; i--) {
149
+ for (const r of rs[i]) {
150
+ if (r && pointInRect(x, y, r, hitSlop)) return i;
151
+ }
152
+ }
153
+ return -1;
154
+ };
94
155
 
95
- /* istanbul ignore next -- gesture worklet runs on the UI thread, not in Jest */
96
- const tapGesture = Gesture.Tap()
97
- .maxDuration(250)
98
- .onEnd((e, success) => {
156
+ /* istanbul ignore next -- worklet, runs on the UI thread */
157
+ const hitTest = (x: number, y: number): boolean => {
99
158
  "worklet";
100
- if (!active || !success) return;
101
- const i = indexAt(e.x, e.y);
102
- if (i >= 0) scheduleOnRN(emitPress, i);
103
- });
159
+ return indexAt(x, y) >= 0;
160
+ };
161
+
162
+ /* istanbul ignore next -- gesture worklet runs on the UI thread, not in Jest */
163
+ const tapGesture = Gesture.Tap()
164
+ .maxDuration(250)
165
+ .onEnd((e, success) => {
166
+ "worklet";
167
+ if (!active || !success) return;
168
+ const i = indexAt(e.x, e.y);
169
+ if (i >= 0) scheduleOnRN(emitPress, i, lineIds.get()[i]);
170
+ });
104
171
 
105
- return { tapGesture, hitTest };
172
+ return { tapGesture, hitTest };
173
+ }, [active, emitPress, hitSlop, lineIds, rects, tagStack]);
106
174
  }
@@ -0,0 +1,81 @@
1
+ import { useMemo, useRef } from "react";
2
+ import type { SkFont } from "@shopify/react-native-skia";
3
+ import { useAnimatedReaction, type SharedValue } from "react-native-reanimated";
4
+ import type { ChartEngineLayout } from "../core/useLiveChartEngine";
5
+ import type { ChartPadding } from "../draw/line";
6
+ import { measureFontTextWidth, type TextWidthCache } from "../lib/measureFontTextWidth";
7
+ import type { AxisBadgeConfig } from "../math/axisBadgeLayout";
8
+ import { classifyReferenceEdge, referenceLineForm, resolveReferenceBadge } from "../math/referenceLines";
9
+ import { EMPTY_TAG_STACK, stackReferenceTags, type ReferenceTag, type ReferenceTagStack, type TagRect } from "../math/referenceTagStack";
10
+ import type { FontConfig, ReferenceLine } from "../types";
11
+ import { computeScrubDotY } from "./crosshairShared";
12
+ import { referenceBadgeFont } from "./referenceBadgeFont";
13
+ import { computeReferenceLineLayout, referenceBadgeRect } from "./useReferenceLine";
14
+
15
+ export type CustomTagSizes = Record<string, { width: number; height: number }>;
16
+
17
+ /** One shared geometry result drives built-in/custom rendering and hit targets. */
18
+ export function useReferenceTagStack({
19
+ enabled, radius, engine, padding, lines, keys, custom, offAxisCustom,
20
+ customSizes, font, fontProp, formatValue, dragValues, valueAxis, obstacle, output,
21
+ }: {
22
+ enabled: boolean; radius: number; engine: ChartEngineLayout; padding: ChartPadding;
23
+ lines: ReferenceLine[]; keys: string[]; custom: boolean[]; offAxisCustom: boolean[];
24
+ customSizes: SharedValue<CustomTagSizes>; font: SkFont; fontProp?: FontConfig;
25
+ formatValue: (value: number) => string; dragValues: SharedValue<number[]>;
26
+ valueAxis: AxisBadgeConfig; obstacle: SharedValue<TagRect | null> | null;
27
+ output: SharedValue<ReferenceTagStack>;
28
+ }) {
29
+ const fonts = useMemo(() => enabled ? lines.map(line => ({
30
+ name: referenceBadgeFont(font, fontProp, resolveReferenceBadge(line) ?? undefined),
31
+ value: referenceBadgeFont(font, fontProp, typeof line.valueBadge === "object" ? line.valueBadge : undefined),
32
+ })) : [], [enabled, lines, font, fontProp]);
33
+ const caches = useRef<TextWidthCache[]>([]);
34
+ const valueCaches = useRef<TextWidthCache[]>([]);
35
+ useAnimatedReaction(() => {
36
+ if (!enabled) return EMPTY_TAG_STACK;
37
+ const w = engine.canvasWidth.get(), h = engine.canvasHeight.get();
38
+ const min = engine.displayMin.get(), max = engine.displayMax.get();
39
+ const tags: ReferenceTag[] = [];
40
+ const values = dragValues.get();
41
+ const sizes = customSizes.get();
42
+ for (let i = 0; i < lines.length; i++) {
43
+ const line = lines[i];
44
+ if (referenceLineForm(line) !== "line" || line.value === undefined) continue;
45
+ const value = values[i] ?? line.value;
46
+ const offAxis = classifyReferenceEdge(value, min, max) !== "in";
47
+ if (custom[i] || (offAxisCustom[i] && offAxis)) {
48
+ const size = sizes[keys[i]];
49
+ if (!size || w <= 0 || h - padding.top - padding.bottom <= 0) continue;
50
+ const anchor = resolveReferenceBadge(line)?.position ?? line.labelPosition ?? "left";
51
+ const y = Math.min(h - padding.bottom - 12, Math.max(padding.top + 12,
52
+ computeScrubDotY(value, min, max, h, padding.top, padding.bottom)));
53
+ const x = anchor === "right" ? w - padding.right - 2 - size.width
54
+ : anchor === "center" ? (padding.left + w - padding.right - size.width) / 2 : padding.left + 2;
55
+ tags.push({ index: i, lineId: line.id, key: keys[i] + ":custom", kind: "custom", x, y: y - size.height / 2, w: size.width, h: size.height, lineY: y });
56
+ continue;
57
+ }
58
+ const nameCache = caches.current[i] ?? (caches.current[i] = {});
59
+ const valueCache = valueCaches.current[i] ?? (valueCaches.current[i] = {});
60
+ const layout = computeReferenceLineLayout(w, h, padding, line, formatValue, fonts[i].name,
61
+ min, max, 0, 1, value, undefined, undefined, 0, font, fonts[i].value, valueAxis, nameCache, valueCache);
62
+ if (!layout.visible) continue;
63
+ let name = referenceBadgeRect(layout, fonts[i].name, line);
64
+ if (!name && layout.label) {
65
+ const fm = fonts[i].name.getMetrics();
66
+ name = { x: layout.labelX, y: layout.labelY + fm.ascent,
67
+ w: measureFontTextWidth(fonts[i].name, layout.label, nameCache), h: fm.descent - fm.ascent };
68
+ }
69
+ if (name) tags.push({ ...name, index: i, lineId: line.id, key: keys[i] + ":name", kind: "name", lineY: layout.y });
70
+ if (layout.valueBadge) tags.push({ ...layout.valueBadge, index: i, lineId: line.id, key: keys[i] + ":value", kind: "value", lineY: layout.y });
71
+ }
72
+ return stackReferenceTags(tags, padding.top, h - padding.bottom, radius, obstacle?.get() ?? null);
73
+ }, (next, previous) => {
74
+ // Avoid waking every tag mapper when the engine ticks but geometry is steady.
75
+ if (previous && next.tags.length === previous.tags.length && next.tags.every((t, i) => {
76
+ const p = previous.tags[i];
77
+ return t.key === p.key && t.index === p.index && t.x === p.x && t.y === p.y && t.w === p.w && t.h === p.h && t.offsetY === p.offsetY && t.lineY === p.lineY;
78
+ })) return;
79
+ output.set(next);
80
+ });
81
+ }
@@ -0,0 +1,79 @@
1
+ import {
2
+ useAnimatedReaction,
3
+ useSharedValue,
4
+ type SharedValue,
5
+ } from "react-native-reanimated";
6
+ import type { ResolvedScrubConfig } from "../core/resolveConfig";
7
+ import { matchScrubMarkers, scrubMarkerRange } from "../math/scrubMarkers";
8
+ import type { CandlePoint, ChartGap, Marker } from "../types";
9
+
10
+ export interface ScrubMarkerOptions {
11
+ markers: SharedValue<Marker[]>;
12
+ radius: number;
13
+ }
14
+
15
+ /** Adapt resolved config for both crosshair hooks. */
16
+ export function resolveScrubMarkerOptions(
17
+ config: ResolvedScrubConfig | null,
18
+ markers: SharedValue<Marker[]>,
19
+ ): ScrubMarkerOptions | undefined {
20
+ if (!config?.markers) return undefined;
21
+ return { markers, radius: config.markers.radius };
22
+ }
23
+
24
+ /** Selection changes notify tooltip consumers; movement within a match does not. */
25
+ export function useScrubMarkers(
26
+ options: ScrubMarkerOptions | undefined,
27
+ active: SharedValue<boolean>,
28
+ time: SharedValue<number>,
29
+ now: SharedValue<number>,
30
+ window: SharedValue<number>,
31
+ canvasWidth: SharedValue<number>,
32
+ horizontalPadding: number,
33
+ candleMode = false,
34
+ candle?: SharedValue<CandlePoint | null>,
35
+ candleWidth = 60,
36
+ gap?: SharedValue<ChartGap | null>,
37
+ ): SharedValue<Marker[]> {
38
+ const source = useSharedValue<Marker[]>([]);
39
+ const selected = useSharedValue<Marker[]>([]);
40
+ // A fresh shallow snapshot also detects .modify() edits where the caller
41
+ // retains the input array/objects. No metadata serialization or frame loop.
42
+ useAnimatedReaction(
43
+ () => options?.markers.get(),
44
+ (markers) => {
45
+ source.set(markers ? markers.slice() : []);
46
+ },
47
+ );
48
+ useAnimatedReaction(
49
+ () => {
50
+ if (!options || !active.get() || gap?.get()) return null;
51
+ return {
52
+ markers: source.get(),
53
+ range: scrubMarkerRange(
54
+ time.get(),
55
+ now.get(),
56
+ window.get(),
57
+ canvasWidth.get() - horizontalPadding,
58
+ options.radius,
59
+ candleMode,
60
+ candle?.get()?.time ?? null,
61
+ candleWidth,
62
+ ),
63
+ };
64
+ },
65
+ (input, previous) => {
66
+ const next = input ? matchScrubMarkers(input.markers, input.range) : [];
67
+ const current = selected.get();
68
+ // Refresh metadata when the input changes, but retain the result array
69
+ // through chart ticks / movement that select the same markers.
70
+ if (
71
+ next.length === current.length &&
72
+ (next.length === 0 || input?.markers === previous?.markers) &&
73
+ next.every((marker, index) => marker === current[index])
74
+ ) return;
75
+ selected.set(next);
76
+ },
77
+ );
78
+ return selected;
79
+ }
@@ -67,10 +67,12 @@ export function useXAxis(
67
67
  padding: ChartPadding,
68
68
  formatTime: (t: number) => string,
69
69
  font: SkFont,
70
+ minGap = 60,
70
71
  ) {
71
72
  const labelAlphas = useSharedValue<
72
73
  Record<number, { alpha: number; text: string }>
73
74
  >({});
75
+ const lastMinGap = useSharedValue(minGap);
74
76
 
75
77
  // A tick's key encodes its time, so its label is formatted once (below) and
76
78
  // never re-formatted per frame — an allocation optimization. That assumes
@@ -105,13 +107,18 @@ export function useXAxis(
105
107
  /* istanbul ignore next -- defensive; Reanimated test mock rarely executes this guard with non-zero w/h */
106
108
  if (chartW <= 0) return [] as XAxisEntry[];
107
109
 
110
+ // Config changes must settle in this run: a paused or parked engine may
111
+ // publish no more frames to finish fading the previous tick set.
112
+ const gapChanged = !Object.is(lastMinGap.get(), minGap);
113
+ if (gapChanged) lastMinGap.set(minGap);
114
+
108
115
  const fadeZone = 50;
109
116
 
110
117
  // Pick interval from the *target* window duration so the cadence is stable
111
118
  // and independent of the window we're animating from.
112
119
  const targetPxPerSec = chartW / targetWindow;
113
120
  let interval = niceTimeInterval(targetWindow);
114
- while (interval * targetPxPerSec < 60 && interval < targetWindow) {
121
+ while (interval * targetPxPerSec < minGap && interval < targetWindow) {
115
122
  interval *= 2;
116
123
  }
117
124
 
@@ -169,7 +176,9 @@ export function useXAxis(
169
176
 
170
177
  const isTarget = xAxisKeyIsTarget(key, targetKeys);
171
178
  const target = isTarget ? edgeAlpha : 0;
172
- let next = lerp(label.alpha, target, FADE, MS_PER_FRAME_60FPS);
179
+ let next = gapChanged
180
+ ? target
181
+ : lerp(label.alpha, target, FADE, MS_PER_FRAME_60FPS);
173
182
  if (Math.abs(next - target) < 0.02) next = target;
174
183
 
175
184
  // Only a key that left the target set is deleted once it has faded out. A
@@ -0,0 +1,263 @@
1
+ import type { SkFont } from "@shopify/react-native-skia";
2
+ import { useMemo } from "react";
3
+ import {
4
+ Gesture,
5
+ type ComposedGesture,
6
+ type GestureType,
7
+ } from "react-native-gesture-handler";
8
+ import {
9
+ cancelAnimation,
10
+ useSharedValue,
11
+ withTiming,
12
+ type SharedValue,
13
+ } from "react-native-reanimated";
14
+ import type { ResolvedYAxisConfig } from "../core/resolveConfig";
15
+ import type { ChartEngineLayout } from "../core/useLiveChartEngine";
16
+ import { rightAnchoredYAxisColumnLayout, type YAxisEntry } from "../draw/grid";
17
+ import type { ChartPadding } from "../draw/line";
18
+
19
+ /** Preserve private scale state across gesture/axis toggles on a mounted chart. */
20
+ export function useYAxisScaleValue(external?: SharedValue<number>) {
21
+ const internal = useSharedValue(1);
22
+ return external ?? internal;
23
+ }
24
+
25
+ /** The reserved gutter, or the actual measured price column when it floats. */
26
+ export function isYAxisScaleHit(
27
+ x: number,
28
+ y: number,
29
+ width: number,
30
+ height: number,
31
+ padding: ChartPadding,
32
+ side: "left" | "right",
33
+ floating: boolean,
34
+ labelRightMargin: number | undefined,
35
+ entries: readonly YAxisEntry[],
36
+ font: SkFont,
37
+ ): boolean {
38
+ "worklet";
39
+ if (
40
+ width <= 0 ||
41
+ height <= 0 ||
42
+ x < 0 ||
43
+ x > width ||
44
+ y < padding.top ||
45
+ y >= height - padding.bottom
46
+ )
47
+ return false;
48
+ if (side === "left") return x < padding.left;
49
+ let left = width - padding.right;
50
+ if (floating || labelRightMargin !== undefined) {
51
+ // Matches YAxisOverlay: floating labels sit 6px off the canvas edge.
52
+ const column = rightAnchoredYAxisColumnLayout(
53
+ width,
54
+ entries,
55
+ font,
56
+ labelRightMargin ?? 6,
57
+ );
58
+ left = Math.min(left, column.labelX);
59
+ }
60
+ return x >= Math.max(padding.left, left);
61
+ }
62
+
63
+ /** Log-space clamping avoids overflow even for very large drag translations. */
64
+ export function draggedYAxisScale(
65
+ start: number,
66
+ dy: number,
67
+ distance: number,
68
+ min: number,
69
+ max: number,
70
+ ): number {
71
+ "worklet";
72
+ const validStart = Number.isFinite(start) && start > 0 ? start : 1;
73
+ const logScale =
74
+ Math.log(Math.max(min, Math.min(max, validStart))) + dy / distance;
75
+ return Math.max(
76
+ min,
77
+ Math.min(
78
+ max,
79
+ Math.exp(Math.max(Math.log(min), Math.min(Math.log(max), logScale))),
80
+ ),
81
+ );
82
+ }
83
+
84
+ type Options = {
85
+ engine: Pick<ChartEngineLayout, "canvasWidth" | "canvasHeight"> & {
86
+ wake?: () => void;
87
+ };
88
+ padding: ChartPadding;
89
+ axis: ResolvedYAxisConfig | null;
90
+ floating?: boolean;
91
+ entries: SharedValue<YAxisEntry[]> | null;
92
+ font: SkFont;
93
+ scale: SharedValue<number>;
94
+ /** Existing plot gesture graph, including pinch. */
95
+ gesture: GestureType | ComposedGesture;
96
+ /** Interactive chart overlays retain their normal tap/drag behavior. */
97
+ deferHit?: (x: number, y: number) => boolean;
98
+ onStart?: () => void;
99
+ active?: SharedValue<boolean>;
100
+ };
101
+
102
+ /** Owns gutter touches at touch-down; fails immediately everywhere else. */
103
+ export function useYAxisScaleGesture({
104
+ engine,
105
+ padding,
106
+ axis,
107
+ floating = false,
108
+ entries,
109
+ font,
110
+ scale,
111
+ gesture,
112
+ deferHit,
113
+ onStart,
114
+ active,
115
+ }: Options) {
116
+ const startScale = useSharedValue(1);
117
+ const startY = useSharedValue(0);
118
+ const armed = useSharedValue(false);
119
+ const { canvasWidth, canvasHeight, wake } = engine;
120
+ const { left, right, top, bottom } = padding;
121
+ const side = axis?.side ?? "right";
122
+ const labelRightMargin = axis?.labelRightMargin;
123
+ const config = axis?.scaleGesture;
124
+ const enabled = config != null;
125
+ const minScale = config?.minScale ?? 0.25;
126
+ const maxScale = config?.maxScale ?? 10;
127
+ const dragDistance = config?.dragDistance ?? 160;
128
+ const doubleTapReset = config?.doubleTapReset ?? true;
129
+
130
+ const axisGesture = useMemo(() => {
131
+ if (!enabled) return null;
132
+ const hit = (x: number, y: number) => {
133
+ "worklet";
134
+ return (
135
+ isYAxisScaleHit(
136
+ x,
137
+ y,
138
+ canvasWidth.get(),
139
+ canvasHeight.get(),
140
+ { left, right, top, bottom },
141
+ side,
142
+ floating,
143
+ labelRightMargin,
144
+ entries?.get() ?? [],
145
+ font,
146
+ ) && !deferHit?.(x, y)
147
+ );
148
+ };
149
+ const pan = Gesture.Manual()
150
+ .onTouchesDown((event, manager) => {
151
+ "worklet";
152
+ const touch = event.allTouches[0];
153
+ if (event.numberOfTouches !== 1 || !touch || !hit(touch.x, touch.y)) {
154
+ armed.set(false);
155
+ manager.fail();
156
+ return;
157
+ }
158
+ // A Manual recognizer owns the entire down→up lifecycle. A Pan with
159
+ // manualActivation can overwrite activation while beginning its native
160
+ // recognition, so it cannot reliably claim a gutter touch on down.
161
+ // Claim before a parent ScrollView or chart scrub can activate.
162
+ // Exclusive below gives this pair priority over the entire plot graph.
163
+ // Native touch moves can arrive before the ACTIVE/onStart event. Seed
164
+ // the drag here so the first move cannot reuse a previous drag's scale.
165
+ cancelAnimation(scale);
166
+ startScale.set(scale.get());
167
+ startY.set(touch.y);
168
+ armed.set(true);
169
+ active?.set(true);
170
+ manager.begin();
171
+ manager.activate();
172
+ })
173
+ .onStart(() => {
174
+ "worklet";
175
+ wake?.();
176
+ active?.set(true);
177
+ onStart?.();
178
+ })
179
+ .onTouchesMove((event) => {
180
+ "worklet";
181
+ const touch = event.allTouches[0];
182
+ if (!armed.get() || !touch) return;
183
+ scale.set(
184
+ draggedYAxisScale(
185
+ startScale.get(),
186
+ touch.y - startY.get(),
187
+ dragDistance,
188
+ minScale,
189
+ maxScale,
190
+ ),
191
+ );
192
+ })
193
+ .onTouchesUp((_event, manager) => {
194
+ "worklet";
195
+ if (armed.get()) {
196
+ armed.set(false);
197
+ manager.end();
198
+ }
199
+ })
200
+ .onTouchesCancelled((_event, manager) => {
201
+ "worklet";
202
+ armed.set(false);
203
+ manager.fail();
204
+ })
205
+ .onFinalize(() => {
206
+ "worklet";
207
+ armed.set(false);
208
+ active?.set(false);
209
+ });
210
+ const reset = Gesture.Tap()
211
+ .enabled(doubleTapReset)
212
+ .numberOfTaps(2)
213
+ .maxDistance(16)
214
+ .onTouchesDown((event, manager) => {
215
+ "worklet";
216
+ const touch = event.allTouches[0];
217
+ if (event.numberOfTouches !== 1 || !touch || !hit(touch.x, touch.y))
218
+ manager.fail();
219
+ })
220
+ .onEnd((_event, success) => {
221
+ "worklet";
222
+ if (!success) return;
223
+ wake?.();
224
+ cancelAnimation(scale);
225
+ scale.set(
226
+ withTiming(Math.max(minScale, Math.min(maxScale, 1)), {
227
+ duration: 240,
228
+ }),
229
+ );
230
+ onStart?.();
231
+ });
232
+ return Gesture.Simultaneous(pan, reset);
233
+ }, [
234
+ enabled,
235
+ canvasWidth,
236
+ canvasHeight,
237
+ left,
238
+ right,
239
+ top,
240
+ bottom,
241
+ side,
242
+ floating,
243
+ labelRightMargin,
244
+ entries,
245
+ font,
246
+ deferHit,
247
+ scale,
248
+ startScale,
249
+ startY,
250
+ armed,
251
+ wake,
252
+ onStart,
253
+ active,
254
+ minScale,
255
+ maxScale,
256
+ dragDistance,
257
+ doubleTapReset,
258
+ ]);
259
+ return useMemo(
260
+ () => (axisGesture ? Gesture.Exclusive(axisGesture, gesture) : gesture),
261
+ [axisGesture, gesture],
262
+ );
263
+ }