Skip to content

Commit

Permalink
Update bar chart
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonioVdlC committed Jul 30, 2023
1 parent fe38011 commit 5a6773d
Show file tree
Hide file tree
Showing 3 changed files with 5,857 additions and 12,207 deletions.
65 changes: 42 additions & 23 deletions app/components/BarChart.client.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,56 @@
import { BarGroup, BarSeries, XYChart } from "@visx/xychart";
import { useState } from "react";
import * as Plot from "@observablehq/plot";
import { useEffect, useRef, useState } from "react";
import type { DashboardElement } from "~/types/dashboard";

type Props = {
data: DashboardElement[];
dataKey: string;
limit?: number;
};

const VIEW_LIMIT = 4;

export default function BarChart({ data, dataKey, limit = VIEW_LIMIT }: Props) {
export default function BarChart({ data, limit = VIEW_LIMIT }: Props) {
const [viewAll, setViewAll] = useState(false);
const chartContainer = useRef<HTMLDivElement>(null);

const height =
55 * (1 + (viewAll || data.length < limit ? data.length : limit));
useEffect(() => {
if (!data.length) return;

const accessors = {
xAccessor: (datum: DashboardElement) => datum.count,
yAccessor: (datum: DashboardElement) => datum.label,
};
const max = data[0].count;
const plot = Plot.plot({
height: 55 * (1 + (viewAll || data.length < limit ? data.length : limit)),
x: { axis: "top", label: null },
y: { axis: null, inset: 6 },
marks: [
Plot.barX(viewAll ? data : data.slice(0, VIEW_LIMIT), {
x: "count",
y: "label",
fill: "steelblue",
sort: { y: "-x" },
}),
Plot.text(viewAll ? data : data.slice(0, VIEW_LIMIT), {
x: "count",
y: "label",
text: (d) => d.label,
textAnchor: "end",
dx: -30,
filter: (d) => d.count / max > 0.5,
fill: "white",
}),
Plot.text(viewAll ? data : data.slice(0, VIEW_LIMIT), {
x: "count",
y: "label",
text: (d) => d.label,
textAnchor: "start",
dx: 3,
filter: (d) => d.count / max <= 0.5,
fill: "currentColor",
}),
],
});
chartContainer.current?.append(plot);
return () => plot.remove();
}, [data, viewAll]);

if (!data.length) {
return (
Expand All @@ -31,19 +62,7 @@ export default function BarChart({ data, dataKey, limit = VIEW_LIMIT }: Props) {

return (
<div className="relative">
<XYChart
height={height}
xScale={{ type: "linear" }}
yScale={{ type: "band" }}
>
<BarGroup>
<BarSeries
dataKey={dataKey}
data={viewAll ? data : data.slice(0, limit)}
{...accessors}
></BarSeries>
</BarGroup>
</XYChart>
<div ref={chartContainer}></div>
{data.length > limit ? (
<div className="absolute right-[70px] top-[-20px] text-xs text-slate-500 hover:text-slate-400">
<a onClick={() => setViewAll(!viewAll)}>
Expand Down
Loading

0 comments on commit 5a6773d

Please sign in to comment.