-
Notifications
You must be signed in to change notification settings - Fork 35
/
TableCard.tsx
95 lines (86 loc) · 3.02 KB
/
TableCard.tsx
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
import PropTypes, { InferProps } from "prop-types";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";
import { Card } from "~/components/ui/card";
type CountByProperty = [string, string][];
function calculateCountPercentages(countByProperty: CountByProperty) {
const totalCount = countByProperty.reduce(
(sum, row) => sum + parseInt(row[1]),
0,
);
return countByProperty.map((row) => {
const count = parseInt(row[1]);
const percentage = ((count / totalCount) * 100).toFixed(2);
return `${percentage}%`;
});
}
export default function TableCard({
countByProperty,
columnHeaders,
}: InferProps<typeof TableCard.propTypes>) {
const barChartPercentages = calculateCountPercentages(
countByProperty as CountByProperty,
);
const countFormatter = Intl.NumberFormat("en", { notation: "compact" });
return (
<Card>
<Table>
<TableHeader>
<TableRow>
{(columnHeaders || []).map((header: string, index) => (
<TableHead
key={header}
className={
index === 0 ? "text-left" : "text-right"
}
>
{header}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{(countByProperty || []).map((item, key) => (
<TableRow
key={item[0]}
className="group [&_td]:last:rounded-b-md"
>
<TableCell
className="font-medium w-4/5"
width={barChartPercentages[key]}
>
{item[0]}
</TableCell>
<TableCell className="text-right w-1/5">
{countFormatter.format(item[1] as number)}
</TableCell>
{item.length > 2 && (
<TableCell className="text-right w-1/5">
{countFormatter.format(item[2] as number)}
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
</Card>
);
}
TableCard.propTypes = {
propertyName: PropTypes.string,
countByProperty: PropTypes.arrayOf(
PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.number.isRequired,
]).isRequired,
).isRequired,
).isRequired,
columnHeaders: PropTypes.array,
};