react-native-livechart 4.21.0 → 4.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/components/AxisLabelOverlay.d.ts +5 -1
  2. package/dist/components/AxisLabelOverlay.d.ts.map +1 -1
  3. package/dist/components/CrosshairOverlay.d.ts +4 -2
  4. package/dist/components/CrosshairOverlay.d.ts.map +1 -1
  5. package/dist/components/CustomMarkerOverlay.d.ts.map +1 -1
  6. package/dist/components/DegenParticlesOverlay.d.ts.map +1 -1
  7. package/dist/components/ExtremaConnectorOverlay.d.ts +5 -1
  8. package/dist/components/ExtremaConnectorOverlay.d.ts.map +1 -1
  9. package/dist/components/LiveChart.d.ts.map +1 -1
  10. package/dist/components/LiveChartSeries.d.ts.map +1 -1
  11. package/dist/components/MarkerOverlay.d.ts +4 -2
  12. package/dist/components/MarkerOverlay.d.ts.map +1 -1
  13. package/dist/components/ReferenceLineOverlay.d.ts +1 -1
  14. package/dist/components/ReferenceLineOverlay.d.ts.map +1 -1
  15. package/dist/core/chartDataPresence.d.ts +8 -0
  16. package/dist/core/chartDataPresence.d.ts.map +1 -0
  17. package/dist/core/useLiveChartEngine.d.ts.map +1 -1
  18. package/dist/core/useLiveChartSeriesEngine.d.ts.map +1 -1
  19. package/dist/draw/markerAtlas.d.ts +3 -2
  20. package/dist/draw/markerAtlas.d.ts.map +1 -1
  21. package/dist/hooks/useChartReveal.d.ts +1 -1
  22. package/dist/hooks/useChartReveal.d.ts.map +1 -1
  23. package/dist/hooks/useCrosshair.d.ts.map +1 -1
  24. package/dist/hooks/useDegen.d.ts.map +1 -1
  25. package/dist/hooks/useLiveChartHasData.d.ts +2 -2
  26. package/dist/hooks/useLiveChartHasData.d.ts.map +1 -1
  27. package/dist/hooks/useReverseMorphEngineInputs.d.ts.map +1 -1
  28. package/dist/types.d.ts +3 -3
  29. package/package.json +1 -1
  30. package/src/components/AxisLabelOverlay.tsx +162 -81
  31. package/src/components/CrosshairOverlay.tsx +394 -147
  32. package/src/components/CustomMarkerOverlay.tsx +9 -6
  33. package/src/components/DegenParticlesOverlay.tsx +34 -23
  34. package/src/components/ExtremaConnectorOverlay.tsx +43 -3
  35. package/src/components/LiveChart.tsx +1692 -1025
  36. package/src/components/LiveChartSeries.tsx +445 -296
  37. package/src/components/MarkerOverlay.tsx +215 -156
  38. package/src/components/ReferenceLineOverlay.tsx +77 -50
  39. package/src/core/chartDataPresence.ts +24 -0
  40. package/src/core/useLiveChartEngine.ts +6 -3
  41. package/src/core/useLiveChartSeriesEngine.ts +2 -0
  42. package/src/draw/markerAtlas.ts +8 -3
  43. package/src/hooks/useChartReveal.ts +1 -1
  44. package/src/hooks/useCrosshair.ts +69 -46
  45. package/src/hooks/useDegen.ts +82 -53
  46. package/src/hooks/useLiveChartHasData.ts +8 -4
  47. package/src/hooks/useReverseMorphEngineInputs.ts +11 -20
  48. package/src/types.ts +3 -3
@@ -2,7 +2,6 @@ import {
2
2
  forwardRef,
3
3
  useEffect,
4
4
  useImperativeHandle,
5
- useLayoutEffect,
6
5
  useMemo,
7
6
  useRef,
8
7
  useState,
@@ -87,7 +86,11 @@ import {
87
86
  computeCandleFocusClip,
88
87
  HIDDEN_CANDLE_FOCUS_CLIP,
89
88
  } from "../draw/candle";
90
- import { dotGlowRadialOutset, pulseRadialOutset } from "../draw/line";
89
+ import {
90
+ dotGlowRadialOutset,
91
+ pulseRadialOutset,
92
+ type ChartPadding,
93
+ } from "../draw/line";
91
94
  import { resolveChartLayout } from "../hooks/resolveChartLayout";
92
95
  import { useBadge } from "../hooks/useBadge";
93
96
  import { useCandleGapPaths } from "../hooks/useCandleGapPaths";
@@ -269,170 +272,119 @@ function thresholdSplitColorVecs(
269
272
  /** Transparent vec4 — the band shader's "threshold ended" rest color. */
270
273
  const TRANSPARENT_VEC4 = [0, 0, 0, 0];
271
274
 
272
- /**
273
- * Resolves props → configs → theme/layout → engine → per-frame derived values and
274
- * overlay hooks, returning a single render model. All the chart's wiring lives
275
- * here so the rendered pieces (`ChartStack`, `ChartScrubLayer`, `LiveChart`) stay
276
- * small and presentational.
277
- */
278
-
279
- function useLiveChartController({
280
- // ── Data ────────────────────────────────────────────────────────────────
281
- data,
282
- value,
283
-
284
- // ── Appearance ──────────────────────────────────────────────────────────
285
- theme = "dark",
286
- accentColor = DEFAULT_ACCENT_COLOR,
287
- gradient = true,
288
- areaDots,
289
- line: lineProp,
290
- font: fontProp,
291
- insets,
292
- style,
293
- seriesOpacity,
294
- canvasMode = "transparent",
295
-
296
- // ── Candlestick ─────────────────────────────────────────────────────────
297
- mode = "line",
298
- candles,
299
- candleWidth = 60,
300
- liveCandle,
301
- candleGaps,
302
- lineGaps,
303
- volume,
304
-
305
- // ── Behaviour ───────────────────────────────────────────────────────────
306
- timeWindow = 30,
307
- paused = false,
308
- loading = false,
309
- transitions,
310
- // `static` is a reserved word — alias it so the destructure parses.
311
- static: isStatic = false,
312
- snapKey,
313
- smoothing = 0.08,
314
- exaggerate = false,
315
- nonNegative = false,
316
- maxValue,
317
- yRangeScale,
318
- windowBuffer = 0,
319
- nowOverride,
320
- timeScroll = false,
321
- returnToLive,
322
- zoom = false,
323
- accessibilityLabel,
324
- accessibilityRole = "image",
325
- emptyText = "No data",
326
- formatValue = defaultFormatValue,
327
- formatTime = defaultFormatTime,
328
-
329
- // ── Overlays ────────────────────────────────────────────────────────────
330
- yAxis = true,
331
- xAxis = true,
332
- axisAutoHide = false,
275
+ function resolveLiveChartFeatureConfig({
276
+ mode,
277
+ yAxis,
278
+ xAxis,
333
279
  topLabel,
334
280
  bottomLabel,
335
- badge = true,
336
- momentum = true,
337
- pulse = true,
338
- dot,
339
- valueLine = true,
340
- showValue = false,
341
- valueMomentumColor = false,
342
- referenceLines,
343
- segments,
344
- threshold,
345
- gridStyle,
346
- palette: paletteOverride,
347
- metrics,
348
- scrub = true,
281
+ badge,
282
+ scrub,
349
283
  scrubAction,
284
+ volume,
285
+ candleGaps,
286
+ lineGaps,
287
+ gradient,
288
+ areaDots,
289
+ threshold,
290
+ valueLine,
291
+ isStatic,
292
+ pulse,
293
+ dot,
350
294
  selectionDot,
351
- tradeStream,
295
+ gridStyle,
352
296
  degen,
353
- markers,
354
- onMarkerPress,
355
- markerHitRadius = 16,
356
- markerCluster,
357
- renderMarker,
358
- renderTooltip,
359
- renderOverlay,
360
- renderThresholdBadge,
361
- renderReferenceLine,
362
- renderOffAxisReferenceLine,
363
- referenceLineGrouping,
364
- leftEdgeFade = true,
365
-
366
- // ── Callbacks ───────────────────────────────────────────────────────────
367
- onScrub,
368
- onScrubAction,
369
- onReferenceLinePress,
370
- onGestureStart,
371
- onGestureEnd,
372
- onVisibleRangeChange,
373
- onReachStart,
374
- onDegenShake,
375
- }: LiveChartProps) {
376
- const fullSeriesOpacity = useSharedValue(1);
377
- const resolvedSeriesOpacity = seriesOpacity ?? fullSeriesOpacity;
378
- const emptyMarkers = useSharedValue<Marker[]>([]);
379
- const markersSV = markers ?? emptyMarkers;
380
- // Stand-in threshold value so `useThreshold` can be called unconditionally
381
- // (hooks can't be); the geometry is ignored when no threshold is configured.
382
- const emptyThresholdValue = useSharedValue(0);
297
+ tradeStream,
298
+ metrics,
299
+ }: Pick<
300
+ LiveChartProps,
301
+ | "mode"
302
+ | "yAxis"
303
+ | "xAxis"
304
+ | "topLabel"
305
+ | "bottomLabel"
306
+ | "badge"
307
+ | "scrub"
308
+ | "scrubAction"
309
+ | "volume"
310
+ | "candleGaps"
311
+ | "lineGaps"
312
+ | "gradient"
313
+ | "areaDots"
314
+ | "threshold"
315
+ | "valueLine"
316
+ | "pulse"
317
+ | "dot"
318
+ | "selectionDot"
319
+ | "gridStyle"
320
+ | "degen"
321
+ | "tradeStream"
322
+ | "metrics"
323
+ > & { isStatic: boolean }) {
383
324
  const isCandle = mode === "candle";
384
-
385
- // ── Resolve feature configs ────────────────────────────────────────────
386
- const yAxisCfg = resolveYAxis(yAxis);
387
- const xAxisCfg = resolveXAxis(xAxis);
388
- const topLabelCfg = resolveAxisLabel(topLabel);
389
- const bottomLabelCfg = resolveAxisLabel(bottomLabel);
390
325
  const badgeCfg = resolveBadge(badge);
391
- const scrubCfg = resolveScrub(scrub);
392
- // Scrub + scrub-action are on-demand touch gestures (event-driven, no per-frame
393
- // loop), so they stay live on static charts — `static` suppresses the continuous
394
- // render loop, not interaction. A still sparkline in a list can still be scrubbed.
395
- const scrubActionCfg = resolveScrubAction(scrubAction);
396
- // Volume bars sit below the candles — a candle-mode-only feature (inert in
397
- // line mode, like the candle paths themselves).
398
- const volumeCfg = isCandle ? resolveVolume(volume) : null;
399
326
  const chartGapsCfg = resolveCandleGaps(isCandle ? candleGaps : lineGaps);
400
- const candleGapsCfg = isCandle ? chartGapsCfg : null;
401
- const lineGapsCfg = isCandle ? null : chartGapsCfg;
402
- const volumeBandHeight = volumeCfg?.maxHeight ?? 0;
403
- const gradientCfg = isCandle ? null : resolveGradient(gradient);
404
- // Dot-lattice area fill (clipped to the under-line region). Inert in candle
405
- // mode, same as the gradient fill.
406
- const areaDotsCfg = isCandle ? null : resolveAreaDots(areaDots);
407
- // Threshold split is a line-mode feature (candle bodies carry their own up/down
408
- // colors), so it's inert in candle mode — same as the area gradient.
409
327
  const thresholdCfg = isCandle ? null : resolveThreshold(threshold);
410
328
  const thresholdSeriesSV = thresholdCfg?.series ?? null;
411
- const thresholdIsSeries =
412
- thresholdSeriesSV !== null || Array.isArray(thresholdCfg?.value);
413
- const valueLineCfg = resolveValueLine(valueLine);
414
- // Static charts run zero loops: force the pulse off so its `withRepeat`-driven
415
- // ring never starts (the DotOverlay reads `pulseCfg`, so null = no pulse).
416
- const pulseCfg = isStatic ? null : resolvePulse(pulse);
417
329
  const dotCfg = resolveDot(dot);
418
- // `badge.followViewEdge` wins over `dot.trackWhileParked`: an edge-pinned dot
419
- // must stay aligned with its badge, so the tracking flag is ignored.
420
- const dotTracksParked =
421
- dotCfg.trackWhileParked && !(badgeCfg?.followViewEdge ?? false);
422
- const selectionDotCfg = resolveSelectionDot(selectionDot);
423
- // Outer visible footprint of the dot, including its crisp ring and optional
424
- // blurred glow. Used by scrub dimming so neither effect leaks through.
425
- const dotOuterRadius = Math.max(
426
- dotCfg.radius + (dotCfg.ring?.width ?? 0),
427
- dotCfg.glow ? dotGlowRadialOutset(dotCfg.glow.radius, dotCfg.glow.blur) : 0,
428
- );
429
- const gridStyleCfg = resolveGridStyle(gridStyle);
430
- // Static charts run zero loops: force degen off so `useDegen`'s frame callback
431
- // never starts (also passed `isStatic` below as a belt-and-braces autostart gate).
432
- const degenCfg = isStatic ? null : resolveDegen(degen);
433
- const tradeStreamResolved = resolveTradeStream(tradeStream);
434
- const metricsCfg = resolveMetrics(metrics);
330
+ const volumeCfg = isCandle ? resolveVolume(volume) : null;
331
+
332
+ return {
333
+ isCandle,
334
+ yAxisCfg: resolveYAxis(yAxis),
335
+ xAxisCfg: resolveXAxis(xAxis),
336
+ topLabelCfg: resolveAxisLabel(topLabel),
337
+ bottomLabelCfg: resolveAxisLabel(bottomLabel),
338
+ badgeCfg,
339
+ scrubCfg: resolveScrub(scrub),
340
+ scrubActionCfg: resolveScrubAction(scrubAction),
341
+ volumeCfg,
342
+ chartGapsCfg,
343
+ candleGapsCfg: isCandle ? chartGapsCfg : null,
344
+ lineGapsCfg: isCandle ? null : chartGapsCfg,
345
+ volumeBandHeight: volumeCfg?.maxHeight ?? 0,
346
+ gradientCfg: isCandle ? null : resolveGradient(gradient),
347
+ areaDotsCfg: isCandle ? null : resolveAreaDots(areaDots),
348
+ thresholdCfg,
349
+ thresholdSeriesSV,
350
+ thresholdIsSeries:
351
+ thresholdSeriesSV !== null || Array.isArray(thresholdCfg?.value),
352
+ valueLineCfg: resolveValueLine(valueLine),
353
+ pulseCfg: isStatic ? null : resolvePulse(pulse),
354
+ dotCfg,
355
+ dotTracksParked:
356
+ dotCfg.trackWhileParked && !(badgeCfg?.followViewEdge ?? false),
357
+ selectionDotCfg: resolveSelectionDot(selectionDot),
358
+ dotOuterRadius: Math.max(
359
+ dotCfg.radius + (dotCfg.ring?.width ?? 0),
360
+ dotCfg.glow
361
+ ? dotGlowRadialOutset(dotCfg.glow.radius, dotCfg.glow.blur)
362
+ : 0,
363
+ ),
364
+ gridStyleCfg: resolveGridStyle(gridStyle),
365
+ degenCfg: isStatic ? null : resolveDegen(degen),
366
+ tradeStreamResolved: resolveTradeStream(tradeStream),
367
+ metricsCfg: resolveMetrics(metrics),
368
+ };
369
+ }
435
370
 
371
+ function resolveLiveChartReferenceConfig({
372
+ chartGapsCfg,
373
+ referenceLines,
374
+ renderReferenceLine,
375
+ renderOffAxisReferenceLine,
376
+ thresholdCfg,
377
+ referenceLineGrouping,
378
+ badgeCfg,
379
+ }: {
380
+ chartGapsCfg: ReturnType<typeof resolveCandleGaps>;
381
+ referenceLines: LiveChartProps["referenceLines"];
382
+ renderReferenceLine: LiveChartProps["renderReferenceLine"];
383
+ renderOffAxisReferenceLine: LiveChartProps["renderOffAxisReferenceLine"];
384
+ thresholdCfg: ReturnType<typeof resolveThreshold>;
385
+ referenceLineGrouping: LiveChartProps["referenceLineGrouping"];
386
+ badgeCfg: ReturnType<typeof resolveBadge>;
387
+ }) {
436
388
  const chartGapBands: ReferenceLine[] =
437
389
  chartGapsCfg?.gaps.flatMap((gap) => {
438
390
  const gapStyle = chartGapsCfg.styles[gap.kind];
@@ -459,54 +411,12 @@ function useLiveChartController({
459
411
  },
460
412
  ];
461
413
  }) ?? [];
462
- // Gap bands append after consumer reference lines so public line indices stay
463
- // stable for callbacks. Time bands contribute no Y values or press targets.
464
- const allRefLines = [...(referenceLines ?? []), ...chartGapBands];
465
- const refValues = collectReferenceValues(allRefLines);
466
-
467
- // Per-line live value overrides + drag flags for draggable lines and the custom
468
- // `renderReferenceLine` slot. One array SharedValue each (the line count varies,
469
- // so a single SharedValue beats N hooks). Seeded from each line's static `value`;
470
- // the drag gesture overwrites a slot, and the effect re-seeds slots not being
471
- // dragged when the props change (so a controlled `value` flows back in).
472
- const dragValues = useSharedValue<number[]>([]);
473
- const dragActive = useSharedValue<boolean[]>([]);
474
- // Last `value` props used to seed each slot, so reconciliation can tell a
475
- // controlled prop change (adopt it) from an unchanged prop (keep the dragged
476
- // value — uncontrolled persistence) without resetting a drop on every re-render.
477
- const seededRef = useRef<(number | undefined)[]>([]);
478
- const refValueSig = allRefLines.map((l) => l.value ?? "_").join(",");
479
- useEffect(() => {
480
- const active = dragActive.get();
481
- const cur = dragValues.get();
482
- const seeded = seededRef.current;
483
- dragValues.set(
484
- allRefLines.map((l, i) => {
485
- const prop = l.value ?? 0;
486
- if (active[i]) return cur[i] ?? prop; // mid-drag → keep the dragged value
487
- if (l.value !== seeded[i]) return prop; // prop changed → adopt (controlled)
488
- return cur[i] ?? prop; // unchanged → keep current (uncontrolled persist)
489
- }),
490
- );
491
- seededRef.current = allRefLines.map((l) => l.value);
492
- if (dragActive.get().length !== allRefLines.length) {
493
- dragActive.set(allRefLines.map((_, i) => active[i] ?? false));
494
- }
495
- // allRefLines is rebuilt every render; key off the value signature + length.
496
- // eslint-disable-next-line react-hooks/exhaustive-deps
497
- }, [refValueSig, allRefLines.length]);
498
-
499
- // Form-A lines a custom `renderReferenceLine` owns → suppress their built-in tag
500
- // (no double-draw). Probed on the JS thread, index-aligned with `allRefLines`.
501
- // Semantic gap bands are library-owned annotations: do not leak them through
502
- // the consumer's reference-line renderer or change its callback cardinality.
503
414
  const consumerRefLines = referenceLines ?? [];
415
+ const allRefLines = [...consumerRefLines, ...chartGapBands];
504
416
  const refLineCustom = [
505
417
  ...customReferenceLineFlags(consumerRefLines, renderReferenceLine),
506
418
  ...chartGapBands.map(() => false),
507
419
  ];
508
- // An off-axis renderer replaces only the edge-pinned tag. A full custom tag
509
- // takes precedence for the same line to avoid mounting two native tags.
510
420
  const refLineOffAxisCustom = [
511
421
  ...customReferenceLineFlags(
512
422
  consumerRefLines,
@@ -515,123 +425,169 @@ function useLiveChartController({
515
425
  ),
516
426
  ...chartGapBands.map(() => false),
517
427
  ].map((custom, index) => custom && !refLineCustom[index]);
518
- const refLineKeys = referenceLineReactKeys(allRefLines);
519
- // RN custom tags report their measured widths here so the Skia connector can
520
- // start after the native badge instead of the hidden built-in pill.
521
- const refLineCustomTagWidths = useSharedValue<number[]>([]);
522
-
523
- // Live Y values of the *draggable* Form-A lines, folded into the engine's
524
- // axis-range fit so dragging a line toward / past the visible edge expands the
525
- // range and the axis follows the finger in one motion (the committed values are
526
- // already in `refValues`). `excludeFromRange` lines opt out, matching the static
527
- // fit. Identity-stable (no re-fit) when nothing is draggable.
528
- //
529
- // `threshold.includeInRange` rides the same channel: the constant benchmark
530
- // contributes its live value; a series contributes its window min/max
531
- // (respecting `extendToNow`), so an off-range break-even expands the axis and
532
- // stays on-plot like a reference line would.
533
428
  const draggableRefIdx: number[] = [];
534
- for (let i = 0; i < allRefLines.length; i++) {
535
- const line = allRefLines[i];
429
+ for (let index = 0; index < allRefLines.length; index++) {
430
+ const line = allRefLines[index];
536
431
  if (
537
432
  line.draggable &&
538
433
  !line.excludeFromRange &&
539
434
  referenceLineForm(line) === "line"
540
435
  ) {
541
- draggableRefIdx.push(i);
436
+ draggableRefIdx.push(index);
542
437
  }
543
438
  }
544
439
  const thresholdInRange = thresholdCfg?.includeInRange === true;
545
- // Constant benchmark → its live value rides this channel. A series threshold
546
- // is folded inside the engine tick instead (`thresholdRangePoints`), which
547
- // already knows the window bounds for the min/max.
548
440
  const thresholdRangeValueSV =
549
441
  thresholdInRange &&
550
442
  thresholdCfg?.value != null &&
551
443
  !Array.isArray(thresholdCfg.value)
552
444
  ? thresholdCfg.value
553
445
  : null;
446
+ const refGroupingCfg =
447
+ typeof referenceLineGrouping === "object"
448
+ ? referenceLineGrouping
449
+ : undefined;
450
+
451
+ return {
452
+ chartGapBands,
453
+ allRefLines,
454
+ refValues: collectReferenceValues(allRefLines),
455
+ refLineCustom,
456
+ refLineOffAxisCustom,
457
+ refLineKeys: referenceLineReactKeys(allRefLines),
458
+ draggableRefIdx,
459
+ thresholdInRange,
460
+ thresholdRangeValueSV,
461
+ refGroupingCfg,
462
+ refGroupingRadius: referenceLineGrouping
463
+ ? (refGroupingCfg?.radius ?? 18)
464
+ : null,
465
+ refGroupBadge: resolveReferenceGroupBadge(refGroupingCfg?.badge),
466
+ refGroupFormat: refGroupingCfg?.format,
467
+ badgeUsesRightGutter:
468
+ badgeCfg !== null && (badgeCfg.position ?? "right") === "right",
469
+ };
470
+ }
471
+
472
+ function useLiveReferenceState(
473
+ allRefLines: ReferenceLine[],
474
+ draggableRefIdx: number[],
475
+ thresholdRangeValueSV: SharedValue<number> | null,
476
+ ) {
477
+ const dragValues = useSharedValue<number[]>([]);
478
+ const dragActive = useSharedValue<boolean[]>([]);
479
+ const seededRef = useRef<(number | undefined)[]>([]);
480
+ const refValueSig = allRefLines.map((line) => line.value ?? "_").join(",");
481
+ const propValues = useMemo<(number | undefined)[]>(() => {
482
+ if (refValueSig === "") return [];
483
+ return refValueSig
484
+ .split(",")
485
+ .map((encoded) => (encoded === "_" ? undefined : Number(encoded)));
486
+ }, [refValueSig]);
487
+ useEffect(() => {
488
+ const active = dragActive.get();
489
+ const current = dragValues.get();
490
+ const seeded = seededRef.current;
491
+ dragValues.set(
492
+ propValues.map((value, index) => {
493
+ const prop = value ?? 0;
494
+ if (active[index]) return current[index] ?? prop;
495
+ if (value !== seeded[index]) return prop;
496
+ return current[index] ?? prop;
497
+ }),
498
+ );
499
+ seededRef.current = propValues;
500
+ if (dragActive.get().length !== propValues.length) {
501
+ dragActive.set(propValues.map((_, index) => active[index] ?? false));
502
+ }
503
+ }, [dragActive, dragValues, propValues]);
504
+
505
+ const refLineCustomTagWidths = useSharedValue<number[]>([]);
554
506
  const liveRefValues = useDerivedValue<number[]>(() => {
555
- if (draggableRefIdx.length === 0 && thresholdRangeValueSV === null)
507
+ if (draggableRefIdx.length === 0 && thresholdRangeValueSV === null) {
556
508
  return EMPTY_NUMS;
557
- const out: number[] = [];
509
+ }
510
+ const output: number[] = [];
558
511
  if (draggableRefIdx.length > 0) {
559
- const dv = dragValues.get();
560
- for (let k = 0; k < draggableRefIdx.length; k++) {
561
- const v = dv[draggableRefIdx[k]];
562
- if (v != null) out.push(v);
512
+ const values = dragValues.get();
513
+ for (let index = 0; index < draggableRefIdx.length; index++) {
514
+ const value = values[draggableRefIdx[index]];
515
+ if (value != null) output.push(value);
563
516
  }
564
517
  }
565
518
  if (thresholdRangeValueSV !== null) {
566
- const v = thresholdRangeValueSV.get();
567
- if (Number.isFinite(v)) out.push(v);
519
+ const value = thresholdRangeValueSV.get();
520
+ if (Number.isFinite(value)) output.push(value);
568
521
  }
569
- return out;
522
+ return output;
570
523
  });
571
524
 
572
- // Reference-line grouping (collapse near-value handles). Resolved once; the
573
- // per-frame clustering runs on the UI thread (see ReferenceLineGroupOverlay).
574
- const refGroupingCfg =
575
- typeof referenceLineGrouping === "object"
576
- ? referenceLineGrouping
577
- : undefined;
578
- const refGroupingRadius = referenceLineGrouping
579
- ? (refGroupingCfg?.radius ?? 18)
580
- : null;
581
- // Count-pill styling (same style/shape config as a per-line badge) + count
582
- // formatter. Resolved once; theme color defaults are applied in the overlay.
583
- const refGroupBadge = resolveReferenceGroupBadge(refGroupingCfg?.badge);
584
- const refGroupFormat = refGroupingCfg?.format;
585
-
586
- const badgeUsesRightGutter =
587
- badgeCfg !== null && (badgeCfg.position ?? "right") === "right";
588
-
589
- // ── Theme, font and layout ─────────────────────────────────────────────
525
+ return { dragValues, dragActive, refLineCustomTagWidths, liveRefValues };
526
+ }
527
+
528
+ function resolveLiveChartPresentationConfig({
529
+ accentColor,
530
+ theme,
531
+ paletteOverride,
532
+ segments,
533
+ leftEdgeFade,
534
+ fontProp,
535
+ badgeCfg,
536
+ refGroupBadge,
537
+ pulseCfg,
538
+ timeScroll,
539
+ isStatic,
540
+ returnToLive,
541
+ zoom,
542
+ yAxisCfg,
543
+ }: {
544
+ accentColor: string;
545
+ theme: NonNullable<LiveChartProps["theme"]>;
546
+ paletteOverride: LiveChartProps["palette"];
547
+ segments: LiveChartProps["segments"];
548
+ leftEdgeFade: LiveChartProps["leftEdgeFade"];
549
+ fontProp: LiveChartProps["font"];
550
+ badgeCfg: ReturnType<typeof resolveBadge>;
551
+ refGroupBadge: ReturnType<typeof resolveReferenceGroupBadge>;
552
+ pulseCfg: ReturnType<typeof resolvePulse>;
553
+ timeScroll: LiveChartProps["timeScroll"];
554
+ isStatic: boolean;
555
+ returnToLive: LiveChartProps["returnToLive"];
556
+ zoom: LiveChartProps["zoom"];
557
+ yAxisCfg: ReturnType<typeof resolveYAxis>;
558
+ }) {
590
559
  const palette = applyPaletteOverride(
591
560
  resolveTheme(accentColor, theme),
592
561
  paletteOverride,
593
562
  );
594
-
595
- // Time-range segments (sessions, after-hours, …). Resolved once per render like
596
- // reference lines; the divider/label/muted colors default to the chart palette
597
- // (no per-segment base color needed). `hasRecolorSegments` is a render-time gate
598
- // for the line-recolor gradient pass (per-frame visibility is handled by the
599
- // gradient's transparent stops, not by mounting/unmounting the Path).
600
- const resolvedSegments = (segments ?? []).map((s) =>
601
- resolveSegment(s, {
563
+ const resolvedSegments = (segments ?? []).map((segment) =>
564
+ resolveSegment(segment, {
602
565
  muted: palette.gridLabel,
603
566
  divider: palette.refLine,
604
567
  label: palette.refLabel,
605
568
  }),
606
569
  );
607
- const hasRecolorSegments = resolvedSegments.some((s) => s.recolorLine);
608
-
609
- const leftEdgeFadeCfg = resolveLeftEdgeFade(
610
- leftEdgeFade,
611
- leftEdgeFadeColorsFromBgRgb(palette.bgRgb),
612
- );
613
-
614
- const skiaFont = useChartSkiaFont(
615
- fontProp,
616
- MONO_FONT_FAMILY,
617
- palette.labelFontSize,
618
- );
619
-
620
- // Larger font for the optional live-value text overlay (showValue).
621
- const valueFont = useChartSkiaFont(
622
- fontProp,
623
- MONO_FONT_FAMILY,
624
- palette.valueFontSize * 2,
625
- );
626
-
627
- // Per-badge font (size/family/weight) override; reuses the chart font when
628
- // none of the badge font knobs are set, so the gutter sizing is unchanged.
629
570
  const badgeHasFontOverride =
630
571
  badgeCfg?.fontSize != null ||
631
572
  badgeCfg?.fontFamily != null ||
632
573
  badgeCfg?.fontWeight != null;
633
- const badgeFontOverride = useChartSkiaFont(
634
- badgeHasFontOverride
574
+ const refGroupBadgeHasFont =
575
+ refGroupBadge.fontSize != null ||
576
+ refGroupBadge.fontFamily != null ||
577
+ refGroupBadge.fontWeight != null;
578
+ const timeScrollEnabled = Boolean(timeScroll) && !isStatic;
579
+ const zoomCfg = resolveZoom(zoom);
580
+
581
+ return {
582
+ palette,
583
+ resolvedSegments,
584
+ hasRecolorSegments: resolvedSegments.some((segment) => segment.recolorLine),
585
+ leftEdgeFadeCfg: resolveLeftEdgeFade(
586
+ leftEdgeFade,
587
+ leftEdgeFadeColorsFromBgRgb(palette.bgRgb),
588
+ ),
589
+ badgeHasFontOverride,
590
+ badgeFontConfig: badgeHasFontOverride
635
591
  ? {
636
592
  ...fontProp,
637
593
  fontFamily: badgeCfg?.fontFamily ?? fontProp?.fontFamily,
@@ -639,18 +595,8 @@ function useLiveChartController({
639
595
  fontWeight: badgeCfg?.fontWeight ?? fontProp?.fontWeight,
640
596
  }
641
597
  : fontProp,
642
- MONO_FONT_FAMILY,
643
- palette.labelFontSize,
644
- );
645
- const badgeFont = badgeHasFontOverride ? badgeFontOverride : skiaFont;
646
-
647
- // Per-badge font for the grouping count pill (same override pattern as above).
648
- const refGroupBadgeHasFont =
649
- refGroupBadge.fontSize != null ||
650
- refGroupBadge.fontFamily != null ||
651
- refGroupBadge.fontWeight != null;
652
- const refGroupBadgeFontOverride = useChartSkiaFont(
653
- refGroupBadgeHasFont
598
+ refGroupBadgeHasFont,
599
+ refGroupBadgeFontConfig: refGroupBadgeHasFont
654
600
  ? {
655
601
  ...fontProp,
656
602
  fontFamily: refGroupBadge.fontFamily ?? fontProp?.fontFamily,
@@ -658,82 +604,1061 @@ function useLiveChartController({
658
604
  fontWeight: refGroupBadge.fontWeight ?? fontProp?.fontWeight,
659
605
  }
660
606
  : fontProp,
661
- MONO_FONT_FAMILY,
662
- palette.labelFontSize,
663
- );
664
- const refGroupBadgeFont = refGroupBadgeHasFont
665
- ? refGroupBadgeFontOverride
666
- : skiaFont;
607
+ pulseConfig: pulseCfg
608
+ ? {
609
+ maxRadius: pulseCfg.maxRadius,
610
+ strokeWidth: pulseCfg.strokeWidth,
611
+ }
612
+ : null,
613
+ timeScrollEnabled,
614
+ returnToLiveMs: resolveReturnToLiveMs(returnToLive),
615
+ timeScrollOverscroll: timeScrollEnabled ? resolveOverscroll(timeScroll) : 0,
616
+ timeScrollFling: resolveFling(timeScroll),
617
+ zoomCfg,
618
+ zoomEnabled: zoomCfg !== null && !isStatic,
619
+ yAxisFloat: yAxisCfg?.float ?? false,
620
+ };
621
+ }
667
622
 
668
- const pulseConfig = pulseCfg
669
- ? {
670
- maxRadius: pulseCfg.maxRadius,
671
- strokeWidth: pulseCfg.strokeWidth,
623
+ function resolveThresholdColorConfig(
624
+ thresholdCfg: ReturnType<typeof resolveThreshold>,
625
+ palette: LiveChartPalette,
626
+ lineProp: LiveChartProps["line"],
627
+ ) {
628
+ return {
629
+ stopColors: thresholdCfg ? thresholdStops(thresholdCfg, palette) : null,
630
+ splitAbove: thresholdCfg
631
+ ? (thresholdCfg.aboveColor ?? palette.candleUp)
632
+ : null,
633
+ splitBelow: thresholdCfg
634
+ ? (thresholdCfg.belowColor ?? palette.candleDown)
635
+ : null,
636
+ fillOpacity: thresholdCfg?.fillOpacity ?? THRESHOLD_FILL_OPACITY_DEFAULT,
637
+ lineColor: lineProp?.color ?? palette.line,
638
+ };
639
+ }
640
+
641
+ function useThresholdGeometryState({
642
+ engine,
643
+ padding,
644
+ thresholdCfg,
645
+ thresholdSeriesSV,
646
+ emptyThresholdValue,
647
+ }: {
648
+ engine: ReturnType<typeof useLiveChartEngine>;
649
+ padding: ChartPadding;
650
+ thresholdCfg: ReturnType<typeof resolveThreshold>;
651
+ thresholdSeriesSV: SharedValue<LiveChartPoint[]> | null;
652
+ emptyThresholdValue: SharedValue<number>;
653
+ }) {
654
+ const thresholdValue = thresholdCfg?.value ?? emptyThresholdValue;
655
+ const [svSeriesNonEmpty, setSvSeriesNonEmpty] = useState(false);
656
+ useAnimatedReaction(
657
+ () => (thresholdSeriesSV ? thresholdSeriesSV.get().length > 0 : false),
658
+ /* istanbul ignore next -- UI-thread reaction */ (hasPoints, previous) => {
659
+ if (hasPoints !== previous) {
660
+ scheduleOnRN(setSvSeriesNonEmpty, hasPoints);
672
661
  }
673
- : null;
674
-
675
- // Snapshot the live value off the render path to size the right gutter to the
676
- // value label. Reading a SharedValue during render trips Reanimated's
677
- // strict-mode warning, and the gutter only needs a representative magnitude —
678
- // so read it in a layout effect (re-measures before paint, no visible reflow)
679
- // once on mount, re-synced if the `value` SharedValue identity changes.
680
- // react-doctor's "derive during render" fix is exactly what Reanimated forbids
681
- // here, so suppress its effect-read rules at this seed.
682
- const [valueLayoutSample, setValueLayoutSample] = useState<
683
- number | undefined
684
- >(undefined);
685
- // react-doctor-disable-next-line react-doctor/no-derived-state-effect -- Reanimated: must read the SharedValue off the render path
686
- useLayoutEffect(() => {
687
- // react-doctor-disable-next-line react-hooks-js/set-state-in-effect -- Reanimated: seeding from a SharedValue off render is the warning-free path
688
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Reanimated: seed from the SharedValue outside render to avoid strict-mode access warnings
689
- setValueLayoutSample(value.get());
690
- }, [value]);
691
-
692
- // `scrolledBack` mirrors the UI-thread scroll state (engine.viewEnd != null)
693
- // onto the JS thread (set by the reaction below, after the engine exists).
694
- const [scrolledBack, setScrolledBack] = useState(false);
695
- const timeScrollEnabled = Boolean(timeScroll) && !isStatic;
696
- // Glide duration for the return-to-live animation (0 = instant). A sibling of
697
- // `timeScroll` so it survives `timeScroll={false}` (the disable that triggers it).
698
- const returnToLiveMs = resolveReturnToLiveMs(returnToLive);
699
- // Overscroll fraction ([0, 1)) — how far pan/zoom may travel past the data
700
- // bounds into blank space. 0 (the default) keeps the classic hard stops.
701
- const timeScrollOverscroll = timeScrollEnabled
702
- ? resolveOverscroll(timeScroll)
703
- : 0;
704
- // Release inertia (fling) — `timeScroll.fling: false` stops the pan dead.
705
- const timeScrollFling = resolveFling(timeScroll);
706
- const zoomCfg = resolveZoom(zoom);
707
- const zoomEnabled = zoomCfg !== null && !isStatic;
662
+ },
663
+ );
664
+ return {
665
+ thresholdSeriesHasPoints: thresholdSeriesSV
666
+ ? svSeriesNonEmpty
667
+ : Array.isArray(thresholdCfg?.value) && thresholdCfg.value.length > 0,
668
+ thresholdGeom: useThreshold(engine, padding, thresholdValue),
669
+ thresholdSeriesGeom: useThresholdSeries(
670
+ engine,
671
+ padding,
672
+ thresholdValue,
673
+ thresholdSeriesSV,
674
+ thresholdCfg?.extendToNow ?? true,
675
+ thresholdCfg?.line?.labelAnchor ?? "last",
676
+ ),
677
+ };
678
+ }
679
+
680
+ function useThresholdShaderUniforms({
681
+ engine,
682
+ padding,
683
+ samples,
684
+ clipRightX,
685
+ thresholdCfg,
686
+ palette,
687
+ lineProp,
688
+ }: {
689
+ engine: ReturnType<typeof useLiveChartEngine>;
690
+ padding: ChartPadding;
691
+ samples: SharedValue<number[]>;
692
+ clipRightX: SharedValue<number>;
693
+ thresholdCfg: ReturnType<typeof resolveThreshold>;
694
+ palette: LiveChartPalette;
695
+ lineProp: LiveChartProps["line"];
696
+ }) {
697
+ const { stopColors, splitAbove, splitBelow, fillOpacity, lineColor } =
698
+ resolveThresholdColorConfig(thresholdCfg, palette, lineProp);
699
+ const vectors = useMemo(() => {
700
+ if (splitAbove === null || splitBelow === null) return null;
701
+ const [r, g, b, a] = parseColorRgba(lineColor);
702
+ return {
703
+ ...thresholdSplitColorVecs(splitAbove, splitBelow, fillOpacity),
704
+ strokeRest: [r / 255, g / 255, b / 255, a],
705
+ };
706
+ }, [splitAbove, splitBelow, fillOpacity, lineColor]);
707
+ return {
708
+ thresholdStrokeColors: stopColors?.stroke ?? null,
709
+ thresholdFillColors: stopColors?.fill ?? null,
710
+ thresholdStrokeUniforms: useThresholdSplitUniforms(
711
+ samples,
712
+ engine,
713
+ padding,
714
+ vectors?.strokeAbove ?? THRESHOLD_FALLBACK_COLOR,
715
+ vectors?.strokeBelow ?? THRESHOLD_FALLBACK_COLOR,
716
+ vectors?.strokeRest ?? THRESHOLD_FALLBACK_COLOR,
717
+ clipRightX,
718
+ ),
719
+ thresholdFillUniforms: useThresholdSplitUniforms(
720
+ samples,
721
+ engine,
722
+ padding,
723
+ vectors?.fillAbove ?? THRESHOLD_FALLBACK_COLOR,
724
+ vectors?.fillBelow ?? THRESHOLD_FALLBACK_COLOR,
725
+ TRANSPARENT_VEC4,
726
+ clipRightX,
727
+ ),
728
+ };
729
+ }
730
+
731
+ function useThresholdBadgeProjection({
732
+ thresholdCfg,
733
+ thresholdIsSeries,
734
+ thresholdGeom,
735
+ thresholdSeriesGeom,
736
+ renderThresholdBadge,
737
+ formatValue,
738
+ }: {
739
+ thresholdCfg: ReturnType<typeof resolveThreshold>;
740
+ thresholdIsSeries: boolean;
741
+ thresholdGeom: ReturnType<typeof useThreshold>;
742
+ thresholdSeriesGeom: ReturnType<typeof useThresholdSeries>;
743
+ renderThresholdBadge: LiveChartProps["renderThresholdBadge"];
744
+ formatValue: (value: number) => string;
745
+ }) {
746
+ const lineY = thresholdIsSeries
747
+ ? thresholdSeriesGeom.badgeLineY
748
+ : thresholdGeom.lineY;
749
+ const markerVisible = thresholdIsSeries
750
+ ? thresholdSeriesGeom.visible
751
+ : thresholdGeom.visible;
752
+ const badgeVisible = thresholdIsSeries
753
+ ? thresholdSeriesGeom.badgeVisible
754
+ : thresholdGeom.visible;
755
+ const markerValue =
756
+ thresholdCfg && !thresholdIsSeries && !Array.isArray(thresholdCfg.value)
757
+ ? (thresholdCfg.value ?? thresholdSeriesGeom.badgeValue)
758
+ : thresholdSeriesGeom.badgeValue;
759
+ const custom = thresholdCfg?.line != null && renderThresholdBadge != null;
760
+ const valueStr = useDerivedValue(() =>
761
+ custom ? formatValue(markerValue.get()) : "",
762
+ );
763
+ return {
764
+ thresholdMarkerLineY: lineY,
765
+ thresholdMarkerVisible: markerVisible,
766
+ thresholdBadgeVisible: badgeVisible,
767
+ thresholdMarkerValue: markerValue,
768
+ thresholdCustomBadge:
769
+ thresholdCfg?.line && renderThresholdBadge
770
+ ? renderThresholdBadge({
771
+ line: thresholdCfg.line,
772
+ value: markerValue,
773
+ valueStr,
774
+ y: lineY,
775
+ visible: badgeVisible,
776
+ })
777
+ : null,
778
+ thresholdSeriesPts: thresholdIsSeries
779
+ ? thresholdSeriesGeom.screenPts
780
+ : undefined,
781
+ };
782
+ }
783
+
784
+ function useLiveChartThresholdModel({
785
+ engine,
786
+ padding,
787
+ thresholdCfg,
788
+ thresholdSeriesSV,
789
+ thresholdIsSeries,
790
+ emptyThresholdValue,
791
+ palette,
792
+ lineProp,
793
+ renderThresholdBadge,
794
+ formatValue,
795
+ }: {
796
+ engine: ReturnType<typeof useLiveChartEngine>;
797
+ padding: ChartPadding;
798
+ thresholdCfg: ReturnType<typeof resolveThreshold>;
799
+ thresholdSeriesSV: SharedValue<LiveChartPoint[]> | null;
800
+ thresholdIsSeries: boolean;
801
+ emptyThresholdValue: SharedValue<number>;
802
+ palette: LiveChartPalette;
803
+ lineProp: LiveChartProps["line"];
804
+ renderThresholdBadge: LiveChartProps["renderThresholdBadge"];
805
+ formatValue: (value: number) => string;
806
+ }) {
807
+ const { thresholdSeriesHasPoints, thresholdGeom, thresholdSeriesGeom } =
808
+ useThresholdGeometryState({
809
+ engine,
810
+ padding,
811
+ thresholdCfg,
812
+ thresholdSeriesSV,
813
+ emptyThresholdValue,
814
+ });
815
+ const shaderModel = useThresholdShaderUniforms({
816
+ engine,
817
+ padding,
818
+ samples: thresholdSeriesGeom.samples,
819
+ clipRightX: thresholdSeriesGeom.clipRightX,
820
+ thresholdCfg,
821
+ palette,
822
+ lineProp,
823
+ });
824
+ const badgeModel = useThresholdBadgeProjection({
825
+ thresholdCfg,
826
+ thresholdIsSeries,
827
+ thresholdGeom,
828
+ thresholdSeriesGeom,
829
+ renderThresholdBadge,
830
+ formatValue,
831
+ });
832
+
833
+ return {
834
+ thresholdGeom,
835
+ thresholdSeriesHasPoints,
836
+ ...shaderModel,
837
+ ...badgeModel,
838
+ thresholdFillLineY:
839
+ thresholdCfg?.fill && !thresholdIsSeries
840
+ ? thresholdGeom.lineY
841
+ : undefined,
842
+ thresholdFillSamples:
843
+ thresholdCfg?.fill && thresholdSeriesHasPoints
844
+ ? thresholdSeriesGeom.samples
845
+ : undefined,
846
+ };
847
+ }
848
+
849
+ function resolveLiveChartInteractionConfig({
850
+ isCandle,
851
+ mode,
852
+ candlesEngine,
853
+ liveEngine,
854
+ candleWidth,
855
+ candleGapsCfg,
856
+ lineGapsCfg,
857
+ markers,
858
+ markerCluster,
859
+ onReferenceLinePress,
860
+ allRefLines,
861
+ isStatic,
862
+ timeScroll,
863
+ timeScrollEnabled,
864
+ scrubCfg,
865
+ }: {
866
+ isCandle: boolean;
867
+ mode: "line" | "candle";
868
+ candlesEngine: SharedValue<CandlePoint[]>;
869
+ liveEngine: SharedValue<CandlePoint | null>;
870
+ candleWidth: number;
871
+ candleGapsCfg: ResolvedCandleGapsConfig | null;
872
+ lineGapsCfg: ResolvedCandleGapsConfig | null;
873
+ markers: LiveChartProps["markers"];
874
+ markerCluster: LiveChartProps["markerCluster"];
875
+ onReferenceLinePress: LiveChartProps["onReferenceLinePress"];
876
+ allRefLines: ReferenceLine[];
877
+ isStatic: boolean;
878
+ timeScroll: LiveChartProps["timeScroll"];
879
+ timeScrollEnabled: boolean;
880
+ scrubCfg: ReturnType<typeof resolveScrub>;
881
+ }) {
882
+ const crosshairChartOpts = isCandle
883
+ ? {
884
+ mode,
885
+ candles: candlesEngine,
886
+ liveCandle: liveEngine,
887
+ candleWidthSecs: candleWidth,
888
+ gaps: candleGapsCfg?.gaps,
889
+ bridgeNoTrades: Boolean(candleGapsCfg?.styles["no-trades"].bridge),
890
+ bridgeUnavailable: Boolean(candleGapsCfg?.styles.unavailable.bridge),
891
+ bridgeUnknown: Boolean(candleGapsCfg?.styles.unknown.bridge),
892
+ }
893
+ : lineGapsCfg
894
+ ? {
895
+ mode,
896
+ gaps: lineGapsCfg.gaps,
897
+ bridgeNoTrades: Boolean(lineGapsCfg.styles["no-trades"].bridge),
898
+ bridgeUnavailable: Boolean(lineGapsCfg.styles.unavailable.bridge),
899
+ bridgeUnknown: Boolean(lineGapsCfg.styles.unknown.bridge),
900
+ }
901
+ : undefined;
902
+ const scrollGestureMode =
903
+ typeof timeScroll === "object"
904
+ ? (timeScroll.gesture ?? "holdToScrub")
905
+ : "holdToScrub";
906
+ const timeScrollHoldMs =
907
+ typeof timeScroll === "object" ? timeScroll.scrubHoldMs : undefined;
908
+
909
+ return {
910
+ crosshairChartOpts,
911
+ markersActive: markers != null,
912
+ markerClusterCfg: resolveMarkerCluster(markerCluster),
913
+ refPressActive: onReferenceLinePress != null && allRefLines.length > 0,
914
+ refDragEnabled:
915
+ !isStatic && allRefLines.some((line) => line.draggable === true),
916
+ scrollGestureMode,
917
+ scrubHoldMs:
918
+ timeScrollEnabled && scrollGestureMode === "holdToScrub"
919
+ ? (timeScrollHoldMs ?? (scrubCfg?.panGestureDelay || HOLD_TO_SCRUB_MS))
920
+ : (scrubCfg?.panGestureDelay ?? 0),
921
+ };
922
+ }
923
+
924
+ function composeLiveChartRootGesture({
925
+ crosshair,
926
+ markerTapGesture,
927
+ refLineTapGesture,
928
+ refDragGesture,
929
+ panScrollGesture,
930
+ pinchZoomGesture,
931
+ markersActive,
932
+ refPressActive,
933
+ refDragEnabled,
934
+ scrubActionActive,
935
+ timeScrollEnabled,
936
+ scrollGestureMode,
937
+ zoomEnabled,
938
+ }: {
939
+ crosshair: ReturnType<typeof useCrosshair>;
940
+ markerTapGesture: ReturnType<typeof useMarkers>["tapGesture"];
941
+ refLineTapGesture: ReturnType<typeof useReferenceLinePress>["tapGesture"];
942
+ refDragGesture: ReturnType<typeof useReferenceDrag>["gesture"];
943
+ panScrollGesture: ReturnType<typeof usePanScroll>;
944
+ pinchZoomGesture: ReturnType<typeof usePinchZoom>;
945
+ markersActive: boolean;
946
+ refPressActive: boolean;
947
+ refDragEnabled: boolean;
948
+ scrubActionActive: boolean;
949
+ timeScrollEnabled: boolean;
950
+ scrollGestureMode: "holdToScrub" | "axisDrag";
951
+ zoomEnabled: boolean;
952
+ }) {
953
+ const baseGesture =
954
+ scrubActionActive && crosshair.tapGesture
955
+ ? Gesture.Exclusive(crosshair.tapGesture, crosshair.gesture)
956
+ : crosshair.gesture;
957
+ const overlayTaps = [
958
+ markersActive ? markerTapGesture : null,
959
+ refPressActive ? refLineTapGesture : null,
960
+ ].filter(
961
+ (gesture): gesture is NonNullable<typeof gesture> => gesture !== null,
962
+ );
963
+ let rootGesture = baseGesture;
964
+ if (overlayTaps.length > 0) {
965
+ const tapGroup =
966
+ overlayTaps.length === 1
967
+ ? overlayTaps[0]
968
+ : Gesture.Simultaneous(overlayTaps[0], overlayTaps[1]);
969
+ rootGesture = Gesture.Simultaneous(baseGesture, tapGroup);
970
+ }
971
+ if (timeScrollEnabled) {
972
+ rootGesture =
973
+ scrollGestureMode === "axisDrag"
974
+ ? Gesture.Exclusive(panScrollGesture, rootGesture)
975
+ : Gesture.Race(panScrollGesture, rootGesture);
976
+ }
977
+ if (refDragEnabled) {
978
+ rootGesture = Gesture.Exclusive(refDragGesture, rootGesture);
979
+ }
980
+ return zoomEnabled
981
+ ? Gesture.Simultaneous(rootGesture, pinchZoomGesture)
982
+ : rootGesture;
983
+ }
984
+
985
+ function useAxisAutoHide({
986
+ config,
987
+ scrollActive,
988
+ scrubActive,
989
+ engine,
990
+ }: {
991
+ config: LiveChartProps["axisAutoHide"];
992
+ scrollActive: SharedValue<boolean>;
993
+ scrubActive: SharedValue<boolean>;
994
+ engine: ReturnType<typeof useLiveChartEngine>;
995
+ }) {
996
+ const resolved = config === true ? {} : config === false ? null : config;
997
+ const idleOpacity = resolved?.idleOpacity ?? 0;
998
+ const fadeInMs = resolved?.fadeInMs ?? 60;
999
+ const fadeOutMs = resolved?.fadeOutMs ?? 250;
1000
+ const hideAfterMs = resolved?.hideAfterMs ?? 3000;
1001
+ const opacity = useSharedValue(resolved ? idleOpacity : 1);
1002
+ const enabled = resolved !== null;
1003
+ const last = useRef({ enabled, idleOpacity });
1004
+ useEffect(() => {
1005
+ if (
1006
+ last.current.enabled === enabled &&
1007
+ last.current.idleOpacity === idleOpacity
1008
+ ) {
1009
+ return;
1010
+ }
1011
+ last.current = { enabled, idleOpacity };
1012
+ cancelAnimation(opacity);
1013
+ opacity.value = enabled ? idleOpacity : 1;
1014
+ }, [enabled, idleOpacity, opacity]);
1015
+ useAnimatedReaction(
1016
+ () => ({
1017
+ gesture: scrollActive.value || scrubActive.value,
1018
+ viewEnd: engine.viewEnd.value,
1019
+ viewWindow: engine.viewWindow.value,
1020
+ }),
1021
+ (current, previous) => {
1022
+ if (!enabled || previous === null) return;
1023
+ const moved =
1024
+ current.gesture !== previous.gesture ||
1025
+ current.viewEnd !== previous.viewEnd ||
1026
+ current.viewWindow !== previous.viewWindow;
1027
+ if (!moved) return;
1028
+ cancelAnimation(opacity);
1029
+ opacity.value = current.gesture
1030
+ ? withTiming(1, { duration: fadeInMs })
1031
+ : withSequence(
1032
+ withTiming(1, { duration: fadeInMs }),
1033
+ withDelay(
1034
+ hideAfterMs,
1035
+ withTiming(idleOpacity, { duration: fadeOutMs }),
1036
+ ),
1037
+ );
1038
+ },
1039
+ [enabled, idleOpacity, fadeInMs, fadeOutMs, hideAfterMs],
1040
+ );
1041
+ return opacity;
1042
+ }
1043
+
1044
+ function resolveLiveEngineModeInputs({
1045
+ isCandle,
1046
+ data,
1047
+ lineEngineData,
1048
+ candles,
1049
+ candlesEngine,
1050
+ liveCandle,
1051
+ liveEngine,
1052
+ candleGapsCfg,
1053
+ thresholdInRange,
1054
+ thresholdIsSeries,
1055
+ thresholdSeriesSV,
1056
+ thresholdCfg,
1057
+ }: {
1058
+ isCandle: boolean;
1059
+ data: LiveChartProps["data"];
1060
+ lineEngineData: LiveChartProps["data"];
1061
+ candles: LiveChartProps["candles"];
1062
+ candlesEngine: SharedValue<CandlePoint[]>;
1063
+ liveCandle: LiveChartProps["liveCandle"];
1064
+ liveEngine: SharedValue<CandlePoint | null>;
1065
+ candleGapsCfg: ResolvedCandleGapsConfig | null;
1066
+ thresholdInRange: boolean;
1067
+ thresholdIsSeries: boolean;
1068
+ thresholdSeriesSV: SharedValue<LiveChartPoint[]> | null;
1069
+ thresholdCfg: ResolvedThresholdConfig | null;
1070
+ }) {
1071
+ return {
1072
+ data: isCandle ? data : lineEngineData,
1073
+ thresholdRangePoints:
1074
+ thresholdInRange && thresholdIsSeries
1075
+ ? (thresholdSeriesSV ?? (thresholdCfg?.value as LiveChartPoint[]))
1076
+ : undefined,
1077
+ thresholdRangeExtendToNow: thresholdCfg?.extendToNow ?? true,
1078
+ candles: isCandle ? candlesEngine : candles,
1079
+ liveCandle: isCandle ? liveEngine : liveCandle,
1080
+ candleGaps: candleGapsCfg?.gaps,
1081
+ candleGapBridgeNoTrades: Boolean(candleGapsCfg?.styles["no-trades"].bridge),
1082
+ candleGapBridgeUnavailable: Boolean(
1083
+ candleGapsCfg?.styles.unavailable.bridge,
1084
+ ),
1085
+ candleGapBridgeUnknown: Boolean(candleGapsCfg?.styles.unknown.bridge),
1086
+ };
1087
+ }
1088
+
1089
+ function resolveCrosshairControllerSettings({
1090
+ scrubCfg,
1091
+ scrubActionCfg,
1092
+ markersActive,
1093
+ refPressActive,
1094
+ refDragEnabled,
1095
+ deferTapHit,
1096
+ timeScrollEnabled,
1097
+ scrollGestureMode,
1098
+ effectivePadding,
1099
+ }: {
1100
+ scrubCfg: ReturnType<typeof resolveScrub>;
1101
+ scrubActionCfg: ReturnType<typeof resolveScrubAction>;
1102
+ markersActive: boolean;
1103
+ refPressActive: boolean;
1104
+ refDragEnabled: boolean;
1105
+ deferTapHit: (x: number, y: number) => boolean;
1106
+ timeScrollEnabled: boolean;
1107
+ scrollGestureMode: "holdToScrub" | "axisDrag";
1108
+ effectivePadding: ChartPadding;
1109
+ }) {
1110
+ return {
1111
+ enabled: scrubCfg !== null || scrubActionCfg !== null,
1112
+ deferTapHit:
1113
+ markersActive || refPressActive || refDragEnabled
1114
+ ? deferTapHit
1115
+ : undefined,
1116
+ tooltipPlacement: scrubCfg?.tooltipPlacement ?? "side",
1117
+ tooltipShowValue: scrubCfg?.tooltipShowValue ?? true,
1118
+ tooltipShowTime: scrubCfg?.tooltipShowTime ?? true,
1119
+ tooltipMargin: scrubCfg?.tooltipMargin ?? 8,
1120
+ scrubBottomExclude:
1121
+ timeScrollEnabled && scrollGestureMode === "axisDrag"
1122
+ ? Math.max(effectivePadding.bottom, AXIS_GRAB_MIN_PX)
1123
+ : 0,
1124
+ clampToPlot: scrubCfg?.clampToPlot ?? false,
1125
+ snapToCandles: scrubCfg?.snapToCandles ?? false,
1126
+ };
1127
+ }
1128
+
1129
+ function resolveAreaDotColorVec(
1130
+ areaDotsCfg: ReturnType<typeof resolveAreaDots>,
1131
+ lineProp: LiveChartProps["line"],
1132
+ palette: LiveChartPalette,
1133
+ ) {
1134
+ const rgb = parseColorRgb(lineProp?.color ?? palette.line);
1135
+ const [r, g, b, a] = parseColorRgba(
1136
+ areaDotsCfg?.color ?? `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, 0.22)`,
1137
+ );
1138
+ return [r / 255, g / 255, b / 255, a * (areaDotsCfg?.opacity ?? 1)];
1139
+ }
1140
+
1141
+ function useLiveIndicatorOpacities({
1142
+ reveal,
1143
+ seriesIndicatorOpacity,
1144
+ seriesOpacity,
1145
+ scrubActive,
1146
+ selectionDotDuringScrub,
1147
+ hideLiveOnScrollBack,
1148
+ dotTracksParked,
1149
+ viewEnd,
1150
+ fadeOverlaysOnScrub,
1151
+ }: {
1152
+ reveal: ReturnType<typeof useChartReveal>;
1153
+ seriesIndicatorOpacity: SharedValue<number>;
1154
+ seriesOpacity: SharedValue<number>;
1155
+ scrubActive: SharedValue<boolean>;
1156
+ selectionDotDuringScrub: boolean;
1157
+ hideLiveOnScrollBack: boolean;
1158
+ dotTracksParked: boolean;
1159
+ viewEnd: SharedValue<number | null>;
1160
+ fadeOverlaysOnScrub: boolean;
1161
+ }) {
1162
+ const liveDotOpacity = useDerivedValue(
1163
+ () =>
1164
+ reveal.dotOpacity.value *
1165
+ (selectionDotDuringScrub && scrubActive.value ? 0 : 1) *
1166
+ liveIndicatorScrollOpacity(
1167
+ hideLiveOnScrollBack && !dotTracksParked,
1168
+ viewEnd.value,
1169
+ ) *
1170
+ seriesIndicatorOpacity.value,
1171
+ );
1172
+ const valueLineOpacity = useDerivedValue(
1173
+ () =>
1174
+ reveal.lineOpacity.value *
1175
+ liveIndicatorScrollOpacity(hideLiveOnScrollBack, viewEnd.value) *
1176
+ seriesOpacity.value,
1177
+ );
1178
+ const liveBadgeOpacity = useDerivedValue(
1179
+ () =>
1180
+ reveal.badgeOpacity.value *
1181
+ liveIndicatorScrollOpacity(hideLiveOnScrollBack, viewEnd.value) *
1182
+ seriesOpacity.value,
1183
+ );
1184
+ const overlayScrubFade = useDerivedValue(() =>
1185
+ fadeOverlaysOnScrub
1186
+ ? withTiming(scrubActive.get() ? 0 : 1, {
1187
+ duration: SCRUB_OVERLAY_FADE_MS,
1188
+ })
1189
+ : 1,
1190
+ );
1191
+ const markerGroupOpacity = useDerivedValue(
1192
+ () => reveal.dotOpacity.get() * overlayScrubFade.get(),
1193
+ );
1194
+ return {
1195
+ liveDotOpacity,
1196
+ valueLineOpacity,
1197
+ liveBadgeOpacity,
1198
+ overlayScrubFade,
1199
+ markerGroupOpacity,
1200
+ };
1201
+ }
1202
+
1203
+ function useReferenceLineGrouping({
1204
+ radius,
1205
+ engine,
1206
+ padding,
1207
+ lines,
1208
+ custom,
1209
+ offAxisCustom,
1210
+ dragValues,
1211
+ }: {
1212
+ radius: number | null;
1213
+ engine: ReturnType<typeof useLiveChartEngine>;
1214
+ padding: ChartPadding;
1215
+ lines: ReferenceLine[];
1216
+ custom: boolean[];
1217
+ offAxisCustom: boolean[];
1218
+ dragValues: SharedValue<number[]>;
1219
+ }) {
1220
+ const result = useDerivedValue<ReferenceGrouping>(() => {
1221
+ if (radius == null) return EMPTY_GROUPING;
1222
+ const canvasHeight = engine.canvasHeight.get();
1223
+ const displayMin = engine.displayMin.get();
1224
+ const displayMax = engine.displayMax.get();
1225
+ const top = padding.top;
1226
+ const bottom = canvasHeight - padding.bottom;
1227
+ const yPositions: number[] = [];
1228
+ for (let index = 0; index < lines.length; index++) {
1229
+ const line = lines[index];
1230
+ if (
1231
+ referenceLineForm(line) !== "line" ||
1232
+ line.value === undefined ||
1233
+ custom[index] ||
1234
+ offAxisCustom[index]
1235
+ ) {
1236
+ yPositions.push(-1);
1237
+ continue;
1238
+ }
1239
+ const value = dragValues.get()[index] ?? line.value;
1240
+ const y = computeScrubDotY(
1241
+ value,
1242
+ displayMin,
1243
+ displayMax,
1244
+ canvasHeight,
1245
+ top,
1246
+ padding.bottom,
1247
+ );
1248
+ yPositions.push(y < 0 ? -1 : Math.min(bottom, Math.max(top, y)));
1249
+ }
1250
+ return groupReferenceLines(yPositions, radius);
1251
+ });
1252
+ const hidden = useDerivedValue<boolean[]>(() => result.get().hidden);
1253
+ return { refGroupResult: result, groupHidden: hidden };
1254
+ }
1255
+
1256
+ function useLiveChartLayoutResources({
1257
+ value,
1258
+ fontProp,
1259
+ palette,
1260
+ badgeHasFontOverride,
1261
+ badgeFontConfig,
1262
+ refGroupBadgeHasFont,
1263
+ refGroupBadgeFontConfig,
1264
+ yAxisFloat,
1265
+ timeScrollEnabled,
1266
+ lineProp,
1267
+ insets,
1268
+ yAxisCfg,
1269
+ badgeCfg,
1270
+ metricsCfg,
1271
+ badgeUsesRightGutter,
1272
+ xAxisCfg,
1273
+ formatValue,
1274
+ pulseConfig,
1275
+ dotCfg,
1276
+ volumeBandHeight,
1277
+ }: {
1278
+ value: LiveChartProps["value"];
1279
+ fontProp: LiveChartProps["font"];
1280
+ palette: LiveChartPalette;
1281
+ badgeHasFontOverride: boolean;
1282
+ badgeFontConfig: LiveChartProps["font"];
1283
+ refGroupBadgeHasFont: boolean;
1284
+ refGroupBadgeFontConfig: LiveChartProps["font"];
1285
+ yAxisFloat: boolean;
1286
+ timeScrollEnabled: boolean;
1287
+ lineProp: LiveChartProps["line"];
1288
+ insets: LiveChartProps["insets"];
1289
+ yAxisCfg: ReturnType<typeof resolveYAxis>;
1290
+ badgeCfg: ReturnType<typeof resolveBadge>;
1291
+ metricsCfg: ReturnType<typeof resolveMetrics>;
1292
+ badgeUsesRightGutter: boolean;
1293
+ xAxisCfg: ReturnType<typeof resolveXAxis>;
1294
+ formatValue: (value: number) => string;
1295
+ pulseConfig: { maxRadius: number; strokeWidth: number } | null;
1296
+ dotCfg: ReturnType<typeof resolveDot>;
1297
+ volumeBandHeight: number;
1298
+ }) {
1299
+ const skiaFont = useChartSkiaFont(
1300
+ fontProp,
1301
+ MONO_FONT_FAMILY,
1302
+ palette.labelFontSize,
1303
+ );
1304
+ const valueFont = useChartSkiaFont(
1305
+ fontProp,
1306
+ MONO_FONT_FAMILY,
1307
+ palette.valueFontSize * 2,
1308
+ );
1309
+ const badgeFontOverride = useChartSkiaFont(
1310
+ badgeFontConfig,
1311
+ MONO_FONT_FAMILY,
1312
+ palette.labelFontSize,
1313
+ );
1314
+ const badgeFont = badgeHasFontOverride ? badgeFontOverride : skiaFont;
1315
+ const refGroupBadgeFontOverride = useChartSkiaFont(
1316
+ refGroupBadgeFontConfig,
1317
+ MONO_FONT_FAMILY,
1318
+ palette.labelFontSize,
1319
+ );
1320
+ const refGroupBadgeFont = refGroupBadgeHasFont
1321
+ ? refGroupBadgeFontOverride
1322
+ : skiaFont;
1323
+ const valueLayoutSample = useInitialSharedValueSample(value);
1324
+ const [scrolledBack, setScrolledBack] = useState(false);
1325
+ const effectiveYAxisFloat =
1326
+ yAxisFloat && (!timeScrollEnabled || scrolledBack);
1327
+ const layout = resolveChartLayout({
1328
+ palette,
1329
+ lineWidthOverride: lineProp?.width,
1330
+ insetsOverride: insets,
1331
+ yAxis: yAxisCfg !== null,
1332
+ yAxisFloat: effectiveYAxisFloat,
1333
+ badge: badgeCfg !== null,
1334
+ badgeMetrics: metricsCfg.badge,
1335
+ badgeUsesRightGutter,
1336
+ badgeShowTail: badgeCfg?.tail ?? true,
1337
+ xAxis: xAxisCfg !== null,
1338
+ font: skiaFont,
1339
+ formatValue,
1340
+ currentValue: valueLayoutSample,
1341
+ pulse: pulseConfig,
1342
+ dotGlow: dotCfg.glow,
1343
+ volumeBandHeight,
1344
+ });
1345
+ return {
1346
+ skiaFont,
1347
+ valueFont,
1348
+ badgeFont,
1349
+ refGroupBadgeFont,
1350
+ effectiveYAxisFloat,
1351
+ setScrolledBack,
1352
+ ...layout,
1353
+ };
1354
+ }
1355
+
1356
+ function useInitialSharedValueSample(value: SharedValue<number>) {
1357
+ const [sample, setSample] = useState<number | undefined>(undefined);
1358
+ const captured = useSharedValue(false);
1359
+ useAnimatedReaction(
1360
+ () => (captured.get() ? null : value.get()),
1361
+ (current) => {
1362
+ if (current === null) return;
1363
+ captured.set(true);
1364
+ scheduleOnRN(setSample, current);
1365
+ },
1366
+ [captured, value],
1367
+ );
1368
+ return sample;
1369
+ }
1370
+
1371
+ function resolveLiveChartModelDefaults({
1372
+ isCandle,
1373
+ candleWidth,
1374
+ loadingCfg,
1375
+ volumeCfg,
1376
+ palette,
1377
+ lineProp,
1378
+ }: {
1379
+ isCandle: boolean;
1380
+ candleWidth: number;
1381
+ loadingCfg: ReturnType<typeof resolveLoading>;
1382
+ volumeCfg: ReturnType<typeof resolveVolume>;
1383
+ palette: LiveChartPalette;
1384
+ lineProp: LiveChartProps["line"];
1385
+ }) {
1386
+ return {
1387
+ extremaTimeOffset: isCandle ? candleWidth / 2 : 0,
1388
+ loadingLineColor: loadingCfg?.color,
1389
+ loadingStrokeWidth: loadingCfg?.strokeWidth,
1390
+ loadingAmplitude: loadingCfg?.amplitude,
1391
+ loadingSpeed: loadingCfg?.speed,
1392
+ loadingAxisLabels: loadingCfg?.axisLabels ?? true,
1393
+ volumeOpacity: volumeCfg?.opacity ?? 1,
1394
+ volumeUpColor: volumeCfg?.upColor ?? palette.candleUp,
1395
+ volumeDownColor: volumeCfg?.downColor ?? palette.candleDown,
1396
+ selectionColor: lineProp?.color ?? palette.line,
1397
+ };
1398
+ }
1399
+
1400
+ /**
1401
+ * Resolves props → configs → theme/layout → engine → per-frame derived values and
1402
+ * overlay hooks, returning a single render model. All the chart's wiring lives
1403
+ * here so the rendered pieces (`ChartStack`, `ChartScrubLayer`, `LiveChart`) stay
1404
+ * small and presentational.
1405
+ */
1406
+
1407
+ function useLiveChartController({
1408
+ // ── Data ────────────────────────────────────────────────────────────────
1409
+ data,
1410
+ value,
1411
+
1412
+ // ── Appearance ──────────────────────────────────────────────────────────
1413
+ theme = "dark",
1414
+ accentColor = DEFAULT_ACCENT_COLOR,
1415
+ gradient = true,
1416
+ areaDots,
1417
+ line: lineProp,
1418
+ font: fontProp,
1419
+ insets,
1420
+ style,
1421
+ seriesOpacity,
1422
+ canvasMode = "transparent",
1423
+
1424
+ // ── Candlestick ─────────────────────────────────────────────────────────
1425
+ mode = "line",
1426
+ candles,
1427
+ candleWidth = 60,
1428
+ liveCandle,
1429
+ candleGaps,
1430
+ lineGaps,
1431
+ volume,
1432
+
1433
+ // ── Behaviour ───────────────────────────────────────────────────────────
1434
+ timeWindow = 30,
1435
+ paused = false,
1436
+ loading = false,
1437
+ transitions,
1438
+ // `static` is a reserved word — alias it so the destructure parses.
1439
+ static: isStatic = false,
1440
+ snapKey,
1441
+ smoothing = 0.08,
1442
+ exaggerate = false,
1443
+ nonNegative = false,
1444
+ maxValue,
1445
+ yRangeScale,
1446
+ windowBuffer = 0,
1447
+ nowOverride,
1448
+ timeScroll = false,
1449
+ returnToLive,
1450
+ zoom = false,
1451
+ accessibilityLabel,
1452
+ accessibilityRole = "image",
1453
+ emptyText = "No data",
1454
+ formatValue = defaultFormatValue,
1455
+ formatTime = defaultFormatTime,
1456
+
1457
+ // ── Overlays ────────────────────────────────────────────────────────────
1458
+ yAxis = true,
1459
+ xAxis = true,
1460
+ axisAutoHide = false,
1461
+ topLabel,
1462
+ bottomLabel,
1463
+ badge = true,
1464
+ momentum = true,
1465
+ pulse = true,
1466
+ dot,
1467
+ valueLine = true,
1468
+ showValue = false,
1469
+ valueMomentumColor = false,
1470
+ referenceLines,
1471
+ segments,
1472
+ threshold,
1473
+ gridStyle,
1474
+ palette: paletteOverride,
1475
+ metrics,
1476
+ scrub = true,
1477
+ scrubAction,
1478
+ selectionDot,
1479
+ tradeStream,
1480
+ degen,
1481
+ markers,
1482
+ onMarkerPress,
1483
+ markerHitRadius = 16,
1484
+ markerCluster,
1485
+ renderMarker,
1486
+ renderTooltip,
1487
+ renderOverlay,
1488
+ renderThresholdBadge,
1489
+ renderReferenceLine,
1490
+ renderOffAxisReferenceLine,
1491
+ referenceLineGrouping,
1492
+ leftEdgeFade = true,
1493
+
1494
+ // ── Callbacks ───────────────────────────────────────────────────────────
1495
+ onScrub,
1496
+ onScrubAction,
1497
+ onReferenceLinePress,
1498
+ onGestureStart,
1499
+ onGestureEnd,
1500
+ onVisibleRangeChange,
1501
+ onReachStart,
1502
+ onDegenShake,
1503
+ }: LiveChartProps) {
1504
+ const fullSeriesOpacity = useSharedValue(1);
1505
+ const resolvedSeriesOpacity = seriesOpacity ?? fullSeriesOpacity;
1506
+ const emptyMarkers = useSharedValue<Marker[]>([]);
1507
+ const markersSV = markers ?? emptyMarkers;
1508
+ // Stand-in threshold value so `useThreshold` can be called unconditionally
1509
+ // (hooks can't be); the geometry is ignored when no threshold is configured.
1510
+ const emptyThresholdValue = useSharedValue(0);
1511
+ const {
1512
+ isCandle,
1513
+ yAxisCfg,
1514
+ xAxisCfg,
1515
+ topLabelCfg,
1516
+ bottomLabelCfg,
1517
+ badgeCfg,
1518
+ scrubCfg,
1519
+ scrubActionCfg,
1520
+ volumeCfg,
1521
+ chartGapsCfg,
1522
+ candleGapsCfg,
1523
+ lineGapsCfg,
1524
+ volumeBandHeight,
1525
+ gradientCfg,
1526
+ areaDotsCfg,
1527
+ thresholdCfg,
1528
+ thresholdSeriesSV,
1529
+ thresholdIsSeries,
1530
+ valueLineCfg,
1531
+ pulseCfg,
1532
+ dotCfg,
1533
+ dotTracksParked,
1534
+ selectionDotCfg,
1535
+ dotOuterRadius,
1536
+ gridStyleCfg,
1537
+ degenCfg,
1538
+ tradeStreamResolved,
1539
+ metricsCfg,
1540
+ } = resolveLiveChartFeatureConfig({
1541
+ mode,
1542
+ yAxis,
1543
+ xAxis,
1544
+ topLabel,
1545
+ bottomLabel,
1546
+ badge,
1547
+ scrub,
1548
+ scrubAction,
1549
+ volume,
1550
+ candleGaps,
1551
+ lineGaps,
1552
+ gradient,
1553
+ areaDots,
1554
+ threshold,
1555
+ valueLine,
1556
+ isStatic,
1557
+ pulse,
1558
+ dot,
1559
+ selectionDot,
1560
+ gridStyle,
1561
+ degen,
1562
+ tradeStream,
1563
+ metrics,
1564
+ });
1565
+
1566
+ const {
1567
+ chartGapBands,
1568
+ allRefLines,
1569
+ refValues,
1570
+ refLineCustom,
1571
+ refLineOffAxisCustom,
1572
+ refLineKeys,
1573
+ draggableRefIdx,
1574
+ thresholdInRange,
1575
+ thresholdRangeValueSV,
1576
+ refGroupingCfg,
1577
+ refGroupingRadius,
1578
+ refGroupBadge,
1579
+ refGroupFormat,
1580
+ badgeUsesRightGutter,
1581
+ } = resolveLiveChartReferenceConfig({
1582
+ chartGapsCfg,
1583
+ referenceLines,
1584
+ renderReferenceLine,
1585
+ renderOffAxisReferenceLine,
1586
+ thresholdCfg,
1587
+ referenceLineGrouping,
1588
+ badgeCfg,
1589
+ });
1590
+
1591
+ const { dragValues, dragActive, refLineCustomTagWidths, liveRefValues } =
1592
+ useLiveReferenceState(allRefLines, draggableRefIdx, thresholdRangeValueSV);
1593
+
1594
+ const {
1595
+ palette,
1596
+ resolvedSegments,
1597
+ hasRecolorSegments,
1598
+ leftEdgeFadeCfg,
1599
+ badgeHasFontOverride,
1600
+ badgeFontConfig,
1601
+ refGroupBadgeHasFont,
1602
+ refGroupBadgeFontConfig,
1603
+ pulseConfig,
1604
+ timeScrollEnabled,
1605
+ returnToLiveMs,
1606
+ timeScrollOverscroll,
1607
+ timeScrollFling,
1608
+ zoomCfg,
1609
+ zoomEnabled,
1610
+ yAxisFloat,
1611
+ } = resolveLiveChartPresentationConfig({
1612
+ accentColor,
1613
+ theme,
1614
+ paletteOverride,
1615
+ segments,
1616
+ leftEdgeFade,
1617
+ fontProp,
1618
+ badgeCfg,
1619
+ refGroupBadge,
1620
+ pulseCfg,
1621
+ timeScroll,
1622
+ isStatic,
1623
+ returnToLive,
1624
+ zoom,
1625
+ yAxisCfg,
1626
+ });
708
1627
 
709
- const yAxisFloat = yAxisCfg?.float ?? false;
710
- // With timeScroll, the floating full-width plot engages only while scrolled
711
- // back; at the live edge the chart keeps a normal right gutter so the
712
- // line/candles don't sit under the floating y-axis labels + badge. Without
713
- // timeScroll, float behaves as before (always full-width).
714
- const effectiveYAxisFloat =
715
- yAxisFloat && (!timeScrollEnabled || scrolledBack);
716
- const { strokeWidth, padding: effectivePadding } = resolveChartLayout({
1628
+ const {
1629
+ skiaFont,
1630
+ valueFont,
1631
+ badgeFont,
1632
+ refGroupBadgeFont,
1633
+ effectiveYAxisFloat,
1634
+ setScrolledBack,
1635
+ strokeWidth,
1636
+ padding: effectivePadding,
1637
+ } = useLiveChartLayoutResources({
1638
+ value,
1639
+ fontProp,
717
1640
  palette,
718
- lineWidthOverride: lineProp?.width,
719
- insetsOverride: insets,
720
- yAxis: yAxisCfg !== null,
721
- yAxisFloat: effectiveYAxisFloat,
722
- badge: badgeCfg !== null,
723
- badgeMetrics: metricsCfg.badge,
1641
+ badgeHasFontOverride,
1642
+ badgeFontConfig,
1643
+ refGroupBadgeHasFont,
1644
+ refGroupBadgeFontConfig,
1645
+ yAxisFloat,
1646
+ timeScrollEnabled,
1647
+ lineProp,
1648
+ insets,
1649
+ yAxisCfg,
1650
+ badgeCfg,
1651
+ metricsCfg,
724
1652
  badgeUsesRightGutter,
725
- badgeShowTail: badgeCfg?.tail ?? true,
726
- xAxis: xAxisCfg !== null,
727
- font: skiaFont,
1653
+ xAxisCfg,
728
1654
  formatValue,
729
- currentValue: valueLayoutSample,
730
- pulse: pulseConfig,
731
- dotGlow: dotCfg.glow,
1655
+ pulseConfig,
1656
+ dotCfg,
732
1657
  volumeBandHeight,
733
1658
  });
734
1659
 
735
1660
  // ── Reveal state ────────────────────────────────────────────
736
- // ≥2 line points or ≥2 committed candles; morphT=1 only when !loading && hasData.
1661
+ // ≥1 line point or ≥1 committed candle; morphT=1 only when !loading && hasData.
737
1662
  const { hasData } = useLiveChartHasData({
738
1663
  isCandle,
739
1664
  data,
@@ -770,8 +1695,22 @@ function useLiveChartController({
770
1695
  // ── Engine ─────────────────────────────────────────────────────────────
771
1696
  // Line mode: tick + paths use `lineEngineData` (stash when reversing). Candle mode:
772
1697
  // parent `data` stays tick/line-morph input; OHLC uses candlesEngine + liveEngine.
1698
+ const engineModeInputs = resolveLiveEngineModeInputs({
1699
+ isCandle,
1700
+ data,
1701
+ lineEngineData,
1702
+ candles,
1703
+ candlesEngine,
1704
+ liveCandle,
1705
+ liveEngine,
1706
+ candleGapsCfg,
1707
+ thresholdInRange,
1708
+ thresholdIsSeries,
1709
+ thresholdSeriesSV,
1710
+ thresholdCfg,
1711
+ });
773
1712
  const engine = useLiveChartEngine({
774
- data: isCandle ? data : lineEngineData,
1713
+ ...engineModeInputs,
775
1714
  value,
776
1715
  timeWindow,
777
1716
  paused,
@@ -785,28 +1724,12 @@ function useLiveChartController({
785
1724
  exaggerate,
786
1725
  referenceValues: refValues,
787
1726
  liveReferenceValues: liveRefValues,
788
- // Series threshold with `includeInRange`: the tick folds its window min/max
789
- // into the Y-range fit (the constant form rides `liveReferenceValues`).
790
- thresholdRangePoints:
791
- thresholdInRange && thresholdIsSeries
792
- ? (thresholdSeriesSV ?? (thresholdCfg?.value as LiveChartPoint[]))
793
- : undefined,
794
- thresholdRangeExtendToNow: thresholdCfg?.extendToNow ?? true,
795
1727
  nonNegative,
796
1728
  maxValue,
797
1729
  yRangeScale,
798
1730
  windowBuffer,
799
1731
  nowOverride,
800
1732
  mode,
801
- candles: isCandle ? candlesEngine : candles,
802
- liveCandle: isCandle ? liveEngine : liveCandle,
803
- candleGaps: candleGapsCfg?.gaps,
804
- candleGapBridgeNoTrades:
805
- Boolean(candleGapsCfg?.styles["no-trades"].bridge),
806
- candleGapBridgeUnavailable:
807
- Boolean(candleGapsCfg?.styles.unavailable.bridge),
808
- candleGapBridgeUnknown:
809
- Boolean(candleGapsCfg?.styles.unknown.bridge),
810
1733
  });
811
1734
 
812
1735
  // Mirror the UI-thread scroll state to React so the floating y-axis can keep
@@ -836,174 +1759,48 @@ function useLiveChartController({
836
1759
  // ── Per-frame derived values ───────────────────────────────────────────
837
1760
  const { layoutWidth, layoutHeight, onLayout } = useCanvasLayout(engine);
838
1761
 
839
- // Reference-line grouping: cluster Form-A lines by their per-frame value-Y so a
840
- // stack of nearby orders collapses into one count handle. `groupHidden` suppresses
841
- // the clustered lines' individual tags; the count pills read `refGroupResult`.
842
- // Identity-stable (no work) when grouping is off.
843
- const refGroupResult = useDerivedValue<ReferenceGrouping>(() => {
844
- if (refGroupingRadius == null) return EMPTY_GROUPING;
845
- const ch = engine.canvasHeight.get();
846
- const dMin = engine.displayMin.get();
847
- const dMax = engine.displayMax.get();
848
- const top = effectivePadding.top;
849
- const bottom = ch - effectivePadding.bottom;
850
- const ys: number[] = [];
851
- for (let i = 0; i < allRefLines.length; i++) {
852
- const l = allRefLines[i];
853
- // Skip bands and lines a custom `renderReferenceLine` owns — a custom tag
854
- // draws itself and isn't suppressed by grouping, so folding it into a
855
- // built-in count pill would double-count it (counted *and* still shown).
856
- if (
857
- referenceLineForm(l) !== "line" ||
858
- l.value === undefined ||
859
- refLineCustom[i] ||
860
- refLineOffAxisCustom[i]
861
- ) {
862
- ys.push(-1);
863
- continue;
864
- }
865
- const v = dragValues.get()[i] ?? l.value;
866
- const y = computeScrubDotY(
867
- v,
868
- dMin,
869
- dMax,
870
- ch,
871
- top,
872
- effectivePadding.bottom,
873
- );
874
- ys.push(y < 0 ? -1 : Math.min(bottom, Math.max(top, y)));
875
- }
876
- return groupReferenceLines(ys, refGroupingRadius);
1762
+ const { refGroupResult, groupHidden } = useReferenceLineGrouping({
1763
+ radius: refGroupingRadius,
1764
+ engine,
1765
+ padding: effectivePadding,
1766
+ lines: allRefLines,
1767
+ custom: refLineCustom,
1768
+ offAxisCustom: refLineOffAxisCustom,
1769
+ dragValues,
877
1770
  });
878
- const groupHidden = useDerivedValue<boolean[]>(
879
- () => refGroupResult.get().hidden,
880
- );
881
1771
 
882
1772
  // Threshold split geometry. Two forms, picked at render by `Array.isArray` (no
883
1773
  // SharedValue read): a constant `SharedValue<number>` benchmark drives the
884
1774
  // vertical hard-stop gradient (`thresholdGeom`); a time-varying `LiveChartPoint[]`
885
1775
  // series drives the per-fragment split shader (`thresholdSeriesGeom`). Both hooks
886
1776
  // run unconditionally — the unused one short-circuits cheaply on the UI thread.
887
- const thresholdValue = thresholdCfg?.value ?? emptyThresholdValue;
888
- // An empty series (e.g. threshold history not fetched yet) must not paint: no
889
- // band, no shader-forced stroke color — unlike the constant form, "no points
890
- // yet" is a reachable state and should look like "no threshold". For the live
891
- // `series` SharedValue form the emptiness lives on the UI thread, so mirror it
892
- // to React state (fires only on empty↔non-empty transitions).
893
- const [svSeriesNonEmpty, setSvSeriesNonEmpty] = useState(false);
894
- useAnimatedReaction(
895
- () => (thresholdSeriesSV ? thresholdSeriesSV.get().length > 0 : false),
896
- /* istanbul ignore next -- Reanimated reaction; state mirrored on the JS thread, not exercised under Jest */
897
- (hasPts, prev) => {
898
- if (hasPts !== prev) scheduleOnRN(setSvSeriesNonEmpty, hasPts);
899
- },
900
- );
901
- const thresholdSeriesHasPoints = thresholdSeriesSV
902
- ? svSeriesNonEmpty
903
- : Array.isArray(thresholdCfg?.value) && thresholdCfg.value.length > 0;
904
- const thresholdGeom = useThreshold(engine, effectivePadding, thresholdValue);
905
- const thresholdSeriesGeom = useThresholdSeries(
1777
+ const {
1778
+ thresholdGeom,
1779
+ thresholdStrokeColors,
1780
+ thresholdFillColors,
1781
+ thresholdSeriesHasPoints,
1782
+ thresholdStrokeUniforms,
1783
+ thresholdFillUniforms,
1784
+ thresholdMarkerLineY,
1785
+ thresholdMarkerVisible,
1786
+ thresholdBadgeVisible,
1787
+ thresholdMarkerValue,
1788
+ thresholdCustomBadge,
1789
+ thresholdSeriesPts,
1790
+ thresholdFillLineY,
1791
+ thresholdFillSamples,
1792
+ } = useLiveChartThresholdModel({
906
1793
  engine,
907
- effectivePadding,
908
- thresholdValue,
1794
+ padding: effectivePadding,
1795
+ thresholdCfg,
909
1796
  thresholdSeriesSV,
910
- thresholdCfg?.extendToNow ?? true,
911
- thresholdCfg?.line?.labelAnchor ?? "last",
912
- );
913
- const thresholdStopColors = thresholdCfg
914
- ? thresholdStops(thresholdCfg, palette)
915
- : null;
916
-
917
- // Split colors as vec4s for the series shader, memoized on the *resolved*
918
- // color strings + opacity (so a threshold added after mount with default
919
- // colors still computes, and the per-frame uniforms worklet isn't rebuilt
920
- // every render). `strokeRest` is the plain line color painted right of the
921
- // `extendToNow: false` cutoff.
922
- const thresholdSplitAbove = thresholdCfg
923
- ? (thresholdCfg.aboveColor ?? palette.candleUp)
924
- : null;
925
- const thresholdSplitBelow = thresholdCfg
926
- ? (thresholdCfg.belowColor ?? palette.candleDown)
927
- : null;
928
- const thresholdFillOpacity =
929
- thresholdCfg?.fillOpacity ?? THRESHOLD_FILL_OPACITY_DEFAULT;
930
- const thresholdLineColorStr = lineProp?.color ?? palette.line;
931
- const thresholdVecs = useMemo(
932
- () =>
933
- thresholdSplitAbove !== null && thresholdSplitBelow !== null
934
- ? {
935
- ...thresholdSplitColorVecs(
936
- thresholdSplitAbove,
937
- thresholdSplitBelow,
938
- thresholdFillOpacity,
939
- ),
940
- strokeRest: (() => {
941
- const [r, g, b, a] = parseColorRgba(thresholdLineColorStr);
942
- return [r / 255, g / 255, b / 255, a];
943
- })(),
944
- }
945
- : null,
946
- [
947
- thresholdSplitAbove,
948
- thresholdSplitBelow,
949
- thresholdFillOpacity,
950
- thresholdLineColorStr,
951
- ],
952
- );
953
- const thresholdStrokeUniforms = useThresholdSplitUniforms(
954
- thresholdSeriesGeom.samples,
955
- engine,
956
- effectivePadding,
957
- thresholdVecs?.strokeAbove ?? THRESHOLD_FALLBACK_COLOR,
958
- thresholdVecs?.strokeBelow ?? THRESHOLD_FALLBACK_COLOR,
959
- thresholdVecs?.strokeRest ?? THRESHOLD_FALLBACK_COLOR,
960
- thresholdSeriesGeom.clipRightX,
961
- );
962
- const thresholdFillUniforms = useThresholdSplitUniforms(
963
- thresholdSeriesGeom.samples,
964
- engine,
965
- effectivePadding,
966
- thresholdVecs?.fillAbove ?? THRESHOLD_FALLBACK_COLOR,
967
- thresholdVecs?.fillBelow ?? THRESHOLD_FALLBACK_COLOR,
968
- TRANSPARENT_VEC4,
969
- thresholdSeriesGeom.clipRightX,
970
- );
971
-
972
- // Marker line + badge sources: a series badge independently selects its first
973
- // or last visible endpoint; the constant case stays at the single benchmark Y.
974
- // The badge gets its own visibility because its selected endpoint can be
975
- // off-plot while older polyline segments are still visible.
976
- const thresholdMarkerLineY = thresholdIsSeries
977
- ? thresholdSeriesGeom.badgeLineY
978
- : thresholdGeom.lineY;
979
- const thresholdMarkerVisible = thresholdIsSeries
980
- ? thresholdSeriesGeom.visible
981
- : thresholdGeom.visible;
982
- const thresholdBadgeVisible = thresholdIsSeries
983
- ? thresholdSeriesGeom.badgeVisible
984
- : thresholdGeom.visible;
985
- const thresholdMarkerValue =
986
- thresholdCfg && !thresholdIsSeries && !Array.isArray(thresholdCfg.value)
987
- ? (thresholdCfg.value ?? thresholdSeriesGeom.badgeValue)
988
- : thresholdSeriesGeom.badgeValue;
989
- const hasCustomThresholdBadge =
990
- thresholdCfg?.line != null && renderThresholdBadge != null;
991
- const thresholdMarkerValueStr = useDerivedValue(() =>
992
- hasCustomThresholdBadge ? formatValue(thresholdMarkerValue.get()) : "",
993
- );
994
- const thresholdCustomBadge =
995
- thresholdCfg?.line && renderThresholdBadge
996
- ? renderThresholdBadge({
997
- line: thresholdCfg.line,
998
- value: thresholdMarkerValue,
999
- valueStr: thresholdMarkerValueStr,
1000
- y: thresholdMarkerLineY,
1001
- visible: thresholdBadgeVisible,
1002
- })
1003
- : null;
1004
- const thresholdSeriesPts = thresholdIsSeries
1005
- ? thresholdSeriesGeom.screenPts
1006
- : undefined;
1797
+ thresholdIsSeries,
1798
+ emptyThresholdValue,
1799
+ palette,
1800
+ lineProp,
1801
+ renderThresholdBadge,
1802
+ formatValue,
1803
+ });
1007
1804
 
1008
1805
  // Straight polyline instead of the monotone cubic when line.curve === "linear".
1009
1806
  // Shared by the path builders and the marker anchoring so glyphs sit on the
@@ -1016,7 +1813,7 @@ function useLiveChartController({
1016
1813
  reveal.morphT,
1017
1814
  // Constant threshold band closes at a single Y (the series closes along the
1018
1815
  // polyline passed as the last arg below).
1019
- thresholdCfg?.fill && !thresholdIsSeries ? thresholdGeom.lineY : undefined,
1816
+ thresholdFillLineY,
1020
1817
  lineIsLinear,
1021
1818
  // The plotted line independently selects the visible edge while historical;
1022
1819
  // badge/live-indicator options affect overlays only.
@@ -1027,9 +1824,7 @@ function useLiveChartController({
1027
1824
  // (so the band matches the shader and doesn't bleed at step risers). An empty
1028
1825
  // series builds no band (its samples are all the far-below fallback, which
1029
1826
  // would tint the entire area under the line).
1030
- thresholdCfg?.fill && thresholdSeriesHasPoints
1031
- ? thresholdSeriesGeom.samples
1032
- : undefined,
1827
+ thresholdFillSamples,
1033
1828
  lineProp?.simplify,
1034
1829
  lineGapsCfg?.gaps,
1035
1830
  );
@@ -1037,17 +1832,11 @@ function useLiveChartController({
1037
1832
  // Area-dots fill shader color as a vec4 (channels 0..1), with the config
1038
1833
  // `opacity` folded into the alpha. Defaults to a faint tint of the line/accent
1039
1834
  // color (theme-aware) so out-of-the-box dots read as a subtle field.
1040
- const areaDotRgb = parseColorRgb(lineProp?.color ?? palette.line);
1041
- const [adR, adG, adB, adA] = parseColorRgba(
1042
- areaDotsCfg?.color ??
1043
- `rgba(${areaDotRgb[0]}, ${areaDotRgb[1]}, ${areaDotRgb[2]}, 0.22)`,
1835
+ const areaDotColorVec = resolveAreaDotColorVec(
1836
+ areaDotsCfg,
1837
+ lineProp,
1838
+ palette,
1044
1839
  );
1045
- const areaDotColorVec = [
1046
- adR / 255,
1047
- adG / 255,
1048
- adB / 255,
1049
- adA * (areaDotsCfg?.opacity ?? 1),
1050
- ];
1051
1840
 
1052
1841
  const { dotX, dotY } = useLiveDot(
1053
1842
  engine,
@@ -1078,33 +1867,31 @@ function useLiveChartController({
1078
1867
  isCandle,
1079
1868
  );
1080
1869
 
1081
- // ── Overlay hooks ─────────────────────────────────────────────────────
1082
- // Scrub/crosshair must see the same stash-backed candles as the engine.
1083
- const crosshairChartOpts = isCandle
1084
- ? {
1085
- mode,
1086
- candles: candlesEngine,
1087
- liveCandle: liveEngine,
1088
- candleWidthSecs: candleWidth,
1089
- gaps: candleGapsCfg?.gaps,
1090
- bridgeNoTrades:
1091
- Boolean(candleGapsCfg?.styles["no-trades"].bridge),
1092
- bridgeUnavailable:
1093
- Boolean(candleGapsCfg?.styles.unavailable.bridge),
1094
- bridgeUnknown: Boolean(candleGapsCfg?.styles.unknown.bridge),
1095
- }
1096
- : lineGapsCfg
1097
- ? {
1098
- mode,
1099
- gaps: lineGapsCfg.gaps,
1100
- bridgeNoTrades: Boolean(lineGapsCfg.styles["no-trades"].bridge),
1101
- bridgeUnavailable: Boolean(lineGapsCfg.styles.unavailable.bridge),
1102
- bridgeUnknown: Boolean(lineGapsCfg.styles.unknown.bridge),
1103
- }
1104
- : undefined;
1105
-
1106
- const markersActive = markers != null;
1107
- const markerClusterCfg = resolveMarkerCluster(markerCluster);
1870
+ const {
1871
+ crosshairChartOpts,
1872
+ markersActive,
1873
+ markerClusterCfg,
1874
+ refPressActive,
1875
+ refDragEnabled,
1876
+ scrollGestureMode,
1877
+ scrubHoldMs,
1878
+ } = resolveLiveChartInteractionConfig({
1879
+ isCandle,
1880
+ mode,
1881
+ candlesEngine,
1882
+ liveEngine,
1883
+ candleWidth,
1884
+ candleGapsCfg,
1885
+ lineGapsCfg,
1886
+ markers,
1887
+ markerCluster,
1888
+ onReferenceLinePress,
1889
+ allRefLines,
1890
+ isStatic,
1891
+ timeScroll,
1892
+ timeScrollEnabled,
1893
+ scrubCfg,
1894
+ });
1108
1895
  // `projected` is used internally by the hit-test gesture; the overlay
1109
1896
  // self-projects, so we only need the gesture + hit-test here. Built BEFORE
1110
1897
  // `useCrosshair` so the scrub-action tap can defer to a marker under the finger.
@@ -1124,7 +1911,6 @@ function useLiveChartController({
1124
1911
 
1125
1912
  // Pressable reference-line badges (working orders / alerts). Built before
1126
1913
  // `useCrosshair` so the scrub-action tap can defer to a badge under the finger.
1127
- const refPressActive = onReferenceLinePress != null && allRefLines.length > 0;
1128
1914
  const { tapGesture: refLineTapGesture, hitTest: refLineHitTest } =
1129
1915
  useReferenceLinePress(
1130
1916
  engine,
@@ -1143,8 +1929,6 @@ function useLiveChartController({
1143
1929
  // unconditionally for stable hook order (and before `useCrosshair` so the scrub
1144
1930
  // can defer to a line under the finger); the gesture self-disables when no line
1145
1931
  // opts in, and it's only composed into the root when `refDragEnabled`.
1146
- const refDragEnabled =
1147
- !isStatic && allRefLines.some((l) => l.draggable === true);
1148
1932
  const { gesture: refDragGesture, hitTest: refDragHitTest } = useReferenceDrag(
1149
1933
  engine,
1150
1934
  effectivePadding,
@@ -1164,24 +1948,6 @@ function useLiveChartController({
1164
1948
  return markerHitTest(x, y) || refLineHitTest(x, y) || refDragHitTest(x, y);
1165
1949
  };
1166
1950
 
1167
- // Time-scroll activation. `holdToScrub`: a quick one-finger drag scrolls while
1168
- // scrub engages on press-and-hold — so the scrub gesture needs a long-press
1169
- // delay (unless the caller set its own `panGestureDelay`). `timeScrollEnabled`
1170
- // is computed earlier (it gates the float gutter).
1171
- const scrollGestureMode =
1172
- typeof timeScroll === "object"
1173
- ? (timeScroll.gesture ?? "holdToScrub")
1174
- : "holdToScrub";
1175
- // In holdToScrub the scrub MUST require a hold so a quick drag scrolls instead.
1176
- // Precedence: explicit timeScroll.scrubHoldMs, then scrub.panGestureDelay, then
1177
- // the default. `||` (not `??`) skips the resolved panGestureDelay's 0 default.
1178
- const timeScrollHoldMs =
1179
- typeof timeScroll === "object" ? timeScroll.scrubHoldMs : undefined;
1180
- const scrubHoldMs =
1181
- timeScrollEnabled && scrollGestureMode === "holdToScrub"
1182
- ? (timeScrollHoldMs ?? (scrubCfg?.panGestureDelay || HOLD_TO_SCRUB_MS))
1183
- : (scrubCfg?.panGestureDelay ?? 0);
1184
-
1185
1951
  // Cross-gesture arbitration for the one-finger touch. `Gesture.Race` below is
1186
1952
  // NOT arbitration — RNGH's Race adds no relation between its children, so both
1187
1953
  // pans recognize independently and each can activate while the other already
@@ -1190,6 +1956,18 @@ function useLiveChartController({
1190
1956
  // (written by the crosshair, read by the scroll pan) is the mirror image.
1191
1957
  const scrollActive = useSharedValue(false);
1192
1958
 
1959
+ const crosshairSettings = resolveCrosshairControllerSettings({
1960
+ scrubCfg,
1961
+ scrubActionCfg,
1962
+ markersActive,
1963
+ refPressActive,
1964
+ refDragEnabled,
1965
+ deferTapHit,
1966
+ timeScrollEnabled,
1967
+ scrollGestureMode,
1968
+ effectivePadding,
1969
+ });
1970
+
1193
1971
  const crosshair = useCrosshair(
1194
1972
  engine,
1195
1973
  effectivePadding,
@@ -1200,7 +1978,7 @@ function useLiveChartController({
1200
1978
  // Scrub / scrub-action stay live even on static charts: the gesture is
1201
1979
  // event-driven (no per-frame loop), so a settled chart costs nothing at rest
1202
1980
  // yet becomes scrubbable on touch. `static` only kills the continuous loop.
1203
- scrubCfg !== null || scrubActionCfg !== null,
1981
+ crosshairSettings.enabled,
1204
1982
  onScrub,
1205
1983
  crosshairChartOpts,
1206
1984
  scrubHoldMs,
@@ -1209,20 +1987,15 @@ function useLiveChartController({
1209
1987
  scrubActionCfg,
1210
1988
  onScrubAction,
1211
1989
  metricsCfg.badge,
1212
- markersActive || refPressActive || refDragEnabled ? deferTapHit : undefined,
1213
- scrubCfg?.tooltipPlacement ?? "side",
1214
- scrubCfg?.tooltipShowValue ?? true,
1215
- scrubCfg?.tooltipShowTime ?? true,
1216
- scrubCfg?.tooltipMargin ?? 8,
1217
- // Axis-drag time-scroll: keep the bottom "time ruler" band scroll-only so a
1218
- // drag there never trips the scrub crosshair.
1219
- timeScrollEnabled && scrollGestureMode === "axisDrag"
1220
- ? Math.max(effectivePadding.bottom, AXIS_GRAB_MIN_PX)
1221
- : 0,
1990
+ crosshairSettings.deferTapHit,
1991
+ crosshairSettings.tooltipPlacement,
1992
+ crosshairSettings.tooltipShowValue,
1993
+ crosshairSettings.tooltipShowTime,
1994
+ crosshairSettings.tooltipMargin,
1995
+ crosshairSettings.scrubBottomExclude,
1222
1996
  scrollActive,
1223
- scrubCfg?.clampToPlot ?? false,
1224
- // Candle mode: snap the crosshair to candle centers (tick-to-tick).
1225
- scrubCfg?.snapToCandles ?? false,
1997
+ crosshairSettings.clampToPlot,
1998
+ crosshairSettings.snapToCandles,
1226
1999
  );
1227
2000
 
1228
2001
  // Capture only the shared value in the worklets below. Referencing
@@ -1276,77 +2049,12 @@ function useLiveChartController({
1276
2049
  },
1277
2050
  });
1278
2051
 
1279
- // Axis auto-hide: fade both axes out at rest and back in while the user
1280
- // interacts. Any movement — scrub / time-scroll touch, or a viewEnd /
1281
- // viewWindow change (fling momentum, pinch-zoom) — shows the axes; once the
1282
- // touch lifts and the view settles, they fade back out after `hideAfterMs`.
1283
- // Only the axis groups' opacity animates; the axis worklets keep running
1284
- // underneath so a fade-in shows current labels.
1285
- const axisAutoHideCfg =
1286
- axisAutoHide === true ? {} : axisAutoHide === false ? null : axisAutoHide;
1287
- const axisIdleOpacity = axisAutoHideCfg?.idleOpacity ?? 0;
1288
- const axisFadeInMs = axisAutoHideCfg?.fadeInMs ?? 60;
1289
- const axisFadeOutMs = axisAutoHideCfg?.fadeOutMs ?? 250;
1290
- const axisHideAfterMs = axisAutoHideCfg?.hideAfterMs ?? 3000;
1291
- const axisAutoHideOpacity = useSharedValue(
1292
- axisAutoHideCfg ? axisIdleOpacity : 1,
1293
- );
1294
- const axisAutoHideEnabled = axisAutoHideCfg !== null;
1295
- const lastAxisAutoHide = useRef({
1296
- enabled: axisAutoHideEnabled,
1297
- idleOpacity: axisIdleOpacity,
2052
+ const axisAutoHideOpacity = useAxisAutoHide({
2053
+ config: axisAutoHide,
2054
+ scrollActive,
2055
+ scrubActive: crosshairScrubActive,
2056
+ engine,
1298
2057
  });
1299
- // `useSharedValue` only reads its initial value on mount. Keep prop changes
1300
- // in sync as well: turning auto-hide off must immediately restore the axes,
1301
- // and turning it on starts from the configured idle opacity.
1302
- useEffect(() => {
1303
- if (
1304
- lastAxisAutoHide.current.enabled === axisAutoHideEnabled &&
1305
- lastAxisAutoHide.current.idleOpacity === axisIdleOpacity
1306
- ) {
1307
- return;
1308
- }
1309
- lastAxisAutoHide.current = {
1310
- enabled: axisAutoHideEnabled,
1311
- idleOpacity: axisIdleOpacity,
1312
- };
1313
- cancelAnimation(axisAutoHideOpacity);
1314
- axisAutoHideOpacity.value = axisAutoHideEnabled ? axisIdleOpacity : 1;
1315
- }, [axisAutoHideEnabled, axisAutoHideOpacity, axisIdleOpacity]);
1316
- useAnimatedReaction(
1317
- () => ({
1318
- gesture: scrollActive.value || crosshairScrubActive.value,
1319
- viewEnd: engine.viewEnd.value,
1320
- viewWindow: engine.viewWindow.value,
1321
- }),
1322
- (curr, prev) => {
1323
- if (!axisAutoHideEnabled || prev === null) return;
1324
- const moved =
1325
- curr.gesture !== prev.gesture ||
1326
- curr.viewEnd !== prev.viewEnd ||
1327
- curr.viewWindow !== prev.viewWindow;
1328
- if (!moved) return;
1329
- cancelAnimation(axisAutoHideOpacity);
1330
- axisAutoHideOpacity.value = curr.gesture
1331
- ? withTiming(1, { duration: axisFadeInMs })
1332
- : // Movement without a held touch (gesture end, fling, pinch): show,
1333
- // then fade back out once the chart goes untouched for a while.
1334
- withSequence(
1335
- withTiming(1, { duration: axisFadeInMs }),
1336
- withDelay(
1337
- axisHideAfterMs,
1338
- withTiming(axisIdleOpacity, { duration: axisFadeOutMs }),
1339
- ),
1340
- );
1341
- },
1342
- [
1343
- axisAutoHideEnabled,
1344
- axisIdleOpacity,
1345
- axisFadeInMs,
1346
- axisFadeOutMs,
1347
- axisHideAfterMs,
1348
- ],
1349
- );
1350
2058
 
1351
2059
  // Paging callbacks: report the visible range / proximity to the oldest data so
1352
2060
  // a host can lazily load history. Inert unless a callback is supplied.
@@ -1361,59 +2069,21 @@ function useLiveChartController({
1361
2069
  // ahead of the pan via Exclusive, so a tap is tried first and only becomes a
1362
2070
  // drag (live-scrub, or lock-adjust once placed) if the finger moves. `Exclusive`
1363
2071
  // (not `Race`) prevents a jittery tap from being swallowed by the pan.
1364
- const baseGesture =
1365
- scrubActionCfg !== null && crosshair.tapGesture
1366
- ? Gesture.Exclusive(crosshair.tapGesture, crosshair.gesture)
1367
- : crosshair.gesture;
1368
-
1369
- // Overlay taps that hit-test discrete targets (marker dots, reference-line
1370
- // badges). They must all see each tap, so they're combined with `Simultaneous`
1371
- // (not `Race`, which cancels the loser and would drop one). The scrub-action
1372
- // action tap defers to them via `deferTapHit`, so a tap on an overlay is routed
1373
- // there instead of placing a reticle.
1374
- const overlayTaps = [
1375
- markersActive ? markerTapGesture : null,
1376
- refPressActive ? refLineTapGesture : null,
1377
- ].filter((g): g is NonNullable<typeof g> => g !== null);
1378
-
1379
- let rootGesture = baseGesture;
1380
- if (overlayTaps.length > 0) {
1381
- const tapGroup =
1382
- overlayTaps.length === 1
1383
- ? overlayTaps[0]
1384
- : Gesture.Simultaneous(overlayTaps[0], overlayTaps[1]);
1385
- // Always `Simultaneous`, never `Race`: on iOS the scrub pan uses
1386
- // `minDistance(0)`, so in a `Race` it activates on touch-down and cancels the
1387
- // overlay tap before it can recognize — `onMarkerPress`/`onReferenceLinePress`
1388
- // would never fire. Sharing the gesture space lets the tap recognize; the pan
1389
- // defers to a marker/badge under the finger via `deferTapHit` (see
1390
- // `useCrosshair`'s scrub `onStart`) so no stray crosshair is dropped there.
1391
- rootGesture = Gesture.Simultaneous(baseGesture, tapGroup);
1392
- }
1393
-
1394
- // Compose the pan-scroll gesture. holdToScrub races the scrub/tap gestures (a
1395
- // quick drag scrolls; a still press-hold falls through to scrub). Axis-drag
1396
- // goes first via Exclusive: it fails instantly outside the axis band, so scrub
1397
- // runs everywhere else.
1398
- if (timeScrollEnabled) {
1399
- rootGesture =
1400
- scrollGestureMode === "axisDrag"
1401
- ? Gesture.Exclusive(panScrollGesture, rootGesture)
1402
- : Gesture.Race(panScrollGesture, rootGesture);
1403
- }
1404
-
1405
- // Draggable reference lines take priority: a vertical grab on a line drags it.
1406
- // The manual-activation pan fails fast off any line (or on horizontal intent), so
1407
- // Exclusive falls through to scrub / scroll everywhere else.
1408
- if (refDragEnabled) {
1409
- rootGesture = Gesture.Exclusive(refDragGesture, rootGesture);
1410
- }
1411
-
1412
- // Pinch runs alongside everything else (two-finger, so it never competes with
1413
- // the one-finger pan/scrub/tap gestures for the same touch).
1414
- if (zoomEnabled) {
1415
- rootGesture = Gesture.Simultaneous(rootGesture, pinchZoomGesture);
1416
- }
2072
+ const rootGesture = composeLiveChartRootGesture({
2073
+ crosshair,
2074
+ markerTapGesture,
2075
+ refLineTapGesture,
2076
+ refDragGesture,
2077
+ panScrollGesture,
2078
+ pinchZoomGesture,
2079
+ markersActive,
2080
+ refPressActive,
2081
+ refDragEnabled,
2082
+ scrubActionActive: scrubActionCfg !== null,
2083
+ timeScrollEnabled,
2084
+ scrollGestureMode,
2085
+ zoomEnabled,
2086
+ });
1417
2087
 
1418
2088
  // ── Derived render values ──────────────────────────────────────────────
1419
2089
  const {
@@ -1446,49 +2116,33 @@ function useLiveChartController({
1446
2116
  // A dot that tracks the true live point while parked is exempt from the
1447
2117
  // scroll-back hide: it no longer marks an off-screen price, and it hides
1448
2118
  // itself once the live point leaves the window (`useLiveDot`'s sentinel).
1449
- const liveDotOpacity = useDerivedValue(
1450
- () =>
1451
- reveal.dotOpacity.value *
1452
- (selectionDotDuringScrub && crosshairScrubActive.value ? 0 : 1) *
1453
- liveIndicatorScrollOpacity(
1454
- hideLiveOnScrollBack && !dotTracksParked,
1455
- engine.viewEnd.value,
1456
- ) *
1457
- seriesIndicatorOpacity.value,
1458
- );
1459
- // Same scrolled-back gating for the value line: it would draw a dashed line
1460
- // at the live value's Y — a price that isn't in the scrolled-back view.
1461
- const valueLineOpacity = useDerivedValue(
1462
- () =>
1463
- reveal.lineOpacity.value *
1464
- liveIndicatorScrollOpacity(hideLiveOnScrollBack, engine.viewEnd.value) *
1465
- resolvedSeriesOpacity.value,
1466
- );
1467
- const liveBadgeOpacity = useDerivedValue(
1468
- () =>
1469
- reveal.badgeOpacity.value *
1470
- liveIndicatorScrollOpacity(hideLiveOnScrollBack, engine.viewEnd.value) *
1471
- resolvedSeriesOpacity.value,
1472
- );
1473
-
1474
- // Fade the annotation overlays (markers + reference lines) out while scrubbing
1475
- // when `scrub.hideOverlays` is set. Eased off the scrub-ACTIVE flag — not the
1476
- // crosshair's edge-proximity fade, which drops to 0 near the live dot and would
1477
- // resurface the overlays mid-scrub. Only this group opacity animates; the
1478
- // marker atlas / reference-line draws stay intact (one batched draw each).
1479
2119
  const fadeOverlaysOnScrub =
1480
2120
  !isStatic && scrubCfg !== null && scrubCfg.hideOverlaysOnScrub === true;
1481
- const overlayScrubFade = useDerivedValue(() =>
1482
- fadeOverlaysOnScrub
1483
- ? withTiming(crosshairScrubActive.get() ? 0 : 1, {
1484
- duration: SCRUB_OVERLAY_FADE_MS,
1485
- })
1486
- : 1,
1487
- );
1488
- // Markers already fade with the dot reveal; fold the scrub-hide fade in too.
1489
- const markerGroupOpacity = useDerivedValue(
1490
- () => reveal.dotOpacity.get() * overlayScrubFade.get(),
1491
- );
2121
+ const {
2122
+ liveDotOpacity,
2123
+ valueLineOpacity,
2124
+ liveBadgeOpacity,
2125
+ overlayScrubFade,
2126
+ markerGroupOpacity,
2127
+ } = useLiveIndicatorOpacities({
2128
+ reveal,
2129
+ seriesIndicatorOpacity,
2130
+ seriesOpacity: resolvedSeriesOpacity,
2131
+ scrubActive: crosshairScrubActive,
2132
+ selectionDotDuringScrub,
2133
+ hideLiveOnScrollBack,
2134
+ dotTracksParked,
2135
+ viewEnd: engine.viewEnd,
2136
+ fadeOverlaysOnScrub,
2137
+ });
2138
+ const modelDefaults = resolveLiveChartModelDefaults({
2139
+ isCandle,
2140
+ candleWidth,
2141
+ loadingCfg,
2142
+ volumeCfg,
2143
+ palette,
2144
+ lineProp,
2145
+ });
1492
2146
 
1493
2147
  return {
1494
2148
  // passthrough props the render needs
@@ -1505,9 +2159,7 @@ function useLiveChartController({
1505
2159
  formatTime,
1506
2160
  isCandle,
1507
2161
  isStatic,
1508
- // Half a candle width (seconds) so an "extrema" axis label's dot lands on the
1509
- // candle's drawn center, not its bucket-start (left) edge. 0 in line mode.
1510
- extremaTimeOffset: isCandle ? candleWidth / 2 : 0,
2162
+ ...modelDefaults,
1511
2163
  // configs
1512
2164
  yAxisCfg,
1513
2165
  yAxisFloat: effectiveYAxisFloat,
@@ -1548,8 +2200,8 @@ function useLiveChartController({
1548
2200
  hasRecolorSegments,
1549
2201
  thresholdCfg,
1550
2202
  thresholdGeom,
1551
- thresholdStrokeColors: thresholdStopColors?.stroke ?? null,
1552
- thresholdFillColors: thresholdStopColors?.fill ?? null,
2203
+ thresholdStrokeColors,
2204
+ thresholdFillColors,
1553
2205
  // Time-varying threshold (a `LiveChartPoint[]` series): the per-fragment split
1554
2206
  // shader + polyline marker, vs. the constant case's gradient.
1555
2207
  thresholdIsSeries,
@@ -1574,13 +2226,8 @@ function useLiveChartController({
1574
2226
  // engine + reveal
1575
2227
  engine,
1576
2228
  reveal,
2229
+ loadingActive,
1577
2230
  axisAutoHideOpacity,
1578
- // loading shell styling (null → not loading)
1579
- loadingLineColor: loadingCfg?.color,
1580
- loadingStrokeWidth: loadingCfg?.strokeWidth,
1581
- loadingAmplitude: loadingCfg?.amplitude,
1582
- loadingSpeed: loadingCfg?.speed,
1583
- loadingAxisLabels: loadingCfg?.axisLabels ?? true,
1584
2231
  // derived render values
1585
2232
  backgroundColor,
1586
2233
  gradientEnd,
@@ -1608,9 +2255,6 @@ function useLiveChartController({
1608
2255
  // the candle palette). The reserved band height is read by the x-axis.
1609
2256
  volumeActive: volumeCfg !== null,
1610
2257
  volumeBandHeight,
1611
- volumeOpacity: volumeCfg?.opacity ?? 1,
1612
- volumeUpColor: volumeCfg?.upColor ?? palette.candleUp,
1613
- volumeDownColor: volumeCfg?.downColor ?? palette.candleDown,
1614
2258
  dotX,
1615
2259
  dotY,
1616
2260
  liveDotOpacity,
@@ -1631,7 +2275,6 @@ function useLiveChartController({
1631
2275
  renderOverlay,
1632
2276
  // selection dot: resolved config + fallback color (the chart line/accent color)
1633
2277
  selectionDot: selectionDotCfg,
1634
- selectionColor: lineProp?.color ?? palette.line,
1635
2278
  // RN axis edge labels (floated over the canvas as a sibling layer)
1636
2279
  topLabelCfg,
1637
2280
  bottomLabelCfg,
@@ -1980,11 +2623,7 @@ function ChartCandleGapLayer({
1980
2623
  model.metricsCfg.candle,
1981
2624
  );
1982
2625
  const batch = (
1983
- <GapBridgePathBatch
1984
- paths={paths}
1985
- config={config}
1986
- palette={model.palette}
1987
- />
2626
+ <GapBridgePathBatch paths={paths} config={config} palette={model.palette} />
1988
2627
  );
1989
2628
  return focusOtherCandles ? (
1990
2629
  <>
@@ -2001,17 +2640,9 @@ function ChartCandleGapLayer({
2001
2640
  /** Line-mode bridge paths live in a child so candle charts register no worklets. */
2002
2641
  function ChartLineGapLayer({ model }: { model: LiveChartModel }) {
2003
2642
  const config = model.lineGapsCfg!;
2004
- const paths = useLineGapPaths(
2005
- model.engine,
2006
- model.effectivePadding,
2007
- config,
2008
- );
2643
+ const paths = useLineGapPaths(model.engine, model.effectivePadding, config);
2009
2644
  return (
2010
- <GapBridgePathBatch
2011
- paths={paths}
2012
- config={config}
2013
- palette={model.palette}
2014
- />
2645
+ <GapBridgePathBatch paths={paths} config={config} palette={model.palette} />
2015
2646
  );
2016
2647
  }
2017
2648
 
@@ -2236,6 +2867,113 @@ function ChartCandleLayer({ model }: { model: LiveChartModel }) {
2236
2867
  );
2237
2868
  }
2238
2869
 
2870
+ function ChartLineStrokeShader({ model }: { model: LiveChartModel }) {
2871
+ const {
2872
+ engine,
2873
+ effectivePadding,
2874
+ palette,
2875
+ resolvedSegments,
2876
+ hasRecolorSegments,
2877
+ crosshair,
2878
+ thresholdCfg,
2879
+ thresholdGeom,
2880
+ thresholdStrokeColors,
2881
+ thresholdIsSeries,
2882
+ thresholdSeriesHasPoints,
2883
+ thresholdStrokeUniforms,
2884
+ lineProp,
2885
+ layoutWidth,
2886
+ } = model;
2887
+ if (thresholdIsSeries) {
2888
+ return thresholdSeriesHasPoints ? (
2889
+ <ThresholdSplitShader uniforms={thresholdStrokeUniforms} />
2890
+ ) : null;
2891
+ }
2892
+ if (thresholdCfg && thresholdStrokeColors) {
2893
+ return (
2894
+ <LinearGradient
2895
+ start={vec(0, 0)}
2896
+ end={thresholdGeom.gradientEnd}
2897
+ colors={thresholdStrokeColors}
2898
+ positions={thresholdGeom.splitPositions}
2899
+ />
2900
+ );
2901
+ }
2902
+ if (hasRecolorSegments) {
2903
+ return (
2904
+ <SegmentLineGradient
2905
+ engine={engine}
2906
+ segments={resolvedSegments}
2907
+ padding={effectivePadding}
2908
+ baseColor={lineProp?.color ?? palette.line}
2909
+ scrubX={crosshair.scrubX}
2910
+ scrubActive={crosshair.scrubActive}
2911
+ />
2912
+ );
2913
+ }
2914
+ if (!lineProp?.colors?.length) return null;
2915
+ return (
2916
+ <LinearGradient
2917
+ start={vec(0, 0)}
2918
+ end={vec(layoutWidth, 0)}
2919
+ colors={lineProp.colors}
2920
+ />
2921
+ );
2922
+ }
2923
+
2924
+ function ChartMainPlotLayer({
2925
+ model,
2926
+ yAxisEntries,
2927
+ }: {
2928
+ model: LiveChartModel;
2929
+ yAxisEntries: YAxisEntries | null;
2930
+ }) {
2931
+ const {
2932
+ engine,
2933
+ effectivePadding,
2934
+ palette,
2935
+ lineGroupOpacity,
2936
+ seriesOpacity,
2937
+ linePath,
2938
+ lineGapsCfg,
2939
+ strokeWidth,
2940
+ lineProp,
2941
+ isCandle,
2942
+ xAxisCfg,
2943
+ yAxisCfg,
2944
+ yAxisFloat,
2945
+ } = model;
2946
+
2947
+ return (
2948
+ <>
2949
+ <Group opacity={seriesOpacity}>
2950
+ <Group opacity={lineGroupOpacity}>
2951
+ <Path
2952
+ path={linePath}
2953
+ style="stroke"
2954
+ strokeWidth={strokeWidth}
2955
+ strokeCap={lineProp?.cap ?? "round"}
2956
+ strokeJoin={lineProp?.join ?? "round"}
2957
+ color={lineProp?.color ?? palette.line}
2958
+ >
2959
+ <ChartLineStrokeShader model={model} />
2960
+ </Path>
2961
+ {lineGapsCfg ? <ChartLineGapLayer model={model} /> : null}
2962
+ </Group>
2963
+ </Group>
2964
+ {isCandle ? <ChartCandleLayer model={model} /> : null}
2965
+ {yAxisCfg && yAxisFloat ? (
2966
+ <ChartYAxisLayer
2967
+ model={model}
2968
+ variant="labels"
2969
+ entries={yAxisEntries!}
2970
+ />
2971
+ ) : null}
2972
+ {xAxisCfg ? <ChartXAxisLayer model={model} /> : null}
2973
+ </>
2974
+ );
2975
+ }
2976
+
2239
2977
  /** Main shaken chart stack drawn ABOVE the left-edge fade so the line stays crisp:
2240
2978
  * segment dividers, value/reference lines, the line/candles, axes, dot, degen,
2241
2979
  * markers, and the loading/empty art. Background fills are in `ChartFillLayer`
@@ -2379,74 +3117,7 @@ function ChartStack({
2379
3117
  />
2380
3118
  )}
2381
3119
 
2382
- {/* Chart line (fades out in candle mode). When segments recolor the line, a
2383
- full-width gradient paints the base color outside segments and each
2384
- segment's color within — so the line itself is recolored/faded (alpha in
2385
- the segment color reduces the line's opacity), not covered by an overlay. */}
2386
- <Group opacity={seriesOpacity}>
2387
- <Group opacity={lineGroupOpacity}>
2388
- <Path
2389
- path={linePath}
2390
- style="stroke"
2391
- strokeWidth={strokeWidth}
2392
- strokeCap={lineProp?.cap ?? "round"}
2393
- strokeJoin={lineProp?.join ?? "round"}
2394
- color={lineProp?.color ?? palette.line}
2395
- >
2396
- {thresholdIsSeries ? (
2397
- // Time-varying split: a per-fragment shader colors the stroke above/
2398
- // below the threshold polyline. Supersedes line.colors + segments.
2399
- // An empty series renders no paint child → the plain stroke color
2400
- // (null here keeps the empty case out of the NaN constant gradient).
2401
- thresholdSeriesHasPoints ? (
2402
- <ThresholdSplitShader uniforms={thresholdStrokeUniforms} />
2403
- ) : null
2404
- ) : thresholdCfg && thresholdStrokeColors ? (
2405
- // Vertical hard split at the threshold Y — supersedes line.colors and
2406
- // segment recoloring for the stroke while a threshold is set.
2407
- <LinearGradient
2408
- start={vec(0, 0)}
2409
- end={thresholdGeom.gradientEnd}
2410
- colors={thresholdStrokeColors}
2411
- positions={thresholdGeom.splitPositions}
2412
- />
2413
- ) : hasRecolorSegments ? (
2414
- <SegmentLineGradient
2415
- engine={engine}
2416
- segments={resolvedSegments}
2417
- padding={effectivePadding}
2418
- baseColor={lineProp?.color ?? palette.line}
2419
- scrubX={crosshair.scrubX}
2420
- scrubActive={crosshair.scrubActive}
2421
- />
2422
- ) : lineProp?.colors?.length ? (
2423
- <LinearGradient
2424
- start={vec(0, 0)}
2425
- end={vec(layoutWidth, 0)}
2426
- colors={lineProp.colors}
2427
- />
2428
- ) : null}
2429
- </Path>
2430
- {lineGapsCfg && <ChartLineGapLayer model={model} />}
2431
- </Group>
2432
- </Group>
2433
-
2434
- {isCandle && <ChartCandleLayer model={model} />}
2435
-
2436
- {/* Floating axis: the labels float ABOVE the candles (right-aligned at the
2437
- edge) so the plot runs full-width and candles stay fully visible behind
2438
- them. (Default non-floating axis draws grid + labels in ChartFillLayer.) */}
2439
- {yAxisCfg && yAxisFloat && (
2440
- <ChartYAxisLayer
2441
- model={model}
2442
- variant="labels"
2443
- entries={yAxisEntries!}
2444
- />
2445
- )}
2446
-
2447
- {/* X-axis time labels. With a volume band the bottom padding is inflated by
2448
- the band height; pass it so the axis shifts back to the very bottom. */}
2449
- {xAxisCfg && <ChartXAxisLayer model={model} />}
3120
+ <ChartMainPlotLayer model={model} yAxisEntries={yAxisEntries} />
2450
3121
 
2451
3122
  {/* Live dot — the badge is drawn later (after the scrub layer) so the
2452
3123
  scrub dim never clips the live-price badge's left edge. Hidden while
@@ -3001,7 +3672,7 @@ function ChartCustomConsumerOverlay({ model }: { model: LiveChartModel }) {
3001
3672
  return <ChartOverlayLayer render={renderOverlay!} context={overlayContext} />;
3002
3673
  }
3003
3674
 
3004
- function ChartView({
3675
+ function ChartCanvas({
3005
3676
  model,
3006
3677
  yAxisEntries,
3007
3678
  degen,
@@ -3011,36 +3682,171 @@ function ChartView({
3011
3682
  degen: DegenState | null;
3012
3683
  }) {
3013
3684
  const {
3014
- rootGesture,
3685
+ canvasMode,
3686
+ engine,
3015
3687
  backgroundColor,
3016
- style,
3017
- onLayout,
3018
- accessibilityLabel,
3019
- accessibilityRole,
3020
3688
  leftEdgeFadeCfg,
3021
3689
  effectivePadding,
3022
- engine,
3023
3690
  palette,
3024
- formatValue,
3691
+ topConnector,
3692
+ bottomConnector,
3693
+ extremaTimeOffset,
3694
+ loadingActive,
3695
+ topLabelCfg,
3696
+ } = model;
3697
+ return (
3698
+ <Canvas
3699
+ key={canvasMode}
3700
+ style={{ flex: 1 }}
3701
+ opaque={canvasMode === "opaque"}
3702
+ >
3703
+ {canvasMode === "opaque" ? (
3704
+ <Rect
3705
+ x={0}
3706
+ y={0}
3707
+ width={engine.canvasWidth}
3708
+ height={engine.canvasHeight}
3709
+ color={backgroundColor}
3710
+ />
3711
+ ) : null}
3712
+ <ChartFillLayer model={model} yAxisEntries={yAxisEntries} degen={degen} />
3713
+ {leftEdgeFadeCfg ? (
3714
+ <LeftEdgeFade
3715
+ paddingLeft={effectivePadding.left}
3716
+ fadeWidth={leftEdgeFadeCfg.width}
3717
+ startColor={leftEdgeFadeCfg.startColor}
3718
+ endColor={leftEdgeFadeCfg.endColor}
3719
+ engine={engine}
3720
+ opaqueBackgroundRgb={
3721
+ canvasMode === "opaque" ? palette.bgRgb : undefined
3722
+ }
3723
+ />
3724
+ ) : null}
3725
+ <ChartStack model={model} yAxisEntries={yAxisEntries} degen={degen} />
3726
+ {topConnector || bottomConnector ? (
3727
+ <ExtremaConnectorOverlay
3728
+ engine={engine}
3729
+ padding={effectivePadding}
3730
+ extremaTimeOffset={extremaTimeOffset}
3731
+ top={topConnector}
3732
+ bottom={bottomConnector}
3733
+ hideExtrema={loadingActive}
3734
+ suppressBottomWhenCoincident={
3735
+ topLabelCfg?.position === "extrema" ||
3736
+ topLabelCfg?.position === "extrema-edge"
3737
+ }
3738
+ />
3739
+ ) : null}
3740
+ <ChartRefBadgeLayer
3741
+ model={model}
3742
+ degen={degen}
3743
+ yAxisEntries={yAxisEntries}
3744
+ />
3745
+ <ChartValueOverlay model={model} degen={degen} />
3746
+ {model.tradeStreamResolved && model.tradeStream ? (
3747
+ <ChartTradeStreamLayer model={model} degen={degen} />
3748
+ ) : null}
3749
+ <ChartScrubLayer model={model} degen={degen} />
3750
+ {model.badgeCfg ? <ChartBadgeLayer model={model} degen={degen} /> : null}
3751
+ <ChartScrubActionLayer model={model} />
3752
+ </Canvas>
3753
+ );
3754
+ }
3755
+
3756
+ function ChartNativeOverlays({ model }: { model: LiveChartModel }) {
3757
+ const {
3025
3758
  topLabelCfg,
3026
3759
  bottomLabelCfg,
3760
+ engine,
3761
+ formatValue,
3762
+ palette,
3763
+ effectivePadding,
3764
+ extremaTimeOffset,
3765
+ loadingActive,
3766
+ thresholdCustomBadge,
3027
3767
  thresholdCfg,
3028
3768
  thresholdMarkerLineY,
3029
3769
  thresholdBadgeVisible,
3030
- thresholdCustomBadge,
3031
3770
  markersActive,
3032
3771
  renderMarker,
3033
- renderTooltip,
3034
- renderOverlay,
3035
3772
  renderReferenceLine,
3036
3773
  renderOffAxisReferenceLine,
3037
3774
  allRefLines,
3038
3775
  scrubCfg,
3776
+ renderTooltip,
3039
3777
  crosshair,
3040
- extremaTimeOffset,
3041
- topConnector,
3042
- bottomConnector,
3043
- canvasMode,
3778
+ renderOverlay,
3779
+ } = model;
3780
+ const hasAnnotations =
3781
+ (markersActive && renderMarker != null) ||
3782
+ ((renderReferenceLine != null || renderOffAxisReferenceLine != null) &&
3783
+ allRefLines.length > 0);
3784
+ return (
3785
+ <>
3786
+ {topLabelCfg || bottomLabelCfg ? (
3787
+ <AxisLabelOverlay
3788
+ topLabel={topLabelCfg}
3789
+ bottomLabel={bottomLabelCfg}
3790
+ engine={engine}
3791
+ formatValue={formatValue}
3792
+ defaultColor={palette.gridLabel}
3793
+ padding={effectivePadding}
3794
+ extremaTimeOffset={extremaTimeOffset}
3795
+ hideExtrema={loadingActive}
3796
+ />
3797
+ ) : null}
3798
+ {thresholdCustomBadge && thresholdCfg?.line ? (
3799
+ <CustomThresholdBadgeOverlay
3800
+ element={thresholdCustomBadge}
3801
+ engine={engine}
3802
+ padding={effectivePadding}
3803
+ y={thresholdMarkerLineY}
3804
+ visible={thresholdBadgeVisible}
3805
+ position={thresholdCfg.line.labelPosition}
3806
+ />
3807
+ ) : null}
3808
+ {hasAnnotations ? <ChartCustomAnnotations model={model} /> : null}
3809
+ {scrubCfg && renderTooltip ? (
3810
+ <CustomTooltipOverlay
3811
+ renderTooltip={renderTooltip}
3812
+ scrubX={crosshair.scrubX}
3813
+ scrubValue={crosshair.scrubValue}
3814
+ scrubTime={crosshair.scrubTime}
3815
+ scrubActive={crosshair.scrubActive}
3816
+ scrubCandle={crosshair.scrubCandle}
3817
+ scrubGap={crosshair.scrubGap}
3818
+ tooltipLayout={crosshair.tooltipLayout}
3819
+ engine={engine}
3820
+ padding={effectivePadding}
3821
+ placement={scrubCfg.tooltipPlacement}
3822
+ margin={scrubCfg.tooltipMargin}
3823
+ crosshairFade={scrubCfg.crosshairFade}
3824
+ crosshairFadeDistance={scrubCfg.crosshairFadeDistance}
3825
+ lineTop={crosshair.tooltipLineTop}
3826
+ scrubDotY={crosshair.scrubDotY}
3827
+ />
3828
+ ) : null}
3829
+ {renderOverlay ? <ChartCustomConsumerOverlay model={model} /> : null}
3830
+ </>
3831
+ );
3832
+ }
3833
+
3834
+ function ChartView({
3835
+ model,
3836
+ yAxisEntries,
3837
+ degen,
3838
+ }: {
3839
+ model: LiveChartModel;
3840
+ yAxisEntries: YAxisEntries | null;
3841
+ degen: DegenState | null;
3842
+ }) {
3843
+ const {
3844
+ rootGesture,
3845
+ backgroundColor,
3846
+ style,
3847
+ onLayout,
3848
+ accessibilityLabel,
3849
+ accessibilityRole,
3044
3850
  } = model;
3045
3851
 
3046
3852
  return (
@@ -3052,147 +3858,8 @@ function ChartView({
3052
3858
  accessibilityLabel={accessibilityLabel}
3053
3859
  accessibilityRole={accessibilityRole}
3054
3860
  >
3055
- {/* Skia chooses TextureView vs SurfaceView when the native Canvas mounts. */}
3056
- <Canvas
3057
- key={canvasMode}
3058
- style={{ flex: 1 }}
3059
- opaque={canvasMode === "opaque"}
3060
- >
3061
- {canvasMode === "opaque" && (
3062
- <Rect
3063
- x={0}
3064
- y={0}
3065
- width={engine.canvasWidth}
3066
- height={engine.canvasHeight}
3067
- color={backgroundColor}
3068
- />
3069
- )}
3070
- {/* Background fills first, then the left-edge fade (a canvas-space sibling
3071
- so dstOut blends correctly), then the line stack on top — so the fade
3072
- softens only the fills and the line stays crisp at the left edge. */}
3073
- <ChartFillLayer
3074
- model={model}
3075
- yAxisEntries={yAxisEntries}
3076
- degen={degen}
3077
- />
3078
-
3079
- {leftEdgeFadeCfg && (
3080
- <LeftEdgeFade
3081
- paddingLeft={effectivePadding.left}
3082
- fadeWidth={leftEdgeFadeCfg.width}
3083
- startColor={leftEdgeFadeCfg.startColor}
3084
- endColor={leftEdgeFadeCfg.endColor}
3085
- engine={engine}
3086
- opaqueBackgroundRgb={
3087
- canvasMode === "opaque" ? palette.bgRgb : undefined
3088
- }
3089
- />
3090
- )}
3091
-
3092
- {/* Line stack above the fade so the line stays crisp at the left edge. */}
3093
- <ChartStack model={model} yAxisEntries={yAxisEntries} degen={degen} />
3094
-
3095
- {/* "extrema-edge" connector lines (dot → edge readout), above the chart
3096
- content so the dashed guide reads over the line / candles. */}
3097
- {(topConnector || bottomConnector) && (
3098
- <ExtremaConnectorOverlay
3099
- engine={engine}
3100
- padding={effectivePadding}
3101
- extremaTimeOffset={extremaTimeOffset}
3102
- top={topConnector}
3103
- bottom={bottomConnector}
3104
- />
3105
- )}
3106
-
3107
- {/* Reference-line badges + labels above the fade so they stay crisp. */}
3108
- <ChartRefBadgeLayer
3109
- model={model}
3110
- degen={degen}
3111
- yAxisEntries={yAxisEntries}
3112
- />
3113
-
3114
- <ChartValueOverlay model={model} degen={degen} />
3115
-
3116
- {model.tradeStreamResolved && model.tradeStream && (
3117
- <ChartTradeStreamLayer model={model} degen={degen} />
3118
- )}
3119
-
3120
- <ChartScrubLayer model={model} degen={degen} />
3121
-
3122
- {/* Live-price badge on top of the scrub dim so the dim never clips
3123
- its left edge (the badge tracks the live value, not the scrub). */}
3124
- {model.badgeCfg && <ChartBadgeLayer model={model} degen={degen} />}
3125
-
3126
- {/* Scrub-action reticle + action badge — top-most, no shake transform. */}
3127
- <ChartScrubActionLayer model={model} />
3128
- </Canvas>
3129
-
3130
- {/* RN labels floated over the canvas (sibling of <Canvas>, an RN view).
3131
- Pinned to the plot's top/bottom edges via the resolved padding. */}
3132
- {(topLabelCfg || bottomLabelCfg) && (
3133
- <AxisLabelOverlay
3134
- topLabel={topLabelCfg}
3135
- bottomLabel={bottomLabelCfg}
3136
- engine={engine}
3137
- formatValue={formatValue}
3138
- defaultColor={palette.gridLabel}
3139
- padding={effectivePadding}
3140
- extremaTimeOffset={extremaTimeOffset}
3141
- />
3142
- )}
3143
-
3144
- {/* Custom threshold badge — a native view positioned from the same live
3145
- value/Y SharedValues as the built-in Skia badge. */}
3146
- {thresholdCustomBadge && thresholdCfg?.line && (
3147
- <CustomThresholdBadgeOverlay
3148
- element={thresholdCustomBadge}
3149
- engine={engine}
3150
- padding={effectivePadding}
3151
- y={thresholdMarkerLineY}
3152
- visible={thresholdBadgeVisible}
3153
- position={thresholdCfg.line.labelPosition}
3154
- />
3155
- )}
3156
-
3157
- {/* Custom-rendered markers — RN views floated over the canvas (non-Skia),
3158
- pinned to each marker's live position. Sibling of <Canvas>. Wrapped in
3159
- a box-none fade layer so `scrub.hideOverlaysOnScrub` hides them with the
3160
- Skia markers (the wrapper is full-bleed; children keep their own
3161
- absolute positions). */}
3162
- {((markersActive && renderMarker) ||
3163
- ((renderReferenceLine || renderOffAxisReferenceLine) &&
3164
- allRefLines.length > 0)) && (
3165
- <ChartCustomAnnotations model={model} />
3166
- )}
3167
-
3168
- {/* Custom scrub tooltip — an RN view floated over the canvas (non-Skia),
3169
- positioned on the UI thread. Sibling of <Canvas>. Works in line and
3170
- candle mode (candle exposes the OHLC via `scrubCandle`). */}
3171
- {scrubCfg && renderTooltip && (
3172
- <CustomTooltipOverlay
3173
- renderTooltip={renderTooltip}
3174
- scrubX={crosshair.scrubX}
3175
- scrubValue={crosshair.scrubValue}
3176
- scrubTime={crosshair.scrubTime}
3177
- scrubActive={crosshair.scrubActive}
3178
- scrubCandle={crosshair.scrubCandle}
3179
- scrubGap={crosshair.scrubGap}
3180
- tooltipLayout={crosshair.tooltipLayout}
3181
- engine={engine}
3182
- padding={effectivePadding}
3183
- placement={scrubCfg.tooltipPlacement}
3184
- margin={scrubCfg.tooltipMargin}
3185
- crosshairFade={scrubCfg.crosshairFade}
3186
- crosshairFadeDistance={scrubCfg.crosshairFadeDistance}
3187
- lineTop={crosshair.tooltipLineTop}
3188
- scrubDotY={crosshair.scrubDotY}
3189
- />
3190
- )}
3191
-
3192
- {/* Custom consumer overlay — an RN view tree floated over the canvas with
3193
- the price↔pixel / time↔pixel bridge, for order / avg-entry / liquidation
3194
- tags etc. Topmost RN sibling; `box-none` so empty areas still scrub. */}
3195
- {renderOverlay && <ChartCustomConsumerOverlay model={model} />}
3861
+ <ChartCanvas model={model} yAxisEntries={yAxisEntries} degen={degen} />
3862
+ <ChartNativeOverlays model={model} />
3196
3863
  </View>
3197
3864
  </GestureDetector>
3198
3865
  );