Skip to content

Commit

Permalink
Tradingview Rerenders (#908)
Browse files Browse the repository at this point in the history
* fix rerendering

* fix style overrides

* add callback and get key from state

* hide until visible

* fix initial asset loading

* fix heights

* specify height in nav to avoid shifting

Co-authored-by: troyb.eth <troy.burmeister@ibotta.com>
  • Loading branch information
Tburm and troyb.eth authored Jul 21, 2022
1 parent 7132127 commit c721230
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 34 deletions.
65 changes: 44 additions & 21 deletions components/TVChart/TVChart.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { useRef, useContext, useEffect, useCallback, useState } from 'react';
import { castArray } from 'lodash';
import { useRouter } from 'next/router';
import { useRef, useContext, useEffect, useCallback, useState, useMemo } from 'react';
import { useRecoilValue } from 'recoil';
import { ThemeContext } from 'styled-components';

import { Synths } from 'constants/currency';
import { ChartBody } from 'sections/exchange/TradeCard/Charts/common/styles';
import { currentThemeState } from 'store/ui';
import { networkState } from 'store/wallet';
Expand All @@ -12,17 +15,17 @@ import {
IPositionLineAdapter,
widget,
} from '../../public/static/charting_library';
import { DEFAULT_RESOLUTION } from './constants';
import DataFeedFactory from './DataFeed';
import { ChartPosition } from './types';

export type ChartProps = {
baseCurrencyKey: string;
quoteCurrencyKey: string;
activePosition?: ChartPosition | null;
potentialTrade?: ChartPosition | null;
onChartReady?: () => void;
};

type Props = ChartProps & {
export type Props = ChartProps & {
interval: string;
containerId: string;
libraryPath: string;
Expand All @@ -33,17 +36,17 @@ type Props = ChartProps & {
};

export function TVChart({
baseCurrencyKey,
quoteCurrencyKey,
interval = '15',
interval = DEFAULT_RESOLUTION,
containerId = 'tv_chart_container',
libraryPath = '/static/charting_library/',
fullscreen = false,
autosize = true,
studiesOverrides = {},
overrides,
activePosition,
potentialTrade,
onChartReady = () => {
return;
},
}: Props) {
const [lastSubscription, setLastSubscription] = useState(0);
const [intervalId, setIntervalId] = useState(0);
Expand All @@ -54,19 +57,28 @@ export function TVChart({

const { colors } = useContext(ThemeContext);
let network = useRecoilValue(networkState);
const router = useRouter();

const DEFAULT_OVERRIDES = {
'paneProperties.background': colors.selectedTheme.background,
'chartProperties.background': colors.selectedTheme.background,
'paneProperties.backgroundType': 'solid',
};

const [marketAsset, marketAssetLoaded] = useMemo(() => {
return router.query.market ? [castArray(router.query.market)[0], true] : [null, false];
}, [router.query]);

useEffect(() => {
const widgetOptions = {
symbol: baseCurrencyKey + ':' + quoteCurrencyKey,
symbol: marketAsset + ':' + Synths.sUSD,
datafeed: DataFeedFactory(network.id, onSubscribe),
interval: interval,
container: containerId,
library_path: libraryPath,

locale: 'en',
enabled_features: ['hide_left_toolbar_by_default'],
disabled_features: [
'use_localstorage_for_settings',
'header_compare',
'study_templates',
'header_symbol_search',
Expand All @@ -81,10 +93,7 @@ export function TVChart({
loading_screen: {
backgroundColor: colors.selectedTheme.background,
},
overrides: overrides ?? {
'paneProperties.background': colors.selectedTheme.background,
'paneProperties.backgroundType': 'solid',
},
overrides: DEFAULT_OVERRIDES,
toolbar_bg: colors.selectedTheme.background,
time_frames: [
{ text: '4H', resolution: '5', description: '4 hours' },
Expand All @@ -109,11 +118,16 @@ export function TVChart({
const tvWidget = new widget(widgetOptions);
_widget.current = tvWidget;

_widget.current?.onChartReady(() => {
_widget.current?.applyOverrides(DEFAULT_OVERRIDES);
onChartReady();
});

return () => {
clearExistingWidget();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [baseCurrencyKey, quoteCurrencyKey, network.id, currentTheme]);
}, [network.id, currentTheme, marketAssetLoaded]);

useEffect(() => {
_widget.current?.onChartReady(() => {
Expand Down Expand Up @@ -163,6 +177,17 @@ export function TVChart({
});
}, [activePosition, potentialTrade, colors.common.primaryRed]);

useEffect(() => {
_widget.current?.onChartReady(() => {
const symbolInterval = _widget.current?.symbolInterval();
_widget.current?.setSymbol(
marketAsset + ':' + Synths.sUSD,
symbolInterval?.interval ?? DEFAULT_RESOLUTION,
() => {}
);
});
}, [marketAsset]);

const onSubscribe = useCallback(
(newIntervalId: number) => {
setLastSubscription(newIntervalId);
Expand All @@ -173,11 +198,9 @@ export function TVChart({
useEffect(() => {
clearInterval(intervalId);
setIntervalId(lastSubscription);
const newDataFeed = DataFeedFactory(network.id, onSubscribe);
if (_widget.current) {
// @ts-ignore
_widget.current._options.datafeed = newDataFeed;
}
_widget.current?.onChartReady(() => {
_widget.current?.chart()?.resetData();
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lastSubscription, onSubscribe, network.id]);

Expand Down
3 changes: 3 additions & 0 deletions components/TVChart/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ResolutionString } from 'public/static/charting_library/charting_library';

export const DEFAULT_RESOLUTION: ResolutionString = '15' as ResolutionString;
7 changes: 1 addition & 6 deletions sections/futures/MobileTrade/OverviewTabs/PriceTab.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import React from 'react';
import { useRecoilValue } from 'recoil';
import styled from 'styled-components';

import TVChart from 'components/TVChart';
import { Synths } from 'constants/currency';
import { currentMarketState } from 'store/futures';

import { Pane } from '../common';

const PriceTab: React.FC = () => {
const marketAsset = useRecoilValue(currentMarketState);

return (
<StyledPane noPadding>
<TVChart baseCurrencyKey={marketAsset} quoteCurrencyKey={Synths.sUSD} />
<TVChart />
</StyledPane>
);
};
Expand Down
20 changes: 13 additions & 7 deletions sections/futures/PositionChart/PositionChart.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { useMemo } from 'react';
import { useMemo, useState } from 'react';
import { useRecoilValue } from 'recoil';
import styled from 'styled-components';

import TVChart from 'components/TVChart';
import { Synths } from 'constants/currency';
import useGetFuturesPositionForAccount from 'queries/futures/useGetFuturesPositionForAccount';
import {
currentMarketState,
Expand All @@ -13,6 +12,7 @@ import {
} from 'store/futures';

export default function PositionChart() {
const [isChartReady, setIsChartReady] = useState(false);
const marketAsset = useRecoilValue(currentMarketState);
const position = useRecoilValue(positionState);

Expand Down Expand Up @@ -50,11 +50,13 @@ export default function PositionChart() {
};
}, [subgraphPosition, position]);

const visible = useMemo(() => {
return isChartReady ? 'visible' : 'hidden';
}, [isChartReady]);

return (
<Container>
<Container visible={visible}>
<TVChart
baseCurrencyKey={marketAsset}
quoteCurrencyKey={Synths.sUSD}
activePosition={activePosition}
potentialTrade={
previewTrade
Expand All @@ -65,12 +67,16 @@ export default function PositionChart() {
}
: null
}
onChartReady={() => {
setIsChartReady(true);
}}
/>
</Container>
);
}

const Container = styled.div`
min-height: 45vh;
const Container = styled.div<{ visible: 'hidden' | 'visible' }>`
min-height: 450px;
background: ${(props) => props.theme.colors.selectedTheme.background};
visibility: ${(props) => props.visible};
`;
1 change: 1 addition & 0 deletions sections/shared/Layout/AppLayout/Header/BalanceActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ const StyledButton = styled(Button)`
`;

const StyledWidgetButton = styled(Button)`
height: 41px;
font-size: 13px;
font-family: ${(props) => props.theme.fonts.mono};
padding: 10px;
Expand Down

0 comments on commit c721230

Please sign in to comment.