react-native-vroom-chart 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,7 @@
10
10
  #include "include/core/SkRect.h"
11
11
  #pragma clang diagnostic pop
12
12
 
13
+ #include <algorithm>
13
14
  #include <cmath>
14
15
 
15
16
  #include "viewport.h"
@@ -29,11 +30,14 @@ void draw(SkCanvas* canvas,
29
30
  float candle_area_h,
30
31
  uint32_t color,
31
32
  float width,
32
- const unsigned char* break_before) {
33
+ const unsigned char* break_before,
34
+ float opacity) {
33
35
  if (!canvas || !values_visible || n == 0 || candle_right <= 0.f ||
34
36
  candle_area_h <= 0.f) {
35
37
  return;
36
38
  }
39
+ opacity = std::clamp(opacity, 0.f, 1.f);
40
+ if (opacity <= 0.f) return;
37
41
 
38
42
  // SkPathBuilder (not SkPath's edit methods, removed in newer Skia tips).
39
43
  SkPathBuilder path;
@@ -59,6 +63,10 @@ void draw(SkCanvas* canvas,
59
63
  SkPaint line;
60
64
  line.setAntiAlias(true);
61
65
  line.setColor(static_cast<SkColor>(color));
66
+ // Fade the line in during the candle→line morph (multiplies the color alpha).
67
+ if (opacity < 1.f) {
68
+ line.setAlphaf(line.getAlphaf() * opacity);
69
+ }
62
70
  line.setStyle(SkPaint::kStroke_Style);
63
71
  line.setStrokeWidth(width > 0.f ? width : 1.5f);
64
72
 
@@ -70,4 +78,71 @@ void draw(SkCanvas* canvas,
70
78
  canvas->restore();
71
79
  }
72
80
 
81
+ void fill_between(SkCanvas* canvas,
82
+ const Layout& lay,
83
+ const PriceBounds& bounds,
84
+ const ::VroomCandle* visible,
85
+ std::size_t n,
86
+ const double* upper_visible,
87
+ const double* lower_visible,
88
+ int64_t window_ms,
89
+ int64_t visible_start_ms,
90
+ int64_t candle_duration_ms,
91
+ float candle_right,
92
+ float candle_area_h,
93
+ uint32_t color,
94
+ float opacity) {
95
+ if (!canvas || !upper_visible || !lower_visible || n == 0 ||
96
+ candle_right <= 0.f || candle_area_h <= 0.f) {
97
+ return;
98
+ }
99
+ opacity = std::clamp(opacity, 0.f, 1.f);
100
+ if (opacity <= 0.f) return;
101
+
102
+ // One closed contour per maximal run where both series are finite; a
103
+ // single-point run has no area. Multiple runs (e.g. around a data gap)
104
+ // become multiple contours in one path.
105
+ SkPathBuilder path;
106
+ std::size_t i = 0;
107
+ while (i < n) {
108
+ if (!std::isfinite(upper_visible[i]) ||
109
+ !std::isfinite(lower_visible[i])) {
110
+ ++i;
111
+ continue;
112
+ }
113
+ std::size_t e = i;
114
+ while (e + 1 < n && std::isfinite(upper_visible[e + 1]) &&
115
+ std::isfinite(lower_visible[e + 1])) {
116
+ ++e;
117
+ }
118
+ if (e > i) {
119
+ const auto x_at = [&](std::size_t k) {
120
+ return vroom::candle_center_x(lay, visible[k].time_ms,
121
+ candle_duration_ms,
122
+ visible_start_ms, window_ms);
123
+ };
124
+ path.moveTo(x_at(i), vroom::price_to_y(lay, bounds, upper_visible[i]));
125
+ for (std::size_t k = i + 1; k <= e; ++k) {
126
+ path.lineTo(x_at(k), vroom::price_to_y(lay, bounds, upper_visible[k]));
127
+ }
128
+ for (std::size_t k = e + 1; k-- > i;) {
129
+ path.lineTo(x_at(k), vroom::price_to_y(lay, bounds, lower_visible[k]));
130
+ }
131
+ path.close();
132
+ }
133
+ i = e + 1;
134
+ }
135
+
136
+ SkPaint fill;
137
+ fill.setAntiAlias(true);
138
+ fill.setColor(static_cast<SkColor>(color));
139
+ fill.setAlphaf(fill.getAlphaf() * opacity);
140
+ fill.setStyle(SkPaint::kFill_Style);
141
+
142
+ canvas->save();
143
+ canvas->clipRect(SkRect::MakeLTRB(0.f, 0.f, candle_right, candle_area_h));
144
+ canvas->drawPath(path.detach(), fill);
145
+ canvas->restore();
146
+ }
147
+
73
148
  } // namespace vroom::ma_overlay
@@ -37,6 +37,28 @@ void draw(SkCanvas* canvas,
37
37
  float candle_area_h,
38
38
  uint32_t color,
39
39
  float width,
40
- const unsigned char* break_before = nullptr);
40
+ const unsigned char* break_before = nullptr,
41
+ float opacity = 1.f);
42
+
43
+ // Fills the closed region between two aligned series (NaN where undefined)
44
+ // with `color` at its alpha × `opacity` — used for the Bollinger Band fill.
45
+ // Runs where either series is NaN are skipped, so the fill never bridges the
46
+ // warmup gap. Plain-alpha SkPaint fill, no gradient shader (the Skia gradient
47
+ // APIs diverge across our pinned versions; see liquidity.cpp). Clipped to the
48
+ // candle area like draw().
49
+ void fill_between(SkCanvas* canvas,
50
+ const Layout& lay,
51
+ const PriceBounds& bounds,
52
+ const ::VroomCandle* visible,
53
+ std::size_t n,
54
+ const double* upper_visible,
55
+ const double* lower_visible,
56
+ int64_t window_ms,
57
+ int64_t visible_start_ms,
58
+ int64_t candle_duration_ms,
59
+ float candle_right,
60
+ float candle_area_h,
61
+ uint32_t color,
62
+ float opacity);
41
63
 
42
64
  } // namespace vroom::ma_overlay
@@ -22,6 +22,7 @@ constexpr uint32_t kDefaultColors[VROOM_COLOR_COUNT_] = {
22
22
  0x00000000, // WICK_BEAR — transparent sentinel: inherit BEAR fill
23
23
  0xff26a69a, // ACCENT_BULL — classic teal-green (price indicator, volume, MACD)
24
24
  0xffef5350, // ACCENT_BEAR — classic red
25
+ 0xffc9d1d9, // LINE — line-chart close polyline; neutral foreground (AXIS_TEXT tone)
25
26
  };
26
27
 
27
28
  constexpr float kDefaultFloats[VROOM_FLOAT_COUNT_] = {
@@ -36,6 +37,7 @@ constexpr float kDefaultFloats[VROOM_FLOAT_COUNT_] = {
36
37
  0.f, // CANDLE_RADIUS_PX — square by default
37
38
  0.f, // WICK_ROUND_CAP — butt caps by default
38
39
  0.f, // VOLUME_RADIUS_PX — square by default
40
+ 1.5f, // LINE_WIDTH_PX — line-chart polyline stroke width
39
41
  };
40
42
 
41
43
  } // namespace
package/lib/index.d.mts CHANGED
@@ -92,6 +92,10 @@ type VroomTheme = {
92
92
  crosshair?: VroomColor;
93
93
  /** Crosshair target — the hollow ring/dot at the intersection. */
94
94
  crosshairTarget?: VroomColor;
95
+ /** Line-chart-mode close polyline color. Defaults to a neutral foreground. */
96
+ lineColor?: VroomColor;
97
+ /** Line-chart-mode polyline stroke width in px. Defaults to 1.5. */
98
+ lineWidth?: number;
95
99
  };
96
100
  /** A time window over the candle data, as Unix epoch milliseconds. */
97
101
  type VisibleRange = {
@@ -106,8 +110,15 @@ type VisibleRange = {
106
110
  * 'draw' — left-clicks place drawing points; panning/zooming are suppressed.
107
111
  */
108
112
  type ChartMode = 'pan' | 'draw';
113
+ /**
114
+ * How the price series is drawn.
115
+ * 'candles' — default: candlestick bodies + wicks.
116
+ * 'line' — a single polyline through each candle's close. Volume, indicators,
117
+ * overlays, crosshair, and drawings still render.
118
+ */
119
+ type ChartType = 'candles' | 'line';
109
120
  /** Active drawing tool while in `draw` mode. `null` draws nothing. */
110
- type DrawTool = null | 'line';
121
+ type DrawTool = null | 'line' | 'box' | 'pencil';
111
122
  /** A drawing anchor in data space, so it stays glued to the candles on pan/zoom. */
112
123
  type DrawPoint = {
113
124
  /** Anchor time as Unix epoch milliseconds (not snapped to a candle slot). */
@@ -115,23 +126,106 @@ type DrawPoint = {
115
126
  /** Anchor price. */
116
127
  price: number;
117
128
  };
118
- /**
119
- * A committed drawing. Pass an array of these via the `drawings` prop to render
120
- * persisted annotations; the chart appends a new one (via `onDrawingComplete`)
121
- * each time the user finishes drawing. For now only the `'line'` (two-point
122
- * trendline) type exists.
123
- */
124
- type Drawing = {
129
+ /** Fields shared by every drawing type. */
130
+ type DrawingBase = {
125
131
  /** Stable unique id (the chart generates one for drawings it creates). */
126
132
  id: string;
127
- type: 'line';
128
- /** The two endpoints, in data space. */
129
- points: [DrawPoint, DrawPoint];
130
- /** Line color (hex string or packed ARGB number). Default solid blue. */
133
+ /** Stroke color (hex string or packed ARGB number). Default solid blue. */
131
134
  color?: VroomColor;
132
135
  /** Stroke width in px. Default 2. */
133
136
  width?: number;
134
137
  };
138
+ /** A two-point trendline from `points[0]` to `points[1]`. */
139
+ type LineDrawing = DrawingBase & {
140
+ type: 'line';
141
+ /** The two endpoints, in data space. */
142
+ points: [DrawPoint, DrawPoint];
143
+ };
144
+ /**
145
+ * An axis-aligned rectangle whose two opposite corners are `points[0]` and
146
+ * `points[1]` (the other two corners are derived).
147
+ */
148
+ type BoxDrawing = DrawingBase & {
149
+ type: 'box';
150
+ /** Two opposite corners, in data space. */
151
+ points: [DrawPoint, DrawPoint];
152
+ };
153
+ /**
154
+ * A freehand pencil stroke: an open path through `points`, in order. Unlike the
155
+ * other tools a stroke has a variable number of points, and once committed it
156
+ * can only be translated — never reshaped.
157
+ */
158
+ type PencilDrawing = DrawingBase & {
159
+ type: 'pencil';
160
+ /** The path's points in draw order (at least 2), in data space. */
161
+ points: DrawPoint[];
162
+ };
163
+ /**
164
+ * A committed drawing. Pass an array of these via the `drawings` prop to render
165
+ * persisted annotations; the chart appends a new one (via `onDrawingComplete`)
166
+ * each time the user finishes drawing.
167
+ *
168
+ * This is a discriminated union on `type` — narrow on it before reading
169
+ * `points[1]`, since a `'pencil'` stroke has a variable-length array while
170
+ * `'line'` and `'box'` are always exactly two points.
171
+ */
172
+ type Drawing = LineDrawing | BoxDrawing | PencilDrawing;
173
+ /**
174
+ * Storage adapter for **managed** drawing persistence. Provide it via the
175
+ * `drawingStore` prop and the chart owns the drawings array itself — loading and
176
+ * saving through this adapter instead of you wiring the controlled `drawings`
177
+ * prop + `onDrawing*` callbacks.
178
+ *
179
+ * The adapter is an **opaque string key-value store** — the chart serializes
180
+ * drawings into a **versioned envelope** (`{ v, drawings }`) and hands you the
181
+ * string; you just persist bytes. Because the library owns the schema and
182
+ * migrates old payloads on load, adding drawing tools or persisted fields later
183
+ * never changes this interface — your adapter is written once.
184
+ *
185
+ * `marketId` is the chart's `seriesKey`, so drawings are bucketed per market:
186
+ * they persist across timeframe changes (same key) but not across markets. Both
187
+ * methods may be async (localStorage is sync; AsyncStorage / MMKV / a REST
188
+ * backend are async). The chart debounces `save`. Consumers that only handle a
189
+ * single market can ignore `marketId`.
190
+ */
191
+ type DrawingStore = {
192
+ /**
193
+ * Return the raw string previously handed to `save` for `marketId`, or
194
+ * `null`/`undefined`/`''` if nothing is stored. Sync or async.
195
+ */
196
+ load: (marketId: string) => string | null | undefined | Promise<string | null | undefined>;
197
+ /**
198
+ * Persist the opaque `data` string for `marketId`. Sync or async; the chart
199
+ * debounces calls. The string is a versioned envelope owned by the library —
200
+ * store it verbatim, don't parse or reshape it.
201
+ */
202
+ save: (marketId: string, data: string) => void | Promise<void>;
203
+ };
204
+ /**
205
+ * Whether undo/redo are currently available for the chart's drawings — the
206
+ * payload of `onHistoryChange`, for binding toolbar button enabled-states.
207
+ */
208
+ type UndoRedoState = {
209
+ canUndo: boolean;
210
+ canRedo: boolean;
211
+ };
212
+ /**
213
+ * Programmatic undo/redo controls, published through the `historyRef` prop in
214
+ * managed mode — for toolbar buttons and other UI outside the chart. The
215
+ * keyboard shortcuts (⌘Z / ⇧⌘Z / Ctrl+Y) work without this.
216
+ */
217
+ type UndoRedoControls = {
218
+ /** Roll back the most recent committed drawing action. No-op when empty. */
219
+ undo: () => void;
220
+ /** Re-apply the most recently undone action. No-op when empty. */
221
+ redo: () => void;
222
+ /**
223
+ * Drop the undo/redo stacks without touching the drawings. Rarely needed —
224
+ * users find a cleared history surprising — but useful when reusing a mounted
225
+ * chart for what the user perceives as a brand-new context.
226
+ */
227
+ clearHistory: () => void;
228
+ };
135
229
  /** RSI indicator config. Rendered in a pane below the candles when enabled. */
136
230
  type RSIConfig = {
137
231
  enabled?: boolean;
@@ -177,6 +271,42 @@ type VWAPConfig = {
177
271
  /** Stroke width in px. Default 1.5. */
178
272
  width?: number;
179
273
  };
274
+ /**
275
+ * Bollinger Bands overlay config. A basis moving average of `source` over
276
+ * `period`, banded at ± `stdDev` × population standard deviation of the same
277
+ * window, drawn as three lines on the price pane with an optional translucent
278
+ * fill between the bands. No pane is reserved.
279
+ */
280
+ type BollingerBandsConfig = {
281
+ enabled?: boolean;
282
+ /** Lookback in candles. Default 20, clamped to >= 1. */
283
+ period?: number;
284
+ /** Standard-deviation multiplier. Default 2. */
285
+ stdDev?: number;
286
+ /** Price source. Default 'close'. */
287
+ source?: MASource;
288
+ /**
289
+ * Basis (middle) line type. Default 'sma'. The stdev always uses the
290
+ * window's arithmetic mean, even with an EMA basis (TradingView semantics).
291
+ */
292
+ basis?: 'sma' | 'ema';
293
+ /** Upper band color (hex string or packed ARGB number). Default blue. */
294
+ upperColor?: string | number;
295
+ /** Upper band stroke width in px. Default 1. */
296
+ upperWidth?: number;
297
+ /** Basis (middle) line color. Default orange. */
298
+ middleColor?: string | number;
299
+ /** Basis line stroke width in px. Default 1. */
300
+ middleWidth?: number;
301
+ /** Lower band color. Default blue. */
302
+ lowerColor?: string | number;
303
+ /** Lower band stroke width in px. Default 1. */
304
+ lowerWidth?: number;
305
+ /** Translucent fill between the bands. Default true. */
306
+ fill?: boolean;
307
+ /** Fill opacity 0..1, applied to the upper band color. Default 0.1. */
308
+ fillOpacity?: number;
309
+ };
180
310
  /**
181
311
  * A single resting-liquidity band: a price interval carrying a total order size
182
312
  * on one side of the book. Consolidate raw L2 levels into these buckets before
@@ -265,6 +395,18 @@ type VroomChartCoreProps = {
265
395
  * devices of different widths.
266
396
  */
267
397
  defaultCandleWidth?: number;
398
+ /**
399
+ * Price-series render style. `'candles'` (default) draws candlesticks;
400
+ * `'line'` draws a polyline through each candle's close (style it with
401
+ * `theme.lineColor` / `theme.lineWidth`). All other layers are unaffected.
402
+ */
403
+ chartType?: ChartType;
404
+ /**
405
+ * Duration (ms) of the animated candle↔line transition when `chartType`
406
+ * changes. Default ~300. `0` snaps instantly. Ignored (snaps) when the OS
407
+ * requests reduced motion, which instead uses a plain cross-fade.
408
+ */
409
+ transitionMs?: number;
268
410
  theme?: VroomTheme;
269
411
  /** RSI indicator (pane below the candles). Omit/disable to hide it. */
270
412
  rsi?: RSIConfig;
@@ -274,6 +416,8 @@ type VroomChartCoreProps = {
274
416
  movingAverages?: MovingAverageOverlay[];
275
417
  /** VWAP overlay (session anchor, configurable reset). */
276
418
  vwap?: VWAPConfig;
419
+ /** Bollinger Bands overlay (three lines + fill on the price pane). */
420
+ bollingerBands?: BollingerBandsConfig;
277
421
  /** Resting-order / order-book liquidity bands drawn behind the candles. */
278
422
  liquidity?: LiquidityConfig;
279
423
  /**
@@ -306,16 +450,70 @@ type VroomChartCoreProps = {
306
450
  * Committed drawings to render, anchored to data so they track the candles on
307
451
  * pan/zoom. This is a controlled prop: append the value the chart hands you in
308
452
  * `onDrawingComplete` to persist it.
453
+ *
454
+ * Ignored when `drawingStore` is set (the chart then owns the array itself).
309
455
  */
310
456
  drawings?: Drawing[];
457
+ /**
458
+ * Opt into **managed** drawing persistence: the chart owns the drawings array
459
+ * internally and loads/saves it through this adapter, keyed by `seriesKey`.
460
+ * When set, `drawings` and the `onDrawing*` callbacks are ignored. Web only.
461
+ * Requires `seriesKey` — without one, drawings work in-session but aren't saved.
462
+ */
463
+ drawingStore?: DrawingStore;
311
464
  /** Fired with the finished drawing when the user completes one. */
312
465
  onDrawingComplete?: (drawing: Drawing) => void;
466
+ /**
467
+ * Fired after the user drags a selected line's endpoint handle. The payload is
468
+ * the same drawing (same `id`) with updated `points`; apply it to your
469
+ * controlled `drawings` state (replace by id). Web only.
470
+ */
471
+ onDrawingChange?: (drawing: Drawing) => void;
472
+ /**
473
+ * Fired when the user deletes the selected line (Backspace/Delete). Remove the
474
+ * drawing with this `id` from your controlled `drawings` state. Web only.
475
+ */
476
+ onDrawingDelete?: (id: string) => void;
313
477
  /**
314
478
  * Fired when the chart wants the mode changed — e.g. it requests `'pan'` after
315
479
  * the user clicks away from a just-drawn line. Since `mode` is controlled, the
316
480
  * host should apply the requested mode.
317
481
  */
318
482
  onModeChange?: (mode: ChartMode) => void;
483
+ /**
484
+ * Max drawing undo depth in managed mode (one step = one committed drawing
485
+ * action). Oldest steps are evicted beyond this. Default 100. History is
486
+ * in-memory and per-`seriesKey`: it resets on market switch and is never
487
+ * persisted — only the drawings themselves are saved. Web only.
488
+ */
489
+ historyLimit?: number;
490
+ /**
491
+ * Fired when drawing undo/redo availability changes in managed mode — bind
492
+ * toolbar undo/redo buttons' enabled-state to it. (In controlled mode you own
493
+ * the history, so track availability yourself.) Web only.
494
+ */
495
+ onHistoryChange?: (state: UndoRedoState) => void;
496
+ /**
497
+ * Receives programmatic `undo`/`redo`/`clearHistory` controls in managed mode
498
+ * (e.g. `useRef<UndoRedoControls | null>(null)` passed here, then
499
+ * `historyRef.current?.undo()` from a toolbar button). Set to `null` while
500
+ * unmounted or when no `drawingStore` is present. Web only.
501
+ */
502
+ historyRef?: {
503
+ current: UndoRedoControls | null;
504
+ };
505
+ /**
506
+ * Fired when the user presses the undo shortcut (⌘Z / Ctrl+Z) in controlled
507
+ * mode — apply the undo to your own drawings state. Ignored when
508
+ * `drawingStore` is set (managed mode undoes internally). Web only.
509
+ */
510
+ onUndo?: () => void;
511
+ /**
512
+ * Fired when the user presses the redo shortcut (⇧⌘Z / Ctrl+Shift+Z /
513
+ * Ctrl+Y) in controlled mode — apply the redo to your own drawings state.
514
+ * Ignored when `drawingStore` is set. Web only.
515
+ */
516
+ onRedo?: () => void;
319
517
  onCrosshair?: (e: CrosshairEvent) => void;
320
518
  onViewportChange?: (startMs: number, endMs: number) => void;
321
519
  };
@@ -349,4 +547,4 @@ declare global {
349
547
  */
350
548
  declare function VroomChart(props: VroomChartProps): React.JSX.Element;
351
549
 
352
- export { type Candle, type CrosshairEvent, type MACDConfig, type MASource, type MovingAverageOverlay, type RSIConfig, type VWAPConfig, type VisibleRange, VroomChart, type VroomChartProps, type VroomColor, type VroomTheme };
550
+ export { type BollingerBandsConfig, type Candle, type ChartType, type CrosshairEvent, type MACDConfig, type MASource, type MovingAverageOverlay, type RSIConfig, type VWAPConfig, type VisibleRange, VroomChart, type VroomChartProps, type VroomColor, type VroomTheme };