forked from hellohublot/native-kline-view
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.js
More file actions
592 lines (519 loc) · 18.8 KB
/
App.js
File metadata and controls
592 lines (519 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/**
* K-line Chart Example Application
* Supports indicators, finger drawing, theme switching and other features
*/
import React, { useState, useEffect, useRef, useCallback } from 'react'
import {
View,
StyleSheet,
StatusBar,
Platform,
PixelRatio,
ScrollView
} from 'react-native'
import RNKLineView from 'react-native-kline-view'
import { ThemeManager } from './utils/themes'
import {
TimeTypes,
DrawTypeConstants,
DrawStateConstants,
DrawToolHelper
} from './utils/constants'
import {
isHorizontalScreen,
formatTime
} from './utils/helpers'
import Toolbar from './components/Toolbar'
import ControlBar from './components/ControlBar'
import OrderInput from './components/OrderInput'
import BuySellMarkInput from './components/BuySellMarkInput'
import Selectors from './components/Selectors'
import {
processKLineData,
packOptionList
} from './utils/businessLogic'
import { generateMockData, generateMoreHistoricalData } from './utils/generateData'
import {
testUpdateLastCandlestick,
testAddCandlesticksAtTheEnd,
testAddCandlesticksAtTheStart
} from './utils/testUtils'
const App = () => {
const MIN_VISIBLE_CANDLES = 10
const [isDarkTheme, setIsDarkTheme] = useState(false)
const [selectedTimeType, setSelectedTimeType] = useState(2) // Corresponds to 1 minute
const [selectedMainIndicator, setSelectedMainIndicator] = useState(1) // Corresponds to MA (1=MA, 2=BOLL)
const [selectedSubIndicator, setSelectedSubIndicator] = useState(4) // Corresponds to KDJ (3=MACD, 4=KDJ, 5=RSI, 6=WR)
const [selectedDrawTool, setSelectedDrawTool] = useState(DrawTypeConstants.none)
const [showIndicatorSelector, setShowIndicatorSelector] = useState(false)
const [showTimeSelector, setShowTimeSelector] = useState(false)
const [showDrawToolSelector, setShowDrawToolSelector] = useState(false)
const [klineData, setKlineData] = useState(generateMockData())
const [drawShouldContinue, setDrawShouldContinue] = useState(true)
const [optionList, setOptionList] = useState(null)
const [lastDataLength, setLastDataLength] = useState(0)
const [currentScrollPosition, setCurrentScrollPosition] = useState(0)
const [showVolumeChart, setShowVolumeChart] = useState(true)
const [candleCornerRadius, setCandleCornerRadius] = useState(0)
const firstCandleTimeRef = useRef(klineData.length > 0 ? klineData[0].time : null)
const [initialDataLoaded, setInitialDataLoaded] = useState(false)
const kLineViewRef = useRef(null)
const updateStatusBar = useCallback(() => {
StatusBar.setBarStyle(
isDarkTheme ? 'light-content' : 'dark-content',
true
)
}, [isDarkTheme])
useEffect(() => {
updateStatusBar()
}, [updateStatusBar])
useEffect(() => {
updateStatusBar()
// Initialize loading K-line data
setLastDataLength(klineData.length)
setTimeout(() => reloadKLineData(), 0)
}, [showVolumeChart, selectedMainIndicator, selectedSubIndicator])
useEffect(() => {
updateStatusBar()
}, [isDarkTheme, updateStatusBar])
// Toggle theme
const toggleTheme = useCallback(() => {
setIsDarkTheme(prev => {
// Reload data after theme switch to apply new colors
setTimeout(() => reloadKLineData(), 0)
return !prev
})
}, [])
// Select time period
const selectTimeType = useCallback((timeType) => {
setSelectedTimeType(timeType)
setShowTimeSelector(false)
// Reset initial data loaded flag and regenerate data
setInitialDataLoaded(false)
setKlineData(generateMockData())
setTimeout(() => reloadKLineData(), 0)
console.log('Switch time period:', TimeTypes[timeType].label)
}, [])
// Select indicator
const selectIndicator = useCallback((type, indicator) => {
if (type === 'main') {
setSelectedMainIndicator(indicator)
} else {
setSelectedSubIndicator(indicator)
}
setShowIndicatorSelector(false)
setTimeout(() => reloadKLineData(), 0)
}, [])
// Select drawing tool
const selectDrawTool = useCallback((tool) => {
setSelectedDrawTool(tool)
setShowDrawToolSelector(false)
setOptionListValue({
drawList: {
shouldReloadDrawItemIndex: tool === DrawTypeConstants.none ? DrawStateConstants.none : DrawStateConstants.showContext,
drawShouldContinue: drawShouldContinue,
drawType: tool,
shouldFixDraw: false,
}
})
}, [drawShouldContinue])
// Clear drawings
const clearDrawings = useCallback(() => {
setSelectedDrawTool(DrawTypeConstants.none)
setOptionListValue({
drawList: {
shouldReloadDrawItemIndex: DrawStateConstants.none,
shouldClearDraw: true,
}
})
}, [])
// Reload K-line data
const reloadKLineData = useCallback((shouldScrollToEnd = true) => {
if (!kLineViewRef.current) {
setTimeout(() => reloadKLineData(shouldScrollToEnd), 100)
return
}
const processedData = processKLineData(klineData, {
selectedMainIndicator,
selectedSubIndicator,
showVolumeChart
}, isDarkTheme)
const newOptionList = packOptionList(processedData, {
isDarkTheme,
selectedTimeType,
selectedMainIndicator,
selectedSubIndicator,
selectedDrawTool,
showIndicatorSelector,
showTimeSelector,
showDrawToolSelector,
klineData,
drawShouldContinue,
optionList,
lastDataLength,
currentScrollPosition,
showVolumeChart,
candleCornerRadius,
minVisibleCandles: MIN_VISIBLE_CANDLES
}, shouldScrollToEnd, kLineViewRef.current ? true : false)
setOptionListValue(newOptionList)
}, [klineData, selectedMainIndicator, selectedSubIndicator, showVolumeChart, isDarkTheme, selectedTimeType, selectedDrawTool, showIndicatorSelector, showTimeSelector, showDrawToolSelector, drawShouldContinue, optionList, lastDataLength, currentScrollPosition, candleCornerRadius])
// Load initial data when component mounts and ref is available
useEffect(() => {
if (kLineViewRef.current && klineData.length > 0 && !initialDataLoaded) {
console.log('Loading initial candlesticks via imperative API:', klineData.length)
const processedData = processKLineData(klineData, {
selectedMainIndicator,
selectedSubIndicator,
showVolumeChart
}, isDarkTheme)
setTimeout(() => {
kLineViewRef.current?.addCandlesticksAtTheEnd(processedData)
setInitialDataLoaded(true)
}, 200) // Give chart time to initialize
}
}, [kLineViewRef.current, klineData, selectedMainIndicator, selectedSubIndicator, showVolumeChart, isDarkTheme, initialDataLoaded])
// Reload K-line data and adjust scroll position to maintain current view
const reloadKLineDataWithScrollAdjustment = useCallback((addedDataCount) => {
if (!kLineViewRef.current) {
setTimeout(() => reloadKLineDataWithScrollAdjustment(addedDataCount), 100)
return
}
const processedData = processKLineData(klineData, {
selectedMainIndicator,
selectedSubIndicator,
showVolumeChart
}, isDarkTheme)
const newOptionList = packOptionList(processedData, {
isDarkTheme,
selectedTimeType,
selectedMainIndicator,
selectedSubIndicator,
selectedDrawTool,
showIndicatorSelector,
showTimeSelector,
showDrawToolSelector,
klineData,
drawShouldContinue,
optionList,
lastDataLength,
currentScrollPosition,
showVolumeChart,
candleCornerRadius,
minVisibleCandles: MIN_VISIBLE_CANDLES
}, false)
// Calculate scroll distance adjustment needed (based on item width)
const pixelRatio = Platform.select({
android: PixelRatio.get(),
ios: 1,
})
const itemWidth = 8 * pixelRatio // This matches itemWidth in configList
const scrollAdjustment = addedDataCount * itemWidth
// Set scroll position adjustment parameters
newOptionList.scrollPositionAdjustment = scrollAdjustment
console.log(`Adjust scroll position: ${addedDataCount} data points, scroll distance: ${scrollAdjustment}px`)
setOptionListValue(newOptionList)
}, [klineData, selectedMainIndicator, selectedSubIndicator, showVolumeChart, isDarkTheme, selectedTimeType, selectedDrawTool, showIndicatorSelector, showTimeSelector, showDrawToolSelector, drawShouldContinue, optionList, lastDataLength, currentScrollPosition, candleCornerRadius])
// Set optionList property
const setOptionListValue = useCallback((optionList) => {
setOptionList(JSON.stringify(optionList))
}, [])
// Drawing item touch event
const onDrawItemDidTouch = useCallback((event) => {
const { nativeEvent } = event
console.log('Drawing item touched:', nativeEvent)
}, [])
// Chart touch event
const onChartTouch = useCallback((event) => {
const { nativeEvent } = event
console.log('Chart touched:', nativeEvent)
if (nativeEvent.isOnClosePriceLabel) {
console.log('🎯 Touched close price label! Scroll to latest position')
scrollToPresent()
}
}, [scrollToPresent])
// Scroll to latest position
const scrollToPresent = useCallback(() => {
reloadKLineData(true)
}, [reloadKLineData])
// Drawing item complete event
const onDrawItemComplete = useCallback((event) => {
const { nativeEvent } = event
console.log('Drawing item complete:', nativeEvent)
// Processing after drawing completion
if (!drawShouldContinue) {
selectDrawTool(DrawTypeConstants.none)
}
}, [drawShouldContinue, selectDrawTool])
// Drawing point complete event
const onDrawPointComplete = useCallback((event) => {
const { nativeEvent } = event
console.log('Drawing point complete:', nativeEvent.pointCount)
// Can display current drawing progress here
const currentTool = selectedDrawTool
const totalPoints = DrawToolHelper.count(currentTool)
if (totalPoints > 0) {
const progress = `${nativeEvent.pointCount}/${totalPoints}`
console.log(`Drawing progress: ${progress}`)
}
}, [selectedDrawTool])
const handleTestAddCandlesticksAtTheStart = useCallback(() => {
console.log("handleTestAddCandlesticksAtTheStart called")
testAddCandlesticksAtTheStart(klineData, showVolumeChart, firstCandleTimeRef.current, (candlesticks) => {
kLineViewRef.current?.addCandlesticksAtTheStart(candlesticks)
firstCandleTimeRef.current = candlesticks[0].time
})
}, [klineData, showVolumeChart,kLineViewRef.current,firstCandleTimeRef.current])
// Handle new data loading triggered by left swipe
const handleScrollLeft = useCallback((event) => {
console.log('Loading 200 new historical candlesticks at start')
handleTestAddCandlesticksAtTheStart()
}, [handleTestAddCandlesticksAtTheStart])
// Wrapper functions for test utilities
const handleTestUpdateLastCandlestick = useCallback(() => {
testUpdateLastCandlestick(klineData, showVolumeChart, (candlestick) => {
kLineViewRef.current?.updateLastCandlestick(candlestick)
})
}, [klineData, showVolumeChart,kLineViewRef.current])
const handleTestAddCandlesticksAtTheEnd = useCallback(() => {
testAddCandlesticksAtTheEnd(klineData, showVolumeChart, (candlesticks) => {
kLineViewRef.current?.addCandlesticksAtTheEnd(candlesticks)
})
}, [klineData, showVolumeChart,kLineViewRef.current])
// Order line management
const [orderIdCounter, setOrderIdCounter] = useState(1)
const [orderLines, setOrderLines] = useState({})
// Buy/sell mark management
const [buySellMarkIdCounter, setBuySellMarkIdCounter] = useState(1)
const [buySellMarks, setBuySellMarks] = useState({})
const handleAddLimitOrder = useCallback((price, label) => {
if (!kLineViewRef.current) return
const orderLine = {
id: `limit-order-${orderIdCounter}`,
type: 'limit',
price: price,
amount: 1,
color: '#00FF00', // Green color for the order line
label: label || `Limit ${orderIdCounter}`,
labelFontSize: 14,
labelBackgroundColor: '#114411AA', // Black background for the label pill
labelColor: '#FFFFFF', // Green color for the label text
labelDescription: 'BUY', // Description text
labelDescriptionColor: '#00FF00' // Gold color for the description text
}
console.log('Adding limit order:', orderLine)
kLineViewRef.current.addOrderLine(orderLine)
setOrderLines(prev => ({ ...prev, [orderLine.id]: orderLine }))
setOrderIdCounter(prev => prev + 1)
}, [kLineViewRef.current, orderIdCounter])
const handleUpdateOrder = useCallback((orderId, newPrice) => {
if (!kLineViewRef.current) return
const existingOrder = orderLines[orderId]
if (!existingOrder) {
console.warn(`Order with ID ${orderId} not found`)
return
}
const updatedOrderLine = {
...existingOrder,
price: newPrice,
color: '#FF9500', // Orange color for updated orders
label: `${existingOrder.label} (Updated)`,
labelFontSize: 12,
labelBackgroundColor: '#333333' // Dark gray background for updated orders
}
console.log('Updating order:', updatedOrderLine)
kLineViewRef.current.updateOrderLine(updatedOrderLine)
setOrderLines(prev => ({ ...prev, [orderId]: updatedOrderLine }))
}, [kLineViewRef.current, orderLines])
// Get current price for the input component
const getCurrentPrice = useCallback(() => {
if (klineData.length > 0) {
return klineData[klineData.length - 1].close
}
return null
}, [klineData])
// Buy/sell mark handlers
const handleAddBuySellMark = useCallback((type, time, price, amount, orderCount) => {
if (!kLineViewRef.current) return
const finalPrice = price || getCurrentPrice() || 0
const finalAmount = amount || '1.0'
const buySellMark = {
id: `buysell-mark-${buySellMarkIdCounter}`,
time: time,
type: type, // 'buy' or 'sell'
amount: finalAmount,
price: finalPrice.toString(),
orderCount: orderCount || 1,
tooltipText: `${type.toUpperCase()} ${finalAmount} at ${finalPrice.toFixed(2)}`
}
console.log('Adding buy/sell mark:', buySellMark)
kLineViewRef.current.addBuySellMark(buySellMark)
setBuySellMarks(prev => ({ ...prev, [buySellMark.id]: buySellMark }))
setBuySellMarkIdCounter(prev => prev + 1)
}, [kLineViewRef.current, buySellMarkIdCounter, getCurrentPrice])
const handleRemoveBuySellMark = useCallback((markId) => {
if (!kLineViewRef.current) return
console.log('Removing buy/sell mark:', markId)
kLineViewRef.current.removeBuySellMark(markId)
setBuySellMarks(prev => {
const newMarks = { ...prev }
delete newMarks[markId]
return newMarks
})
}, [kLineViewRef.current])
const handleUpdateBuySellMark = useCallback((markId, newType, newPrice, newAmount, newOrderCount) => {
if (!kLineViewRef.current) return
const existingMark = buySellMarks[markId]
if (!existingMark) {
console.warn(`Buy/sell mark with ID ${markId} not found`)
return
}
const finalType = newType || existingMark.type
const finalPrice = newPrice || parseFloat(existingMark.price)
const finalAmount = newAmount || existingMark.amount
const updatedMark = {
...existingMark,
type: finalType,
price: finalPrice.toString(),
amount: finalAmount,
orderCount: newOrderCount || existingMark.orderCount,
tooltipText: `${finalType.toUpperCase()} ${finalAmount} at ${finalPrice.toFixed(2)}`
}
console.log('Updating buy/sell mark:', updatedMark)
kLineViewRef.current.updateBuySellMark(updatedMark)
setBuySellMarks(prev => ({ ...prev, [markId]: updatedMark }))
}, [kLineViewRef.current, buySellMarks])
const renderKLineChart = useCallback((styles) => {
const directRender = (
<RNKLineView
ref={kLineViewRef}
style={styles.chart}
optionList={optionList}
onDrawItemDidTouch={onDrawItemDidTouch}
onScrollLeft={handleScrollLeft}
onChartTouch={onChartTouch}
onDrawItemComplete={onDrawItemComplete}
onDrawPointComplete={onDrawPointComplete}
/>
)
if (global?.nativeFabricUIManager && Platform.OS == 'ios') {
return directRender
}
return (
<View style={{ flex: 1 }} collapsable={false}>
<View style={{ flex: 1 }} collapsable={false}>
<View style={styles.chartContainer} collapsable={false}>
{directRender}
</View>
</View>
</View>
)
}, [optionList, onDrawItemDidTouch, handleScrollLeft, onChartTouch, onDrawItemComplete, onDrawPointComplete])
const getStyles = useCallback((theme) => {
return StyleSheet.create({
container: {
flex: 1,
backgroundColor: theme.backgroundColor,
paddingTop: isHorizontalScreen ? 10 : 50,
paddingBottom: isHorizontalScreen ? 20 : 100,
},
chartContainer: {
flex: 1,
margin: 8,
borderRadius: 8,
backgroundColor: theme.backgroundColor,
borderWidth: 1,
borderColor: theme.gridColor,
},
chart: {
flex: 1,
backgroundColor: 'transparent',
},
})
}, [])
const theme = ThemeManager.getCurrentTheme(isDarkTheme)
const styles = getStyles(theme)
console.log("App.js render", Platform.OS)
return (
<View style={styles.container}>
{/* Top toolbar */}
<Toolbar
theme={theme}
isDarkTheme={isDarkTheme}
onToggleTheme={toggleTheme}
onTestUpdate={handleTestUpdateLastCandlestick}
onTestAddCandles={handleTestAddCandlesticksAtTheEnd}
onTestAddCandlesAtStart={handleTestAddCandlesticksAtTheStart}
/>
{/* K-line chart */}
<View style={{height: 400}}>
{renderKLineChart(styles)}
</View>
<ScrollView style={{maxHeight: 400}}>
{/* Order input */}
<OrderInput
theme={theme}
onAddOrder={handleAddLimitOrder}
onUpdateOrder={handleUpdateOrder}
currentPrice={getCurrentPrice()}
orderLines={orderLines}
/>
{/* Buy/Sell mark input */}
<BuySellMarkInput
theme={theme}
onAddBuySellMark={handleAddBuySellMark}
onRemoveBuySellMark={handleRemoveBuySellMark}
onUpdateBuySellMark={handleUpdateBuySellMark}
currentPrice={getCurrentPrice()}
buySellMarks={buySellMarks}
klineData={klineData}
/>
{/* Bottom control bar */}
<ControlBar
theme={theme}
selectedTimeType={selectedTimeType}
selectedMainIndicator={selectedMainIndicator}
selectedSubIndicator={selectedSubIndicator}
selectedDrawTool={selectedDrawTool}
showVolumeChart={showVolumeChart}
candleCornerRadius={candleCornerRadius}
onShowTimeSelector={() => setShowTimeSelector(true)}
onShowIndicatorSelector={() => setShowIndicatorSelector(true)}
onToggleDrawToolSelector={() => {
setShowDrawToolSelector(!showDrawToolSelector)
setShowIndicatorSelector(false)
setShowTimeSelector(false)
}}
onClearDrawings={clearDrawings}
onToggleVolume={() => {
setShowVolumeChart(!showVolumeChart)
setTimeout(() => reloadKLineData(), 0)
}}
onToggleRounded={() => {
setCandleCornerRadius(candleCornerRadius > 0 ? 0 : 1)
setTimeout(() => reloadKLineData(), 0)
}}
/>
{/* Selector popup */}
<Selectors
theme={theme}
showTimeSelector={showTimeSelector}
showIndicatorSelector={showIndicatorSelector}
showDrawToolSelector={showDrawToolSelector}
selectedTimeType={selectedTimeType}
selectedMainIndicator={selectedMainIndicator}
selectedSubIndicator={selectedSubIndicator}
selectedDrawTool={selectedDrawTool}
drawShouldContinue={drawShouldContinue}
onSelectTimeType={selectTimeType}
onSelectIndicator={selectIndicator}
onSelectDrawTool={selectDrawTool}
onCloseTimeSelector={() => setShowTimeSelector(false)}
onCloseIndicatorSelector={() => setShowIndicatorSelector(false)}
onToggleDrawShouldContinue={(value) => setDrawShouldContinue(value)}
/>
</ScrollView>
</View>
)
}
export default App