File size: 5,105 Bytes
1e92f2d |
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 |
"use client"
import type { Tokens } from "@chakra-ui/react"
import { useChakraContext, useLocaleContext } from "@chakra-ui/react"
import * as React from "react"
export type ChartColor = Tokens["colors"] | React.CSSProperties["color"]
export type ChartSize = Tokens["sizes"] | (string & {})
export type ChartSpacing = Tokens["spacing"] | (string & {})
type ItemDataKey<T> = keyof T
interface SeriesItem<T> {
name?: ItemDataKey<T>
color?: ChartColor
icon?: React.ReactNode
label?: React.ReactNode
stackId?: string
yAxisId?: string
strokeDasharray?: string
id?: string
}
export interface UseChartProps<T> {
data: T[]
series?: SeriesItem<T>[]
sort?: { by: ItemDataKey<T>; direction: "asc" | "desc" }
}
type ValueDomain =
| [number, number]
| ((props: { min: number; max: number }) => [number, number])
export function useChart<T = any>(props: UseChartProps<T>) {
const { data, series = [], sort } = props
const id = React.useId()
const [highlightedSeries, setHighlightedSeries] = React.useState<
string | null
>(null)
const isHighlightedSeries = (name: string | undefined) =>
highlightedSeries === name
const env = useLocaleContext()
const sys = useChakraContext()
const color = (key: ChartColor | undefined) => sys.token(`colors.${key}`, key)
const size = (key: ChartSize | undefined) => sys.token(`sizes.${key}`, key)
const spacing = (key: ChartSpacing | undefined) =>
sys.token(`spacing.${key}`, key)
const key = <K extends ItemDataKey<T>>(prop: K | undefined): K =>
prop ?? ("value" as K)
const formatNumber = React.useCallback(
(options?: Intl.NumberFormatOptions) => {
const formatter = new Intl.NumberFormat(env.locale, options)
return (value: number) => formatter.format(value)
},
[env.locale],
)
const formatDate = React.useCallback(
(options?: Intl.DateTimeFormatOptions) => {
return (value: string) =>
new Date(value).toLocaleDateString(env.locale, options)
},
[env.locale],
)
const getSeries = (item: unknown) => {
if (!isObject(item)) return
const result = series.find((s) => {
return (
s.name === item.name ||
s.name === getProp(item.payload, "name") ||
s.name === item.dataKey ||
s.name === getProp(item.payload, "dataKey")
)
}) || { color: undefined }
result.color ||= getProp(item.payload, "color")
result.label ||=
result.name?.toLocaleString() || getProp(item.payload, "name")
return result
}
const getTotal = (key: keyof T) => {
return data.reduce((acc, d) => acc + Number(d[key]), 0)
}
function getPayloadTotal<T extends { value?: string }>(
payload: Array<T> | undefined,
) {
return payload?.reduce((acc, item) => {
if (!item.value) return acc
const num = Number(item.value)
const value = Number.isNaN(num) ? 0 : num
return acc + value
}, 0)
}
function getMin(key: keyof T) {
return Math.min(...data.map((d) => Number(d[key])))
}
function getMax(key: keyof T) {
return Math.max(...data.map((d) => Number(d[key])))
}
function getValuePercent(key: keyof T, value: number, domain?: ValueDomain) {
const min = getMin(key)
const max = getMax(key)
if (domain) {
const d = typeof domain === "function" ? domain({ min, max }) : domain
return ((value - d[0]) / (d[1] - d[0])) * 100
}
return (value / getTotal(key)) * 100
}
const sortedData = React.useMemo(() => {
if (!sort) return data
return data.sort((a, b) => {
const aValue = Number(a[sort.by])
const bValue = Number(b[sort.by])
return sort.direction === "desc" ? bValue - aValue : aValue - bValue
})
}, [data, sort])
const getSeriesOpacity = (name: string | undefined, fallback = 0.2) => {
if (name && highlightedSeries)
return isHighlightedSeries(name) ? 1 : fallback
}
const groupByImpl = (key: ItemDataKey<T>) => {
return groupBy(data, key)
}
return {
id,
key,
// series
data: sortedData,
groupBy: groupByImpl,
series,
getSeries,
// token functions
color,
size,
spacing,
// formatters
formatNumber,
formatDate,
// state
highlightedSeries,
setHighlightedSeries,
isHighlightedSeries,
getSeriesOpacity,
// value functions
getTotal,
getMin,
getMax,
getPayloadTotal,
getValuePercent,
}
}
export type UseChartReturn<T> = ReturnType<typeof useChart<T>>
const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null
export function getProp<T = unknown>(
item: unknown,
key: string | undefined,
): T | undefined {
if (!key || !isObject(item)) return
return Reflect.get(item, key) as T | undefined
}
function groupBy<T>(data: T[], key: keyof T): T[][] {
const groups = new Map<unknown, T[]>()
for (const item of data) {
const value = item[key]
const group = groups.get(value) || []
group.push(item)
groups.set(value, group)
}
return Array.from(groups.values())
}
|