Repository navigation
Add stats page #55
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add stats page #55
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| import { buildPageMetadata } from "@/lib/seo" | ||
| import { cn } from "@/lib/utils" | ||
| import { getSiteStats, type CategoryCount, type WeekCommits } from "@/lib/stats" | ||
|
|
||
| export const revalidate = 3600 | ||
|
|
||
| export const metadata = buildPageMetadata({ | ||
| title: "Stats", | ||
| description: | ||
| "Open numbers for 23rd: components shipped, GitHub stars, forks, contributors, and commits over the past year.", | ||
| path: "/stats", | ||
| keywords: ["stats", "open source", "open metrics"], | ||
| }) | ||
|
|
||
| const numberFormat = new Intl.NumberFormat("en") | ||
| const weekFormat = new Intl.DateTimeFormat("en", { | ||
| month: "short", | ||
| day: "numeric", | ||
| timeZone: "UTC", | ||
| }) | ||
| const monthFormat = new Intl.DateTimeFormat("en", { | ||
| month: "short", | ||
| timeZone: "UTC", | ||
| }) | ||
|
|
||
| function StatTile({ | ||
| label, | ||
| value, | ||
| className, | ||
| }: { | ||
| label: string | ||
| value: number | null | ||
| className?: string | ||
| }) { | ||
| return ( | ||
| <div | ||
| className={cn( | ||
| "flex flex-col gap-1 rounded-xl bg-sheet p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] sm:p-5", | ||
| className | ||
| )} | ||
| > | ||
| <dt className="text-sm text-muted-foreground">{label}</dt> | ||
| <dd className="text-3xl font-semibold tracking-tight tabular-nums"> | ||
| {value === null ? "–" : numberFormat.format(value)} | ||
| </dd> | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| function CommitChart({ weeks }: { weeks: WeekCommits[] }) { | ||
| const max = Math.max(1, ...weeks.map((week) => week.total)) | ||
|
|
||
| return ( | ||
| <section aria-labelledby="commits-heading" className="flex flex-col gap-4"> | ||
| <h2 id="commits-heading" className="text-sm font-medium"> | ||
| Commits per week | ||
| </h2> | ||
| <div className="rounded-xl bg-sheet p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] sm:p-5"> | ||
| <div className="flex h-40 items-end gap-[2px]" aria-hidden="true"> | ||
| {weeks.map((week) => { | ||
| const date = new Date(week.week * 1000) | ||
| return ( | ||
| <div | ||
| key={week.week} | ||
| className="group relative flex h-full flex-1 items-end" | ||
| > | ||
| <div | ||
| className="w-full rounded-t-[4px] bg-foreground/80 transition-colors group-hover:bg-foreground" | ||
| style={{ | ||
| height: week.total | ||
| ? `${Math.max(2, (week.total / max) * 100)}%` | ||
| : "2px", | ||
| opacity: week.total ? undefined : 0.15, | ||
| }} | ||
| /> | ||
| <div className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2 rounded-md bg-popover px-2 py-1 text-xs whitespace-nowrap opacity-0 shadow-md transition-opacity group-hover:opacity-100"> | ||
| <span className="font-medium tabular-nums"> | ||
| {numberFormat.format(week.total)} | ||
| </span>{" "} | ||
| <span className="text-muted-foreground"> | ||
| week of {weekFormat.format(date)} | ||
| </span> | ||
| </div> | ||
| </div> | ||
| ) | ||
| })} | ||
| </div> | ||
| <div | ||
| className="mt-2 flex justify-between text-xs text-muted-foreground" | ||
| aria-hidden="true" | ||
| > | ||
| <span>{monthFormat.format(new Date(weeks[0].week * 1000))}</span> | ||
| <span> | ||
| {monthFormat.format(new Date(weeks[weeks.length - 1].week * 1000))} | ||
| </span> | ||
| </div> | ||
| <table className="sr-only"> | ||
| <caption>Commits per week over the past year</caption> | ||
| <thead> | ||
| <tr> | ||
| <th scope="col">Week of</th> | ||
| <th scope="col">Commits</th> | ||
| </tr> | ||
| </thead> | ||
| <tbody> | ||
| {weeks.map((week) => ( | ||
| <tr key={week.week}> | ||
| <td>{weekFormat.format(new Date(week.week * 1000))}</td> | ||
| <td>{week.total}</td> | ||
| </tr> | ||
| ))} | ||
| </tbody> | ||
| </table> | ||
| </div> | ||
| </section> | ||
| ) | ||
| } | ||
|
|
||
| function CategoryBars({ categories }: { categories: CategoryCount[] }) { | ||
| const max = Math.max(1, ...categories.map((category) => category.count)) | ||
|
|
||
| return ( | ||
| <section | ||
| aria-labelledby="categories-heading" | ||
| className="flex flex-col gap-4" | ||
| > | ||
| <h2 id="categories-heading" className="text-sm font-medium"> | ||
| Components by category | ||
| </h2> | ||
| <ul className="flex flex-col gap-3 rounded-xl bg-sheet p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] sm:p-5"> | ||
| {categories.map((category) => ( | ||
| <li | ||
| key={category.name} | ||
| className="grid grid-cols-[7.5rem_1fr_2rem] items-center gap-3 text-sm sm:grid-cols-[9rem_1fr_2rem]" | ||
| > | ||
| <span className="truncate text-muted-foreground"> | ||
| {category.name} | ||
| </span> | ||
| <span className="h-2 overflow-hidden rounded-full bg-wash"> | ||
| <span | ||
| className="block h-full rounded-full bg-foreground/80" | ||
| style={{ width: `${(category.count / max) * 100}%` }} | ||
| /> | ||
| </span> | ||
| <span className="text-right font-medium tabular-nums"> | ||
| {category.count} | ||
| </span> | ||
| </li> | ||
| ))} | ||
| </ul> | ||
| </section> | ||
| ) | ||
| } | ||
|
|
||
| export default async function StatsPage() { | ||
| const stats = await getSiteStats() | ||
|
|
||
| return ( | ||
| <main className="flex-1 overflow-x-clip"> | ||
| <div className="mx-auto flex w-full max-w-4xl flex-col gap-12 px-4 pt-12 pb-24 sm:px-6 sm:pt-16"> | ||
| <header className="flex flex-col items-center gap-4 text-center"> | ||
| <h1 className="text-4xl font-semibold tracking-tight">Stats</h1> | ||
| <p className="max-w-xl text-balance text-muted-foreground"> | ||
| 23rd in numbers, refreshed every hour. | ||
| </p> | ||
| </header> | ||
|
|
||
| <dl className="grid grid-cols-2 gap-3 lg:grid-cols-5"> | ||
| <StatTile label="Components" value={stats.components} /> | ||
| <StatTile label="Stars" value={stats.stars} /> | ||
| <StatTile label="Forks" value={stats.forks} /> | ||
| <StatTile label="Contributors" value={stats.contributors} /> | ||
| <StatTile | ||
| className="col-span-2 lg:col-span-1" | ||
| label="Commits past year" | ||
| value={stats.commitsPastYear} | ||
| /> | ||
| </dl> | ||
|
|
||
| {stats.weeks ? <CommitChart weeks={stats.weeks} /> : null} | ||
|
|
||
| <CategoryBars categories={stats.categories} /> | ||
| </div> | ||
| </main> | ||
| ) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| import componentsMeta from "@/content/docs/components/meta.json" | ||
|
|
||
| const REPO = "radiumcoders/23rd.dev" | ||
| const REVALIDATE_SECONDS = 3600 | ||
|
|
||
| export type CategoryCount = { name: string; count: number } | ||
| export type WeekCommits = { week: number; total: number } | ||
|
|
||
| export type SiteStats = { | ||
| components: number | ||
| categories: CategoryCount[] | ||
| stars: number | null | ||
| forks: number | null | ||
| contributors: number | null | ||
| commitsPastYear: number | null | ||
| weeks: WeekCommits[] | null | ||
| } | ||
|
|
||
| /** Groups the docs sidebar's "---Group---" separators into component counts. */ | ||
| export function getCategoryCounts(): CategoryCount[] { | ||
| const categories: CategoryCount[] = [] | ||
| for (const page of componentsMeta.pages) { | ||
| const group = /^---(.+)---$/.exec(page) | ||
| if (group) { | ||
| categories.push({ name: group[1], count: 0 }) | ||
| } else if (categories.length > 0) { | ||
| categories[categories.length - 1].count += 1 | ||
| } | ||
| } | ||
| return categories.filter((category) => category.count > 0) | ||
| } | ||
|
|
||
| async function github(path: string): Promise<Response | null> { | ||
| const token = process.env.GITHUB_TOKEN | ||
| try { | ||
| const res = await fetch(`https://api.github.com/repos/${REPO}${path}`, { | ||
| headers: { | ||
| Accept: "application/vnd.github+json", | ||
| "User-Agent": "23rd.dev", | ||
| ...(token ? { Authorization: `Bearer ${token}` } : {}), | ||
| }, | ||
| next: { revalidate: REVALIDATE_SECONDS }, | ||
| signal: AbortSignal.timeout(5000), | ||
| }) | ||
| if (!res.ok) { | ||
| console.warn(`GitHub ${path}: ${res.status} ${res.statusText}`) | ||
| return null | ||
| } | ||
| return res | ||
| } catch (error) { | ||
| console.warn(`GitHub ${path}: request failed`, error) | ||
| return null | ||
| } | ||
| } | ||
|
|
||
| async function getRepo() { | ||
| const res = await github("") | ||
| if (!res) return null | ||
| return (await res.json()) as { stargazers_count: number; forks_count: number } | ||
| } | ||
|
|
||
| /** One contributor per page, so the last page number is the total. */ | ||
| async function getContributorCount(): Promise<number | null> { | ||
| const res = await github("/contributors?per_page=1&anon=1") | ||
| if (!res) return null | ||
| const last = /[?&]page=(\d+)>; rel="last"/.exec(res.headers.get("link") ?? "") | ||
| if (last) return Number(last[1]) | ||
| const list = (await res.json()) as unknown[] | ||
| return list.length | ||
| } | ||
|
|
||
| const WEEK_MS = 7 * 24 * 60 * 60 * 1000 | ||
| const WEEKS = 52 | ||
|
|
||
| /** | ||
| * Buckets the past year's commits into Sunday-start weeks. Counted from the | ||
| * commit list because /stats/commit_activity answers 202 until GitHub has | ||
| * cached it, which leaves a cold build with no chart. | ||
| */ | ||
| async function getWeeklyCommits(): Promise<WeekCommits[] | null> { | ||
| const now = new Date() | ||
| const thisSunday = Date.UTC( | ||
| now.getUTCFullYear(), | ||
| now.getUTCMonth(), | ||
| now.getUTCDate() - now.getUTCDay() | ||
| ) | ||
| const firstWeek = thisSunday - (WEEKS - 1) * WEEK_MS | ||
| const since = new Date(firstWeek).toISOString() | ||
| const totals = new Array<number>(WEEKS).fill(0) | ||
|
|
||
| for (let page = 1; page <= 20; page++) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not stop counting while commit pages remain. If the repository has more than 2,000 commits in the queried period, this loop stops after page 20.
|
||
| const res = await github( | ||
| `/commits?since=${since}&per_page=100&page=${page}` | ||
| ) | ||
| if (!res) return null | ||
| const commits = (await res.json()) as { | ||
| commit: { author: { date: string } | null } | ||
| }[] | ||
| for (const { commit } of commits) { | ||
| if (!commit.author) continue | ||
| const index = Math.floor( | ||
| (Date.parse(commit.author.date) - firstWeek) / WEEK_MS | ||
| ) | ||
| if (index >= 0 && index < WEEKS) totals[index] += 1 | ||
| } | ||
| if (commits.length < 100) break | ||
| } | ||
|
|
||
| // Start the chart at the first active week, so a young repo isn't mostly | ||
| // empty bars. | ||
| const firstActive = totals.findIndex((total) => total > 0) | ||
| const start = firstActive === -1 ? 0 : Math.min(firstActive, WEEKS - 8) | ||
|
|
||
| return totals.slice(start).map((total, index) => ({ | ||
| week: (firstWeek + (start + index) * WEEK_MS) / 1000, | ||
| total, | ||
| })) | ||
| } | ||
|
|
||
| export async function getSiteStats(): Promise<SiteStats> { | ||
| const categories = getCategoryCounts() | ||
| const [repo, contributors, weeks] = await Promise.all([ | ||
| getRepo(), | ||
| getContributorCount(), | ||
| getWeeklyCommits(), | ||
| ]) | ||
|
|
||
| return { | ||
| components: categories.reduce((sum, category) => sum + category.count, 0), | ||
| categories, | ||
| stars: repo?.stargazers_count ?? null, | ||
| forks: repo?.forks_count ?? null, | ||
| contributors, | ||
| commitsPastYear: weeks | ||
| ? weeks.reduce((sum, week) => sum + week.total, 0) | ||
| : null, | ||
| weeks, | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make weekly commit values available by keyboard.
The tooltip appears only on
group-hover. The bars cannot receive focus, and the alternative table is visually hidden. A keyboard-only visitor without a screen reader cannot inspect individual weekly totals. Add a keyboard-accessible way to reveal the values, such as a visible table option or focusable chart items with focus-triggered details. (w3.org)