Skip to content
Open
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
40 changes: 3 additions & 37 deletions app/(root)/dashboard/DashboardPageWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,13 @@
'use client';

import { useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import LoadingScreen from './LoadingScreen';

interface DashboardPageWrapperProps {
children: React.ReactNode;
}

/**
* Wraps dashboard page content and guarantees LoadingScreen plays its full
* 3500ms animation regardless of how fast Next.js receives API data.
*
* The overlay is rendered via a React Portal directly into document.body β€”
* this means it escapes ALL stacking contexts (navbar, layout wrappers, etc.)
* and is unconditionally on top of everything on the page.
* Wraps dashboard page content.
* Now renders instantly to support React Suspense streaming.
*/
export default function DashboardPageWrapper({ children }: DashboardPageWrapperProps) {
const [ready, setReady] = useState(false);

const mounted = useSyncExternalStore(
() => () => {},
() => true,
() => false
);

return (
<>
{/* Real page β€” renders immediately but stays invisible until animation ends */}
<div
style={{
opacity: ready ? 1 : 0,
transition: 'opacity 0.3s ease',
pointerEvents: ready ? 'auto' : 'none',
}}
>
{children}
</div>

{/* Overlay portalled into document.body β€” escapes every stacking context */}
{mounted &&
!ready &&
createPortal(<LoadingScreen onComplete={() => setReady(true)} />, document.body)}
</>
);
return <>{children}</>;
}
65 changes: 56 additions & 9 deletions app/(root)/dashboard/[username]/page.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Metadata } from 'next';
import { render, screen } from '@testing-library/react';
import { Suspense } from 'react';
import { render, screen, waitFor, act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import DashboardPage, { generateMetadata } from './page';
import { getFullDashboardData } from '@/lib/github';
import { getFullDashboardData, fetchUserProfile } from '@/lib/github';

const { mockNotFound } = vi.hoisted(() => ({
mockNotFound: vi.fn(),
Expand All @@ -21,7 +22,41 @@ vi.mock('next/navigation', () => ({
}));

vi.mock('@/lib/github', () => ({
getFullDashboardData: vi.fn(),
getFullDashboardData: vi.fn().mockReturnValue(
Promise.resolve({
profile: {
login: 'octocat',
avatar_url: 'https://avatars.githubusercontent.com/u/583231?v=4',
html_url: 'https://github.com/octocat',
name: 'The Octocat',
bio: null,
company: '@github',
blog: 'https://github.blog',
location: 'San Francisco',
email: null,
hireable: null,
twitter_username: null,
public_repos: 8,
public_gists: 8,
followers: 3938,
following: 9,
created_at: '2011-01-25T18:44:36Z',
updated_at: '2023-01-22T12:13:14Z',
},
stats: {
currentStreak: 5,
peakStreak: 15,
totalContributions: 500,
},
activity: [],
languages: [],
commitTimes: [],
achievements: [],
recommendations: [],
})
),
fetchUserProfile: vi.fn().mockResolvedValue({ type: 'User', name: '' }),
fetchUserRepos: vi.fn().mockResolvedValue([]),
}));

// --- Mocking Core UI Blocks ---
Expand Down Expand Up @@ -222,7 +257,10 @@ describe('DashboardPage', () => {
const DashboardContent = SuspenseTree.props.children.type;
const PageContent = await DashboardContent(SuspenseTree.props.children.props);

render(PageContent);
await act(async () => {
render(<Suspense fallback="loading">{PageContent}</Suspense>);
});
await waitFor(() => expect(screen.queryByText('loading')).not.toBeInTheDocument());

expect(getFullDashboardData).toHaveBeenCalledWith(
'octocat',
Expand Down Expand Up @@ -258,7 +296,10 @@ describe('DashboardPage', () => {
const DashboardContent = SuspenseTree.props.children.type;
const PageContent = await DashboardContent(SuspenseTree.props.children.props);

render(PageContent);
await act(async () => {
render(<Suspense fallback="loading">{PageContent}</Suspense>);
});
await waitFor(() => expect(screen.queryByText('loading')).not.toBeInTheDocument());

expect(getFullDashboardData).toHaveBeenCalledWith(
'octocat',
Expand All @@ -279,7 +320,10 @@ describe('DashboardPage', () => {
const DashboardContent = SuspenseTree.props.children.type;
const PageContent = await DashboardContent(SuspenseTree.props.children.props);

render(PageContent);
await act(async () => {
render(<Suspense fallback="loading">{PageContent}</Suspense>);
});
await waitFor(() => expect(screen.queryByText('loading')).not.toBeInTheDocument());

expect(getFullDashboardData).toHaveBeenCalledWith(
'octocat',
Expand All @@ -300,14 +344,17 @@ describe('DashboardPage', () => {
const DashboardContent = SuspenseTree.props.children.type;
const PageContent = await DashboardContent(SuspenseTree.props.children.props);

render(PageContent);
await act(async () => {
render(<Suspense fallback="loading">{PageContent}</Suspense>);
});
await waitFor(() => expect(screen.queryByText('loading')).not.toBeInTheDocument());

const trendView = screen.getByTestId('historical-trend-view');
expect(JSON.parse(trendView.getAttribute('data-prop') ?? '[]')).toEqual(mockData.activity);
});

it('calls notFound when dashboard data fetch throws an error', async () => {
vi.mocked(getFullDashboardData).mockRejectedValueOnce(new Error('User not found'));
it('calls notFound when fetchUserProfile throws an error', async () => {
vi.mocked(fetchUserProfile).mockRejectedValueOnce(new Error('Fetch failed'));

const SuspenseTree = await DashboardPage({
params: Promise.resolve({ username: 'missing-user' }),
Expand Down
43 changes: 18 additions & 25 deletions app/(root)/dashboard/[username]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,36 +136,29 @@ async function DashboardContent({
const session = await auth();
const sessionUsername = (session?.user as { username?: string })?.username ?? null;

let data;

let fallbackProfile;
try {
data = await getFullDashboardData(username, {
fallbackProfile = await fetchUserProfile(username, {
bypassCache,
from: period.from,
to: period.to,
rangeLabel: period.label,
token: userToken,
excludeBots,
});
} catch (error) {
if (error instanceof Error && error.message.includes('not found')) {
let fallbackProfile;
try {
fallbackProfile = await fetchUserProfile(username, {
bypassCache,
token: userToken,
});
} catch {
return notFound();
}
if (fallbackProfile.type === 'Organization') {
redirect(`/dashboard/org/${username}`);
}
return notFound();
}
throw error;
} catch {
return notFound();
}

if (fallbackProfile.type === 'Organization') {
redirect(`/dashboard/org/${username}`);
}

const data = getFullDashboardData(username, {
bypassCache,
from: period.from,
to: period.to,
rangeLabel: period.label,
token: userToken,
excludeBots,
});

let allRepos: RepoActivityInfo[] = [];
try {
const reposData = await fetchUserRepos(username, { bypassCache, token: userToken });
Expand Down Expand Up @@ -196,7 +189,7 @@ async function DashboardContent({
<DashboardPageWrapper>
<EducationalCurveTracker username={username} />
<DashboardClient
initialData={data}
initialDataPromise={data}
allRepoActivity={allRepos}
username={username}
compareData={compareData}
Expand Down
20 changes: 20 additions & 0 deletions app/api/streak/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,26 @@ describe('GET /api/streak', () => {
expect(response.headers.get('Content-Type')).toContain('image/svg+xml');
});

it('returns JSON 400 when the user parameter is missing and format=json', async () => {
const response = await GET(makeRequest({ format: 'json' }));
expect(response.status).toBe(400);
const body = await response.json();
expect(body).toHaveProperty('error');
expect(body.error).toContain('Missing user parameter');
expect(response.headers.get('Content-Type')).toContain('application/json');
});

it('returns 404 JSON for a nonexistent user when format=json', async () => {
vi.mocked(fetchGitHubContributions).mockRejectedValue(
new Error("Could not resolve to a User with the login of 'nonexistentuser'")
);
const response = await GET(makeRequest({ user: 'nonexistentuser', format: 'json' }));
expect(response.status).toBe(404);
const body = await response.json();
expect(body).toHaveProperty('error');
expect(response.headers.get('Content-Type')).toContain('application/json');
});

it('returns 400 when org parameter contains spaces and invalid characters', async () => {
const response = await GET(
makeRequest({ user: 'octocat', org: 'invalid_org_name_with_spaces' })
Expand Down
17 changes: 16 additions & 1 deletion app/api/streak/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
} from '@/types';
import { getNormalizedThemeKey, themes, resolveErrorTheme } from '@/lib/svg/themes';
import { streakParamsSchema, coerceQueryParams } from '@/lib/validations';
import { sanitizeHexColor, sanitizeRadius, escapeXML } from '@/lib/svg/sanitizer';

Check warning on line 54 in app/api/streak/route.ts

View workflow job for this annotation

GitHub Actions / Format Β· Lint Β· Typecheck Β· Test

'escapeXML' is defined but never used. Allowed unused vars must match /^_/u
import { getClientIp } from '@/utils/getClientIp';
import { quotaMonitor } from '@/services/github/quota-monitor';
import { refreshPolicy } from '@/services/github/refresh-policy';
Expand Down Expand Up @@ -101,6 +101,21 @@
Object.values(fieldErrors.fieldErrors).flat()[0] ??
fieldErrors.formErrors[0] ??
'Invalid parameters';

if (searchParams.get('format') === 'json') {
return NextResponse.json(
{ error: firstError },
{
status: 400,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'X-Request-ID': requestId,
},
}
);
}

const errTheme = resolveErrorTheme(searchParams);
const errorSvg = buildInlineErrorSVG(firstError, {
bg: errTheme.bg,
Expand Down Expand Up @@ -1035,7 +1050,7 @@
}

if (isNotFound) {
const match = message.match(/"([^"]+)"|login of '([^']+)'/);
const match = rawMessage.match(/"([^"]+)"|login of '([^']+)'/);
const fallbackTarget = parseResult.success
? parseResult.data.org || parseResult.data.user
: 'unknown';
Expand Down
33 changes: 17 additions & 16 deletions app/burnout-analyzer/page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,17 @@ vi.mock('next/navigation', () => ({
}),
}));

vi.mock('framer-motion', async () => {
const actual = await vi.importActual('framer-motion');
return {
...(actual as object),
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
};
});

describe('BurnoutAnalyzerPage repository input handling', () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
mockHistoryBack.mockReset();
mockRouterPush.mockReset();
Expand Down Expand Up @@ -115,14 +124,10 @@ describe('BurnoutAnalyzerPage repository input handling', () => {
}),
});
vi.stubGlobal('fetch', fetchMock);
Object.defineProperty(window, 'history', {
value: { length: 2, back: mockHistoryBack },
configurable: true,
});
Object.defineProperty(document, 'referrer', {
value: 'http://localhost/burnout-analyzer',
configurable: true,
});
vi.spyOn(window.history, 'length', 'get').mockReturnValue(2);
vi.spyOn(window.history, 'back').mockImplementation(mockHistoryBack);
vi.spyOn(window.history, 'pushState').mockImplementation(vi.fn());
vi.spyOn(document, 'referrer', 'get').mockReturnValue('http://localhost/burnout-analyzer');

render(<BurnoutAnalyzerPage />);
fireEvent.change(screen.getByPlaceholderText(/facebook\/react/i), {
Expand Down Expand Up @@ -154,14 +159,10 @@ describe('BurnoutAnalyzerPage repository input handling', () => {
}),
});
vi.stubGlobal('fetch', fetchMock);
Object.defineProperty(window, 'history', {
value: { length: 1, back: mockHistoryBack },
configurable: true,
});
Object.defineProperty(document, 'referrer', {
value: 'http://localhost/another-page',
configurable: true,
});
vi.spyOn(window.history, 'length', 'get').mockReturnValue(1);
vi.spyOn(window.history, 'back').mockImplementation(mockHistoryBack);
vi.spyOn(window.history, 'pushState').mockImplementation(vi.fn());
vi.spyOn(document, 'referrer', 'get').mockReturnValue('http://localhost/another-page');

render(<BurnoutAnalyzerPage />);
fireEvent.change(screen.getByPlaceholderText(/facebook\/react/i), {
Expand Down
14 changes: 10 additions & 4 deletions components/dashboard/DashboardClient.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import { copyToClipboard } from '@/utils/clipboard';
import { useState, useEffect, useRef, useCallback, useSyncExternalStore } from 'react';
import { useState, useRef, useEffect, useCallback, useSyncExternalStore, use } from 'react';
import { createPortal } from 'react-dom';
import { AnimatePresence, motion } from 'framer-motion';
import DashboardSkeleton from './DashboardSkeleton';
Expand Down Expand Up @@ -106,8 +106,9 @@ export interface DashboardData {
rawCommits?: string[];
}

interface DashboardClientProps {
initialData: DashboardData;
export interface DashboardClientProps {
initialDataPromise?: Promise<DashboardData>;
initialData?: DashboardData;
allRepoActivity?: RepoActivityInfo[];
username: string;
compareData?: DashboardData | null;
Expand Down Expand Up @@ -330,7 +331,8 @@ function getPersonalityTags(
}

export default function DashboardClient({
initialData,
initialDataPromise,
initialData: initialDataProp,
allRepoActivity = [],
username,
compareData = null,
Expand All @@ -342,6 +344,10 @@ export default function DashboardClient({
() => false,
() => (process.env.NODE_ENV === 'test' ? false : true)
);

// Use React.use() if a promise is provided, otherwise use the direct object (for tests)
const initialData = initialDataProp || use(initialDataPromise!);

const [secondUserData, setSecondUserData] = useState<DashboardData | null>(compareData);
const [activeTab, setActiveTab] = useState<'overview' | 'pr-insights' | 'ci-analytics'>(
'overview'
Expand Down
Loading
Loading