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
4 changes: 2 additions & 2 deletions web/e2e/navigation.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ test("following a link doesn't reload the page", async ({ page }) => {
(window as { stillHere?: boolean }).stillHere = true;
});
await page
.getByRole("main")
.getByRole("link", { name: "Browse maps" })
.getByRole("banner")
.getByRole("link", { name: "Maps", exact: true })
.click();
await expect(page).toHaveURL(/\/maps$/);
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Maps");
Expand Down
151 changes: 81 additions & 70 deletions web/src/features/home/HomeHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,77 +1,88 @@
// The home page's header: the site's picture with its name over it, and the way in.
import Image from "next/image";
import type { CSSProperties } from "react";
import { ButtonLink } from "@/ui/Button";
import { HeaderDepth } from "./HeaderDepth";
import header from "./header.png";
import headerDepth from "./header-depth.webp";
import { ArrowUpRight } from "lucide-react";
import { Dot } from "@/ui/Dot";
import { formatDate } from "@/features/runs/time";
import { latestUpload, youtubeChannel } from "./latestUpload";
import { UploadPlayer } from "./UploadPlayer";

// Wider than a phone, the picture is shown at its own size, centered and cropped: shrinking it to fit averages
// away its fine grain, which is what makes it look sharp. Centered by position rather than a transform, which
// the browser snaps to whole pixels; a half-pixel offset would blur the picture again.
const nativeSize =
"sm:absolute sm:top-(--top) sm:left-(--left) sm:h-(--height) sm:w-(--width) sm:max-w-none";
const nativePlacement = {
"--width": `${header.width}px`,
"--height": `${header.height}px`,
"--left": `calc(50% - ${header.width / 2}px)`,
"--top": `calc(50% - ${header.height / 2}px)`,
} as CSSProperties;
const views = new Intl.NumberFormat("en", {
notation: "compact",
maximumFractionDigits: 1,
});

export async function HomeHeader() {
const upload = await latestUpload().catch(() => null);
const hasRun = upload?.map && upload.player && upload.time;

/** A static import, so Next.js knows the size, serves modern formats at the screen's width, and blurs in. */
export function HomeHeader() {
return (
<header className="border-border relative flex h-80 overflow-hidden rounded-md border sm:h-72">
{/* On a phone the text takes the lower half, so the picture fills only the top two thirds and fades out
there: the jumper then sits between the top edge and the text instead of behind it. The settle zoom is
on this box so the depth canvas moves with the picture. */}
<div className="motion-settle absolute inset-x-0 top-0 h-2/3 sm:inset-0 sm:h-auto">
<Image
src={header}
alt=""
priority
quality={90}
placeholder="blur"
sizes={`(min-width: 40rem) ${header.width}px, 100vw`}
style={nativePlacement}
className={`size-full object-cover ${nativeSize}`}
/>
<HeaderDepth
depth={headerDepth.src}
style={nativePlacement}
className={`pointer-events-none hidden ${nativeSize} sm:block`}
/>
<div className="from-bg absolute inset-x-0 bottom-0 h-1/2 bg-linear-to-t to-transparent sm:hidden" />
</div>
{/* Fades the picture into the page at the bottom and darkens its left side, so the text stays readable on
any part of it. */}
<div className="from-bg absolute inset-0 bg-linear-to-t via-transparent to-transparent" />
<div className="from-bg/80 absolute inset-0 bg-linear-to-r to-transparent to-60%" />
<div className="relative mt-auto flex flex-col gap-4 p-6 sm:p-8">
<div className="flex flex-col gap-1">
<h1 className="motion-enter xs:text-4xl text-3xl font-bold tracking-tight">
SourceJump
</h1>
<p className="motion-enter text-text-muted text-lg" style={delay(80)}>
The global bunnyhop community for Counter-Strike: Source.
</p>
</div>
{/* Its own compositing layer: with the depth canvas redrawing beneath every frame, some GPU browsers drew a
hovered button's new color for a frame and then the stale one again (Chromium, NVIDIA, 2026-11-08). */}
<div
className="motion-enter flex flex-wrap items-center gap-3 will-change-transform"
style={delay(160)}
<section
aria-labelledby="latest-upload-heading"
className="flex flex-col gap-3"
>
<h1 className="sr-only">SourceJump</h1>
<div className="flex items-center justify-between gap-4">
<h2 id="latest-upload-heading" className="text-lg font-bold">
Latest upload
</h2>
<a
href={youtubeChannel}
target="_blank"
rel="noreferrer"
className="text-text-muted hover:text-accent inline-flex items-center gap-1 text-sm transition-colors"
>
<ButtonLink href="/servers" variant="primary">
Find a server
</ButtonLink>
<ButtonLink href="/maps">Browse maps</ButtonLink>
</div>
Open channel <ArrowUpRight aria-hidden className="size-4" />
</a>
</div>
</header>
{upload ? (
<div className="border-border bg-surface grid overflow-hidden rounded-md border md:grid-cols-5">
<UploadPlayer
key={upload.id}
id={upload.id}
title={upload.title}
thumbnail={upload.thumbnail}
/>
<div className="flex min-w-0 flex-col justify-center gap-5 p-5 sm:p-7 md:col-span-2">
<div className="flex flex-col gap-4">
<h3 className="text-xl font-bold wrap-anywhere sm:text-2xl">
{hasRun ? upload.title.split(/\s+in\s+\d/)[0] : upload.title}
</h3>
{hasRun && (
<p className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<span
aria-label={`Run time ${upload.time}`}
className="text-accent text-2xl font-bold tabular-nums"
>
{upload.time}
</span>
<span className="text-text-muted text-sm">
by <span className="text-text">{upload.player}</span>
</span>
</p>
)}
</div>
<div className="flex flex-col gap-4">
<p className="text-text-subtle flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
{upload.views !== undefined && (
<>
<span>{views.format(upload.views)} views</span>
<Dot />
</>
)}
<time
dateTime={upload.publishedAt}
title={formatDate(upload.publishedAt)}
>
{upload.age}
</time>
</p>
</div>
</div>
</div>
) : (
<p className="border-border bg-surface text-text-muted rounded-md border p-6 text-sm">
The latest upload couldn&apos;t be loaded. You can still watch it on
the channel.
</p>
)}
</section>
);
}

function delay(ms: number): CSSProperties {
return { "--motion-delay": `${ms}ms` } as CSSProperties;
}
53 changes: 53 additions & 0 deletions web/src/features/home/UploadPlayer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"use client";

import { Play } from "lucide-react";
import { useState } from "react";

export function UploadPlayer({
id,
title,
thumbnail,
}: {
id: string;
title: string;
thumbnail: string;
}) {
const [playing, setPlaying] = useState(false);

return (
<div className="bg-bg relative aspect-video overflow-hidden md:col-span-3">
{playing ? (
<iframe
src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1&controls=1&playsinline=1&rel=0`}
title={title}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
referrerPolicy="strict-origin-when-cross-origin"
onLoad={(event) => event.currentTarget.focus()}
className="absolute inset-0 size-full border-0"
/>
) : (
<button
type="button"
onClick={() => setPlaying(true)}
aria-label={`Play ${title}`}
className="group focus-visible:outline-accent absolute inset-0 flex size-full items-center justify-center focus-visible:-outline-offset-4"
>
{/* The player loads only when requested; the homepage starts with just its thumbnail. */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={thumbnail}
alt=""
width={1280}
height={720}
fetchPriority="high"
className="absolute inset-0 size-full object-cover"
/>
<span className="bg-accent text-on-accent group-hover:bg-accent-hover relative inline-flex size-16 items-center justify-center rounded-full transition-colors">
<Play aria-hidden className="size-7 fill-current" />
</span>
</button>
)}
</div>
);
}
75 changes: 75 additions & 0 deletions web/src/features/home/latestUpload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { afterEach, expect, it, vi } from "vitest";
import { latestUpload, parseUploadFeed } from "./latestUpload";

vi.mock("next/cache", () => ({ cacheLife: vi.fn() }));

const entry = (id: string, date: string, description = "") => `<entry>
<yt:videoId>${id}</yt:videoId>
<yt:channelId>UCyEAWx-xBlI-uP2RkqaG43A</yt:channelId>
<title>bhop_test in 1:15 by A &amp; B</title>
<published>${date}</published>
<media:description>${description}</media:description>
<media:statistics views="0"/>
</entry>`;
const feed = `<feed>${entry("abcdefghijk", "2026-11-01T12:00:00Z")}${entry("v7AFSKcOvSE", "2026-11-08T22:21:09Z", "Player: A &amp; B\nMap: bhop_&#116;est\nTime: 1:15.784")}</feed>`;

afterEach(() => vi.unstubAllGlobals());

it("chooses the newest published upload and reads real run details and zero views", () => {
expect(parseUploadFeed(feed)).toMatchObject({
id: "v7AFSKcOvSE",
title: "bhop_test in 1:15 by A & B",
views: 0,
player: "A & B",
map: "bhop_test",
time: "1:15.784",
});
});

it("keeps a normal upload usable without run details or view counts", () => {
const upload = parseUploadFeed(
feed
.replace(/<media:description>[\s\S]*?<\/media:description>/g, "")
.replace(/<media:statistics[^>]*\/>/g, ""),
);
expect(upload.title).toBeTruthy();
expect(upload.map).toBeUndefined();
expect(upload.views).toBeUndefined();
});

it("rejects malformed feeds and entries from another channel", () => {
expect(() => parseUploadFeed("<feed/>")).toThrow();
expect(() =>
parseUploadFeed(
feed.replaceAll("UCyEAWx-xBlI-uP2RkqaG43A", "another-channel"),
),
).toThrow();
expect(() =>
parseUploadFeed(
feed.replaceAll(
/<published>.*?<\/published>/g,
"<published>not-a-date</published>",
),
),
).toThrow();
});

it("uses a standard thumbnail when a high-resolution version is unavailable", async () => {
const fetch = vi
.fn()
.mockResolvedValueOnce(new Response(feed))
.mockResolvedValueOnce(new Response(null, { status: 404 }));
vi.stubGlobal("fetch", fetch);
const upload = await latestUpload();
expect(upload.thumbnail).toBe(
"https://i.ytimg.com/vi/v7AFSKcOvSE/hqdefault.jpg",
);
});

it("surfaces feed failures so the component can show its channel fallback", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(new Response(null, { status: 503 })),
);
await expect(latestUpload()).rejects.toThrow("503");
});
91 changes: 91 additions & 0 deletions web/src/features/home/latestUpload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { cacheLife } from "next/cache";
import { formatSince } from "../runs/time";

export const youtubeChannel = "https://www.youtube.com/@SourceJump";
const channelId = "UCyEAWx-xBlI-uP2RkqaG43A";

function text(xml: string, tag: string): string | undefined {
const value = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`))?.[1];
if (!value) return undefined;
const entities: Record<string, string> = {
amp: "&",
lt: "<",
gt: ">",
quot: '"',
apos: "'",
};
return value
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
.replace(
/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos);/gi,
(_, entity: string) => {
if (!entity.startsWith("#")) return entities[entity.toLowerCase()]!;
const hex = entity.slice(1, 2).toLowerCase() === "x";
return String.fromCodePoint(
parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10),
);
},
)
.trim();
}

/** Read the known fields of YouTube's Atom feed; titles and descriptions stay plain text. */
export function parseUploadFeed(xml: string) {
const uploads = Array.from(xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g))
.map((match) => {
const entry = match[1]!;
const id = text(entry, "yt:videoId");
const title = text(entry, "title");
const publishedAt = text(entry, "published");
if (
text(entry, "yt:channelId") !== channelId ||
!id ||
!/^[\w-]{11}$/.test(id) ||
!title ||
!publishedAt ||
!Number.isFinite(Date.parse(publishedAt))
)
return null;
const description = text(entry, "media:description") ?? "";
const views = entry.match(/<media:statistics\b[^>]*\bviews="(\d+)"/)?.[1];
return {
id,
title,
publishedAt,
views: views === undefined ? undefined : Number(views),
map: description.match(/^Map:\s*(.+)$/m)?.[1]?.trim(),
player: description.match(/^Player:\s*(.+)$/m)?.[1]?.trim(),
time: description.match(
/^Time:\s*(\d+(?::\d{2}){0,2}\.\d{3})\s*$/m,
)?.[1],
};
})
.filter((upload) => upload !== null)
.sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt));
if (!uploads[0]) throw new Error("YouTube feed contains no valid uploads");
return uploads[0];
}

export async function latestUpload() {
"use cache";
cacheLife({ stale: 300, revalidate: 900, expire: 86400 });
const response = await fetch(
`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`,
{ signal: AbortSignal.timeout(8000) },
);
if (!response.ok) throw new Error(`YouTube feed returned ${response.status}`);
const upload = parseUploadFeed(await response.text());
const highResolution = `https://i.ytimg.com/vi/${upload.id}/maxresdefault.jpg`;
// Some uploads have no maximum-resolution thumbnail; keep the standard version available.
const image = await fetch(highResolution, {
method: "HEAD",
signal: AbortSignal.timeout(3000),
}).catch(() => null);
return {
...upload,
thumbnail: image?.ok
? highResolution
: `https://i.ytimg.com/vi/${upload.id}/hqdefault.jpg`,
age: formatSince(upload.publishedAt),
};
}
Loading