Skip to content

Commit

Permalink
Add useComputedStyle hook
Browse files Browse the repository at this point in the history
  • Loading branch information
kitloong committed May 14, 2024
1 parent 994294c commit ca13929
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
24 changes: 8 additions & 16 deletions src/components/Page/Dashboard/TrafficChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,16 @@ import {
Tooltip,
} from 'chart.js'
import useDictionary from '@/locales/dictionary-hook'
import useComputedStyle from '@/hooks/use-computed-style'

Chart.register(CategoryScale, LinearScale, PointElement, LineElement, BarElement, Tooltip, Filler)

const random = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1) + min)

export default function TrafficChart() {
const dict = useDictionary()

const getStyle = (property: string) => {
if (typeof window === 'undefined') {
return ''
}
if (typeof document === 'undefined') {
return ''
}
const element = document.body
return window.getComputedStyle(element, null).getPropertyValue(property).replace(/^\s/, '')
}
const borderColor = useComputedStyle('--bs-border-color')
const bodyColor = useComputedStyle('--bs-body-color')

return (
<Line
Expand Down Expand Up @@ -93,24 +85,24 @@ export default function TrafficChart() {
scales: {
x: {
grid: {
color: getStyle('--bs-border-color'),
color: borderColor,
drawOnChartArea: false,
},
ticks: {
color: getStyle('--bs-body-color'),
color: bodyColor,
},
},
y: {
beginAtZero: true,
border: {
color: getStyle('--bs-border-color'),
color: borderColor,
},
grid: {
color: getStyle('--bs-border-color'),
color: borderColor,
},
max: 250,
ticks: {
color: getStyle('--bs-body-color'),
color: bodyColor,
maxTicksLimit: 5,
stepSize: Math.ceil(250 / 5),
},
Expand Down
17 changes: 17 additions & 0 deletions src/hooks/use-computed-style.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useEffect, useState } from 'react'
import Cookies from 'js-cookie'

export default function useComputedStyle(property: string) {
const [style, setStyle] = useState('')
const theme = Cookies.get('theme')

useEffect(() => {
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
const element = document.body
const computedStyle = window.getComputedStyle(element, null).getPropertyValue(property).replace(/^\s/, '')
setStyle(computedStyle)
}
}, [property, theme])

return style
}

0 comments on commit ca13929

Please sign in to comment.