Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

fix(dashboard): stop the activity donut overlapping its total and flickering on panel toggle

Khuram Niaz27b931b77471
diff --git a/__tests__/JobsActivityCard.spec.tsx b/__tests__/JobsActivityCard.spec.tsx
index cf2f7e1..223b327 100644
--- a/__tests__/JobsActivityCard.spec.tsx
+++ b/__tests__/JobsActivityCard.spec.tsx
@@ -2,12 +2,20 @@ import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import JobsActivityCard from "@/components/dashboard/JobsActivityCard";
+// jsdom measures every element as 0 wide, so the card's compact threshold is
+// driven from here instead.
+const chartWidth = vi.hoisted(() => ({ value: 400 }));
+
+vi.mock("@/hooks/useElementWidth", () => ({
+ useElementWidth: () => [{ current: null }, chartWidth.value] as const,
+}));
+
vi.mock("next-themes", () => ({
useTheme: () => ({ resolvedTheme: "light" }),
}));
vi.mock("@nivo/pie", () => ({
- ResponsivePie: (props: any) => (
+ Pie: (props: any) => (
<div data-testid="donut">
{props.data.map((slice: any) => (
<div key={slice.id} data-testid={`slice-${slice.id}`}>
@@ -26,6 +34,7 @@ describe("JobsActivityCard", () => {
// "30d" decides the starting tab for every test after it.
beforeEach(() => {
localStorage.clear();
+ chartWidth.value = 400;
});
const data = [
@@ -126,6 +135,23 @@ describe("JobsActivityCard", () => {
expect(within(total).queryByText("0%")).not.toBeInTheDocument();
});
+ it("holds the donut back until the card has measured itself", () => {
+ chartWidth.value = 0;
+ render(<JobsActivityCard data={data} />);
+
+ expect(screen.queryByTestId("donut")).not.toBeInTheDocument();
+ });
+
+ it("drops the trend line when the donut hole gets too small for it", () => {
+ chartWidth.value = 220;
+ render(<JobsActivityCard data={data} />);
+
+ const total = screen.getByTestId("jobs-activity-total");
+
+ expect(within(total).getByText("63.4h")).toBeInTheDocument();
+ expect(within(total).queryByText("25%")).not.toBeInTheDocument();
+ });
+
it("says one job, not one jobs", () => {
render(
<JobsActivityCard
diff --git a/__tests__/jobsActivityChart.spec.ts b/__tests__/jobsActivityChart.spec.ts
index 1fb85e0..a5ff72f 100644
--- a/__tests__/jobsActivityChart.spec.ts
+++ b/__tests__/jobsActivityChart.spec.ts
@@ -1,6 +1,7 @@
import {
buildDonutSlices,
arcLabelLines,
+ donutLayout,
OTHER_SLICE_ID,
} from "@/components/dashboard/jobsActivityChart";
@@ -81,23 +82,73 @@ describe("buildDonutSlices", () => {
describe("arcLabelLines", () => {
it("splits the name and the hours onto separate lines", () => {
expect(
- arcLabelLines({
- id: "Jobsync",
- label: "Jobsync",
- value: 28.1,
- color: "#2a9d90",
- }),
+ arcLabelLines(
+ {
+ id: "Jobsync",
+ label: "Jobsync",
+ value: 28.1,
+ color: "#2a9d90",
+ },
+ 12,
+ ),
).toEqual(["Jobsync", "28.1h"]);
});
it("trims a long activity name so it cannot run off the card", () => {
expect(
- arcLabelLines({
- id: "x",
- label: "Interview Preparation Deep Dive",
- value: 4,
- color: "#2a9d90",
- }),
- ).toEqual(["Interview Prepa…", "4h"]);
+ arcLabelLines(
+ {
+ id: "x",
+ label: "Interview Preparation Deep Dive",
+ value: 4,
+ color: "#2a9d90",
+ },
+ 12,
+ ),
+ ).toEqual(["Interview P…", "4h"]);
+ });
+
+ it("trims harder when the card only affords a narrow gutter", () => {
+ expect(
+ arcLabelLines(
+ {
+ id: "x",
+ label: "Interview Preparation Deep Dive",
+ value: 4,
+ color: "#2a9d90",
+ },
+ 7,
+ ),
+ ).toEqual(["Interv…", "4h"]);
+ });
+});
+
+describe("donutLayout", () => {
+ it("gives the labels their full gutter when the card has room", () => {
+ const layout = donutLayout(400);
+
+ expect(layout.gutter).toBe(100);
+ expect(layout.maxLabelChars).toBe(12);
+ expect(layout.holeDiameter).toBeCloseTo(148 * 0.72);
+ });
+
+ it("assumes the roomy case before the card has measured itself", () => {
+ expect(donutLayout(0)).toEqual(donutLayout(348));
+ });
+
+ it("spends gutter, not donut, as the card narrows", () => {
+ const layout = donutLayout(320);
+
+ expect(layout.gutter).toBe(86);
+ expect(layout.maxLabelChars).toBe(10);
+ expect(layout.holeDiameter).toBeCloseTo(148 * 0.72);
+ });
+
+ it("shrinks the donut only once the gutter has bottomed out", () => {
+ const layout = donutLayout(260);
+
+ expect(layout.gutter).toBe(76);
+ expect(layout.maxLabelChars).toBe(8);
+ expect(layout.holeDiameter).toBeCloseTo(108 * 0.72);
});
});
diff --git a/src/components/dashboard/JobsActivityCard.tsx b/src/components/dashboard/JobsActivityCard.tsx
index 47482d8..edcab7f 100644
--- a/src/components/dashboard/JobsActivityCard.tsx
+++ b/src/components/dashboard/JobsActivityCard.tsx
@@ -1,11 +1,13 @@
"use client";
-import { PieSvgProps, ResponsivePie } from "@nivo/pie";
+import { RefObject, useMemo, useRef } from "react";
+import { Pie, PieSvgProps } from "@nivo/pie";
import { animated } from "@react-spring/web";
import { useTheme } from "next-themes";
import { TrendingDown, TrendingUp } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { JobsActivitySummary } from "@/actions/dashboard.actions";
+import { useElementWidth } from "@/hooks/useElementWidth";
import { usePersistedTabIndex } from "@/hooks/usePersistedTabIndex";
import { APP_CONSTANTS } from "@/lib/constants";
import { cn } from "@/lib/utils";
@@ -13,6 +15,8 @@ import {
ARC_LABEL_TEXT_COLOR,
arcLabelLines,
buildDonutSlices,
+ CHART_HEIGHT,
+ donutLayout,
DonutSlice,
} from "./jobsActivityChart";
@@ -27,35 +31,43 @@ type ArcLinkLabelProps = Parameters<
NonNullable<PieSvgProps<DonutSlice>["arcLinkLabelComponent"]>
>[0];
+// Hole the total needs before the hours, jobs and trend lines all clear the
+// ring; under it the trend goes and the other two step down a size.
+const FULL_TOTAL_HOLE = 96;
+
// nivo renders an arc link label as one <text>, so stacking the hours under
// the name needs a custom component rather than a label formatter.
-function ArcLinkLabel({ datum, style }: ArcLinkLabelProps) {
- const [name, hours] = arcLabelLines(datum.data);
+// The budget arrives by ref because a new component type would remount the
+// whole label subtree on every frame the card resizes.
+function makeArcLinkLabel(maxChars: RefObject<number>) {
+ return function ArcLinkLabel({ datum, style }: ArcLinkLabelProps) {
+ const [name, hours] = arcLabelLines(datum.data, maxChars.current);
- return (
- <animated.g opacity={style.opacity}>
- <animated.path
- fill="none"
- stroke={style.linkColor}
- strokeWidth={style.thickness}
- d={style.path}
- />
- <animated.text
- transform={style.textPosition}
- textAnchor={style.textAnchor}
- dominantBaseline="central"
- fill={style.textColor}
- fontSize={11}
- >
- <tspan x={0} dy="-0.5em">
- {name}
- </tspan>
- <tspan x={0} dy="1.15em" fontWeight={600}>
- {hours}
- </tspan>
- </animated.text>
- </animated.g>
- );
+ return (
+ <animated.g opacity={style.opacity}>
+ <animated.path
+ fill="none"
+ stroke={style.linkColor}
+ strokeWidth={style.thickness}
+ d={style.path}
+ />
+ <animated.text
+ transform={style.textPosition}
+ textAnchor={style.textAnchor}
+ dominantBaseline="central"
+ fill={style.textColor}
+ fontSize={11}
+ >
+ <tspan x={0} dy="-0.5em">
+ {name}
+ </tspan>
+ <tspan x={0} dy="1.15em" fontWeight={600}>
+ {hours}
+ </tspan>
+ </animated.text>
+ </animated.g>
+ );
+ };
}
export default function JobsActivityCard({ data }: JobsActivityCardProps) {
@@ -63,12 +75,21 @@ export default function JobsActivityCard({ data }: JobsActivityCardProps) {
APP_CONSTANTS.DASHBOARD_JOBS_ACTIVITY_STORAGE_KEY,
data.map((item) => item.label),
);
+ const [chartRef, chartWidth] = useElementWidth<HTMLDivElement>();
const { resolvedTheme } = useTheme();
const theme = resolvedTheme === "light" ? "light" : "dark";
const current = data[activeIndex];
const { jobsApplied, jobsTrend, topActivities, otherHours, totalHours } =
current.summary;
const slices = buildDonutSlices(topActivities, otherHours, theme);
+ const layout = donutLayout(chartWidth);
+ const roomyTotal = layout.holeDiameter >= FULL_TOTAL_HOLE;
+ const maxLabelChars = useRef(layout.maxLabelChars);
+ maxLabelChars.current = layout.maxLabelChars;
+ const arcLinkLabelComponent = useMemo(
+ () => makeArcLinkLabel(maxLabelChars),
+ [],
+ );
return (
<Card className="@lg:col-span-2">
@@ -101,7 +122,7 @@ export default function JobsActivityCard({ data }: JobsActivityCardProps) {
</div>
</CardHeader>
<CardContent>
- <div className="relative h-[200px] w-full">
+ <div ref={chartRef} className="relative h-[200px] w-full">
{slices.length === 0 ? (
<div className="flex h-full w-full items-center justify-center">
<div className="h-[132px] w-[132px] rounded-full border-[18px] border-muted" />
@@ -110,57 +131,84 @@ export default function JobsActivityCard({ data }: JobsActivityCardProps) {
</p>
</div>
) : (
- <ResponsivePie
- data={slices}
- margin={{ top: 26, right: 84, bottom: 26, left: 84 }}
- innerRadius={0.72}
- padAngle={2}
- cornerRadius={2}
- activeOuterRadiusOffset={4}
- colors={{ datum: "data.color" }}
- borderWidth={0}
- enableArcLabels={false}
- enableArcLinkLabels
- arcLinkLabelComponent={ArcLinkLabel}
- arcLinkLabelsThickness={2}
- arcLinkLabelsDiagonalLength={10}
- arcLinkLabelsStraightLength={12}
- arcLinkLabelsTextOffset={4}
- arcLinkLabelsColor={{ from: "data.color" }}
- arcLinkLabelsTextColor={ARC_LABEL_TEXT_COLOR[theme]}
- theme={{
- text: { fontSize: 11 },
- tooltip: {
- container: { background: "#1e293b", color: "#fff" },
- },
- }}
- tooltip={({ datum }) => (
- <div
- style={{
- background: "#1e293b",
- color: "#fff",
- padding: "6px 12px",
- borderRadius: "4px",
- fontSize: "12px",
- whiteSpace: "nowrap",
- }}
- >
- <strong>{datum.data.label}</strong> — {datum.value}h
- </div>
- )}
- />
+ chartWidth > 0 && (
+ <Pie
+ data={slices}
+ // Sized from the card's own measurement rather than a second
+ // one of nivo's: two observers on this box update a frame
+ // apart, and the frame where the new gutters met the old
+ // width collapsed the donut to half its radius.
+ width={chartWidth}
+ height={CHART_HEIGHT}
+ // Width changes land on every frame of the panel's 200ms
+ // transition, so the donut tracks them instead of springing
+ // toward each one in turn.
+ animate={false}
+ margin={{
+ top: 26,
+ right: layout.gutter,
+ bottom: 26,
+ left: layout.gutter,
+ }}
+ innerRadius={0.72}
+ padAngle={2}
+ cornerRadius={2}
+ activeOuterRadiusOffset={4}
+ colors={{ datum: "data.color" }}
+ borderWidth={0}
+ enableArcLabels={false}
+ enableArcLinkLabels
+ arcLinkLabelComponent={arcLinkLabelComponent}
+ arcLinkLabelsThickness={2}
+ arcLinkLabelsDiagonalLength={10}
+ arcLinkLabelsStraightLength={12}
+ arcLinkLabelsTextOffset={4}
+ arcLinkLabelsColor={{ from: "data.color" }}
+ arcLinkLabelsTextColor={ARC_LABEL_TEXT_COLOR[theme]}
+ theme={{
+ text: { fontSize: 11 },
+ tooltip: {
+ container: { background: "#1e293b", color: "#fff" },
+ },
+ }}
+ tooltip={({ datum }) => (
+ <div
+ style={{
+ background: "#1e293b",
+ color: "#fff",
+ padding: "6px 12px",
+ borderRadius: "4px",
+ fontSize: "12px",
+ whiteSpace: "nowrap",
+ }}
+ >
+ <strong>{datum.data.label}</strong> — {datum.value}h
+ </div>
+ )}
+ />
+ )
)}
<div
className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-px text-center"
data-testid="jobs-activity-total"
>
- <span className="text-xl font-bold leading-tight tabular-nums">
+ <span
+ className={cn(
+ "font-bold leading-tight tabular-nums",
+ roomyTotal ? "text-xl" : "text-base",
+ )}
+ >
{totalHours}h
</span>
- <span className="text-sm text-muted-foreground tabular-nums">
+ <span
+ className={cn(
+ "text-muted-foreground tabular-nums",
+ roomyTotal ? "text-sm" : "text-xs",
+ )}
+ >
{jobsApplied} {jobsApplied === 1 ? "job" : "jobs"}
</span>
- {jobsTrend !== 0 && (
+ {jobsTrend !== 0 && roomyTotal && (
<span
className={cn(
"flex items-center gap-0.5 text-[10px] tabular-nums",
diff --git a/src/components/dashboard/jobsActivityChart.ts b/src/components/dashboard/jobsActivityChart.ts
index 03be866..f05bd46 100644
--- a/src/components/dashboard/jobsActivityChart.ts
+++ b/src/components/dashboard/jobsActivityChart.ts
@@ -54,14 +54,61 @@ export const ARC_LABEL_TEXT_COLOR = {
dark: "#e2e8f0",
} as const;
-const ARC_LABEL_MAX_CHARS = 16;
+// Arc link label geometry. The gutters either side of the donut hold these
+// labels; anything wider than the gutter runs off the SVG and is clipped.
+const ARC_LABEL_CHAR_WIDTH = 6;
+const ARC_LABEL_LINK_LENGTH = 26;
+const MAX_ARC_LABEL_GUTTER = 100;
+const MIN_ARC_LABEL_GUTTER = 76;
+
+// The chart box is 200px tall with 26px above and below the donut.
+export const CHART_HEIGHT = 200;
+const CHART_VERTICAL_MARGIN = 26;
+const MAX_DONUT_DIAMETER = CHART_HEIGHT - CHART_VERTICAL_MARGIN * 2;
+const INNER_RADIUS_RATIO = 0.72;
+
+// Width the card assumes before it has measured itself.
+const FULL_CHART_WIDTH = MAX_ARC_LABEL_GUTTER * 2 + MAX_DONUT_DIAMETER;
+
+export interface DonutLayout {
+ gutter: number;
+ maxLabelChars: number;
+ holeDiameter: number;
+}
+
+// nivo sizes the donut from min(width - gutters, height), so fixed gutters
+// make a narrow card shrink the donut into its own centre text. Letting the
+// gutters give way first spends label characters instead, and the caller
+// gets back the hole it has left to fit that centre text into.
+export function donutLayout(width: number): DonutLayout {
+ const available = width > 0 ? width : FULL_CHART_WIDTH;
+ const gutter = Math.max(
+ MIN_ARC_LABEL_GUTTER,
+ Math.min(MAX_ARC_LABEL_GUTTER, (available - MAX_DONUT_DIAMETER) / 2),
+ );
+ const diameter = Math.max(
+ 0,
+ Math.min(MAX_DONUT_DIAMETER, available - gutter * 2),
+ );
+
+ return {
+ gutter,
+ maxLabelChars: Math.floor(
+ (gutter - ARC_LABEL_LINK_LENGTH) / ARC_LABEL_CHAR_WIDTH,
+ ),
+ holeDiameter: diameter * INNER_RADIUS_RATIO,
+ };
+}
// The label renders as two lines, so the name is trimmed rather than left
// to run off the card edge.
-export function arcLabelLines(slice: DonutSlice): [string, string] {
+export function arcLabelLines(
+ slice: DonutSlice,
+ maxChars: number,
+): [string, string] {
const name =
- slice.label.length > ARC_LABEL_MAX_CHARS
- ? `${slice.label.slice(0, ARC_LABEL_MAX_CHARS - 1).trimEnd()}…`
+ slice.label.length > maxChars
+ ? `${slice.label.slice(0, maxChars - 1).trimEnd()}…`
: slice.label;
return [name, `${slice.value}h`];
diff --git a/src/hooks/useElementWidth.ts b/src/hooks/useElementWidth.ts
new file mode 100644
index 0000000..a602f81
--- /dev/null
+++ b/src/hooks/useElementWidth.ts
@@ -0,0 +1,28 @@
+import { useLayoutEffect, useRef, useState } from "react";
+
+// Content-box width of the observed element. The first read happens in a
+// layout effect rather than waiting on the observer, so a width-dependent
+// layout never paints the wrong variant first.
+export function useElementWidth<T extends HTMLElement>() {
+ const ref = useRef<T | null>(null);
+ const [width, setWidth] = useState(0);
+
+ useLayoutEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+
+ setWidth(element.getBoundingClientRect().width);
+
+ // Deliberately undebounced: callers size a chart from this, and a
+ // delayed width lands after the layout transition it belongs to,
+ // arriving as a jump rather than as part of the movement.
+ const observer = new ResizeObserver((entries) => {
+ setWidth(entries[0].contentRect.width);
+ });
+ observer.observe(element);
+
+ return () => observer.disconnect();
+ }, []);
+
+ return [ref, width] as const;
+}