feat(default): add real rankings data

This commit is contained in:
CaIon
2026-05-06 18:20:02 +08:00
parent 0f9f094a48
commit f8cf9c57c4
41 changed files with 1498 additions and 1912 deletions
+15
View File
@@ -0,0 +1,15 @@
import { api } from '@/lib/api'
import type { RankingPeriod, RankingsSnapshot } from './types'
type RankingsResponse = {
success: boolean
message?: string
data: RankingsSnapshot
}
export async function getRankings(
period: RankingPeriod
): Promise<RankingsResponse> {
const res = await api.get('/api/rankings', { params: { period } })
return res.data
}
@@ -1,97 +0,0 @@
import { ExternalLink, Rocket } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Badge } from '@/components/ui/badge'
import { formatTokens } from '../lib/format'
import type { AppListing } from '../types'
import { GrowthText } from './growth-text'
type AppsSectionProps = {
rows: AppListing[]
}
/**
* "Top Apps" card — clean two-column listing of the apps consuming the
* most tokens through new-api in the active period. Apps don't get a
* dedicated chart (each app has too much variance to plot meaningfully);
* instead we keep the focus on the leaderboard itself.
*/
export function AppsSection(props: AppsSectionProps) {
const { t } = useTranslation()
const half = Math.ceil(props.rows.length / 2)
const left = props.rows.slice(0, half)
const right = props.rows.slice(half)
return (
<section className='bg-card overflow-hidden rounded-lg border'>
<header className='px-5 py-4'>
<h2 className='text-foreground inline-flex items-center gap-2 text-base font-semibold'>
<Rocket className='text-primary size-4' />
{t('Top Apps')}
</h2>
<p className='text-muted-foreground mt-1 text-sm'>
{t('Apps using the most tokens through new-api')}
</p>
</header>
{props.rows.length === 0 ? (
<div className='text-muted-foreground/80 border-t px-5 py-8 text-center text-sm'>
{t('No apps match the selected filters')}
</div>
) : (
<div className='grid grid-cols-1 gap-x-8 border-t px-5 pt-3 pb-4 md:grid-cols-2'>
<AppList rows={left} />
{right.length > 0 && <AppList rows={right} />}
</div>
)}
</section>
)
}
function AppList(props: { rows: AppListing[] }) {
return (
<ul>
{props.rows.map((row) => (
<li key={row.name} className='flex items-center gap-3 py-2.5'>
<span className='text-muted-foreground/80 w-6 shrink-0 text-right font-mono text-xs tabular-nums'>
{row.rank}.
</span>
<span className='bg-muted text-muted-foreground inline-flex size-9 shrink-0 items-center justify-center rounded-md text-sm font-bold uppercase'>
{row.initial}
</span>
<div className='min-w-0 flex-1'>
<div className='flex items-center gap-2 text-sm font-semibold'>
{row.url ? (
<a
href={row.url}
target='_blank'
rel='noopener noreferrer'
className='text-foreground hover:text-primary inline-flex items-center gap-1 truncate transition-colors'
>
<span className='truncate'>{row.name}</span>
<ExternalLink className='text-muted-foreground/60 size-3 shrink-0' />
</a>
) : (
<span className='text-foreground truncate'>{row.name}</span>
)}
<Badge
variant='outline'
className='h-4 shrink-0 rounded-sm px-1 text-[10px] font-normal'
>
{row.category}
</Badge>
</div>
<p className='text-muted-foreground/80 truncate text-xs'>
{row.description}
</p>
</div>
<div className='shrink-0 text-right'>
<div className='text-foreground font-mono text-sm font-semibold tabular-nums'>
{formatTokens(row.total_tokens)}
</div>
<GrowthText value={row.growth_pct} className='text-[11px]' />
</div>
</li>
))}
</ul>
)
}
@@ -1,205 +0,0 @@
import { useMemo } from 'react'
import { VChart } from '@visactor/react-vchart'
import { useTranslation } from 'react-i18next'
import { useChartTheme } from '@/lib/use-chart-theme'
import { VCHART_OPTION } from '@/lib/vchart'
import { formatTokens } from '../lib/format'
import type { CategorySection as CategorySectionData } from '../types'
import { ModelLeaderboard } from './model-leaderboard'
const TOOLTIP_MAX_ROWS = 8
const MAX_LEADERBOARD_ROWS = 8
type CategorySectionProps = {
section: CategorySectionData
}
/**
* Per-category ranking unit: a compact stacked-bar chart of token usage
* over time paired with a 2-column leaderboard of the top models in that
* category. Renders as a self-contained card; the rankings page stacks
* one of these per category for quick browsing.
*/
export function CategorySection(props: CategorySectionProps) {
const { t } = useTranslation()
const { resolvedTheme, themeReady } = useChartTheme()
const orderedPoints = useMemo(() => {
const order = new Map(
props.section.models_history.models.map(
(m, idx) => [m.name, idx] as const
)
)
return [...props.section.models_history.points].sort((a, b) => {
const tsCmp = a.ts.localeCompare(b.ts)
if (tsCmp !== 0) return tsCmp
return (order.get(a.model) ?? 999) - (order.get(b.model) ?? 999)
})
}, [props.section.models_history])
const spec = useMemo(() => {
if (orderedPoints.length === 0) return null
return {
type: 'bar' as const,
data: [{ id: 'category-history', values: orderedPoints }],
xField: 'label',
yField: 'tokens',
seriesField: 'model',
stack: true,
bar: { style: { cornerRadius: 1 } },
legends: { visible: false },
axes: [
{
orient: 'bottom',
label: {
style: { fill: 'currentColor', fontSize: 9 },
autoHide: true,
autoLimit: true,
},
tick: { visible: false },
},
{
orient: 'left',
label: {
formatMethod: (val: number | string) => formatTokens(Number(val)),
style: { fill: 'currentColor', fontSize: 9 },
},
grid: { visible: true, style: { lineDash: [3, 3] } },
},
],
tooltip: {
mark: {
content: [
{
key: (datum: Record<string, unknown>) =>
String(datum?.model ?? ''),
value: (datum: Record<string, unknown>) =>
formatTokens(Number(datum?.tokens) || 0),
},
],
},
dimension: {
title: {
value: (datum: Record<string, unknown>) =>
String(datum?.label ?? ''),
},
content: [
{
key: (datum: Record<string, unknown>) =>
String(datum?.model ?? ''),
value: (datum: Record<string, unknown>) =>
Number(datum?.tokens) || 0,
},
],
updateContent: (
array: Array<{ key: string; value: string | number }>
) => {
array.sort((a, b) => Number(b.value) - Number(a.value))
const visible = array.slice(0, TOOLTIP_MAX_ROWS)
return visible.map((item) => ({
key: item.key,
value: formatTokens(Number(item.value) || 0),
}))
},
},
},
animationAppear: { duration: 400 },
}
}, [orderedPoints])
return (
<article
id={`category-${props.section.category}`}
className='bg-card scroll-mt-20 overflow-hidden rounded-lg border'
>
<header className='flex items-start justify-between gap-4 px-5 py-3.5'>
<div className='min-w-0 flex-1'>
<h3 className='text-foreground text-base font-semibold'>
{t(props.section.label)}
</h3>
<p className='text-muted-foreground/80 mt-0.5 truncate text-xs'>
{t(props.section.description)}
</p>
</div>
<div className='shrink-0 text-right'>
<div className='text-foreground font-mono text-base font-semibold tabular-nums'>
{formatTokens(props.section.total_tokens)}
</div>
<div className='text-muted-foreground/80 text-[10px] tracking-widest uppercase'>
{t('tokens')}
</div>
</div>
</header>
<div className='px-5 pb-4'>
<div className='h-44 sm:h-48'>
{themeReady && spec ? (
<VChart
key={`category-history-${props.section.category}-${resolvedTheme}`}
spec={{
...spec,
theme: resolvedTheme === 'dark' ? 'dark' : 'light',
background: 'transparent',
}}
option={VCHART_OPTION}
/>
) : (
<div className='text-muted-foreground/80 flex h-full items-center justify-center text-xs'>
{t('No history data available')}
</div>
)}
</div>
</div>
{props.section.models.length === 0 ? (
<div className='text-muted-foreground/80 border-t px-5 py-6 text-center text-sm'>
{t('No models match the selected filters')}
</div>
) : (
<div className='border-t px-5 pt-2 pb-4'>
<ModelLeaderboard
rows={props.section.models}
limit={MAX_LEADERBOARD_ROWS}
variant='compact'
/>
</div>
)}
</article>
)
}
type CategorySectionsProps = {
sections: CategorySectionData[]
}
/**
* Renders the per-category rankings strip (one card per category).
* Includes a strip header so users understand the page structure shifts
* from the global view to category drill-downs.
*/
export function CategorySections(props: CategorySectionsProps) {
const { t } = useTranslation()
if (props.sections.length === 0) return null
return (
<section className='space-y-5'>
<header className='space-y-1'>
<p className='text-muted-foreground text-[11px] font-medium tracking-widest uppercase'>
{t('By category')}
</p>
<h2 className='text-foreground text-xl font-semibold tracking-tight'>
{t('Browse rankings by category')}
</h2>
<p className='text-muted-foreground/80 max-w-2xl text-sm'>
{t('Discover the leading models in each domain')}
</p>
</header>
<div className='grid grid-cols-1 gap-5 lg:grid-cols-2'>
{props.sections.map((section) => (
<CategorySection key={section.category} section={section} />
))}
</div>
</section>
)
}
-2
View File
@@ -1,5 +1,3 @@
export * from './apps-section'
export * from './category-section'
export * from './entity-links'
export * from './growth-text'
export * from './market-share-section'
@@ -16,7 +16,7 @@ const PERIOD_DESCRIPTIONS: Record<RankingPeriod, string> = {
all: 'Token share by model author since launch',
}
/** Stable colour palette for vendors, used in both the area chart and the
/** Stable colour palette for vendors, used in both the share chart and the
* legend dots. Falls back to a neutral palette for unknown vendors so that
* future additions still render. */
const VENDOR_COLOURS: Record<string, string> = {
@@ -77,7 +77,7 @@ type MarketShareSectionProps = {
}
/**
* Combined "Market Share" card: a 100%-stacked area chart showing each
* Combined "Market Share" card: a 100%-stacked bar chart showing each
* vendor's slice of total token volume, paired below with a two-column
* vendor list.
*/
@@ -104,18 +104,15 @@ export function MarketShareSection(props: MarketShareSectionProps) {
const spec = useMemo(() => {
if (orderedPoints.length === 0) return null
return {
type: 'area' as const,
type: 'bar' as const,
data: [{ id: 'vendor-share', values: orderedPoints }],
xField: 'label',
yField: 'share',
seriesField: 'vendor',
stack: true,
paddingInner: 0.12,
legends: { visible: false },
area: {
style: { fillOpacity: 0.85, curveType: 'monotone' },
},
line: { style: { lineWidth: 0, curveType: 'monotone' } },
point: { visible: false },
bar: { style: { cornerRadius: 1 } },
color: { specified: colourMap },
axes: [
{
@@ -1,33 +1,28 @@
import {
ArrowDownRight,
ArrowUpRight,
Sparkles,
TrendingDown,
TrendingUp,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { getLobeIcon } from '@/lib/lobe-icon'
import { cn } from '@/lib/utils'
import { formatReleaseDate, formatTokens } from '../lib/format'
import type { NewModelEntry, RankingMover } from '../types'
import type { RankingMover } from '../types'
import { ModelLink, VendorLink } from './entity-links'
type PulseSectionProps = {
movers: RankingMover[]
droppers: RankingMover[]
newModels: NewModelEntry[]
}
/**
* Three-up "Pulse" panel: rank gainers, rank losers, and recently released
* models — the "what's changing" footer of the rankings page. Each card
* is intentionally compact so the trio fits in one row on desktop.
* Rank movement panel: gainers and losers calculated from the previous period.
*/
export function PulseSection(props: PulseSectionProps) {
const { t } = useTranslation()
return (
<section className='grid grid-cols-1 gap-4 lg:grid-cols-3'>
<section className='grid grid-cols-1 gap-4 lg:grid-cols-2'>
<PulseCard
title={t('Trending up')}
description={t('Models climbing the leaderboard')}
@@ -59,22 +54,6 @@ export function PulseSection(props: PulseSectionProps) {
</ul>
)}
</PulseCard>
<PulseCard
title={t('Newly released')}
description={t('Recently launched models')}
icon={<Sparkles className='size-4 text-amber-500' />}
>
{props.newModels.length === 0 ? (
<PulseEmpty label={t('No new models yet')} />
) : (
<ul>
{props.newModels.slice(0, 6).map((row) => (
<NewModelRow key={row.model_name} row={row} />
))}
</ul>
)}
</PulseCard>
</section>
)
}
@@ -145,28 +124,3 @@ function MoverRow(props: { row: RankingMover; intent: 'up' | 'down' }) {
</li>
)
}
function NewModelRow(props: { row: NewModelEntry }) {
return (
<li className='flex items-center gap-3 px-4 py-2'>
<span className='shrink-0'>{getLobeIcon(props.row.vendor_icon, 20)}</span>
<div className='min-w-0 flex-1'>
<ModelLink
modelName={props.row.model_name}
className='text-foreground block truncate font-mono text-xs font-medium'
>
{props.row.model_name}
</ModelLink>
<p className='text-muted-foreground/80 truncate text-[11px]'>
{formatReleaseDate(props.row.release_date)} ·{' '}
<VendorLink vendor={props.row.vendor}>
{props.row.vendor.toLowerCase()}
</VendorLink>
</p>
</div>
<span className='text-foreground shrink-0 font-mono text-xs font-semibold tabular-nums'>
{formatTokens(props.row.total_tokens)}
</span>
</li>
)
}
@@ -17,9 +17,7 @@ type RankingsHeroProps = {
/**
* Hero strip for the rankings page. Intentionally minimal — title +
* subtitle + period tabs only. Category filtering is no longer needed
* because every category is rendered inline as its own section further
* down the page.
* subtitle + period tabs only.
*/
export function RankingsHero(props: RankingsHeroProps) {
const { t } = useTranslation()
@@ -35,7 +33,7 @@ export function RankingsHero(props: RankingsHeroProps) {
</h1>
<p className='text-muted-foreground/80 max-w-2xl text-sm'>
{t(
'Discover the most-used models, top apps, and rising vendors on the platform updated continuously across every category.'
'Discover the most-used models and rising vendors on the platform, updated from live usage data.'
)}
</p>
</div>
+9 -13
View File
@@ -1,15 +1,11 @@
import { useMemo } from 'react'
import { buildRankingsSnapshot } from '../lib/mock-rankings'
import type { RankingPeriod, RankingsSnapshot } from '../types'
import { useQuery } from '@tanstack/react-query'
import { getRankings } from '../api'
import type { RankingPeriod } from '../types'
/**
* Memoised rankings snapshot for a period.
*
* Currently this synchronously builds deterministic mock data. When the
* backend ships real analytics endpoints, swap the body to a
* `useQuery`-based fetch — the consuming components don't care which side
* produced the data as long as it conforms to {@link RankingsSnapshot}.
*/
export function useRankings(period: RankingPeriod): RankingsSnapshot {
return useMemo(() => buildRankingsSnapshot(period), [period])
export function useRankings(period: RankingPeriod) {
return useQuery({
queryKey: ['rankings', period],
queryFn: () => getRankings(period),
staleTime: 5 * 60 * 1000,
})
}
+55 -30
View File
@@ -1,10 +1,9 @@
import { useNavigate, useSearch } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { Skeleton } from '@/components/ui/skeleton'
import { PublicLayout } from '@/components/layout'
import { PageTransition } from '@/components/page-transition'
import {
AppsSection,
CategorySections,
MarketShareSection,
ModelsSection,
PulseSection,
@@ -26,7 +25,8 @@ export function Rankings() {
? (search.period as RankingPeriod)
: 'week'
const snapshot = useRankings(period)
const rankingsQuery = useRankings(period)
const snapshot = rankingsQuery.data?.data
const handlePeriodChange = (next: RankingPeriod) => {
navigate({
@@ -56,37 +56,62 @@ export function Rankings() {
<PageTransition className='relative mx-auto w-full max-w-[1280px] space-y-8 px-3 pt-16 pb-10 sm:px-6 sm:pt-20 sm:pb-12 xl:px-8'>
<RankingsHero period={period} onPeriodChange={handlePeriodChange} />
{/* Overall (all-categories) view ----------------------------- */}
<ModelsSection
history={snapshot.models_history}
rows={snapshot.models}
period={period}
/>
{rankingsQuery.isLoading ? (
<RankingsLoading />
) : !snapshot ? (
<RankingsError
message={
rankingsQuery.error instanceof Error
? rankingsQuery.error.message
: t('Unable to load rankings data')
}
/>
) : (
<>
<ModelsSection
history={snapshot.models_history}
rows={snapshot.models}
period={period}
/>
<MarketShareSection
history={snapshot.vendor_share_history}
rows={snapshot.vendors}
period={period}
/>
<MarketShareSection
history={snapshot.vendor_share_history}
rows={snapshot.vendors}
period={period}
/>
<AppsSection rows={snapshot.apps} />
<PulseSection
movers={snapshot.top_movers}
droppers={snapshot.top_droppers}
newModels={snapshot.new_models}
/>
{/* Per-category drill-downs --------------------------------- */}
<CategorySections sections={snapshot.category_sections} />
<p className='text-muted-foreground/60 mx-auto max-w-3xl text-center text-[11px] leading-relaxed'>
{t(
'Ranking data is currently simulated for preview purposes and will be replaced with live analytics once the backend integration ships.'
)}
</p>
<PulseSection
movers={snapshot.top_movers}
droppers={snapshot.top_droppers}
/>
</>
)}
</PageTransition>
</div>
</PublicLayout>
)
}
function RankingsLoading() {
return (
<div className='space-y-6'>
<Skeleton className='h-[420px] w-full rounded-xl' />
<Skeleton className='h-[360px] w-full rounded-xl' />
<Skeleton className='h-[180px] w-full rounded-xl' />
</div>
)
}
function RankingsError(props: { message: string }) {
const { t } = useTranslation()
return (
<div className='bg-card rounded-xl border border-dashed px-6 py-12 text-center'>
<h2 className='text-foreground text-base font-semibold'>
{t('Unable to load rankings')}
</h2>
<p className='text-muted-foreground mx-auto mt-2 max-w-md text-sm'>
{props.message}
</p>
</div>
)
}
-1
View File
@@ -1,2 +1 @@
export * from './format'
export * from './mock-rankings'
File diff suppressed because it is too large Load Diff
+1 -80
View File
@@ -2,11 +2,7 @@
// Rankings types
// ----------------------------------------------------------------------------
//
// Shape of the data shown on the /rankings page. The backend has not yet
// implemented these analytics endpoints, so the helpers in
// `lib/mock-rankings.ts` produce deterministic mock values seeded from the
// (period, category) tuple. When the real APIs land, these types double as
// the response shape the UI expects.
// Shape of the real data shown on the /rankings page.
export type RankingPeriod = 'today' | 'week' | 'month' | 'year' | 'all'
@@ -24,13 +20,6 @@ export type RankingCategoryId =
| 'productivity'
| 'multimodal'
export type RankingCategory = {
id: RankingCategoryId
/** Default English label, fed through i18n at render time. */
label: string
description: string
}
export type ModelRanking = {
rank: number
/** Previous rank in the same period; undefined means "new". */
@@ -47,37 +36,6 @@ export type ModelRanking = {
growth_pct: number
}
export type AppCategory =
| 'Coding'
| 'Chat'
| 'Productivity'
| 'Education'
| 'Creative'
| 'Roleplay'
| 'Translation'
| 'Marketing'
| 'Health'
| 'Finance'
| 'Research'
| 'Other'
export type AppListing = {
rank: number
previous_rank?: number
name: string
description: string
category: AppCategory
url?: string
/** Total tokens this app sent through new-api in the period. */
total_tokens: number
/** Period-over-period change. */
growth_pct: number
/** Top model used by this app (model_name). */
top_model: string
/** Logo letter / initial. */
initial: string
}
export type VendorRanking = {
rank: number
vendor: string
@@ -102,17 +60,6 @@ export type RankingMover = {
growth_pct: number
}
export type NewModelEntry = {
model_name: string
vendor: string
vendor_icon?: string
category: RankingCategoryId
release_date: string
total_tokens: number
/** % growth since the model launched. */
growth_pct: number
}
/**
* One sample of a model's token usage at a given timestamp.
* Flat shape ready to feed VChart's stacked-bar spec.
@@ -158,42 +105,16 @@ export type VendorShareSeries = {
buckets: number
}
/**
* Self-contained ranking unit for a single category. Pairs the small
* stacked-bar chart with the leaderboard data it summarises so
* `<CategorySection>` can render both halves from one prop. Every
* category gets one of these rendered inline on the rankings page.
*/
export type CategorySection = {
category: RankingCategoryId
/** English source label, fed through i18n at render time. */
label: string
/** English source description, fed through i18n at render time. */
description: string
/** Top models in this category, ordered by total tokens desc. */
models: ModelRanking[]
/** Stacked-bar history of token usage by model in this category. */
models_history: ModelHistorySeries
/** Sum of all `models[].total_tokens` (cached for the section header). */
total_tokens: number
}
export type RankingsSnapshot = {
// Overall (all categories) ------------------------------------------------
models: ModelRanking[]
apps: AppListing[]
vendors: VendorRanking[]
/** Largest rank gainers in this period. */
top_movers: RankingMover[]
/** Largest rank losers in this period. */
top_droppers: RankingMover[]
/** Newly launched / recently added models. */
new_models: NewModelEntry[]
/** Stacked-bar history of token usage by model over the period. */
models_history: ModelHistorySeries
/** 100%-stacked area history of token share by vendor over the period. */
vendor_share_history: VendorShareSeries
// Per-category sections ---------------------------------------------------
/** Independent ranking sections, one per non-`all` category. */
category_sections: CategorySection[]
}