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
2 changes: 1 addition & 1 deletion src/components/layout/app-header.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";

import Link from "next/link";
import { Trophy } from "lucide-react";
import { Link } from "@/components/ui/link";
import { BrandLogo } from "./brand-logo";
import { LanguageSwitcher } from "@/components/providers/language-switcher";
import { ThemeToggle } from "@/components/providers/theme-toggle";
Expand Down
1 change: 1 addition & 0 deletions src/components/ui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from "./alert";
export * from "./button";
export * from "./card";
export * from "./input";
export * from "./link";
export * from "./progress";
export * from "./skeleton";
export * from "./tooltip";
Expand Down
51 changes: 51 additions & 0 deletions src/components/ui/link.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// @vitest-environment jsdom

import { cleanup, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ReactNode } from "react";
import { Link } from "./link";

const mockNextLink = vi.fn(
({
children,
href,
prefetch,
}: {
children: ReactNode;
href: string;
prefetch?: boolean | "auto" | null;
}) => (
<a href={href} data-prefetch={String(prefetch)}>
{children}
</a>
),
);

vi.mock("next/link", () => ({
default: (props: { children: ReactNode; href: string; prefetch?: boolean | "auto" | null }) =>
mockNextLink(props),
}));

describe("Link", () => {
afterEach(cleanup);

it("disables prefetching by default", () => {
render(<Link href="/leaderboard">Leaderboard</Link>);

const anchor = screen.getByRole("link", { name: "Leaderboard" });
expect(anchor).toHaveAttribute("href", "/leaderboard");
expect(anchor).toHaveAttribute("data-prefetch", "false");
});

it("allows explicit prefetch override when needed", () => {
render(
<Link href="/leaderboard" prefetch={true}>
Leaderboard
</Link>,
);

const anchor = screen.getByRole("link", { name: "Leaderboard" });
expect(anchor).toHaveAttribute("data-prefetch", "true");
});
});
11 changes: 11 additions & 0 deletions src/components/ui/link.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import NextLink from "next/link";
import type { ComponentProps } from "react";

export type LinkProps = ComponentProps<typeof NextLink>;

/**
* Shared navigation Link wrapper that disables Next.js background prefetching by default.
*/
export function Link({ prefetch = false, ...props }: LinkProps) {
return <NextLink prefetch={prefetch} {...props} />;
}
4 changes: 1 addition & 3 deletions src/features/comparison/components/result-dashboard.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"use client";

import { useMemo, useState, useRef } from "react";
import Link from "next/link";
import type { Route } from "next";
import { Check, Copy, ExternalLink, Trophy, Share2, XCircle } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { useClipboardCopy } from "@/hooks";
import dynamic from "next/dynamic";
import { Avatar } from "@/components/ui";
import { Avatar, Button, Card, CardContent, CardHeader, CardTitle, Link } from "@/components/ui";

const ComparisonChart = dynamic(
() => import("./comparison-chart").then((mod) => mod.ComparisonChart),
Expand All @@ -21,7 +20,6 @@ const ComparisonChart = dynamic(
import { TopList } from "./top-list";
import { InsightsList } from "./insights-list";
import { ScoreCard } from "@/components/cards";
import { Button, Card, CardContent, CardHeader, CardTitle } from "@/components/ui";
import { getSignalMetricEntries, type UserResult } from "@/features/developer";
import { useTranslation } from "@/components/providers";
import { formatComparisonToMarkdown } from "../services/format-comparison-to-markdown";
Expand Down
3 changes: 1 addition & 2 deletions src/features/comparison/components/top-list.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"use client";

import Link from "next/link";
import type { Route } from "next";
import { ExternalLink, GitPullRequest, MessageSquare, Star } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui";
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Link } from "@/components/ui";
import type { UserResult } from "@/features/developer";
import {
RepoCardItem,
Expand Down
11 changes: 9 additions & 2 deletions src/features/developer/components/user-not-found.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
"use client";

import Link from "next/link";
import { ArrowLeft, Search, Trophy } from "lucide-react";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui";
import {
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
Link,
} from "@/components/ui";
import { useTranslation } from "@/components/providers";

type Props = {
Expand Down
2 changes: 1 addition & 1 deletion src/features/developer/components/user-profile-client.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import type { Route } from "next";
import { useClipboardCopy } from "@/hooks";
Expand All @@ -26,6 +25,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
Link,
Progress,
} from "@/components/ui";
import {
Expand Down
3 changes: 2 additions & 1 deletion src/features/developer/services/user-persistence.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring";
import { getDatabaseStore } from "@/lib/db";
import { detectCountry } from "@/lib/geo";
import { getGitHubUserStaleDays } from "@/utils/stale";
import type { GitHubUserData } from "@/lib/github";

export type PersistUserOptions = {
Expand Down Expand Up @@ -30,7 +31,7 @@ export async function persistUserScores({
}

const country = explicitCountry !== undefined ? explicitCountry : detectCountry(data.location);
const resolvedStaleDays = staleDays ?? parseInt(process.env.GITHUB_USER_STALE_DAYS ?? "14", 10);
const resolvedStaleDays = staleDays ?? getGitHubUserStaleDays();

// Compute canonical unfiltered score if languages were selected or score was omitted
const canonicalScore =
Expand Down
3 changes: 2 additions & 1 deletion src/features/developer/services/user-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getUserData } from "@/lib/github";
import { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring";
import { scheduleBackground } from "@/lib/background";
import { isUserDataFresh } from "@/utils/stale";
import { persistUserScores } from "./user-persistence";
import { getCachedProfile, setCachedProfile } from "./profile-cache";
import type { UserProfileResponse, UserResult } from "../types";
Expand Down Expand Up @@ -46,7 +47,7 @@ export async function getUserProfile(
if (typeof db.getUserProfile === "function") {
const row = await db.getUserProfile(normalizedUsername);

if (row && row.scores && row.stale_after > new Date()) {
if (row && row.scores && isUserDataFresh(row.updated_at)) {
const scores = row.scores as CalculateUserScoreResult;
const profile: UserProfileResponse = {
user: {
Expand Down
77 changes: 75 additions & 2 deletions src/features/developer/tests/profile-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";

const mocks = vi.hoisted(() => ({
cacheGet: vi.fn(),
Expand Down Expand Up @@ -52,6 +52,10 @@ describe("Profile & Score Caching", () => {
vi.clearAllMocks();
});

afterEach(() => {
vi.unstubAllEnvs();
});

describe("buildProfileCacheKey", () => {
test("builds canonical key for user", () => {
const key = buildProfileCacheKey(" Torvalds ");
Expand Down Expand Up @@ -172,7 +176,8 @@ describe("Profile & Score Caching", () => {
topPullRequests: [],
topCommunityContributions: [],
},
stale_after: new Date(Date.now() + 86400000), // fresh for 1 day
stale_after: new Date(Date.now() + 86400000),
updated_at: new Date(Date.now() - 86400000), // updated 1 day ago
});

const result = await getUserProfile("torvalds");
Expand All @@ -192,5 +197,73 @@ describe("Profile & Score Caching", () => {
expect(mocks.getUserData).not.toHaveBeenCalled();
expect(mocks.calculateUserScore).not.toHaveBeenCalled();
});

test("Tier 2: evaluates staleness using GITHUB_USER_STALE_DAYS and updated_at instead of stale_after", async () => {
vi.stubEnv("GITHUB_USER_STALE_DAYS", "7");
mocks.cacheGet.mockResolvedValueOnce(null);

// Even if stale_after is in the future, updated_at is 8 days ago (> 7 days) -> stale!
mocks.getUserProfile.mockResolvedValueOnce({
username: "torvalds",
name: "Linus Torvalds",
avatar_url: "https://example.com/avatar.png",
location: "Finland",
country: "Finland",
repo_score: 92,
pr_score: 92,
contribution_score: 92,
final_score: 92,
scores: {
repoScore: 92,
prScore: 92,
contributionScore: 92,
finalScore: 92,
topRepos: [],
topPullRequests: [],
topCommunityContributions: [],
},
stale_after: new Date(Date.now() + 30 * 86_400_000),
updated_at: new Date(Date.now() - 8 * 86_400_000),
});

mocks.getUserData.mockResolvedValueOnce({
data: {
login: "torvalds",
name: "Linus Torvalds",
avatarUrl: "https://example.com/avatar.png",
location: "Finland",
repos: [],
pullRequests: [],
contributions: {
totalCommitContributions: 0,
totalPullRequestContributions: 0,
totalIssueContributions: 0,
},
issues: [],
discussions: [],
},
metrics: { duration: 10, errors: [] },
});

mocks.calculateUserScore.mockReturnValueOnce({
repoScore: 95,
prScore: 95,
contributionScore: 95,
finalScore: 95,
normalizedRepoScore: 95,
normalizedPRScore: 95,
normalizedContributionScore: 95,
normalizedFinalScore: 95,
topRepos: [],
topPullRequests: [],
topCommunityContributions: [],
});

const result = await getUserProfile("torvalds");

expect(mocks.getUserData).toHaveBeenCalledTimes(1);
expect(mocks.calculateUserScore).toHaveBeenCalledTimes(1);
expect(result.user.finalScore).toBe(95);
});
});
});
3 changes: 1 addition & 2 deletions src/features/leaderboard/components/country-grid-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import { useState, useMemo } from "react";
import { Globe, Users } from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Link } from "@/components/ui/link";
import { useTranslation } from "@/components/providers/language-provider";
import { getCountryCode } from "@/lib/geo";
import type { CountryInfo } from "../types";
Expand Down Expand Up @@ -89,7 +89,6 @@ export function CountryGridClient({ countries }: Props) {
<Link
key={c.slug}
href={`/leaderboard/${c.slug}` as Route}
prefetch={false}
className="group flex flex-col items-start gap-0.5 rounded-lg border border-border bg-card px-3 py-2.5 text-start transition-colors hover:border-primary/40 hover:bg-primary/5"
>
<span className="flex items-center gap-1.5 text-sm font-medium text-foreground group-hover:text-primary">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use client";

import { useState } from "react";
import Link from "next/link";
import { ArrowLeft, Loader2 } from "lucide-react";
import { LeaderboardTable } from "./leaderboard-table";
import { Button } from "@/components/ui/button";
import { Link } from "@/components/ui/link";
import { useTranslation } from "@/components/providers/language-provider";
import type { LeaderboardResult } from "../types";

Expand Down
5 changes: 2 additions & 3 deletions src/features/leaderboard/components/leaderboard-table.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"use client";

import { useState, useMemo } from "react";
import Link from "next/link";
import type { Route } from "next";
import {
AlertTriangle,
Expand All @@ -20,6 +19,7 @@ import {
CardDescription,
CardHeader,
CardTitle,
Link,
Tooltip,
TooltipContent,
TooltipTrigger,
Expand Down Expand Up @@ -357,7 +357,7 @@ export function LeaderboardTable({

return (
<div className="flex items-center gap-2">
<Link href={profileUrl} prefetch={false}>
<Link href={profileUrl}>
<Avatar
src={user.avatarUrl}
alt={user.name || user.username}
Expand All @@ -369,7 +369,6 @@ export function LeaderboardTable({
<div className="flex items-center gap-1.5">
<Link
href={profileUrl}
prefetch={false}
className="truncate font-semibold text-primary hover:underline"
>
{user.name || user.username}
Expand Down
Loading
Loading