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 src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ const PLATFORM_ORIGINS_JSON = JSON.stringify([product.origin, `https://www.${pro
* React 往往还没水合,先在这里收下并派发事件,再由 embed-bridge.tsx 消费。
* 只认直接父窗口与产品主站的两个入口域名。
*/
const IFRAME_SCRIPT = `(function(){var d=document.documentElement,f=false;try{f=window.self!==window.top}catch(e){f=true}if(!f)return;d.classList.add('in-iframe');if(window.origin==='null')window.__cfBeacon={load:'single'};var O=${PLATFORM_ORIGINS_JSON};window.addEventListener('message',function(e){var m=e.data;if(e.source!==window.parent||!m||typeof m!=='object'||O.indexOf(e.origin)<0)return;if(m.themeMode==='light'||m.themeMode==='dark'){window.__embedTheme=m.themeMode;window.dispatchEvent(new Event('fishxcode:embed-theme'))}if(typeof m.lang==='string'){window.__embedLang=m.lang;window.dispatchEvent(new Event('fishxcode:embed-lang'))}})})();`;
const IFRAME_SCRIPT = `(function(){var d=document.documentElement,f=false;try{f=window.self!==window.top}catch(e){f=true}if(f&&(location.hostname==='localhost'||location.hostname==='127.0.0.1'))f=false;if(!f)return;d.classList.add('in-iframe');if(window.origin==='null')window.__cfBeacon={load:'single'};var O=${PLATFORM_ORIGINS_JSON};window.addEventListener('message',function(e){var m=e.data;if(e.source!==window.parent||!m||typeof m!=='object'||O.indexOf(e.origin)<0)return;if(m.themeMode==='light'||m.themeMode==='dark'){window.__embedTheme=m.themeMode;window.dispatchEvent(new Event('fishxcode:embed-theme'))}if(typeof m.lang==='string'){window.__embedLang=m.lang;window.dispatchEvent(new Event('fishxcode:embed-lang'))}})})();`;

/**
* 浏览器语言探测:只在站点根路径触发(已带语言前缀的路径不干预)。
Expand All @@ -104,7 +104,7 @@ const IFRAME_SCRIPT = `(function(){var d=document.documentElement,f=false;try{f=
* navigator.languages 顺序匹配——zh-TW/HK/MO/Hant 归繁体,其余 zh 归简体,
* 其他语言按前缀匹配;找不到就留在默认语言。
*/
const LOCALE_DETECTION_SCRIPT = `(function(){try{if(document.documentElement.classList.contains('in-iframe'))return;var L=${LOCALES_JSON},def=${DEFAULT_LOCALE_JSON},seg=location.pathname.split('/').filter(Boolean);if(seg.length&&L.indexOf(seg[0])>=0)return;if(location.pathname!=='/'&&location.pathname!=='')return;var pick=null;try{var s=localStorage.getItem('docs-lang');if(s&&L.indexOf(s)>=0)pick=s}catch(e){}if(!pick){var list=navigator.languages||[navigator.language||''];for(var i=0;i<list.length&&!pick;i++){var t=String(list[i]).toLowerCase().replace('_','-');if(t.indexOf('zh')===0){pick=/tw|hk|mo|hant/.test(t)&&L.indexOf('zh-TW')>=0?'zh-TW':L.indexOf('zh')>=0?'zh':null;continue}for(var j=0;j<L.length;j++){if(L[j]!==def&&t.indexOf(L[j].toLowerCase())===0){pick=L[j];break}}}}if(pick&&pick!==def)location.replace('/'+pick+'/'+location.search+location.hash)}catch(e){}})();`;
const LOCALE_DETECTION_SCRIPT = `(function(){try{if(location.hostname==='localhost'||location.hostname==='127.0.0.1')return;if(document.documentElement.classList.contains('in-iframe'))return;var L=${LOCALES_JSON},def=${DEFAULT_LOCALE_JSON},seg=location.pathname.split('/').filter(Boolean);if(seg.length&&L.indexOf(seg[0])>=0)return;if(location.pathname!=='/'&&location.pathname!=='')return;var pick=null;try{var s=localStorage.getItem('docs-lang');if(s&&L.indexOf(s)>=0)pick=s}catch(e){}if(!pick){var list=navigator.languages||[navigator.language||''];for(var i=0;i<list.length&&!pick;i++){var t=String(list[i]).toLowerCase().replace('_','-');if(t.indexOf('zh')===0){pick=/tw|hk|mo|hant/.test(t)&&L.indexOf('zh-TW')>=0?'zh-TW':L.indexOf('zh')>=0?'zh':null;continue}for(var j=0;j<L.length;j++){if(L[j]!==def&&t.indexOf(L[j].toLowerCase())===0){pick=L[j];break}}}}if(pick&&pick!==def)location.replace('/'+pick+'/'+location.search+location.hash)}catch(e){}})();`;

/** 静态导出下根布局无法按路由设置 <html lang>,首帧前按路径前缀同步 */
const HTML_LANG_SCRIPT = `(function(){try{var m=${HTML_LANG_JSON},s=location.pathname.split('/').filter(Boolean)[0];if(s&&m[s])document.documentElement.lang=m[s]}catch(e){}})();`;
Expand Down
279 changes: 279 additions & 0 deletions src/components/home/live-data.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from '@/components/app-link';
import type { HomeRedesignCopy } from '@/lib/home-redesign-copy';
import { localePath, type Locale } from '@/lib/i18n';
import { statusFamilyLabel } from '@/lib/status-copy';
import { FAMILY_ORDER, STATUS_DATA_ROUTES, toSnapshot, type StatusModel } from '@/lib/status';
import { container, Eyebrow, narrowHeadingClass, Phrases, TextLink } from './primitives';

interface PricingResponse {
data?: unknown[] | Record<string, unknown>;
vendors?: Array<{ id: number; name?: string }>;
}

interface PerfResponse {
data?: {
summary?: {
avg_latency_ms?: number;
success_rate?: number;
avg_tps?: number;
};
};
}

interface LiveData {
modelCount: number | null;
vendorCount: number | null;
successRate: number | null;
avgLatencyMs: number | null;
avgTps: number | null;
models: StatusModel[];
}

const EMPTY: LiveData = {
modelCount: null,
vendorCount: null,
successRate: null,
avgLatencyMs: null,
avgTps: null,
models: [],
};

const STATE_ORDER = ['ok', 'warn', 'bad', 'unknown'] as const;
type ModelState = (typeof STATE_ORDER)[number];

const STATE_COLOR: Record<ModelState, string> = {
ok: 'bg-[#1D9E75]',
warn: 'bg-[#BA7517]',
bad: 'bg-[#E24B4A]',
unknown: 'bg-fd-border',
};

function countStates(models: StatusModel[]): Record<ModelState, number> {
const counts: Record<ModelState, number> = { ok: 0, warn: 0, bad: 0, unknown: 0 };
for (const model of models) counts[model.state in counts ? model.state : 'unknown'] += 1;
return counts;
}

async function readJson<T>(url: string, signal: AbortSignal): Promise<T> {
const response = await fetch(url, { headers: { Accept: 'application/json' }, cache: 'no-store', signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<T>;
}

function formatLatency(ms: number | null, lang: Locale): string {
if (ms === null || !Number.isFinite(ms)) return '—';
if (ms >= 1000) return `${new Intl.NumberFormat(lang, { maximumFractionDigits: 1 }).format(ms / 1000)}s`;
return `${Math.round(ms)}ms`;
}

/** 首屏数据带与可靠性区块:全部从公开接口读取,失败时显示占位符而不写死假数据 */
export function LiveMetricsSections({ lang, redesign }: { lang: Locale; redesign: HomeRedesignCopy }) {
const [data, setData] = useState<LiveData>(EMPTY);
const [active, setActive] = useState<StatusModel | null>(null);
const [loadState, setLoadState] = useState<'loading' | 'ready' | 'error'>('loading');
const [reloadKey, setReloadKey] = useState(0);

useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
setLoadState('loading');

Check warning on line 82 in src/components/home/live-data.tsx

View workflow job for this annotation

GitHub Actions / check

react(set-state-in-effect)

src/components/home/live-data.tsx:82:5: Calling setState synchronously within an effect can trigger cascading renders

Promise.all([
readJson<PricingResponse>(STATUS_DATA_ROUTES.pricing, signal),
readJson<unknown>(STATUS_DATA_ROUTES.overview, signal),
readJson<PerfResponse>(`${STATUS_DATA_ROUTES.perfSummary}?hours=24`, signal),
])
.then(([pricing, statusPayload, perf]) => {
const models = Array.isArray(pricing.data)
? pricing.data
: pricing.data && typeof pricing.data === 'object'
? Object.values(pricing.data)
: [];
const vendorIds = new Set(
models
.map((model) => (model as { vendor_id?: number }).vendor_id)
.filter((id): id is number => typeof id === 'number'),
);
const snapshot = toSnapshot(statusPayload, Date.now());
const liveModels = snapshot?.models ?? [];
setData({
modelCount: models.length || null,
vendorCount: pricing.vendors?.length || vendorIds.size || null,
successRate: perf.data?.summary?.success_rate ?? null,
avgLatencyMs: perf.data?.summary?.avg_latency_ms ?? null,
avgTps: perf.data?.summary?.avg_tps ?? null,
models: liveModels,
});
setActive(liveModels[0] ?? null);
setLoadState('ready');
})
.catch(() => {
if (!signal.aborted) {
setData(EMPTY);
setActive(null);
setLoadState('error');
}
});

return () => controller.abort();
}, [reloadKey]);

const counts = useMemo(() => countStates(data.models), [data.models]);
const families = useMemo(
() =>
FAMILY_ORDER.map((family) => ({
family,
models: data.models.filter((model) => model.family === family),
})).filter((entry) => entry.models.length > 0),
[data.models],
);

const { stats, reliability, status } = redesign;
const values = [
data.modelCount === null ? '—' : new Intl.NumberFormat(lang).format(data.modelCount),
data.vendorCount === null ? '—' : new Intl.NumberFormat(lang).format(data.vendorCount),
data.successRate === null ? '—' : `${data.successRate.toFixed(2)}%`,
formatLatency(data.avgLatencyMs, lang),
];

const activeIndex = active ? STATE_ORDER.indexOf(active.state as ModelState) : -1;
const activeLabel = activeIndex >= 0 ? status.legend[activeIndex] : '';
const activeDetail =
loadState === 'loading'
? status.loading
: loadState === 'error'
? status.error
: active
? `${active.model} · ${activeLabel} · 24h ${active.successRate === null ? '—' : `${active.successRate.toFixed(0)}%`} · ${formatLatency(active.latency, lang)}`
: status.note;

return (
<>
<section className="bg-ink text-white">
<div className={`${container} grid grid-cols-2 divide-x divide-y divide-white/15 md:grid-cols-4 md:divide-y-0`}>
{stats.map((stat, index) => (
<div key={stat.label} className="px-6 py-8">
<p className="text-xs text-white/60">{stat.label}</p>
{loadState === 'loading' ? (
<span aria-hidden="true" className="mt-4 block h-8 w-16 animate-pulse rounded bg-white/20" />
) : (
<p className="mt-3 text-3xl font-semibold tracking-tight">{values[index]}</p>
)}
</div>
))}
</div>
</section>

<section className="py-20 md:py-28">
<div className={`${container} grid gap-12 lg:grid-cols-12 lg:gap-16`}>
<div className="lg:col-span-5">
<Eyebrow>{reliability.eyebrow}</Eyebrow>
<h2 className={narrowHeadingClass}>
<Phrases text={reliability.title} />
</h2>
<p className="mt-5 text-pretty text-fd-muted-foreground md:text-lg">{reliability.description}</p>
<div className="mt-8">
<TextLink href={localePath(lang, '/status')}>{reliability.linkLabel}</TextLink>
</div>
</div>

<div className="rounded-xl border border-fd-border bg-paper p-6 lg:col-span-7">
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="font-semibold">{status.title}</h3>
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-fd-muted-foreground">
{status.legend.map((item, index) => {
const key = STATE_ORDER[index];
return (
<li key={item} className="inline-flex items-center gap-1.5">
<span
aria-hidden="true"
className={`size-2 rounded-full ${STATE_COLOR[key]}`}
/>
{item} {loadState === 'ready' ? new Intl.NumberFormat(lang).format(counts[key]) : '—'}
</li>
);
})}
</ul>
</div>

{loadState === 'loading' ? (
<div className="mt-6 space-y-3" aria-hidden="true">
{Array.from({ length: 5 }, (_, row) => (
<div key={row} className="grid grid-cols-[5.5rem_minmax(0,1fr)] items-center gap-3">
<span className="h-3 w-16 animate-pulse rounded bg-fd-muted" />
<div className="flex gap-1.5">
{Array.from({ length: 14 }, (_, cell) => (
<span key={cell} className="size-2.5 animate-pulse rounded-sm bg-fd-muted" />
))}
</div>
</div>
))}
</div>
) : loadState === 'error' ? (
<div className="mt-6 rounded-lg border border-fd-border bg-fd-muted/40 p-5 text-center">
<p className="text-xs text-fd-muted-foreground">{status.error}</p>
<button
type="button"
onClick={() => setReloadKey((key) => key + 1)}
className="mt-3 rounded-md border border-fd-border px-3 py-1.5 text-xs hover:border-brand/50 hover:text-brand focus-visible:ring-2 focus-visible:ring-fd-ring focus-visible:outline-none"
>
{status.retry}
</button>
</div>
) : families.length > 0 ? (
<div className="mt-6 space-y-3">
{families.map(({ family, models: list }) => {
const familyHref = localePath(lang, `/status/${family}`);
return (
<div key={family} className="grid grid-cols-[5.5rem_minmax(0,1fr)] items-center gap-3">
<Link
href={familyHref}
className="truncate rounded-sm text-xs text-fd-muted-foreground hover:text-brand focus-visible:ring-2 focus-visible:ring-fd-ring focus-visible:outline-none"
>
{statusFamilyLabel(lang, family)}
</Link>
<div className="flex flex-wrap gap-1.5">
{list.map((model) => {
const index = STATE_ORDER.indexOf(model.state as ModelState);
const label = index >= 0 ? status.legend[index] : '';
const title = `${model.model} · ${label} · ${formatLatency(model.latency, lang)}`;
const modelHref = localePath(lang, `/status/model/${encodeURIComponent(model.model)}`);
return (
<Link
key={model.model}
href={modelHref}
title={title}
aria-label={title}
onMouseEnter={() => setActive(model)}
onFocus={() => setActive(model)}
className={`block size-2.5 rounded-sm transition-opacity focus-visible:ring-2 focus-visible:ring-fd-ring focus-visible:outline-none ${STATE_COLOR[model.state as ModelState] ?? STATE_COLOR.unknown} ${active?.model === model.model ? 'ring-1 ring-fd-foreground' : ''}`}
/>
);
})}
</div>
</div>
);
})}
</div>
) : (
<div className="mt-6 h-24 rounded-lg border border-fd-border bg-fd-muted/40" />
)}

<div className="mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-fd-border pt-4">
<p className="text-xs text-fd-muted-foreground">{activeDetail}</p>
<TextLink href={localePath(lang, '/status')}>{reliability.linkLabel}</TextLink>
</div>
{data.avgTps !== null ? (
<p className="mt-2 text-xs text-fd-muted-foreground">
{new Intl.NumberFormat(lang, { maximumFractionDigits: 1 }).format(data.avgTps)} TPS
</p>
) : null}
</div>
</div>
</section>
</>
);
}
Loading
Loading