react-use#usePrevious JavaScript Examples
The following examples show how to use
react-use#usePrevious.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From spooky-info with GNU General Public License v3.0 | 4 votes |
CandleStickChart = ({
data,
width,
height = 300,
base,
margin = true,
valueFormatter = (val) => formattedNum(val, true),
}) => {
// reference for DOM element to create with chart
const ref = useRef()
const formattedData = data?.map((entry) => {
return {
time: parseFloat(entry.timestamp),
open: parseFloat(entry.open),
low: parseFloat(entry.open),
close: parseFloat(entry.close),
high: parseFloat(entry.close),
}
})
if (formattedData && formattedData.length > 0) {
formattedData.push({
time: dayjs().unix(),
open: parseFloat(formattedData[formattedData.length - 1].close),
close: parseFloat(base),
low: Math.min(parseFloat(base), parseFloat(formattedData[formattedData.length - 1].close)),
high: Math.max(parseFloat(base), parseFloat(formattedData[formattedData.length - 1].close)),
})
}
// pointer to the chart object
const [chartCreated, setChartCreated] = useState(false)
const dataPrev = usePrevious(data)
const [darkMode] = useDarkModeManager()
const textColor = darkMode ? 'white' : 'black'
const previousTheme = usePrevious(darkMode)
// reset the chart if theme switches
useEffect(() => {
if (chartCreated && previousTheme !== darkMode) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id')
let node = document.getElementById('test-id')
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, darkMode, previousTheme])
useEffect(() => {
if (data !== dataPrev && chartCreated) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id')
let node = document.getElementById('test-id')
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, data, dataPrev])
// if no chart created yet, create one with options and add to DOM manually
useEffect(() => {
if (!chartCreated) {
const chart = createChart(ref.current, {
width: width,
height: height,
layout: {
backgroundColor: 'transparent',
textColor: textColor,
},
grid: {
vertLines: {
color: 'rgba(197, 203, 206, 0.5)',
},
horzLines: {
color: 'rgba(197, 203, 206, 0.5)',
},
},
crosshair: {
mode: CrosshairMode.Normal,
},
rightPriceScale: {
borderColor: 'rgba(197, 203, 206, 0.8)',
visible: true,
},
timeScale: {
borderColor: 'rgba(197, 203, 206, 0.8)',
},
localization: {
priceFormatter: (val) => formattedNum(val),
},
})
var candleSeries = chart.addCandlestickSeries({
upColor: 'green',
downColor: 'red',
borderDownColor: 'red',
borderUpColor: 'green',
wickDownColor: 'red',
wickUpColor: 'green',
})
candleSeries.setData(formattedData)
var toolTip = document.createElement('div')
toolTip.setAttribute('id', 'tooltip-id')
toolTip.className = 'three-line-legend'
ref.current.appendChild(toolTip)
toolTip.style.display = 'block'
toolTip.style.left = (margin ? 116 : 10) + 'px'
toolTip.style.top = 50 + 'px'
toolTip.style.backgroundColor = 'transparent'
// get the title of the chart
function setLastBarText() {
toolTip.innerHTML = base
? `<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` + valueFormatter(base) + '</div>'
: ''
}
setLastBarText()
// update the title when hovering on the chart
chart.subscribeCrosshairMove(function (param) {
if (
param === undefined ||
param.time === undefined ||
param.point.x < 0 ||
param.point.x > width ||
param.point.y < 0 ||
param.point.y > height
) {
setLastBarText()
} else {
var price = param.seriesPrices.get(candleSeries).close
const time = dayjs.unix(param.time).format('MM/DD h:mm A')
toolTip.innerHTML =
`<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` +
valueFormatter(price) +
`<span style="font-size: 12px; margin: 4px 6px; color: ${textColor}">` +
time +
' UTC' +
'</span>' +
'</div>'
}
})
chart.timeScale().fitContent()
setChartCreated(chart)
}
}, [chartCreated, formattedData, width, height, valueFormatter, base, margin, textColor])
// responsiveness
useEffect(() => {
if (width) {
chartCreated && chartCreated.resize(width, height)
chartCreated && chartCreated.timeScale().scrollToPosition(0)
}
}, [chartCreated, height, width])
return (
<div>
<div ref={ref} id="test-id" />
<IconWrapper>
<Play
onClick={() => {
chartCreated && chartCreated.timeScale().fitContent()
}}
/>
</IconWrapper>
</div>
)
}
Example #2
Source File: index.js From spooky-info with GNU General Public License v3.0 | 4 votes |
TokenChart = ({ address, color, base }) => {
// settings for the window and candle width
const [chartFilter, setChartFilter] = useState(CHART_VIEW.PRICE)
const [frequency, setFrequency] = useState(DATA_FREQUENCY.HOUR)
const [darkMode] = useDarkModeManager()
const textColor = darkMode ? 'white' : 'black'
// reset view on new address
const addressPrev = usePrevious(address)
useEffect(() => {
if (address !== addressPrev && addressPrev) {
setChartFilter(CHART_VIEW.LIQUIDITY)
}
}, [address, addressPrev])
let chartData = useTokenChartData(address)
const [timeWindow, setTimeWindow] = useState(timeframeOptions.WEEK)
const prevWindow = usePrevious(timeWindow)
// hourly and daily price data based on the current time window
const hourlyWeek = useTokenPriceData(address, timeframeOptions.WEEK, 3600)
const hourlyMonth = useTokenPriceData(address, timeframeOptions.MONTH, 3600)
const hourlyAll = useTokenPriceData(address, timeframeOptions.ALL_TIME, 3600)
const dailyWeek = useTokenPriceData(address, timeframeOptions.WEEK, 86400)
const dailyMonth = useTokenPriceData(address, timeframeOptions.MONTH, 86400)
const dailyAll = useTokenPriceData(address, timeframeOptions.ALL_TIME, 86400)
const priceData =
timeWindow === timeframeOptions.MONTH
? // monthly selected
frequency === DATA_FREQUENCY.DAY
? dailyMonth
: hourlyMonth
: // weekly selected
timeWindow === timeframeOptions.WEEK
? frequency === DATA_FREQUENCY.DAY
? dailyWeek
: hourlyWeek
: // all time selected
frequency === DATA_FREQUENCY.DAY
? dailyAll
: hourlyAll
// switch to hourly data when switched to week window
useEffect(() => {
if (timeWindow === timeframeOptions.WEEK && prevWindow && prevWindow !== timeframeOptions.WEEK) {
setFrequency(DATA_FREQUENCY.HOUR)
}
}, [prevWindow, timeWindow])
// switch to daily data if switche to month or all time view
useEffect(() => {
if (timeWindow === timeframeOptions.MONTH && prevWindow && prevWindow !== timeframeOptions.MONTH) {
setFrequency(DATA_FREQUENCY.DAY)
}
if (timeWindow === timeframeOptions.ALL_TIME && prevWindow && prevWindow !== timeframeOptions.ALL_TIME) {
setFrequency(DATA_FREQUENCY.DAY)
}
}, [prevWindow, timeWindow])
const below1080 = useMedia('(max-width: 1080px)')
const below600 = useMedia('(max-width: 600px)')
let utcStartTime = getTimeframe(timeWindow)
const domain = [(dataMin) => (dataMin > utcStartTime ? dataMin : utcStartTime), 'dataMax']
const aspect = below1080 ? 60 / 32 : below600 ? 60 / 42 : 60 / 22
chartData = chartData?.filter((entry) => entry.date >= utcStartTime)
// update the width on a window resize
const ref = useRef()
const isClient = typeof window === 'object'
const [width, setWidth] = useState(ref?.current?.container?.clientWidth)
useEffect(() => {
if (!isClient) {
return false
}
function handleResize() {
setWidth(ref?.current?.container?.clientWidth ?? width)
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [isClient, width]) // Empty array ensures that effect is only run on mount and unmount
return (
<ChartWrapper>
{below600 ? (
<RowBetween mb={40}>
<DropdownSelect options={CHART_VIEW} active={chartFilter} setActive={setChartFilter} color={color} />
<DropdownSelect options={timeframeOptions} active={timeWindow} setActive={setTimeWindow} color={color} />
</RowBetween>
) : (
<RowBetween
mb={
chartFilter === CHART_VIEW.LIQUIDITY ||
chartFilter === CHART_VIEW.VOLUME ||
(chartFilter === CHART_VIEW.PRICE && frequency === DATA_FREQUENCY.LINE)
? 40
: 0
}
align="flex-start"
>
<AutoColumn gap="8px">
<RowFixed>
<OptionButton
active={chartFilter === CHART_VIEW.LIQUIDITY}
onClick={() => setChartFilter(CHART_VIEW.LIQUIDITY)}
style={{ marginRight: '6px' }}
>
Liquidity
</OptionButton>
<OptionButton
active={chartFilter === CHART_VIEW.VOLUME}
onClick={() => setChartFilter(CHART_VIEW.VOLUME)}
style={{ marginRight: '6px' }}
>
Volume
</OptionButton>
<OptionButton
active={chartFilter === CHART_VIEW.PRICE}
onClick={() => {
setChartFilter(CHART_VIEW.PRICE)
}}
>
Price
</OptionButton>
</RowFixed>
{chartFilter === CHART_VIEW.PRICE && (
<AutoRow gap="4px">
<PriceOption
active={frequency === DATA_FREQUENCY.DAY}
onClick={() => {
setTimeWindow(timeframeOptions.MONTH)
setFrequency(DATA_FREQUENCY.DAY)
}}
>
D
</PriceOption>
<PriceOption
active={frequency === DATA_FREQUENCY.HOUR}
onClick={() => setFrequency(DATA_FREQUENCY.HOUR)}
>
H
</PriceOption>
<PriceOption
active={frequency === DATA_FREQUENCY.LINE}
onClick={() => setFrequency(DATA_FREQUENCY.LINE)}
>
<Activity size={14} />
</PriceOption>
</AutoRow>
)}
</AutoColumn>
<AutoRow justify="flex-end" gap="6px" align="flex-start">
<OptionButton
active={timeWindow === timeframeOptions.WEEK}
onClick={() => setTimeWindow(timeframeOptions.WEEK)}
>
1W
</OptionButton>
<OptionButton
active={timeWindow === timeframeOptions.MONTH}
onClick={() => setTimeWindow(timeframeOptions.MONTH)}
>
1M
</OptionButton>
<OptionButton
active={timeWindow === timeframeOptions.ALL_TIME}
onClick={() => setTimeWindow(timeframeOptions.ALL_TIME)}
>
All
</OptionButton>
</AutoRow>
</RowBetween>
)}
{chartFilter === CHART_VIEW.LIQUIDITY && chartData && (
<ResponsiveContainer aspect={aspect}>
<AreaChart margin={{ top: 0, right: 10, bottom: 6, left: 0 }} barCategoryGap={1} data={chartData}>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.35} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis
tickLine={false}
axisLine={false}
interval="preserveEnd"
tickMargin={16}
minTickGap={120}
tickFormatter={(tick) => toNiceDate(tick)}
dataKey="date"
tick={{ fill: textColor }}
type={'number'}
domain={['dataMin', 'dataMax']}
/>
<YAxis
type="number"
orientation="right"
tickFormatter={(tick) => '$' + toK(tick)}
axisLine={false}
tickLine={false}
interval="preserveEnd"
minTickGap={80}
yAxisId={0}
tick={{ fill: textColor }}
/>
<Tooltip
cursor={true}
formatter={(val) => formattedNum(val, true)}
labelFormatter={(label) => toNiceDateYear(label)}
labelStyle={{ paddingTop: 4 }}
contentStyle={{
padding: '10px 14px',
borderRadius: 10,
borderColor: color,
color: 'black',
}}
wrapperStyle={{ top: -70, left: -10 }}
/>
<Area
key={'other'}
dataKey={'totalLiquidityUSD'}
stackId="2"
strokeWidth={2}
dot={false}
type="monotone"
name={'Liquidity'}
yAxisId={0}
stroke={darken(0.12, color)}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
)}
{chartFilter === CHART_VIEW.PRICE &&
(frequency === DATA_FREQUENCY.LINE ? (
<ResponsiveContainer aspect={below1080 ? 60 / 32 : 60 / 16}>
<AreaChart margin={{ top: 0, right: 10, bottom: 6, left: 0 }} barCategoryGap={1} data={chartData}>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.35} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis
tickLine={false}
axisLine={false}
interval="preserveEnd"
tickMargin={16}
minTickGap={120}
tickFormatter={(tick) => toNiceDate(tick)}
dataKey="date"
tick={{ fill: textColor }}
type={'number'}
domain={domain}
/>
<YAxis
type="number"
orientation="right"
tickFormatter={(tick) => '$' + toK(tick)}
axisLine={false}
tickLine={false}
interval="preserveEnd"
minTickGap={80}
yAxisId={0}
tick={{ fill: textColor }}
/>
<Tooltip
cursor={true}
formatter={(val) => formattedNum(val, true)}
labelFormatter={(label) => toNiceDateYear(label)}
labelStyle={{ paddingTop: 4 }}
contentStyle={{
padding: '10px 14px',
borderRadius: 10,
borderColor: color,
color: 'black',
}}
wrapperStyle={{ top: -70, left: -10 }}
/>
<Area
key={'other'}
dataKey={'priceUSD'}
stackId="2"
strokeWidth={2}
dot={false}
type="monotone"
name={'Price'}
yAxisId={0}
stroke={darken(0.12, color)}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
) : priceData ? (
<ResponsiveContainer aspect={aspect} ref={ref}>
<CandleStickChart data={priceData} width={width} base={base} />
</ResponsiveContainer>
) : (
<LocalLoader />
))}
{chartFilter === CHART_VIEW.VOLUME && (
<ResponsiveContainer aspect={aspect}>
<BarChart margin={{ top: 0, right: 10, bottom: 6, left: 10 }} barCategoryGap={1} data={chartData}>
<XAxis
tickLine={false}
axisLine={false}
interval="preserveEnd"
minTickGap={80}
tickMargin={14}
tickFormatter={(tick) => toNiceDate(tick)}
dataKey="date"
tick={{ fill: textColor }}
type={'number'}
domain={['dataMin', 'dataMax']}
/>
<YAxis
type="number"
axisLine={false}
tickMargin={16}
tickFormatter={(tick) => '$' + toK(tick)}
tickLine={false}
orientation="right"
interval="preserveEnd"
minTickGap={80}
yAxisId={0}
tick={{ fill: textColor }}
/>
<Tooltip
cursor={{ fill: color, opacity: 0.1 }}
formatter={(val) => formattedNum(val, true)}
labelFormatter={(label) => toNiceDateYear(label)}
labelStyle={{ paddingTop: 4 }}
contentStyle={{
padding: '10px 14px',
borderRadius: 10,
borderColor: color,
color: 'black',
}}
wrapperStyle={{ top: -70, left: -10 }}
/>
<Bar
type="monotone"
name={'Volume'}
dataKey={'dailyVolumeUSD'}
fill={color}
opacity={'0.4'}
yAxisId={0}
stroke={color}
/>
</BarChart>
</ResponsiveContainer>
)}
</ChartWrapper>
)
}
Example #3
Source File: index.js From spooky-info with GNU General Public License v3.0 | 4 votes |
TradingViewChart = ({
type = CHART_TYPES.BAR,
data,
base,
baseChange,
field,
title,
width,
useWeekly = false,
}) => {
// reference for DOM element to create with chart
const ref = useRef()
// pointer to the chart object
const [chartCreated, setChartCreated] = useState(false)
const dataPrev = usePrevious(data)
useEffect(() => {
if (data !== dataPrev && chartCreated && type === CHART_TYPES.BAR) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id' + type)
let node = document.getElementById('test-id' + type)
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, data, dataPrev, type])
// parese the data and format for tardingview consumption
const formattedData = data?.map((entry) => {
return {
time: dayjs.unix(entry.date).utc().format('YYYY-MM-DD'),
value: parseFloat(entry[field]),
}
})
// adjust the scale based on the type of chart
const topScale = type === CHART_TYPES.AREA ? 0.32 : 0.2
const [darkMode] = useDarkModeManager()
const textColor = darkMode ? 'white' : 'black'
const previousTheme = usePrevious(darkMode)
// reset the chart if them switches
useEffect(() => {
if (chartCreated && previousTheme !== darkMode) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id' + type)
let node = document.getElementById('test-id' + type)
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, darkMode, previousTheme, type])
// if no chart created yet, create one with options and add to DOM manually
useEffect(() => {
if (!chartCreated && formattedData) {
var chart = createChart(ref.current, {
width: width,
height: HEIGHT,
layout: {
backgroundColor: 'transparent',
textColor: textColor,
},
rightPriceScale: {
scaleMargins: {
top: topScale,
bottom: 0,
},
borderVisible: false,
},
timeScale: {
borderVisible: false,
},
grid: {
horzLines: {
color: 'rgba(197, 203, 206, 0.5)',
visible: false,
},
vertLines: {
color: 'rgba(197, 203, 206, 0.5)',
visible: false,
},
},
crosshair: {
horzLine: {
visible: false,
labelVisible: false,
},
vertLine: {
visible: true,
style: 0,
width: 2,
color: 'rgba(32, 38, 46, 0.1)',
labelVisible: false,
},
},
localization: {
priceFormatter: (val) => formattedNum(val, true),
},
})
var series =
type === CHART_TYPES.BAR
? chart.addHistogramSeries({
color: '#51C0E1',
priceFormat: {
type: 'volume',
},
scaleMargins: {
top: 0.32,
bottom: 0,
},
lineColor: '#51C0E1',
lineWidth: 3,
})
: chart.addAreaSeries({
topColor: 'rgba(81,192,225,1)',
bottomColor: 'rgba(81,192,225,0)',
lineColor: '#51C0E1',
lineWidth: 3,
})
series.setData(formattedData)
var toolTip = document.createElement('div')
toolTip.setAttribute('id', 'tooltip-id' + type)
toolTip.className = darkMode ? 'three-line-legend-dark' : 'three-line-legend'
ref.current.appendChild(toolTip)
toolTip.style.display = 'block'
toolTip.style.fontWeight = '500'
toolTip.style.left = -4 + 'px'
toolTip.style.top = '-' + 8 + 'px'
toolTip.style.backgroundColor = 'transparent'
// format numbers
let percentChange = baseChange?.toFixed(2)
let formattedPercentChange = (percentChange > 0 ? '+' : '') + percentChange + '%'
let color = percentChange >= 0 ? 'green' : 'red'
// get the title of the chart
function setLastBarText() {
toolTip.innerHTML =
`<div style="font-size: 16px; margin: 4px 0px; color: ${textColor};">${title} ${
type === CHART_TYPES.BAR && !useWeekly ? '(24hr)' : ''
}</div>` +
`<div style="font-size: 22px; margin: 4px 0px; color:${textColor}" >` +
formattedNum(base ?? 0, true) +
`<span style="margin-left: 10px; font-size: 16px; color: ${color};">${formattedPercentChange}</span>` +
'</div>'
}
setLastBarText()
// update the title when hovering on the chart
chart.subscribeCrosshairMove(function (param) {
if (
param === undefined ||
param.time === undefined ||
param.point.x < 0 ||
param.point.x > width ||
param.point.y < 0 ||
param.point.y > HEIGHT
) {
setLastBarText()
} else {
let dateStr = useWeekly
? dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day)
.startOf('week')
.format('MMMM D, YYYY') +
'-' +
dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day)
.endOf('week')
.format('MMMM D, YYYY')
: dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day).format('MMMM D, YYYY')
var price = param.seriesPrices.get(series)
toolTip.innerHTML =
`<div style="font-size: 16px; margin: 4px 0px; color: ${textColor};">${title}</div>` +
`<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` +
formattedNum(price, true) +
'</div>' +
'<div>' +
dateStr +
'</div>'
}
})
chart.timeScale().fitContent()
setChartCreated(chart)
}
}, [
base,
baseChange,
chartCreated,
darkMode,
data,
formattedData,
textColor,
title,
topScale,
type,
useWeekly,
width,
])
const widthPrev = usePrevious(width)
// responsiveness
useEffect(() => {
if (width !== widthPrev) {
chartCreated && chartCreated.resize(width, HEIGHT)
chartCreated && chartCreated.timeScale().scrollToPosition(0)
}
}, [chartCreated, width])
return (
<Wrapper>
<div ref={ref} id={'test-id' + type} />
<IconWrapper>
<Play
onClick={() => {
chartCreated && chartCreated.timeScale().fitContent()
}}
/>
</IconWrapper>
</Wrapper>
)
}
Example #4
Source File: ol-init.js From raster-playground with GNU General Public License v3.0 | 4 votes |
export default function OlInit() {
const [shape] = useQueryParam(URL_SHAPE, StringParam);
const [tiles] = useQueryParam(URL_TILES, StringParam);
const [colors] = useQueryParam(URL_COLORS, StringParam);
const [opacity] = useQueryParam(URL_OPACITY, StringParam);
const prevTiles = usePrevious(tiles);
const prevShape = usePrevious(shape);
useEffect(() => {
const olInstances = olMain({ shape, tiles, colors, opacity });
setSource(olInstances.map.getLayers().getArray()[0].values_.source);
if (olInstances.rasterSource && shape && prevTiles !== tiles) {
olInstances.rasterSource.setUrl(tiles);
olInstances.rasterSource.refresh();
}
if (olInstances.shapeSource && shape && prevShape !== shape) {
olInstances.shapeSource.setUrl(shape);
olInstances.shapeSource.refresh();
olInstances.shapeSource.on('change', () => {
let shapeExtentArray = olInstances.shapeSource.getExtent();
if (
shapeExtentArray &&
!shapeExtentArray.includes(Infinity) &&
!shapeExtentArray.includes(-Infinity)
) {
olInstances.map.getView().fit(olInstances.shapeSource.getExtent(), {
padding: [20, 20, 20, 420],
});
}
});
}
if (olInstances.rasterLayer) {
olInstances.rasterLayer.setOpacity(parseFloat(opacity));
}
if (olInstances.rasterSource) {
olInstances.rasterSource.refresh();
}
}, [shape, tiles, colors, opacity, prevTiles, prevShape]);
return (
<>
<div>
<div id="map" className="main-map">
<div className="ol-control location-btn">
<button onClick={() => handleLocationButton()}>
<FontAwesomeIcon icon={faCompass} />
</button>
</div>
</div>
<div id="popup" class="ol-popup">
<div className="powered">
Powered by{' '}
<a href="http://blueskyhq.in/" target="_blank" rel="noreferrer">
Blue Sky Analytics
</a>{' '}
| Made on{' '}
<a href="https://openlayers.org/" target="_blank" rel="noreferrer">
OpenLayers
</a>{' '}
| Basemap by{' '}
<a href="mapbox.com" target="_blank" rel="noreferrer">
Mapbox
</a>
</div>
<div className="badges">
{FOOTER_ICON.map(footer => (
<a href={footer.url} target="_blank" rel="noreferrer">
<img src={footer.img} alt={footer.label} />
</a>
))}
</div>
</div>
</div>
</>
);
}
Example #5
Source File: index.js From pancake-info-v1 with GNU General Public License v3.0 | 4 votes |
CandleStickChart = ({
data,
width,
height = 300,
base,
margin = true,
valueFormatter = (val) => formattedNum(val, true),
}) => {
// reference for DOM element to create with chart
const ref = useRef()
const formattedData = data?.map((entry) => {
return {
time: parseFloat(entry.timestamp),
open: parseFloat(entry.open),
low: parseFloat(entry.open),
close: parseFloat(entry.close),
high: parseFloat(entry.close),
}
})
if (formattedData && formattedData.length > 0) {
formattedData.push({
time: dayjs.unix(1616025600).unix(),
open: parseFloat(formattedData[formattedData.length - 1].close),
close: parseFloat(base),
low: Math.min(parseFloat(base), parseFloat(formattedData[formattedData.length - 1].close)),
high: Math.max(parseFloat(base), parseFloat(formattedData[formattedData.length - 1].close)),
})
}
// pointer to the chart object
const [chartCreated, setChartCreated] = useState(false)
const dataPrev = usePrevious(data)
const [darkMode] = useDarkModeManager()
const textColor = darkMode ? 'white' : 'black'
const previousTheme = usePrevious(darkMode)
// reset the chart if theme switches
useEffect(() => {
if (chartCreated && previousTheme !== darkMode) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id')
let node = document.getElementById('test-id')
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, darkMode, previousTheme])
useEffect(() => {
if (data !== dataPrev && chartCreated) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id')
let node = document.getElementById('test-id')
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, data, dataPrev])
// if no chart created yet, create one with options and add to DOM manually
useEffect(() => {
if (!chartCreated) {
const chart = createChart(ref.current, {
width: width,
height: height,
layout: {
backgroundColor: 'transparent',
textColor: textColor,
},
grid: {
vertLines: {
color: 'rgba(197, 203, 206, 0.5)',
},
horzLines: {
color: 'rgba(197, 203, 206, 0.5)',
},
},
crosshair: {
mode: CrosshairMode.Normal,
},
rightPriceScale: {
borderColor: 'rgba(197, 203, 206, 0.8)',
visible: true,
},
timeScale: {
borderColor: 'rgba(197, 203, 206, 0.8)',
},
localization: {
priceFormatter: (val) => formattedNum(val),
},
})
var candleSeries = chart.addCandlestickSeries({
upColor: 'green',
downColor: 'red',
borderDownColor: 'red',
borderUpColor: 'green',
wickDownColor: 'red',
wickUpColor: 'green',
})
candleSeries.setData(formattedData)
var toolTip = document.createElement('div')
toolTip.setAttribute('id', 'tooltip-id')
toolTip.className = 'three-line-legend'
ref.current.appendChild(toolTip)
toolTip.style.display = 'block'
toolTip.style.left = (margin ? 116 : 10) + 'px'
toolTip.style.top = 50 + 'px'
toolTip.style.backgroundColor = 'transparent'
// get the title of the chart
function setLastBarText() {
toolTip.innerHTML = base
? `<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` + valueFormatter(base) + '</div>'
: ''
}
setLastBarText()
// update the title when hovering on the chart
chart.subscribeCrosshairMove(function (param) {
if (
param === undefined ||
param.time === undefined ||
param.point.x < 0 ||
param.point.x > width ||
param.point.y < 0 ||
param.point.y > height
) {
setLastBarText()
} else {
var price = param.seriesPrices.get(candleSeries).close
const time = dayjs.unix(param.time).format('MM/DD h:mm A')
toolTip.innerHTML =
`<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` +
valueFormatter(price) +
`<span style="font-size: 12px; margin: 4px 6px; color: ${textColor}">` +
time +
' UTC' +
'</span>' +
'</div>'
}
})
chart.timeScale().fitContent()
setChartCreated(chart)
}
}, [chartCreated, formattedData, width, height, valueFormatter, base, margin, textColor])
// responsiveness
useEffect(() => {
if (width) {
chartCreated && chartCreated.resize(width, height)
chartCreated && chartCreated.timeScale().scrollToPosition(0)
}
}, [chartCreated, height, width])
return (
<div>
<div ref={ref} id="test-id" />
<IconWrapper>
<Play
onClick={() => {
chartCreated && chartCreated.timeScale().fitContent()
}}
/>
</IconWrapper>
</div>
)
}
Example #6
Source File: index.js From pancake-info-v1 with GNU General Public License v3.0 | 4 votes |
TokenChart = ({ address, color, base }) => {
// settings for the window and candle width
const [chartFilter, setChartFilter] = useState(CHART_VIEW.PRICE)
const [frequency, setFrequency] = useState(DATA_FREQUENCY.HOUR)
const [darkMode] = useDarkModeManager()
const textColor = darkMode ? 'white' : 'black'
// reset view on new address
const addressPrev = usePrevious(address)
useEffect(() => {
if (address !== addressPrev && addressPrev) {
setChartFilter(CHART_VIEW.LIQUIDITY)
}
}, [address, addressPrev])
let chartData = useTokenChartData(address)
const [timeWindow, setTimeWindow] = useState(timeframeOptions.ALL_TIME)
const prevWindow = usePrevious(timeWindow)
// hourly and daily price data based on the current time window
const hourlyWeek = useTokenPriceData(address, timeframeOptions.WEEK, 3600)
const hourlyMonth = useTokenPriceData(address, timeframeOptions.MONTH, 3600)
const hourlyAll = useTokenPriceData(address, timeframeOptions.ALL_TIME, 3600)
const dailyWeek = useTokenPriceData(address, timeframeOptions.WEEK, 86400)
const dailyMonth = useTokenPriceData(address, timeframeOptions.MONTH, 86400)
const dailyAll = useTokenPriceData(address, timeframeOptions.ALL_TIME, 86400)
const priceData =
timeWindow === timeframeOptions.MONTH
? // monthly selected
frequency === DATA_FREQUENCY.DAY
? dailyMonth
: hourlyMonth
: // weekly selected
timeWindow === timeframeOptions.WEEK
? frequency === DATA_FREQUENCY.DAY
? dailyWeek
: hourlyWeek
: // all time selected
frequency === DATA_FREQUENCY.DAY
? dailyAll
: hourlyAll
// switch to hourly data when switched to week window
useEffect(() => {
if (timeWindow === timeframeOptions.WEEK && prevWindow && prevWindow !== timeframeOptions.WEEK) {
setFrequency(DATA_FREQUENCY.HOUR)
}
}, [prevWindow, timeWindow])
// switch to daily data if switche to month or all time view
useEffect(() => {
if (timeWindow === timeframeOptions.MONTH && prevWindow && prevWindow !== timeframeOptions.MONTH) {
setFrequency(DATA_FREQUENCY.DAY)
}
if (timeWindow === timeframeOptions.ALL_TIME && prevWindow && prevWindow !== timeframeOptions.ALL_TIME) {
setFrequency(DATA_FREQUENCY.DAY)
}
}, [prevWindow, timeWindow])
const below1080 = useMedia('(max-width: 1080px)')
const below600 = useMedia('(max-width: 600px)')
let utcStartTime = getTimeframe(timeWindow)
const domain = [(dataMin) => (dataMin > utcStartTime ? dataMin : utcStartTime), 'dataMax']
const aspect = below1080 ? 60 / 32 : below600 ? 60 / 42 : 60 / 22
chartData = chartData?.filter((entry) => entry.date >= utcStartTime)
// update the width on a window resize
const ref = useRef()
const isClient = typeof window === 'object'
const [width, setWidth] = useState(ref?.current?.container?.clientWidth)
useEffect(() => {
if (!isClient) {
return false
}
function handleResize() {
setWidth(ref?.current?.container?.clientWidth ?? width)
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [isClient, width]) // Empty array ensures that effect is only run on mount and unmount
return (
<ChartWrapper>
{below600 ? (
<RowBetween mb={40}>
<DropdownSelect options={CHART_VIEW} active={chartFilter} setActive={setChartFilter} color={color} />
<DropdownSelect options={timeframeOptions} active={timeWindow} setActive={setTimeWindow} color={color} />
</RowBetween>
) : (
<RowBetween
mb={
chartFilter === CHART_VIEW.LIQUIDITY ||
chartFilter === CHART_VIEW.VOLUME ||
(chartFilter === CHART_VIEW.PRICE && frequency === DATA_FREQUENCY.LINE)
? 40
: 0
}
align="flex-start"
>
<AutoColumn gap="8px">
<RowFixed>
<OptionButton
active={chartFilter === CHART_VIEW.LIQUIDITY}
onClick={() => setChartFilter(CHART_VIEW.LIQUIDITY)}
style={{ marginRight: '6px' }}
>
Liquidity
</OptionButton>
<OptionButton
active={chartFilter === CHART_VIEW.VOLUME}
onClick={() => setChartFilter(CHART_VIEW.VOLUME)}
style={{ marginRight: '6px' }}
>
Volume
</OptionButton>
<OptionButton
active={chartFilter === CHART_VIEW.PRICE}
onClick={() => {
setChartFilter(CHART_VIEW.PRICE)
}}
>
Price
</OptionButton>
</RowFixed>
{chartFilter === CHART_VIEW.PRICE && (
<AutoRow gap="4px">
<PriceOption
active={frequency === DATA_FREQUENCY.DAY}
onClick={() => {
setTimeWindow(timeframeOptions.MONTH)
setFrequency(DATA_FREQUENCY.DAY)
}}
>
D
</PriceOption>
<PriceOption
active={frequency === DATA_FREQUENCY.HOUR}
onClick={() => setFrequency(DATA_FREQUENCY.HOUR)}
>
H
</PriceOption>
<PriceOption
active={frequency === DATA_FREQUENCY.LINE}
onClick={() => setFrequency(DATA_FREQUENCY.LINE)}
>
<Activity size={14} />
</PriceOption>
</AutoRow>
)}
</AutoColumn>
<AutoRow justify="flex-end" gap="6px" align="flex-start">
<OptionButton
active={timeWindow === timeframeOptions.WEEK}
onClick={() => setTimeWindow(timeframeOptions.WEEK)}
>
1W
</OptionButton>
<OptionButton
active={timeWindow === timeframeOptions.MONTH}
onClick={() => setTimeWindow(timeframeOptions.MONTH)}
>
1M
</OptionButton>
<OptionButton
active={timeWindow === timeframeOptions.ALL_TIME}
onClick={() => setTimeWindow(timeframeOptions.ALL_TIME)}
>
All
</OptionButton>
</AutoRow>
</RowBetween>
)}
{chartFilter === CHART_VIEW.LIQUIDITY && chartData && (
<ResponsiveContainer aspect={aspect}>
<AreaChart margin={{ top: 0, right: 10, bottom: 6, left: 0 }} barCategoryGap={1} data={chartData}>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.35} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis
tickLine={false}
axisLine={false}
interval="preserveEnd"
tickMargin={16}
minTickGap={120}
tickFormatter={(tick) => toNiceDate(tick)}
dataKey="date"
tick={{ fill: textColor }}
type={'number'}
domain={['dataMin', 'dataMax']}
/>
<YAxis
type="number"
orientation="right"
tickFormatter={(tick) => '$' + toK(tick)}
axisLine={false}
tickLine={false}
interval="preserveEnd"
minTickGap={80}
yAxisId={0}
tick={{ fill: textColor }}
/>
<Tooltip
cursor={true}
formatter={(val) => formattedNum(val, true)}
labelFormatter={(label) => toNiceDateYear(label)}
labelStyle={{ paddingTop: 4 }}
contentStyle={{
padding: '10px 14px',
borderRadius: 10,
borderColor: color,
color: 'black',
}}
wrapperStyle={{ top: -70, left: -10 }}
/>
<Area
key={'other'}
dataKey={'totalLiquidityUSD'}
stackId="2"
strokeWidth={2}
dot={false}
type="monotone"
name={'Liquidity'}
yAxisId={0}
stroke={darken(0.12, color)}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
)}
{chartFilter === CHART_VIEW.PRICE &&
(frequency === DATA_FREQUENCY.LINE ? (
<ResponsiveContainer aspect={below1080 ? 60 / 32 : 60 / 16}>
<AreaChart margin={{ top: 0, right: 10, bottom: 6, left: 0 }} barCategoryGap={1} data={chartData}>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.35} />
<stop offset="95%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis
tickLine={false}
axisLine={false}
interval="preserveEnd"
tickMargin={16}
minTickGap={120}
tickFormatter={(tick) => toNiceDate(tick)}
dataKey="date"
tick={{ fill: textColor }}
type={'number'}
domain={domain}
/>
<YAxis
type="number"
orientation="right"
tickFormatter={(tick) => '$' + toK(tick)}
axisLine={false}
tickLine={false}
interval="preserveEnd"
minTickGap={80}
yAxisId={0}
tick={{ fill: textColor }}
/>
<Tooltip
cursor={true}
formatter={(val) => formattedNum(val, true)}
labelFormatter={(label) => toNiceDateYear(label)}
labelStyle={{ paddingTop: 4 }}
contentStyle={{
padding: '10px 14px',
borderRadius: 10,
borderColor: color,
color: 'black',
}}
wrapperStyle={{ top: -70, left: -10 }}
/>
<Area
key={'other'}
dataKey={'priceUSD'}
stackId="2"
strokeWidth={2}
dot={false}
type="monotone"
name={'Price'}
yAxisId={0}
stroke={darken(0.12, color)}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
) : priceData ? (
<ResponsiveContainer aspect={aspect} ref={ref}>
<CandleStickChart data={priceData} width={width} base={base} />
</ResponsiveContainer>
) : (
<LocalLoader />
))}
{chartFilter === CHART_VIEW.VOLUME && (
<ResponsiveContainer aspect={aspect}>
<BarChart margin={{ top: 0, right: 10, bottom: 6, left: 10 }} barCategoryGap={1} data={chartData}>
<XAxis
tickLine={false}
axisLine={false}
interval="preserveEnd"
minTickGap={80}
tickMargin={14}
tickFormatter={(tick) => toNiceDate(tick)}
dataKey="date"
tick={{ fill: textColor }}
type={'number'}
domain={['dataMin', 'dataMax']}
/>
<YAxis
type="number"
axisLine={false}
tickMargin={16}
tickFormatter={(tick) => '$' + toK(tick)}
tickLine={false}
orientation="right"
interval="preserveEnd"
minTickGap={80}
yAxisId={0}
tick={{ fill: textColor }}
/>
<Tooltip
cursor={{ fill: color, opacity: 0.1 }}
formatter={(val) => formattedNum(val, true)}
labelFormatter={(label) => toNiceDateYear(label)}
labelStyle={{ paddingTop: 4 }}
contentStyle={{
padding: '10px 14px',
borderRadius: 10,
borderColor: color,
color: 'black',
}}
wrapperStyle={{ top: -70, left: -10 }}
/>
<Bar
type="monotone"
name={'Volume'}
dataKey={'dailyVolumeUSD'}
fill={color}
opacity={'0.4'}
yAxisId={0}
stroke={color}
/>
</BarChart>
</ResponsiveContainer>
)}
</ChartWrapper>
)
}
Example #7
Source File: index.js From pancake-info-v1 with GNU General Public License v3.0 | 4 votes |
TradingViewChart = ({
type = CHART_TYPES.BAR,
data,
base,
baseChange,
field,
title,
width,
useWeekly = false,
}) => {
// reference for DOM element to create with chart
const ref = useRef()
// pointer to the chart object
const [chartCreated, setChartCreated] = useState(false)
const dataPrev = usePrevious(data)
useEffect(() => {
if (data !== dataPrev && chartCreated && type === CHART_TYPES.BAR) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id' + type)
let node = document.getElementById('test-id' + type)
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, data, dataPrev, type])
// parese the data and format for tardingview consumption
const formattedData = data?.map((entry) => {
return {
time: dayjs.unix(entry.date).utc().format('YYYY-MM-DD'),
value: parseFloat(entry[field]),
}
})
// adjust the scale based on the type of chart
const topScale = type === CHART_TYPES.AREA ? 0.32 : 0.2
const [darkMode] = useDarkModeManager()
const textColor = darkMode ? 'white' : 'black'
const previousTheme = usePrevious(darkMode)
// reset the chart if them switches
useEffect(() => {
if (chartCreated && previousTheme !== darkMode) {
// remove the tooltip element
let tooltip = document.getElementById('tooltip-id' + type)
let node = document.getElementById('test-id' + type)
node.removeChild(tooltip)
chartCreated.resize(0, 0)
setChartCreated()
}
}, [chartCreated, darkMode, previousTheme, type])
// if no chart created yet, create one with options and add to DOM manually
useEffect(() => {
if (!chartCreated && formattedData) {
var chart = createChart(ref.current, {
width: width,
height: HEIGHT,
layout: {
backgroundColor: 'transparent',
textColor: textColor,
},
rightPriceScale: {
scaleMargins: {
top: topScale,
bottom: 0,
},
borderVisible: false,
},
timeScale: {
borderVisible: false,
},
grid: {
horzLines: {
color: 'rgba(79, 216, 222, 0.5)',
visible: false,
},
vertLines: {
color: 'rgba(79, 216, 222, 0.5)',
visible: false,
},
},
crosshair: {
horzLine: {
visible: false,
labelVisible: false,
},
vertLine: {
visible: true,
style: 0,
width: 2,
color: 'rgba(32, 38, 46, 0.1)',
labelVisible: false,
},
},
localization: {
priceFormatter: (val) => formattedNum(val, true),
},
})
var series =
type === CHART_TYPES.BAR
? chart.addHistogramSeries({
color: '#4FD8DE',
priceFormat: {
type: 'volume',
},
scaleMargins: {
top: 0.32,
bottom: 0,
},
lineColor: '#4FD8DE',
lineWidth: 3,
})
: chart.addAreaSeries({
topColor: '#4FD8DE',
bottomColor: 'rgba(79, 216, 222, 0)',
lineColor: '#4FD8DE',
lineWidth: 3,
})
series.setData(formattedData)
var toolTip = document.createElement('div')
toolTip.setAttribute('id', 'tooltip-id' + type)
toolTip.className = darkMode ? 'three-line-legend-dark' : 'three-line-legend'
ref.current.appendChild(toolTip)
toolTip.style.display = 'block'
toolTip.style.fontWeight = '500'
toolTip.style.left = -4 + 'px'
toolTip.style.top = '-' + 8 + 'px'
toolTip.style.backgroundColor = 'transparent'
// format numbers
let percentChange = baseChange?.toFixed(2)
let formattedPercentChange = (percentChange > 0 ? '+' : '') + percentChange + '%'
let color = percentChange >= 0 ? 'green' : 'red'
// get the title of the chart
function setLastBarText() {
toolTip.innerHTML =
`<div style="font-size: 16px; margin: 4px 0px; color: ${textColor};">${title} ${
type === CHART_TYPES.BAR && !useWeekly ? '(24hr)' : ''
}</div>` +
`<div style="font-size: 22px; margin: 4px 0px; color:${textColor}" >` +
formattedNum(base ?? 0, true) +
`<span style="margin-left: 10px; font-size: 16px; color: ${color};">${formattedPercentChange}</span>` +
'</div>'
}
setLastBarText()
// update the title when hovering on the chart
chart.subscribeCrosshairMove(function (param) {
if (
param === undefined ||
param.time === undefined ||
param.point.x < 0 ||
param.point.x > width ||
param.point.y < 0 ||
param.point.y > HEIGHT
) {
setLastBarText()
} else {
let dateStr = useWeekly
? dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day)
.startOf('week')
.format('MMMM D, YYYY') +
'-' +
dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day)
.endOf('week')
.format('MMMM D, YYYY')
: dayjs(param.time.year + '-' + param.time.month + '-' + param.time.day).format('MMMM D, YYYY')
var price = param.seriesPrices.get(series)
toolTip.innerHTML =
`<div style="font-size: 16px; margin: 4px 0px; color: ${textColor};">${title}</div>` +
`<div style="font-size: 22px; margin: 4px 0px; color: ${textColor}">` +
formattedNum(price, true) +
'</div>' +
'<div>' +
dateStr +
'</div>'
}
})
chart.timeScale().fitContent()
setChartCreated(chart)
}
}, [
base,
baseChange,
chartCreated,
darkMode,
data,
formattedData,
textColor,
title,
topScale,
type,
useWeekly,
width,
])
// responsiveness
useEffect(() => {
if (width) {
chartCreated && chartCreated.resize(width, HEIGHT)
chartCreated && chartCreated.timeScale().scrollToPosition(0)
}
}, [chartCreated, width])
return (
<Wrapper>
<div ref={ref} id={'test-id' + type} />
<IconWrapper>
<Play
onClick={() => {
chartCreated && chartCreated.timeScale().fitContent()
}}
/>
</IconWrapper>
</Wrapper>
)
}