Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions client/__tests__/AppSidebar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/** @vitest-environment jsdom */
import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import type { Game } from "@shared/schema";

import AppSidebar from "../src/components/AppSidebar";
import { SidebarProvider } from "../src/components/ui/sidebar";

vi.mock("@/lib/auth", () => ({
useAuth: () => ({ logout: vi.fn(), user: { username: "tester" } }),
}));

vi.mock("@/components/GitHubVersionLink", () => ({
GitHubVersionLink: () => null,
}));

function renderSidebar(statuses: string[]) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity, queryFn: () => null } },
});
queryClient.setQueryData(
["/api/games"],
statuses.map((status, i) => ({ id: `g${i}`, status }) as unknown as Game)
);
queryClient.setQueryData(["/api/downloads"], { downloads: [] });
return render(
<QueryClientProvider client={queryClient}>
<SidebarProvider>
<AppSidebar />
</SidebarProvider>
</QueryClientProvider>
);
}

describe("AppSidebar library counts", () => {
it("shows the library total, wishlist and playing counts", () => {
renderSidebar(["wanted", "playing", "playing", "owned", "completed"]);

expect(screen.getByRole("button", { name: "All Games, 5 games" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Wishlist, 1 game" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Playing, 2 games" })).toBeInTheDocument();
expect(screen.getByTestId("badge-all-games")).toHaveTextContent("5");
expect(screen.getByTestId("badge-playing")).toHaveTextContent("2");
});

it("styles the playing count with the playing status color, unlike the wishlist", () => {
renderSidebar(["wanted", "playing"]);

expect(screen.getByTestId("badge-playing")).toHaveClass("bg-cyan-600");
expect(screen.getByTestId("badge-wishlist")).not.toHaveClass("bg-cyan-600");
});

it("hides the counts when there is nothing to count", () => {
renderSidebar([]);

expect(screen.queryByTestId("badge-all-games")).not.toBeInTheDocument();
expect(screen.queryByTestId("badge-playing")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Playing" })).toBeInTheDocument();
});
});
44 changes: 34 additions & 10 deletions client/src/components/AppSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,15 @@
type AppNavItem,
} from "@/components/navigation-items";
import { withBasePath } from "@/lib/app-path";
import { cn } from "@/lib/utils";

interface AppSidebarProps {
activeItem?: string;
onNavigate?: (url: string) => void;
}

// Stable reference for useQuery's no-data fallback so `games` doesn't change
// identity on every render (which would otherwise defeat wishlistCount's memo).
// identity on every render (which would otherwise defeat the count memos).
const EMPTY_GAMES: Game[] = [];

export default function AppSidebar({ activeItem = "/", onNavigate }: Readonly<AppSidebarProps>) {
Expand All @@ -58,12 +59,14 @@
// once and allocates an intermediate array that's immediately discarded.
// Memoized so heavily re-rendered components like this sidebar don't recompute
// on every render.
const wishlistCount = useMemo(() => {
let count = 0;
const { wishlistCount, playingCount } = useMemo(() => {
let wanted = 0;
let playing = 0;
for (const game of games) {
if (game.status === "wanted") count++;
if (game.status === "wanted") wanted++;
else if (game.status === "playing") playing++;
}
return count;
return { wishlistCount: wanted, playingCount: playing };
}, [games]);

const activeDownloadsCount = useMemo(() => {
Expand All @@ -78,17 +81,35 @@

type NavItemWithBadge = Omit<AppNavItem, "children"> & {
badge?: string | undefined;
badgeClassName?: string | undefined;
badgeVariant?: "secondary" | "outline" | undefined;
children?: NavItemWithBadge[] | undefined;
};

const withBadge = (item: AppNavItem): NavItemWithBadge => {
let badge: string | undefined;
if (item.title === "Wishlist" && wishlistCount > 0) {
let badgeClassName: string | undefined;
let badgeVariant: NavItemWithBadge["badgeVariant"];
if (item.title === "All Games" && games.length > 0) {
// Neutral outline so the library total doesn't compete with the status counts.
badge = games.length.toString();
badgeVariant = "outline";
} else if (item.title === "Wishlist" && wishlistCount > 0) {
badge = wishlistCount.toString();
} else if (item.title === "Playing" && playingCount > 0) {
// Same cyan as the Playing status badge (see StatusBadge).
badge = playingCount.toString();
badgeClassName = "border-transparent bg-cyan-600 text-white";
} else if (item.title === "Downloads" && activeDownloadsCount > 0) {
badge = activeDownloadsCount.toString();
}
return { ...item, badge, children: item.children?.map(withBadge) };
return {
...item,
badge,
badgeClassName,
badgeVariant,
children: item.children?.map(withBadge),
};
};

const navigation = primaryNavigation.map(withBadge);
Expand Down Expand Up @@ -145,7 +166,9 @@
onClick={() => handleNavigation(child.url)}
className="flex items-center justify-between w-full"
aria-label={
child.badge ? `${child.title}, ${child.badge} items` : undefined
child.badge
? `${child.title}, ${child.badge} ${child.badge === "1" ? "game" : "games"}`

Check warning on line 170 in client/src/components/AppSidebar.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=Doezer_Questarr&issues=AaERBVB-8TlcgzpMAzHz&open=AaERBVB-8TlcgzpMAzHz&pullRequest=1161
: undefined
}
>
<div className="flex items-center gap-2">
Expand All @@ -154,9 +177,10 @@
</div>
{child.badge && (
<Badge
variant="secondary"
className="ml-auto text-xs"
variant={child.badgeVariant ?? "secondary"}
className={cn("ml-auto text-xs", child.badgeClassName)}
aria-hidden="true"
data-testid={`badge-${child.title.toLowerCase().replace(/\s+/g, "-")}`}
>
{child.badge}
</Badge>
Expand Down
2 changes: 1 addition & 1 deletion docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ All notable changes to this project will be documented in this file.
- **Wishlist**: configurable grid column count (#871).
- **Content filtering**: filters to hide erotic and age-restricted (ESRB AO / PEGI 18) games from the library, search, and discovery pages (#808).
- **Windows 2000 style mode**: a retro cosmetic theme (#807).
- **Sidebar**: moved the xREL and RSS pages under Discover (#1086). Wishlist moved into Library group alongside Playing; on mobile, Playing replaced Wishlist in the pinned bottom-nav slots (Wishlist stays reachable via "More") (#1080).
- **Sidebar**: moved the xREL and RSS pages under Discover (#1086). Wishlist moved into Library group alongside Playing; on mobile, Playing replaced Wishlist in the pinned bottom-nav slots (Wishlist stays reachable via "More") (#1080). All Games and Playing now show their game counts like Wishlist, Playing in its cyan status color.

#### Downloads & Import

Expand Down
Loading