|
| 1 | +import React from 'react'; |
| 2 | +import styled from 'styled-components'; |
| 3 | +import AsyncScriptLoader from 'react-async-script'; |
| 4 | + |
| 5 | +import { TRADING_VIEW_DEFAULT_CONFIG } from '../utils/data/chartDataUtils'; |
| 6 | + |
| 7 | +const DEFAULT_INTERVAL = 'D'; |
| 8 | + |
| 9 | +interface ITradingView { |
| 10 | + id: string, |
| 11 | + symbol: string, |
| 12 | +} |
| 13 | + |
| 14 | +interface ITradingViewState { |
| 15 | + widgetInstance: any, |
| 16 | + container_id: string, |
| 17 | + symbol: string, |
| 18 | +} |
| 19 | + |
| 20 | +const StyledTradingView = styled.div` |
| 21 | + width: 100%; |
| 22 | + height: 570px; |
| 23 | +`; |
| 24 | + |
| 25 | +const AsyncScriptLoaderTradingView = AsyncScriptLoader( |
| 26 | + '/assets/tradingview/charting_library/charting_library.min.js', |
| 27 | +)(StyledTradingView); |
| 28 | + |
| 29 | +class TradingView extends React.PureComponent<ITradingView, ITradingViewState> { |
| 30 | + constructor(props: ITradingView) { |
| 31 | + super(props); |
| 32 | + this.state = { |
| 33 | + symbol: props.symbol, |
| 34 | + widgetInstance: null, |
| 35 | + container_id: `${props.id}-tv-identifier`, |
| 36 | + }; |
| 37 | + this.initializedTradingView = this.initializedTradingView.bind(this); |
| 38 | + } |
| 39 | + |
| 40 | + componentDidUpdate({ symbol }: ITradingView) { |
| 41 | + if (symbol !== this.props.symbol) { |
| 42 | + this.setState({ symbol: this.props.symbol }, () => { |
| 43 | + const { widgetInstance, symbol: symbolState } = this.state; |
| 44 | + if (widgetInstance) { |
| 45 | + widgetInstance.setSymbol(symbolState, DEFAULT_INTERVAL); |
| 46 | + } |
| 47 | + }); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + initializedTradingView() { |
| 52 | + if (!window) { |
| 53 | + return; |
| 54 | + } |
| 55 | + const { symbol, container_id } = this.state; |
| 56 | + const tvConfig = { |
| 57 | + symbol, |
| 58 | + container_id, |
| 59 | + interval: DEFAULT_INTERVAL, |
| 60 | + datafeed: new (window as any).Datafeeds.UDFCompatibleDatafeed( |
| 61 | + process.env.REACT_APP_DATA_FEED_URL, |
| 62 | + ), |
| 63 | + ...TRADING_VIEW_DEFAULT_CONFIG, |
| 64 | + }; |
| 65 | + this.setState({ |
| 66 | + widgetInstance: new (window as any).TradingView.widget(tvConfig), |
| 67 | + }); |
| 68 | + } |
| 69 | + |
| 70 | + render() { |
| 71 | + const { container_id } = this.state; |
| 72 | + return ( |
| 73 | + <AsyncScriptLoaderTradingView |
| 74 | + asyncScriptOnLoad={this.initializedTradingView} |
| 75 | + id={container_id} |
| 76 | + /> |
| 77 | + ); |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +export default TradingView; |
0 commit comments