From 39f610c5f2a966a137e737d30f19c89ae146745d Mon Sep 17 00:00:00 2001 From: Nexmoe <16796652+nexmoe@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:47:37 +0800 Subject: [PATCH 1/2] Redesign the LMSpeed Models catalog directories --- apps/site/src/components/Catalogue.astro | 197 +- .../src/components/DevelopersDirectory.astro | 39 + apps/site/src/components/Directory.astro | 48 + apps/site/src/components/DirectoryLinks.astro | 11 + apps/site/src/components/HelpDialog.astro | 85 + apps/site/src/components/Icon.astro | 10 + apps/site/src/components/LocaleLinks.astro | 11 + apps/site/src/components/Logo.astro | 10 + .../site/src/components/ModelsDirectory.astro | 255 +-- .../src/components/ProvidersDirectory.astro | 123 +- apps/site/src/components/TableHead.astro | 19 + apps/site/src/lib/catalogue-controls.ts | 517 ++++-- apps/site/src/lib/catalogue.ts | 117 +- apps/site/src/lib/details.ts | 479 +++++ apps/site/src/lib/directory-data.ts | 69 + apps/site/src/lib/element.ts | 8 + apps/site/src/lib/glyphs.ts | 16 + apps/site/src/lib/markdown.ts | 2 +- apps/site/src/lib/search-controls.ts | 200 ++ apps/site/src/lib/table-controls.ts | 86 + apps/site/src/messages/en.json | 83 +- apps/site/src/messages/ru.json | 83 +- apps/site/src/messages/zh.json | 83 +- apps/site/src/pages/404.astro | 17 +- apps/site/src/pages/[...directory].astro | 14 + apps/site/src/pages/index.astro | 4 - apps/site/src/pages/llms-full.txt.ts | 4 +- apps/site/src/pages/ru/index.astro | 4 - apps/site/src/pages/search.json.ts | 3 + apps/site/src/pages/sitemap.xml.ts | 27 +- apps/site/src/pages/zh/index.astro | 4 - apps/site/src/styles/catalogue.css | 1613 ++++++++++++----- apps/site/wrangler.jsonc | 2 +- scripts/validate-artifacts.ts | 96 +- tests/site.spec.ts | 313 +++- 35 files changed, 3505 insertions(+), 1147 deletions(-) create mode 100644 apps/site/src/components/DevelopersDirectory.astro create mode 100644 apps/site/src/components/Directory.astro create mode 100644 apps/site/src/components/DirectoryLinks.astro create mode 100644 apps/site/src/components/HelpDialog.astro create mode 100644 apps/site/src/components/Icon.astro create mode 100644 apps/site/src/components/LocaleLinks.astro create mode 100644 apps/site/src/components/Logo.astro create mode 100644 apps/site/src/components/TableHead.astro create mode 100644 apps/site/src/lib/details.ts create mode 100644 apps/site/src/lib/directory-data.ts create mode 100644 apps/site/src/lib/element.ts create mode 100644 apps/site/src/lib/glyphs.ts create mode 100644 apps/site/src/lib/search-controls.ts create mode 100644 apps/site/src/lib/table-controls.ts create mode 100644 apps/site/src/pages/[...directory].astro delete mode 100644 apps/site/src/pages/index.astro delete mode 100644 apps/site/src/pages/ru/index.astro create mode 100644 apps/site/src/pages/search.json.ts delete mode 100644 apps/site/src/pages/zh/index.astro diff --git a/apps/site/src/components/Catalogue.astro b/apps/site/src/components/Catalogue.astro index d459bb30..f6306e54 100644 --- a/apps/site/src/components/Catalogue.astro +++ b/apps/site/src/components/Catalogue.astro @@ -1,131 +1,130 @@ --- import '@fontsource-variable/noto-sans'; -import { catalog } from '@lmspeed/models-publish'; -import { - type Locale, - localePath, - locales, - messages, - siteUrl, -} from '../lib/catalogue'; +import { type Locale, localePath, locales, markdownPath, messages, type Section, siteUrl } from '../lib/catalogue'; +import { glyphs } from '../lib/glyphs'; import '../styles/catalogue.css'; +import DevelopersDirectory from './DevelopersDirectory.astro'; +import DirectoryLinks from './DirectoryLinks.astro'; +import HelpDialog from './HelpDialog.astro'; +import Icon from './Icon.astro'; +import LocaleLinks from './LocaleLinks.astro'; import ModelsDirectory from './ModelsDirectory.astro'; import ProvidersDirectory from './ProvidersDirectory.astro'; interface Props { - locale?: Locale; + locale: Locale; + section: Section; } -const { locale = 'en' } = Astro.props; +const { locale, section } = Astro.props; const t = messages[locale]; -const canonical = `${siteUrl}${localePath(locale)}`; -const counts = catalog.api.counts; -const snippets = { - HTTP: `curl ${siteUrl}/v2/models/openai/gpt-5.json -curl ${siteUrl}/v2/providers/openai.json -curl ${siteUrl}/v2/api.json`, - 'JavaScript / TypeScript': `import { Client } from '@lmspeed/models'; - -const client = new Client(); -const model = await client.fetchModel('openai/gpt-5'); -const provider = await client.fetchProvider('openai'); -const catalog = await client.refresh();`, -}; +const canonical = `${siteUrl}${localePath(locale, section)}`; +const title = `${section === 'models' ? t.title : t[section]} · LMSpeed Models`; +const description = section === 'models' ? t.description : `${t[section]} · ${t.description}`; +const ogLocales = { en: 'en_US', zh: 'zh_CN', ru: 'ru_RU' }; +const github = 'https://github.com/LMSpeed/models'; --- - - {t.title} · LMSpeed - - - + + + {title} + + + + + + + {locales.filter(language => language !== locale).map(language => )} - - {locales.map(language => )} - + + {locales.map(language => )} + + -
-
-
-

{t.title}

-

{t.description}

-
- ↓ {t.download} -
-
- {counts.models.toLocaleString(locale)} {t.showing} - {counts.developers.toLocaleString(locale)} {t.developersCount} - {catalog.api.buildHash.slice(0, 12)} + {section === 'models' && } + {section === 'providers' && } + {section === 'developers' && } + + +

{t.searchAction}

+
+ + + +
-
- - - +
+

+
+ +
+
+ ↑ ↓ {t.navigate} + ↵ {t.select} + Esc {t.dismiss}
-
-
-

{t.readDocs}

-

{t.docsDescription}

-
+ + + + +
+ + +
+
+ + + + GitHub + +
+
+ + +
+ + + +
+
+
+ +

{t.loading}

+
-
- {Object.entries(snippets).map(([language, code]) => ( -
- {language} -
{code}
-
- ))} -
- -
- + diff --git a/apps/site/src/components/DevelopersDirectory.astro b/apps/site/src/components/DevelopersDirectory.astro new file mode 100644 index 00000000..0231392a --- /dev/null +++ b/apps/site/src/components/DevelopersDirectory.astro @@ -0,0 +1,39 @@ +--- +import { detailPath, displayNumber, type Locale, messages, missing } from '../lib/catalogue'; +import { developers } from '../lib/directory-data'; +import Directory from './Directory.astro'; +import Logo from './Logo.astro'; +import TableHead from './TableHead.astro'; + +interface Props { locale: Locale } +const { locale } = Astro.props; +const t = messages[locale]; +const sorted = [...developers].sort((a, b) => a.name.localeCompare(b.name, locale, { numeric: true })); +--- + + + + {sorted.map(developer => { + const { id, name, icon, description, counts, released } = developer; + const href = detailPath(locale, 'developer', id); + return ( + + + + + {displayNumber(counts.models, locale)} + {displayNumber(counts.providers, locale)} + {displayNumber(counts.open, locale)} + {released ?? missing} + {description ?? missing} + + ); + })} + + diff --git a/apps/site/src/components/Directory.astro b/apps/site/src/components/Directory.astro new file mode 100644 index 00000000..ae59d4a5 --- /dev/null +++ b/apps/site/src/components/Directory.astro @@ -0,0 +1,48 @@ +--- +import { displayNumber, type Locale, messages, type Section } from '../lib/catalogue'; +import Icon from './Icon.astro'; + +interface Props { + locale: Locale; + section: Section; + count: number; +} +const { locale, section, count } = Astro.props; +const t = messages[locale]; +const filter = { models: t.filterModels, providers: t.filterProviders, developers: t.filterDevelopers }[section]; +--- +
+

{t[section]}

+
+
+

+ {displayNumber(count, locale)} {t[`${section}Label`]} +

+ + + +
+ + + +
+ + + + +
{t[section]}
+ +
+ +
diff --git a/apps/site/src/components/DirectoryLinks.astro b/apps/site/src/components/DirectoryLinks.astro new file mode 100644 index 00000000..10313007 --- /dev/null +++ b/apps/site/src/components/DirectoryLinks.astro @@ -0,0 +1,11 @@ +--- +import { type Locale, localePath, messages, type Section, sections } from '../lib/catalogue'; + +interface Props { locale: Locale; section: Section } +const { locale, section } = Astro.props; +--- + diff --git a/apps/site/src/components/HelpDialog.astro b/apps/site/src/components/HelpDialog.astro new file mode 100644 index 00000000..e4e1667b --- /dev/null +++ b/apps/site/src/components/HelpDialog.astro @@ -0,0 +1,85 @@ +--- +import { type Locale, messages, siteUrl } from '../lib/catalogue'; +import Icon from './Icon.astro'; + +interface Props { locale: Locale } +const { locale } = Astro.props; +const t = messages[locale]; +const snippets = [ + ['API', `curl ${siteUrl}/v2/api.json +curl ${siteUrl}/v2/providers/openai.json +curl ${siteUrl}/v2/models/openai/gpt-5.json`], + ['JavaScript', `npm install @lmspeed/models@0.2.0`, +`import { Client } from '@lmspeed/models'; + +const client = new Client(); +const model = await client.fetchModel('openai/gpt-5'); +const provider = await client.fetchProvider('openai');`], + ['Python', `pip install lmspeed-models==0.2.0`, +`from lmspeed_models import Client + +with Client() as client: + model = client.fetch_model("openai/gpt-5") + provider = client.fetch_provider("openai")`], + ['Rust', `cargo add lmspeed-models@0.2.0`, +`use lmspeed_models::{Client, DEFAULT_URL}; +use std::time::Duration; + +let client = Client::new(DEFAULT_URL, Duration::from_secs(30))?; +let model = client.fetch_model("openai/gpt-5").await?; +let provider = client.fetch_provider("openai").await?;`], + ['Go', `go get github.com/lmspeed/models/sdk/go@v0.2.0`, +`package main + +import ( + "context" + "log" + + models "github.com/lmspeed/models/sdk/go" +) + +func main() { + client := models.NewClient(models.DefaultURL) + card, err := client.FetchModel(context.Background(), "openai/gpt-5") + if err != nil { + log.Fatal(err) + } + provider, err := client.FetchProvider(context.Background(), "openai") + if err != nil { + log.Fatal(err) + } + log.Println(card, provider) +}`], +]; +--- + +
+

{t.docs}

+ +
+
+

{t.docsDescription}

+
+ {snippets.map(([label], index) => ( + + ))} +
+ {snippets.map(([, ...codes], index) => ( + + ))} +
+ +
diff --git a/apps/site/src/components/Icon.astro b/apps/site/src/components/Icon.astro new file mode 100644 index 00000000..3281a214 --- /dev/null +++ b/apps/site/src/components/Icon.astro @@ -0,0 +1,10 @@ +--- +import type { glyphs } from '../lib/glyphs'; + +interface Props { + name: keyof typeof glyphs; + size?: number; +} +const { name, size = 16 } = Astro.props; +--- + diff --git a/apps/site/src/components/LocaleLinks.astro b/apps/site/src/components/LocaleLinks.astro new file mode 100644 index 00000000..7274df68 --- /dev/null +++ b/apps/site/src/components/LocaleLinks.astro @@ -0,0 +1,11 @@ +--- +import { type Locale, localeLabels, localePath, locales, messages, type Section } from '../lib/catalogue'; + +interface Props { locale: Locale; section: Section } +const { locale, section } = Astro.props; +--- + diff --git a/apps/site/src/components/Logo.astro b/apps/site/src/components/Logo.astro new file mode 100644 index 00000000..1b40ac59 --- /dev/null +++ b/apps/site/src/components/Logo.astro @@ -0,0 +1,10 @@ +--- +import { logoUrl } from '../lib/catalogue'; + +interface Props { + icon?: string; + size: number; +} +const { icon, size } = Astro.props; +--- + diff --git a/apps/site/src/components/ModelsDirectory.astro b/apps/site/src/components/ModelsDirectory.astro index c6dd59bd..33e18bdd 100644 --- a/apps/site/src/components/ModelsDirectory.astro +++ b/apps/site/src/components/ModelsDirectory.astro @@ -1,183 +1,116 @@ --- -import { catalog, logoPath } from '@lmspeed/models-publish'; -import { - catalogueRows, - displayNumber, - type Locale, - messages, - modelModalities, - modelPath, -} from '../lib/catalogue'; +import { catalog } from '@lmspeed/models-publish'; +import { booleanText, detailPath, developerId, displayNumber, formatCost, type Locale, messages, missing, modelModalities, parametersText } from '../lib/catalogue'; +import { aliasesByModel, developers, modelPrices, models } from '../lib/directory-data'; +import Directory from './Directory.astro'; +import Icon from './Icon.astro'; +import Logo from './Logo.astro'; +import TableHead from './TableHead.astro'; -interface Props { - locale: Locale; -} +interface Props { locale: Locale } const { locale } = Astro.props; const t = messages[locale]; -const models = catalogueRows(catalog.modelCards); -const types = [...new Set(models.map(({ type }) => type))].sort(); -const modalities = [...new Set(models.flatMap(modelModalities))].sort(); -const developers = Object.entries(catalog.models.developers).sort( - ([, a], [, b]) => a.name.localeCompare(b.name, locale), -); -const columns = [ - ['name', t.model], - ['developerName', t.developer], - ['type', t.type], - ['', t.modality], - ['context', t.limits], - ['parameters', t.parameters], - ['', t.benchmarks], - ['providerCount', t.providers], - ['released', t.released], -] as const; -const aliasesByModel = new Map(); -for (const [alias, id] of Object.entries(catalog.models.aliases)) { - const aliases = aliasesByModel.get(id) ?? []; - aliases.push(alias); - aliasesByModel.set(id, aliases); -} +const types = [...new Set(models.map(({ type }) => type))].sort((a, b) => t.types[a].localeCompare(t.types[b], locale)); +const modalityLabels = { text: t.text, image: t.modalityImage, audio: t.modalityAudio, video: t.modalityVideo, pdf: t.pdf, embedding: t.types.embedding, reranking: t.types.reranking, decision: t.types.decision }; +type Modality = keyof typeof modalityLabels; +const mainModalities = ['text', 'image', 'audio', 'video', 'pdf'] as const; +const actualModalities = [...new Set(models.flatMap(modelModalities))].sort(); +const quickTypes = ['chat', 'image', 'video', 'audio', 'embedding'] as const; +const orderedDevelopers = [...developers].sort((a, b) => a.name.localeCompare(b.name, locale)); --- - -
- -
-
- - - ⌘/Ctrl K -
-
+ + + + + + + + + {models.map((model) => { + const id = developerId(model.id); + const developer = catalog.models.developers[id]; + const modalities = modelModalities(model); + const weights = model.open_weights === undefined ? undefined : model.open_weights ? 'open' : 'closed'; + const price = modelPrices.get(model.id); + const href = detailPath(locale, 'model', model.id); + const rate = price?.input === undefined && price?.output === undefined ? missing : `${formatCost(price.input)} / ${formatCost(price.output)}`; + const tools = booleanText(model.capabilities.tools?.supported, locale); + const reasoning = booleanText(model.capabilities.reasoning?.supported, locale); + return ( + + + + {model.name} + {model.id} + + + + + + {developer.name} + + + {displayNumber(model.providers.length, locale)} + {parametersText(model.parameters, locale)} + {displayNumber(model.limit?.context, locale)} + {displayNumber(model.limit?.output, locale)} + modalityLabels[value as Modality] ?? value).sort().join(' ') || undefined}> +
+ {mainModalities.filter(modality => modalities.includes(modality)).map(modality => ( + + ))} + {modalities.filter(value => !mainModalities.some(modality => modality === value)).map(value => ( + {value.slice(0, 1).toUpperCase()} + ))} + {modalities.length === 0 && missing} +
+ + {tools} + {reasoning} + + {weights === 'open' ? {t.openLabel} : weights ? t.closedLabel : missing} + + {rate} + {model.release_date ?? missing} + + ); + })} + + diff --git a/apps/site/src/components/ProvidersDirectory.astro b/apps/site/src/components/ProvidersDirectory.astro index 1e3a4b75..ac4218a8 100644 --- a/apps/site/src/components/ProvidersDirectory.astro +++ b/apps/site/src/components/ProvidersDirectory.astro @@ -1,90 +1,45 @@ --- -import { catalog, logoPath } from '@lmspeed/models-publish'; -import { - type Locale, - messages, - providerEndpoints, - providerPath, - providerPrice, -} from '../lib/catalogue'; +import { catalog } from '@lmspeed/models-publish'; +import { detailPath, displayNumber, type Locale, messages, missing, publicLink } from '../lib/catalogue'; +import { providers } from '../lib/directory-data'; +import Directory from './Directory.astro'; +import Icon from './Icon.astro'; +import Logo from './Logo.astro'; +import TableHead from './TableHead.astro'; -interface Props { - locale: Locale; -} +interface Props { locale: Locale } const { locale } = Astro.props; const t = messages[locale]; -const providers = Object.values(catalog.providerShards).sort( - (a, b) => a.name.localeCompare(b.name, locale) || a.id.localeCompare(b.id), -); -const priceNumber = new Intl.NumberFormat(locale, { - style: 'currency', - currency: 'USD', - currencyDisplay: 'narrowSymbol', - maximumSignificantDigits: 10, -}); -type Unit = 'token' | 'character' | 'image' | 'megapixel' | 'second' | 'minute'; -function rate(price: number, unit: Unit = 'token') { - const scale = unit === 'token' || unit === 'character' ? '1M ' : ''; - return `${priceNumber.format(price)} / ${scale}${t[unit]}`; -} +const sorted = [...providers].sort((a, b) => a.name.localeCompare(b.name, locale, { numeric: true })); --- - -
- -
- - - - - - - - + + + + {sorted.map((provider) => { + const listing = catalog.providerShards[provider.id]; + const endpoint = listing.api ?? Object.values(listing.models).flatMap(model => Object.values(model.api ?? {})).find(api => api.base_url)?.base_url; + const sdk = listing.npm === 'none' ? undefined : listing.npm; + const docs = publicLink(provider.doc); + const href = detailPath(locale, 'provider', provider.id); + const types = provider.types.map(type => t.types[type]); + return ( + + + + + + + - - - {providers.map(provider => { - const endpoints = providerEndpoints(provider); - const price = providerPrice(provider); - const count = catalog.index.providers[provider.id].modelCount; - return ( - - - - - - - ); - })} - -
{t.providers}
{t.providers}{t.models}{t.endpoints}{t.pricing}
+ + {displayNumber(provider.modelCount, locale)}
{types.length ? types.map(type => {type}) : missing}
{endpoint ?? missing}{sdk ?? missing}{docs ? {t.docsLink} : missing}
-
- -
- {provider.name} - {provider.id} -
-
-
{count.toLocaleString(locale)} - {endpoints.length ? endpoints.map(endpoint => {endpoint}) : '—'} - {provider.doc?.startsWith('https://') && {t.docs} ↗} - - {price ? ( - <> - {price.name}{price.kind === 'modality' && ` · ${price.modality}`} - {price.kind === 'search' - ? {priceNumber.format(price.search)} / 1,000 {t.searches} - : <> - {price.input && {t.input}: {rate(price.input.price, price.input.unit)}} - {price.output && {t.output}: {rate(price.output.price, price.output.unit)}} - } - - ) : '—'} -
-
- -
+ ); + })} + + diff --git a/apps/site/src/components/TableHead.astro b/apps/site/src/components/TableHead.astro new file mode 100644 index 00000000..e75dfd6b --- /dev/null +++ b/apps/site/src/components/TableHead.astro @@ -0,0 +1,19 @@ +--- +interface Props { + columns: [string, string, type?: 'number' | 'date', title?: string][]; + initial: string; + descending?: boolean; +} +const { columns, initial, descending } = Astro.props; +--- + + + {columns.map(([key, label, type, title]) => ( + + + + ))} + + diff --git a/apps/site/src/lib/catalogue-controls.ts b/apps/site/src/lib/catalogue-controls.ts index 809d78af..1089766c 100644 --- a/apps/site/src/lib/catalogue-controls.ts +++ b/apps/site/src/lib/catalogue-controls.ts @@ -1,186 +1,375 @@ -const modelsTab = document.querySelector('#models-tab'); -const providersTab = - document.querySelector('#providers-tab'); -const modelsPanel = document.querySelector('#models'); -const providersPanel = document.querySelector('#providers'); - -if (modelsTab && providersTab && modelsPanel && providersPanel) { - const tabs = [modelsTab, providersTab]; - const panels = [modelsPanel, providersPanel]; - let active = location.hash === '#providers' ? 1 : 0; - const selectTab = (index: number) => { - active = index; - for (const [position, tab] of tabs.entries()) { - const selected = index === position; - tab.setAttribute('aria-selected', String(selected)); - tab.tabIndex = selected ? 0 : -1; - panels[position].hidden = !selected; - } - }; - for (const [index, tab] of tabs.entries()) { - tab.addEventListener('click', (event) => { - if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) - return; - event.preventDefault(); - selectTab(index); - if (location.hash !== tab.hash) history.pushState(null, '', tab.hash); - }); - tab.addEventListener('keydown', (event) => { - const next = { - ArrowLeft: 1 - index, - ArrowRight: 1 - index, - Home: 0, - End: 1, - }[event.key]; - if (next === undefined && event.key !== ' ') return; - event.preventDefault(); - const target = tabs[next ?? index]; - target.focus(); - target.click(); - }); +import { + type DetailKind, + detailKinds, + type Locale, + messages, + modelPath, + providerPath, +} from './catalogue'; +import { + renderDeveloper, + renderModel, + renderProvider, + setupProviderListings, +} from './details'; +import { element } from './element'; +import { loadSearchIndex, logoImage, setupSearch } from './search-controls'; +import { setupFilter, setupTable } from './table-controls'; + +const locale = document.documentElement.lang as Locale; +const t = messages[locale]; +const dialogs = Array.from(document.querySelectorAll('dialog')); +const drawer = element(document, '#detail-dialog'); +const detailKind = element(document, '#detail-kind'); +const detailTitle = element(document, '#detail-title'); +const detailId = element(document, '#detail-id'); +const detailLogo = element(document, '#detail-logo'); +const detailCopy = element(document, '#detail-copy'); +const detailContent = element(document, '#detail-content'); +let detailRequest: AbortController | undefined; + +const localeLinks = + document.querySelectorAll('[data-locale-path]'); +function updateLocaleLinks() { + for (const link of localeLinks) { + link.href = `${link.dataset.localePath}${location.search}${location.hash}`; } - window.addEventListener('hashchange', () => { - if (location.hash === '#providers') selectTab(1); - else if (location.hash === '#models' || !location.hash) selectTab(0); - else selectTab(active); +} + +function replaceUrl(update: (query: URLSearchParams) => void) { + const url = new URL(location.href); + update(url.searchParams); + if (url.href !== location.href) history.replaceState(history.state, '', url); + updateLocaleLinks(); +} + +function show(dialog: HTMLDialogElement) { + for (const other of dialogs) { + if (other !== dialog && other.open && other !== drawer) other.close(); + } + if (!dialog.open) dialog.showModal(); +} + +function openDetail(kind: DetailKind, id: string) { + replaceUrl((query) => { + for (const key of detailKinds) query.delete(key); + query.set(kind, id); }); - selectTab(active); + void openDrawer(kind, id); } -const search = document.querySelector('#search'); -const body = document.querySelector('#model-rows'); -const form = document.querySelector('#filters'); -if (search && body && form) { - const rows = Array.from(body.rows); - const fields = [search, ...form.querySelectorAll('select')]; - const buttons = Array.from( - document.querySelectorAll('[data-sort]'), - ); - const params = new URLSearchParams(location.search); - const requestedSort = params.get('sort'); - let sort = - buttons.some((button) => button.dataset.sort === requestedSort) && - requestedSort - ? requestedSort - : 'released'; - let descending = params.get('direction') !== 'asc'; - const numericKeys = new Set(['context', 'parameters', 'providerCount']); +const palette = element(document, '#search-dialog'); +const prepareSearch = setupSearch(palette, locale, openDetail); - for (const field of fields) { - field.value = params.get(field.name) ?? ''; - if (field instanceof HTMLSelectElement && field.selectedIndex < 0) - field.value = ''; +async function openDrawer(kind: DetailKind, id: string) { + detailRequest?.abort(); + const request = new AbortController(); + detailRequest = request; + detailKind.textContent = t[kind]; + detailTitle.textContent = id; + detailId.textContent = id; + detailCopy.dataset.copy = id; + detailCopy.textContent = t.copy; + detailLogo.hidden = true; + detailLogo.replaceChildren(); + const progress = document.createElement('p'); + progress.setAttribute('role', 'status'); + progress.textContent = t.loading; + detailContent.replaceChildren(progress); + show(drawer); + drawer.querySelector('.drawer-body')?.scrollTo(0, 0); + + function render(name: string, icon: string | undefined, html: string) { + detailTitle.textContent = name; + detailLogo.replaceChildren(logoImage(icon, 28)); + detailLogo.hidden = false; + detailContent.innerHTML = html; } - const refresh = () => { - const query = search.value.trim().toLowerCase(); - let count = 0; - for (const row of rows) { - const matches = - (!query || row.dataset.search?.includes(query)) && - fields.every( - (field) => - field === search || - !field.value || - row.dataset[field.name]?.split(' ').includes(field.value), - ); - row.hidden = !matches; - if (matches) count++; - } - const counter = document.querySelector('#result-count'); - if (counter) counter.textContent = String(count); - const empty = document.querySelector('#empty-state'); - if (empty) empty.hidden = count !== 0; - const url = new URL(location.href); - for (const field of fields) { - if (field.value) url.searchParams.set(field.name, field.value); - else url.searchParams.delete(field.name); + try { + if ( + !/^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)?$/.test(id) || + (kind === 'model') !== id.includes('/') + ) { + throw new Error('Invalid detail ID'); } - if (sort === 'released' && descending) { - url.searchParams.delete('sort'); - url.searchParams.delete('direction'); + if (kind === 'developer') { + const index = await loadSearchIndex(); + if (request.signal.aborted) return; + const developer = index.find( + (item) => item.kind === 'developer' && item.id === id, + ); + if (!developer) throw new Error('Unknown developer'); + render( + developer.name, + developer.icon, + renderDeveloper(developer, locale, index), + ); } else { - url.searchParams.set('sort', sort); - url.searchParams.set('direction', descending ? 'desc' : 'asc'); + const path = kind === 'model' ? modelPath(id) : providerPath(id); + const response = await fetch(path, { signal: request.signal }); + if (!response.ok) throw new Error('Entry unavailable'); + if (kind === 'model') { + const [model, index] = await Promise.all([ + response.json(), + loadSearchIndex().catch(() => []), + ]); + if (request.signal.aborted) return; + render(model.name, model.icon, renderModel(model, locale, index)); + } else { + const provider = await response.json(); + if (request.signal.aborted) return; + render(provider.name, provider.icon, renderProvider(provider, locale)); + setupProviderListings(detailContent, locale); + } } - history.replaceState(null, '', url); - }; - - const order = () => { - const sorted = [...rows].sort((a, b) => { - const left = a.dataset[sort] ?? ''; - const right = b.dataset[sort] ?? ''; - if (!left && right) return 1; - if (left && !right) return -1; - const result = numericKeys.has(sort) - ? Number(left) - Number(right) - : left.localeCompare(right, 'en', { numeric: true }); + } catch { + if (request.signal.aborted) return; + progress.textContent = t.loadFailed; + const retry = document.createElement('button'); + retry.className = 'button'; + retry.textContent = t.retry; + retry.addEventListener('click', () => void openDrawer(kind, id)); + detailContent.append(retry); + } +} + +function restoreDrawer() { + const query = new URLSearchParams(location.search); + for (const kind of detailKinds) { + const id = query.get(kind); + if (!id) continue; + void openDrawer(kind, id); + return; + } + if (drawer.open) drawer.close(); +} + +drawer.addEventListener('close', () => { + if (drawer.open) return; + detailRequest?.abort(); + replaceUrl((query) => { + for (const key of detailKinds) query.delete(key); + }); +}); + +const main = element(document, '.page-scroll'); +const form = element(main, '#filters'); +const input = element(form, 'input[type=search]'); +const table = element(main, 'table'); +const fields = Array.from( + form.querySelectorAll('input, select'), +); +const pills = Array.from( + form.querySelectorAll('button[data-type]'), +); +const type = form.querySelector('select[name=type]'); +const count = element(form, '#result-count'); +const empty = element(main, '#empty-state'); +const { rows, sort } = setupTable(table, locale, (key, direction) => { + replaceUrl((query) => { + query.set('sort', key); + query.set('direction', direction); + }); +}); + +const fieldValue = (field: HTMLInputElement | HTMLSelectElement) => + field instanceof HTMLInputElement && field.type === 'checkbox' + ? field.checked + ? field.value + : '' + : field.value; +const filter = setupFilter( + rows, + input, + (row) => + fields.every((field) => { + const value = fieldValue(field); return ( - (descending ? -result : result) || - (a.dataset.model ?? '').localeCompare(b.dataset.model ?? '') + field === input || + !value || + Boolean(row.dataset[field.name]?.split(' ').includes(value)) + ); + }), + (matches) => { + count.textContent = matches.toLocaleString(locale); + empty.hidden = matches > 0; + for (const pill of pills) + pill.setAttribute( + 'aria-pressed', + String(pill.dataset.type === type?.value), ); - }); - body.append(...sorted); - for (const button of buttons) { - const header = button.closest('th'); - const selected = button.dataset.sort === sort; - if (selected) - header?.setAttribute( - 'aria-sort', - descending ? 'descending' : 'ascending', - ); - else header?.removeAttribute('aria-sort'); - const icon = button.querySelector('.sort-icon'); - if (icon) icon.textContent = selected ? (descending ? '↓' : '↑') : '↕'; + }, +); + +function saveFilters() { + filter(); + replaceUrl((query) => { + for (const field of fields) { + const value = fieldValue(field); + if (value) query.set(field.name, value); + else query.delete(field.name); + } + }); +} + +function restoreFilters() { + const query = new URLSearchParams(location.search); + for (const field of fields) { + const value = query.get(field.name) ?? ''; + if (field instanceof HTMLInputElement && field.type === 'checkbox') { + field.checked = value === field.value; + } else { + field.value = value; + if (field instanceof HTMLSelectElement && field.selectedIndex < 0) + field.value = ''; } - }; + } + const key = query.get('sort'); + if (key) sort(key, query.get('direction') === 'desc'); + filter(); +} - for (const field of fields) - field.addEventListener(field === search ? 'input' : 'change', refresh); - form.addEventListener('submit', (event) => event.preventDefault()); - form.addEventListener('reset', (event) => { - event.preventDefault(); - for (const field of fields) field.value = ''; - refresh(); - search.focus(); +form.addEventListener('submit', (event) => event.preventDefault()); +form.addEventListener('reset', (event) => { + event.preventDefault(); + for (const field of fields) { + if (field instanceof HTMLInputElement && field.type === 'checkbox') + field.checked = false; + else field.value = ''; + } + saveFilters(); + input.focus(); +}); +form.addEventListener('change', saveFilters); +input.addEventListener('input', saveFilters); +for (const pill of pills) { + pill.addEventListener('click', () => { + if (type) type.value = pill.dataset.type ?? ''; + saveFilters(); }); - for (const button of buttons) { - button.addEventListener('click', () => { - const next = button.dataset.sort ?? 'name'; - descending = - sort === next - ? !descending - : numericKeys.has(next) || next === 'released'; - sort = next; - order(); - refresh(); - }); +} + +for (const shortcut of document.querySelectorAll('[data-shortcut]')) { + if (/Mac|iPhone|iPad/i.test(navigator.userAgent)) shortcut.textContent = '⌘K'; +} + +document.addEventListener('keydown', (event) => { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') { + event.preventDefault(); + show(palette); + prepareSearch(); } - document.addEventListener('keydown', (event) => { - if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') { - event.preventDefault(); - if (modelsPanel?.hidden) modelsTab?.click(); - search.focus(); - } +}); + +for (const dialog of dialogs) { + dialog.addEventListener('click', (event) => { + if (event.target !== dialog) return; + const bounds = dialog.getBoundingClientRect(); + if ( + event.clientX < bounds.left || + event.clientX > bounds.right || + event.clientY < bounds.top || + event.clientY > bounds.bottom + ) + dialog.close(); }); - if (requestedSort !== null || !descending) order(); - refresh(); } -document - .querySelector('#language') - ?.addEventListener('change', (event) => { - if (!(event.currentTarget instanceof HTMLSelectElement)) return; - const target = new URL(location.href); - target.pathname = event.currentTarget.value; - location.assign(target); +const sdkTabs = Array.from( + document.querySelectorAll('.sdk-tabs [role=tab]'), +); +function selectTab(tab: HTMLButtonElement) { + for (const option of sdkTabs) { + const selected = option === tab; + option.setAttribute('aria-selected', String(selected)); + option.tabIndex = selected ? 0 : -1; + const panel = document.getElementById( + option.getAttribute('aria-controls') ?? '', + ); + if (panel) panel.hidden = !selected; + } +} +for (const [index, tab] of sdkTabs.entries()) { + tab.addEventListener('click', () => selectTab(tab)); + tab.addEventListener('keydown', (event) => { + const length = sdkTabs.length; + const next = { + ArrowRight: (index + 1) % length, + ArrowLeft: (index + length - 1) % length, + Home: 0, + End: length - 1, + }[event.key]; + if (next === undefined) return; + event.preventDefault(); + sdkTabs[next].focus(); + selectTab(sdkTabs[next]); }); +} + +async function copy(button: HTMLButtonElement) { + const value = button.dataset.copy ?? ''; + try { + await navigator.clipboard.writeText(value); + if (button.dataset.copy === value) button.textContent = t.copied; + } catch { + if (button.dataset.copy === value) button.textContent = t.copyFailed; + } + window.setTimeout(() => { + if (button.dataset.copy === value) button.textContent = t.copy; + }, 1600); +} + +document.addEventListener('click', (event) => { + if (!(event.target instanceof Element)) return; + const target = event.target; + const trigger = target.closest('[data-open]'); + if (trigger) { + const dialog = dialogs.find((item) => item.id === trigger.dataset.open); + if (dialog) { + show(dialog); + if (dialog === palette) prepareSearch(); + } + return; + } + if (target.closest('[data-close]')) { + target.closest('dialog')?.close(); + return; + } + const copyButton = target.closest('[data-copy]'); + if (copyButton) { + void copy(copyButton); + return; + } + if ( + event.defaultPrevented || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + const anchor = target.closest('a'); + const row = target.closest('tr[data-entry]'); + const detail = + anchor ?? + (getSelection()?.isCollapsed + ? row?.querySelector('a[data-detail]') + : undefined); + const kind = detail?.dataset.detail as DetailKind | undefined; + const id = detail?.dataset.id; + if (kind && id) { + event.preventDefault(); + openDetail(kind, id); + } +}); -document.querySelector('#theme')?.addEventListener('click', () => { - const dark = - document.documentElement.classList.contains('dark') || - (!document.documentElement.classList.contains('light') && - matchMedia('(prefers-color-scheme: dark)').matches); - document.documentElement.classList.toggle('dark', !dark); - document.documentElement.classList.toggle('light', dark); +window.addEventListener('hashchange', updateLocaleLinks); +window.addEventListener('popstate', () => { + updateLocaleLinks(); + restoreFilters(); + restoreDrawer(); }); +updateLocaleLinks(); +restoreFilters(); +restoreDrawer(); diff --git a/apps/site/src/lib/catalogue.ts b/apps/site/src/lib/catalogue.ts index 030ffa98..ff8a8bbd 100644 --- a/apps/site/src/lib/catalogue.ts +++ b/apps/site/src/lib/catalogue.ts @@ -1,20 +1,34 @@ -import type { - ResolvedModelV2, - ResolvedProviderModelV2, - ResolvedProviderV2, -} from '@lmspeed/models-core'; +import type { ResolvedModelV2 } from '@lmspeed/models-core'; import en from '../messages/en.json'; import ru from '../messages/ru.json'; import zh from '../messages/zh.json'; -export type Locale = 'en' | 'zh' | 'ru'; export const messages = { en, zh, ru }; -export const locales: Locale[] = ['en', 'zh', 'ru']; -export const localePath = (locale: Locale) => - locale === 'en' ? '/' : `/${locale}/`; +export type Locale = keyof typeof messages; +export const locales = ['en', 'zh', 'ru'] as const; +export const sections = ['models', 'providers', 'developers'] as const; +export type Section = (typeof sections)[number]; +export const detailKinds = ['model', 'provider', 'developer'] as const; +export type DetailKind = (typeof detailKinds)[number]; + +export const localeLabels = { en: 'EN', zh: '中文', ru: 'RU' }; +export const localePath = (locale: Locale, section: Section = 'models') => + `${locale === 'en' ? '' : `/${locale}`}${section === 'models' ? '' : `/${section}`}` || + '/'; +export const markdownPath = (locale: Locale) => + locale === 'en' ? '/index.md' : `/${locale}/index.md`; export const siteUrl = 'https://models.lmspeed.net'; export const modelPath = (id: string) => `/v2/models/${id}.json`; export const providerPath = (id: string) => `/v2/providers/${id}.json`; +export const developerId = (id: string) => id.split('/')[0]; +export const logoUrl = (icon = 'default') => + `/v2/logos/${encodeURIComponent(icon)}.svg`; +export const missing = '–'; + +export function detailPath(locale: Locale, kind: DetailKind, id: string) { + const value = id.split('/').map(encodeURIComponent).join('/'); + return `${localePath(locale, `${kind}s`)}?${kind}=${value}`; +} export function catalogueRows(models: Record) { return Object.values(models).sort( @@ -25,52 +39,57 @@ export function catalogueRows(models: Record) { } export const displayNumber = (value: number | undefined, locale: Locale) => - value === undefined ? '—' : value.toLocaleString(locale); + value === undefined ? missing : value.toLocaleString(locale); -export function modelModalities(model: ResolvedModelV2) { - const modalities = [...model.modalities.input, ...model.modalities.output]; +export function modelModalities({ modalities }: ResolvedModelV2) { return [ - ...new Set(modalities.flatMap((value) => [value, value.split('/')[0]])), + ...new Set( + [...modalities.input, ...modalities.output].map((value) => + value === 'application/pdf' ? 'pdf' : value.split('/')[0], + ), + ), ]; } -function pricePreview(model: ResolvedProviderModelV2) { - for (const modality of ['text', 'image', 'audio', 'video'] as const) { - const rates = model.cost?.[modality]; - if (rates?.input || rates?.output) { - return { - kind: 'modality' as const, - id: model.id, - name: model.name, - modality, - input: rates.input, - output: rates.output, - }; - } - } - if (model.cost?.web_search) - return { - kind: 'search' as const, - id: model.id, - name: model.name, - search: model.cost.web_search.price, - }; +export function parametersText( + parameters: ResolvedModelV2['parameters'], + locale: Locale, +) { + const { total_billions: total, active_billions: active } = parameters ?? {}; + const totalText = + total === undefined ? '' : `${displayNumber(total, locale)}B`; + const activeText = + active === undefined ? '' : `${displayNumber(active, locale)}B`; + if (totalText && activeText) return `${totalText} (${activeText})`; + return ( + totalText || + (activeText && `${activeText} (${messages[locale].active})`) || + missing + ); } -export function providerPrice(provider: ResolvedProviderV2) { - for (const model of Object.values(provider.models)) { - const preview = pricePreview(model); - if (preview) return preview; - } -} +const currency = new Intl.NumberFormat('en-US', { + minimumFractionDigits: 2, + maximumFractionDigits: 12, + useGrouping: true, +}); +export const formatCost = (value?: number) => + value === undefined ? missing : `$${currency.format(value)}`; +export const booleanText = (value: boolean | undefined, locale: Locale) => + value === undefined ? missing : messages[locale][value ? 'yes' : 'no']; -export function providerEndpoints(provider: ResolvedProviderV2) { - const endpoints = new Set(); - if (provider.api) endpoints.add(provider.api); - for (const model of Object.values(provider.models)) { - for (const api of Object.values(model.api ?? {})) { - if (api.base_url) endpoints.add(api.base_url); - } - } - return [...endpoints]; +export function publicLink(value?: string) { + return value && /^https?:\/\//i.test(value) ? value : undefined; } + +export type SearchItem = { + kind: DetailKind; + id: string; + name: string; + icon?: string; + terms?: string; + description?: string; + website?: string; + counts?: { models: number; providers: number; open: number }; + released?: string; +}; diff --git a/apps/site/src/lib/details.ts b/apps/site/src/lib/details.ts new file mode 100644 index 00000000..ac683c02 --- /dev/null +++ b/apps/site/src/lib/details.ts @@ -0,0 +1,479 @@ +import type { + ResolvedModelV2, + ResolvedProviderModelV2, + ResolvedProviderV2, +} from '@lmspeed/models-core'; +import { + booleanText, + detailPath, + developerId, + displayNumber, + formatCost, + type Locale, + localePath, + logoUrl, + messages, + missing, + modelPath, + parametersText, + providerPath, + publicLink, + type SearchItem, +} from './catalogue'; +import { element } from './element'; +import { setupFilter, setupTable } from './table-controls'; + +const escapeHtml = (value: string | number) => + String(value).replace( + /[&<>"']/g, + (character) => + ({ + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + })[character] ?? character, + ); + +function link(label: string, href: string, className = '') { + return `${escapeHtml(label)}`; +} + +function logo(icon?: string) { + return ``; +} + +function chips(items: string[]) { + return items.length + ? `
${items.map((item) => `${escapeHtml(item)}`).join('')}
` + : missing; +} + +function facts(items: [string, string][]) { + return `
${items + .map( + ([label, value]) => + `
${escapeHtml(label)}
${escapeHtml(value)}
`, + ) + .join('')}
`; +} + +function section(heading: string, contents: string) { + return `

${escapeHtml(heading)}

${contents}
`; +} + +function description(value?: string) { + return value ? `

${escapeHtml(value)}

` : ''; +} + +function table( + headers: [string, string?, ('number' | 'date')?][], + rows: string[], + caption: string, + sortable = false, +) { + return `
+ ${headers + .map(([label, key, type], index) => { + const sort = sortable && index === 0 ? ' aria-sort="ascending"' : ''; + const content = key + ? `` + : escapeHtml(label); + return ``; + }) + .join('')}${rows.join('')}
${escapeHtml(caption)}
${content}
`; +} + +function cell(content: string, value?: string | number, className = '') { + const attribute = + value === undefined ? '' : ` data-value="${escapeHtml(value)}"`; + return `${content}`; +} + +function resourceLinks( + resources: { url: string; label?: string; note?: string }[], +) { + return resources + .flatMap(({ url, label, note }) => { + const href = publicLink(url); + return href + ? [ + `
  • ${link(label ?? new URL(href).hostname, href)}${note ? ` ${escapeHtml(note)}` : ''}
  • `, + ] + : []; + }) + .join(''); +} + +function fieldName(key: string, locale: Locale): string { + const t = messages[locale]; + const names: Record = { + tools: t.tools, + reasoning: t.reasoning, + cache: t.cache, + input: t.input, + output: t.output, + context: t.context, + text: t.text, + image: t.modalityImage, + audio: t.modalityAudio, + video: t.modalityVideo, + pdf: t.pdf, + embedding: t.types.embedding, + rerank: t.types.reranking, + }; + return names[key] ?? key.replaceAll('_', ' '); +} + +function fieldValue(value: unknown, locale: Locale): string { + if (typeof value === 'boolean') return booleanText(value, locale); + if (typeof value === 'number') return displayNumber(value, locale); + if (typeof value === 'string') return value; + if (Array.isArray(value)) + return value.map((item) => fieldValue(item, locale)).join(', '); + if (value && typeof value === 'object') { + return Object.entries(value) + .map( + ([key, entry]) => + `${fieldName(key, locale)} · ${fieldValue(entry, locale)}`, + ) + .join(' · '); + } + return missing; +} + +function fieldRows(object: Record, locale: Locale) { + return Object.entries(object).map(([key, value]) => { + if ( + value && + typeof value === 'object' && + 'supported' in value && + typeof value.supported === 'boolean' + ) { + const { supported, ...fields } = value; + const details = fieldValue(fields, locale); + return [ + fieldName(key, locale), + [booleanText(supported, locale), details].filter(Boolean).join(' · '), + ] as [string, string]; + } + return [fieldName(key, locale), fieldValue(value, locale)] as [ + string, + string, + ]; + }); +} + +export function renderModel( + model: ResolvedModelV2, + locale: Locale, + index: SearchItem[], +) { + const t = messages[locale]; + const limits = model.limit; + const status = { + active: t.activeStatus, + deprecated: t.deprecatedStatus, + alpha: 'Alpha', + beta: 'Beta', + }; + const badges = [ + t.types[model.type], + model.status && status[model.status], + model.open_weights === undefined + ? undefined + : model.open_weights + ? t.openWeights + : t.closed, + model.license, + ].filter((value): value is string => Boolean(value)); + const modalities = (direction: 'input' | 'output') => + model.modalities[direction] + .map((value) => fieldName(value, locale)) + .join(', ') || missing; + const developer = index.find( + (item) => item.kind === 'developer' && item.id === developerId(model.id), + ); + const providers = new Map( + index + .filter((item) => item.kind === 'provider') + .map((item) => [item.id, item]), + ); + const benchmarks = model.benchmarks?.map( + ({ + name, + score, + metric, + dataset, + date, + source, + version, + variant, + harness, + }) => { + const href = publicLink(source); + const notes = [dataset, version, variant, harness] + .filter(Boolean) + .join(' · '); + return `${cell(href ? link(name, href) : escapeHtml(name))}${cell(escapeHtml(score), undefined, 'numeric')}${cell(escapeHtml(metric ?? missing))}${cell(escapeHtml(notes || missing))}${cell(escapeHtml(date ?? missing), undefined, 'date')}`; + }, + ); + const sources = model.sources?.map((source) => ({ + ...source, + note: [source.checked_at, source.fields?.join(', ')] + .filter(Boolean) + .join(' · '), + })); + const weights = model.weights?.map((weight) => ({ + ...weight, + note: [weight.format, weight.quantization].filter(Boolean).join(' · '), + })); + const extraLimits = limits + ? Object.entries(limits).filter( + ([key]) => !['context', 'input', 'output'].includes(key), + ) + : []; + return [ + chips(badges), + description(model.description), + ``, + facts([ + [t.parameters, parametersText(model.parameters, locale)], + [t.context, displayNumber(limits?.context, locale)], + [t.maxInput, displayNumber(limits?.input, locale)], + [t.maxOutput, displayNumber(limits?.output, locale)], + [t.knowledge, model.knowledge ?? missing], + [t.released, model.release_date ?? missing], + [`${t.modalities} · ${t.input}`, modalities('input')], + [`${t.modalities} · ${t.output}`, modalities('output')], + ...(model.parameters?.architecture + ? [[t.architecture, model.parameters.architecture] as [string, string]] + : []), + ...(model.languages?.length + ? [[t.languages, model.languages.join(', ')] as [string, string]] + : []), + ]), + Object.keys(model.capabilities).length + ? section(t.capabilities, facts(fieldRows(model.capabilities, locale))) + : '', + ...Object.entries(model.specs ?? {}).map(([key, value]) => + section( + `${t.specifications} · ${fieldName(key, locale)}`, + facts(fieldRows(value, locale)), + ), + ), + extraLimits.length + ? section( + t.limits, + facts(fieldRows(Object.fromEntries(extraLimits), locale)), + ) + : '', + benchmarks?.length + ? section( + t.benchmarks, + table( + [[t.benchmarks], [t.score], [t.metric], [t.dataset], [t.released]], + benchmarks, + t.benchmarks, + ), + ) + : '', + ...( + [ + [t.weights, weights], + [t.links, model.links], + [t.sources, sources], + ] as const + ).map(([label, items]) => { + const links = items && resourceLinks(items); + return links + ? section(label, `
      ${links}
    `) + : ''; + }), + section( + t.providers, + model.providers.length + ? `` + : `

    ${missing}

    `, + ), + ].join(''); +} + +type ListingCost = NonNullable; +type ModalityCost = NonNullable; +const tokenRate = (rate: { unit?: string } | undefined) => + rate && (!rate.unit || rate.unit === 'token'); + +function batchAndTiers(model: ResolvedProviderModelV2, locale: Locale) { + const labels = new Set(model.capabilities?.service_tier); + if (model.capabilities?.batch) labels.add('Batch'); + function collect(condition: unknown) { + if (!condition || typeof condition !== 'object') return; + for (const [key, rule] of Object.entries(condition)) { + if (key === 'batch' && rule.equals === true) labels.add('Batch'); + if (key === 'service_tier') { + if (rule.equals) labels.add(rule.equals); + for (const tier of rule.in ?? []) labels.add(tier); + } + if (key === 'all' || key === 'any') { + for (const item of rule) collect(item); + } + } + } + for (const multiplier of model.cost?.multipliers ?? []) + collect(multiplier.when); + for (const kind of ['text', 'audio', 'image', 'video'] as const) { + for (const direction of ['input', 'output'] as const) { + for (const override of model.cost?.[kind]?.[direction]?.overrides ?? []) + collect(override.when); + } + } + for (const [name, mode] of Object.entries(model.experimental?.modes ?? {})) { + if (mode.service_tier) labels.add(mode.service_tier); + else labels.add(name); + } + return [...labels].map((label) => + label === 'Batch' ? messages[locale].batch : label, + ); +} + +function priceCell( + value: number | undefined, + rate: ModalityCost['input'] | ModalityCost['output'], + locale: Locale, +) { + const unit = rate?.unit ?? 'token'; + const suffix = + unit === 'token' + ? '' + : ` / ${unit === 'character' ? '1M ' : ''}${messages[locale][unit]}`; + return cell( + escapeHtml(value === undefined ? missing : formatCost(value) + suffix), + tokenRate(rate) ? value : undefined, + 'numeric', + ); +} + +export function renderProvider(provider: ResolvedProviderV2, locale: Locale) { + const t = messages[locale]; + const listings = Object.values(provider.models).sort((a, b) => + a.id.localeCompare(b.id, locale, { numeric: true }), + ); + const rows = listings.map((model) => { + const protocol = Object.keys(model.api ?? {}); + const { input, output } = + model.cost?.text ?? + model.cost?.image ?? + model.cost?.audio ?? + model.cost?.video ?? + {}; + const cache = model.cost?.text?.input?.cache; + const cacheRead = cache?.read ?? cache?.explicit?.read; + const tiers = batchAndTiers(model, locale); + const webSearch = model.cost?.web_search?.price; + const title = model.model + ? link( + model.name, + detailPath(locale, 'model', model.model), + 'listing-name', + ) + : escapeHtml(model.name); + const id = `${escapeHtml(model.id)}`; + return ` + ${title}${id} + ${cell(displayNumber(model.limit?.context, locale), model.limit?.context, 'numeric')} + ${cell(displayNumber(model.limit?.output, locale), model.limit?.output, 'numeric')} + ${priceCell(input?.price, input, locale)}${priceCell(output?.price, output, locale)} + ${priceCell(cacheRead, model.cost?.text?.input, locale)} + ${cell(chips(tiers), tiers.join(' ') || undefined)} + ${cell(chips(protocol), protocol.join(' ') || undefined)} + ${webSearch !== undefined ? cell(escapeHtml(`${formatCost(webSearch)} / 1,000 ${t.searches}`), webSearch, 'numeric') : cell(missing)} + `; + }); + const doc = publicLink(provider.doc); + const website = publicLink(provider.website); + return [ + ``, + facts([ + [t.models, displayNumber(listings.length, locale)], + ['API', provider.api ?? missing], + [t.sdk, provider.npm === 'none' ? missing : (provider.npm ?? missing)], + ]), + `
    `, + table( + [ + [t.providerModelId, 'id'], + [t.context, 'context', 'number'], + [t.output, 'output', 'number'], + [t.inputRate, 'input', 'number'], + [t.outputRate, 'output-rate', 'number'], + [t.cacheRate, 'cache', 'number'], + [t.batchTier, 'batch'], + [t.protocols, 'protocols'], + [t.webSearch, 'search', 'number'], + ], + rows, + t.models, + true, + ), + `

    ${escapeHtml(t.priceNote)}

    `, + ].join(''); +} + +export function setupProviderListings(content: HTMLElement, locale: Locale) { + const input = element(content, 'input[type=search]'); + const count = element(content, '.listing-count'); + const { rows } = setupTable( + element(content, 'table'), + locale, + ); + const filter = setupFilter( + rows, + input, + () => true, + (matches) => { + count.textContent = `${matches.toLocaleString(locale)} ${messages[locale].modelsLabel}`; + }, + ); + input.addEventListener('input', filter); + filter(); +} + +export function renderDeveloper( + developer: SearchItem, + locale: Locale, + index: SearchItem[], +) { + const t = messages[locale]; + const website = publicLink(developer.website); + const models = index.filter( + (item) => item.kind === 'model' && developerId(item.id) === developer.id, + ); + return [ + description(developer.description), + ``, + facts([ + [t.models, displayNumber(developer.counts?.models, locale)], + [t.providers, displayNumber(developer.counts?.providers, locale)], + [t.openWeights, displayNumber(developer.counts?.open, locale)], + [t.latestRelease, developer.released ?? missing], + ]), + models.length + ? section( + t.models, + `
      ${models + .map( + (model) => + `
    • ${link(model.name, detailPath(locale, 'model', model.id))} ${escapeHtml(model.id)}
    • `, + ) + .join('')}
    `, + ) + : '', + ].join(''); +} diff --git a/apps/site/src/lib/directory-data.ts b/apps/site/src/lib/directory-data.ts new file mode 100644 index 00000000..42257eb9 --- /dev/null +++ b/apps/site/src/lib/directory-data.ts @@ -0,0 +1,69 @@ +import { catalog } from '@lmspeed/models-publish'; +import { catalogueRows, developerId, type SearchItem } from './catalogue'; + +export const models = catalogueRows(catalog.modelCards); +export const providers = Object.values(catalog.index.providers); +export const aliasesByModel = new Map(); +for (const [alias, id] of Object.entries(catalog.models.aliases)) { + const aliases = aliasesByModel.get(id) ?? []; + aliases.push(alias); + aliasesByModel.set(id, aliases); +} + +type ModelPrice = { input?: number; output?: number }; +export const modelPrices = new Map(); +for (const provider of Object.values(catalog.providerShards)) { + for (const model of Object.values(provider.models)) { + if (!model.model || !model.cost?.text) continue; + const price = modelPrices.get(model.model) ?? {}; + for (const direction of ['input', 'output'] as const) { + const rate = model.cost.text[direction]; + if (!rate || (rate.unit && rate.unit !== 'token')) continue; + price[direction] = Math.min(price[direction] ?? Infinity, rate.price); + } + modelPrices.set(model.model, price); + } +} + +const modelsByDeveloper = Map.groupBy(models, (model) => developerId(model.id)); +export const developers = Object.entries(catalog.models.developers).map( + ([id, developer]) => { + const entries = modelsByDeveloper.get(id) ?? []; + return { + id, + ...developer, + released: entries.find((model) => model.release_date)?.release_date, + counts: { + models: entries.length, + providers: new Set(entries.flatMap((model) => model.providers)).size, + open: entries.filter((model) => model.open_weights === true).length, + }, + }; + }, +); + +export function searchIndex(): SearchItem[] { + return [ + ...models.map(({ id, name, icon, release_date }) => ({ + kind: 'model' as const, + id, + name, + icon, + released: release_date, + terms: [ + catalog.models.developers[developerId(id)].name, + ...(aliasesByModel.get(id) ?? []), + ].join(' '), + })), + ...providers.map(({ id, name, icon }) => ({ + kind: 'provider' as const, + id, + name, + icon, + })), + ...developers.map((developer) => ({ + kind: 'developer' as const, + ...developer, + })), + ]; +} diff --git a/apps/site/src/lib/element.ts b/apps/site/src/lib/element.ts new file mode 100644 index 00000000..b9586df7 --- /dev/null +++ b/apps/site/src/lib/element.ts @@ -0,0 +1,8 @@ +export function element( + root: ParentNode, + selector: string, +): T { + const match = root.querySelector(selector); + if (!match) throw new Error(`Missing catalog element: ${selector}`); + return match; +} diff --git a/apps/site/src/lib/glyphs.ts b/apps/site/src/lib/glyphs.ts new file mode 100644 index 00000000..d59f7883 --- /dev/null +++ b/apps/site/src/lib/glyphs.ts @@ -0,0 +1,16 @@ +// Interface glyphs. Catalog logos are served as separate LobeHub assets. +export const glyphs = { + search: '', + menu: '', + close: '', + external: '', + text: '', + image: + '', + audio: '', + video: + '', + pdf: '', + github: + '', +}; diff --git a/apps/site/src/lib/markdown.ts b/apps/site/src/lib/markdown.ts index 5946b198..175ed77f 100644 --- a/apps/site/src/lib/markdown.ts +++ b/apps/site/src/lib/markdown.ts @@ -47,7 +47,7 @@ export function catalogueMarkdown(locale: Locale) { t.input, t.output, t.context, - t.limits, + t.maxOutput, t.parameters, t.providers, t.sources, diff --git a/apps/site/src/lib/search-controls.ts b/apps/site/src/lib/search-controls.ts new file mode 100644 index 00000000..08e46d1a --- /dev/null +++ b/apps/site/src/lib/search-controls.ts @@ -0,0 +1,200 @@ +import { + type DetailKind, + detailPath, + type Locale, + logoUrl, + messages, + type SearchItem, +} from './catalogue'; +import { element } from './element'; +import { searchTerms } from './table-controls'; + +let indexPromise: Promise | undefined; +export function loadSearchIndex() { + indexPromise ??= fetch('/search.json') + .then((response) => { + if (!response.ok) throw new Error('Search index unavailable'); + return response.json() as Promise; + }) + .catch((error) => { + indexPromise = undefined; + throw error; + }); + return indexPromise; +} + +export function logoImage(icon: string | undefined, size: number) { + const img = document.createElement('img'); + img.src = logoUrl(icon); + img.alt = ''; + img.width = size; + img.height = size; + return img; +} + +function highlight(element: HTMLElement, value: string, terms: string[]) { + const escaped = [...terms] + .sort((a, b) => b.length - a.length) + .map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); + if (!escaped.length) { + element.textContent = value; + return; + } + const pattern = new RegExp(escaped.join('|'), 'giu'); + let end = 0; + for (const match of value.matchAll(pattern)) { + element.append(value.slice(end, match.index)); + const mark = document.createElement('mark'); + mark.textContent = match[0]; + element.append(mark); + end = match.index + match[0].length; + } + element.append(value.slice(end)); +} + +function searchable({ name, id, terms }: SearchItem) { + return [name, id, terms ?? ''].map((value) => + value.normalize('NFKC').toLowerCase(), + ); +} + +function score(fields: string[], terms: string[]) { + let total = 0; + for (const term of terms) { + const scores = fields.map((field, index) => { + if (field === term) return 200 - index * 20; + if (field.startsWith(term)) return 100 - index * 20; + return field.includes(term) ? 40 - index * 10 : 0; + }); + const best = Math.max(...scores); + if (!best) return -1; + total += best; + } + return total; +} + +export function setupSearch( + dialog: HTMLDialogElement, + locale: Locale, + openDetail: (kind: DetailKind, id: string) => void, +) { + const t = messages[locale]; + const query = element(dialog, '#palette-query'); + const results = element(dialog, '#palette-results'); + const status = element(dialog, '#palette-status'); + const retry = element(dialog, '#palette-retry'); + let index: { item: SearchItem; fields: string[] }[] | undefined; + let options: HTMLAnchorElement[] = []; + let active = 0; + + function select(position: number, scroll = false) { + options[active]?.setAttribute('aria-selected', 'false'); + active = position; + const option = options[active]; + if (!option) { + query.removeAttribute('aria-activedescendant'); + return; + } + option.setAttribute('aria-selected', 'true'); + query.setAttribute('aria-activedescendant', option.id); + if (scroll) option.scrollIntoView({ block: 'nearest' }); + } + + function render() { + if (!index) return; + const terms = searchTerms(query.value); + const matches = terms.length + ? index + .map(({ item, fields }) => ({ item, rank: score(fields, terms) })) + .filter(({ rank }) => rank >= 0) + .sort((a, b) => b.rank - a.rank) + .map(({ item }) => item) + : index.map(({ item }) => item); + const visible = matches.slice(0, 60); + options = visible.map(({ kind, id, name, icon }, position) => { + const option = document.createElement('a'); + option.href = detailPath(locale, kind, id); + option.id = `palette-option-${position}`; + option.className = 'palette-option'; + option.tabIndex = -1; + option.setAttribute('role', 'option'); + option.setAttribute('aria-selected', 'false'); + const logo = document.createElement('span'); + logo.className = 'logo'; + logo.append(logoImage(icon, 20)); + const label = document.createElement('span'); + label.className = 'palette-label'; + const title = document.createElement('strong'); + const subtitle = document.createElement('code'); + highlight(title, name, terms); + highlight(subtitle, id, terms); + label.append(title, subtitle); + const category = document.createElement('span'); + category.className = 'chip'; + category.textContent = t[kind]; + option.append(logo, label, category); + option.addEventListener('click', (event) => { + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) + return; + event.preventDefault(); + openDetail(kind, id); + }); + return option; + }); + results.replaceChildren(...options); + status.textContent = matches.length + ? `${matches.length > visible.length ? `${visible.length} / ` : ''}${matches.length.toLocaleString(locale)} ${t.results}` + : t.noResults; + select(0); + dialog.querySelector('.palette-scroll')?.scrollTo(0, 0); + } + + async function prepare() { + if (index) { + render(); + return; + } + retry.hidden = true; + status.textContent = t.loading; + try { + index = (await loadSearchIndex()).map((item) => ({ + item, + fields: searchable(item), + })); + if (dialog.open) render(); + } catch { + status.textContent = t.searchFailed; + retry.hidden = false; + } + } + + retry.addEventListener('click', prepare); + query.addEventListener('input', render); + query.addEventListener('keydown', (event) => { + if (!options.length || event.isComposing) return; + switch (event.key) { + case 'ArrowDown': + case 'ArrowUp': + event.preventDefault(); + select( + (active + (event.key === 'ArrowDown' ? 1 : -1) + options.length) % + options.length, + true, + ); + break; + case 'Enter': + event.preventDefault(); + options[active]?.click(); + break; + } + }); + dialog.addEventListener('close', () => { + if (!dialog.open) query.setAttribute('aria-expanded', 'false'); + }); + return () => { + query.setAttribute('aria-expanded', 'true'); + query.focus(); + query.select(); + void prepare(); + }; +} diff --git a/apps/site/src/lib/table-controls.ts b/apps/site/src/lib/table-controls.ts new file mode 100644 index 00000000..5851f4e3 --- /dev/null +++ b/apps/site/src/lib/table-controls.ts @@ -0,0 +1,86 @@ +const normalized = (value: string) => value.normalize('NFKC').toLowerCase(); +export const searchTerms = (value: string) => + normalized(value).trim().split(/\s+/).filter(Boolean); + +export function setupTable( + table: HTMLTableElement, + locale: string, + onSort?: (key: string, direction: string) => void, +) { + const body = table.tBodies[0]; + const rows = Array.from(body.rows); + const buttons = Array.from( + table.querySelectorAll('thead button[data-sort]'), + ); + const collator = new Intl.Collator(locale, { + numeric: true, + sensitivity: 'base', + }); + let active = buttons.find((button) => + button.closest('th')?.hasAttribute('aria-sort'), + ); + let descending = + active?.closest('th')?.getAttribute('aria-sort') === 'descending'; + + function sort(key: string, reverse: boolean) { + const button = buttons.find((item) => item.dataset.sort === key); + const header = button?.closest('th'); + if (!button || !header) return; + const column = header.cellIndex; + const number = button.dataset.order === 'number'; + const sorted = [...rows].sort((a, b) => { + const left = a.cells[column].dataset.value; + const right = b.cells[column].dataset.value; + if (left === undefined) return right === undefined ? 0 : 1; + if (right === undefined) return -1; + const order = number + ? Number(left) - Number(right) + : collator.compare(left, right); + return reverse ? -order : order; + }); + const fragment = document.createDocumentFragment(); + for (const row of sorted) fragment.append(row); + body.append(fragment); + active = button; + descending = reverse; + for (const item of buttons) { + item.closest('th')?.removeAttribute('aria-sort'); + const icon = item.querySelector('.sort-icon'); + if (icon) + icon.textContent = item === button ? (reverse ? '↓' : '↑') : '↕'; + } + header.setAttribute('aria-sort', reverse ? 'descending' : 'ascending'); + } + + for (const button of buttons) { + button.addEventListener('click', () => { + const key = button.dataset.sort ?? ''; + const reverse = + button === active ? !descending : Boolean(button.dataset.order); + sort(key, reverse); + onSort?.(key, reverse ? 'desc' : 'asc'); + }); + } + return { sort, rows }; +} + +export function setupFilter( + rows: HTMLTableRowElement[], + input: HTMLInputElement, + extra: (row: HTMLTableRowElement) => boolean, + update: (count: number) => void, +) { + const haystacks = rows.map((row) => normalized(row.dataset.search ?? '')); + function filter() { + const terms = searchTerms(input.value); + let count = 0; + for (const [index, row] of rows.entries()) { + const matches = + extra(row) && terms.every((term) => haystacks[index].includes(term)); + row.hidden = !matches; + if (matches) count++; + } + update(count); + } + return filter; +} diff --git a/apps/site/src/messages/en.json b/apps/site/src/messages/en.json index 76c47d5d..69014ff0 100644 --- a/apps/site/src/messages/en.json +++ b/apps/site/src/messages/en.json @@ -24,7 +24,7 @@ "language": "Language", "theme": "Toggle color theme", "attribution": "Credit LMSpeed and retain the original field sources when reusing this data.", - "skip": "Skip to models", + "skip": "Skip to directory", "licenses": "Licenses", "developersCount": "developers", "description": "Browse model specifications, find API providers, and compare published pricing.", @@ -66,5 +66,84 @@ "realtime": "Realtime", "extraction": "Extraction", "audio": "Audio" - } + }, + "tagline": "An open-source database of AI models", + "directories": "Directories", + "developers": "Developers", + "provider": "Provider", + "modelsLabel": "models", + "providersLabel": "providers", + "developersLabel": "developers", + "searchAction": "Search", + "searchCatalog": "Search models, providers, developers…", + "filterModels": "Filter models", + "filterProviders": "Filter providers", + "filterDevelopers": "Filter developers", + "filterListings": "Filter provider models", + "clear": "Clear", + "all": "All", + "openWeights": "Open Weights", + "openLabel": "Open", + "closedLabel": "Closed", + "modalities": "Modalities", + "tools": "Tools", + "reasoning": "Reasoning", + "cache": "Cache", + "yes": "Yes", + "no": "No", + "price": "Price", + "minimumPrice": "Lowest published base input and output token rates across providers, in USD per 1M tokens.", + "sdk": "SDK / npm", + "docsLink": "Docs", + "latestRelease": "Latest release", + "descriptionLabel": "Description", + "menu": "Menu", + "close": "Close", + "copy": "Copy", + "copied": "Copied", + "copyFailed": "Copy failed", + "loading": "Loading…", + "loadFailed": "Could not load this entry.", + "searchFailed": "Could not load the search index.", + "retry": "Retry", + "noResults": "No results found.", + "results": "results", + "navigate": "Navigate", + "select": "Open", + "dismiss": "Close", + "matches": "Matches", + "status": "Status", + "activeStatus": "Active", + "deprecatedStatus": "Deprecated", + "license": "License", + "maxInput": "Max input", + "maxOutput": "Max output", + "knowledge": "Knowledge cutoff", + "capabilities": "Capabilities", + "specifications": "Specifications", + "links": "Links", + "architecture": "Architecture", + "languages": "Languages", + "json": "Raw JSON", + "website": "Website", + "score": "Score", + "metric": "Metric", + "dataset": "Dataset", + "protocols": "API protocols", + "batchTier": "Batch / Tier", + "inputRate": "Input $/1M", + "outputRate": "Output $/1M", + "cacheRate": "Cache read $/1M", + "providerModelId": "Provider model ID", + "viewModels": "View models", + "text": "Text", + "pdf": "PDF", + "modalityImage": "Image", + "modalityAudio": "Audio", + "modalityVideo": "Video", + "tableScroll": "Scroll to see more columns", + "unknownValue": "–", + "batch": "Batch", + "webSearch": "Web search", + "typesLabel": "Types" } diff --git a/apps/site/src/messages/ru.json b/apps/site/src/messages/ru.json index 9e9fb76f..5ae74efa 100644 --- a/apps/site/src/messages/ru.json +++ b/apps/site/src/messages/ru.json @@ -24,7 +24,7 @@ "language": "Язык", "theme": "Переключить тему", "attribution": "При использовании укажите LMSpeed и сохраните исходные ссылки полей.", - "skip": "К таблице моделей", + "skip": "К каталогу", "licenses": "Лицензии", "developersCount": "разработчиков", "description": "Изучайте характеристики моделей, находите поставщиков API и сравнивайте опубликованные цены.", @@ -66,5 +66,84 @@ "realtime": "Реальное время", "extraction": "Извлечение", "audio": "Аудио" - } + }, + "tagline": "Открытая база моделей ИИ", + "directories": "Каталоги", + "developers": "Разработчики", + "provider": "Провайдер", + "modelsLabel": "моделей", + "providersLabel": "провайдеров", + "developersLabel": "разработчиков", + "searchAction": "Поиск", + "searchCatalog": "Поиск моделей, провайдеров и разработчиков…", + "filterModels": "Фильтр моделей", + "filterProviders": "Фильтр провайдеров", + "filterDevelopers": "Фильтр разработчиков", + "filterListings": "Фильтр моделей провайдера", + "clear": "Сбросить", + "all": "Все", + "openWeights": "Открытые веса", + "openLabel": "Открытые", + "closedLabel": "Закрытые", + "modalities": "Модальности", + "tools": "Инструменты", + "reasoning": "Рассуждение", + "cache": "Кэш", + "yes": "Да", + "no": "Нет", + "price": "Цена", + "minimumPrice": "Минимальные базовые цены провайдеров за ввод и вывод в долларах США за 1 млн токенов.", + "sdk": "SDK / npm", + "docsLink": "Документация", + "latestRelease": "Последний выпуск", + "descriptionLabel": "Описание", + "menu": "Меню", + "close": "Закрыть", + "copy": "Копировать", + "copied": "Скопировано", + "copyFailed": "Ошибка копирования", + "loading": "Загрузка…", + "loadFailed": "Не удалось загрузить запись.", + "searchFailed": "Не удалось загрузить поиск.", + "retry": "Повторить", + "noResults": "Ничего не найдено.", + "results": "результатов", + "navigate": "Навигация", + "select": "Открыть", + "dismiss": "Закрыть", + "matches": "Совпадения", + "status": "Статус", + "activeStatus": "Активная", + "deprecatedStatus": "Устаревшая", + "license": "Лицензия", + "maxInput": "Макс. ввод", + "maxOutput": "Макс. вывод", + "knowledge": "Граница знаний", + "capabilities": "Возможности", + "specifications": "Характеристики", + "links": "Ссылки", + "architecture": "Архитектура", + "languages": "Языки", + "json": "JSON", + "website": "Сайт", + "score": "Баллы", + "metric": "Метрика", + "dataset": "Набор данных", + "protocols": "Протоколы API", + "batchTier": "Пакет / Уровень", + "inputRate": "Ввод $/1 млн", + "outputRate": "Вывод $/1 млн", + "cacheRate": "Чтение кэша $/1 млн", + "providerModelId": "ID модели провайдера", + "viewModels": "Смотреть модели", + "text": "Текст", + "pdf": "PDF", + "modalityImage": "Изображение", + "modalityAudio": "Аудио", + "modalityVideo": "Видео", + "tableScroll": "Прокрутите, чтобы увидеть остальные столбцы", + "unknownValue": "–", + "batch": "Пакет", + "webSearch": "Веб-поиск", + "typesLabel": "Типы" } diff --git a/apps/site/src/messages/zh.json b/apps/site/src/messages/zh.json index b5517f2d..db488dd3 100644 --- a/apps/site/src/messages/zh.json +++ b/apps/site/src/messages/zh.json @@ -24,7 +24,7 @@ "language": "语言", "theme": "切换明暗主题", "attribution": "重用数据时请署名 LMSpeed,并保留字段的原始来源。", - "skip": "跳转到模型", + "skip": "跳转到目录", "licenses": "许可声明", "developersCount": "位开发者", "description": "查看模型规格,查找 API 服务商并对比公开价格。", @@ -66,5 +66,84 @@ "realtime": "实时", "extraction": "提取", "audio": "音频" - } + }, + "tagline": "开源 AI 模型数据库", + "directories": "目录", + "developers": "开发者", + "provider": "服务商", + "modelsLabel": "个模型", + "providersLabel": "家服务商", + "developersLabel": "位开发者", + "searchAction": "搜索", + "searchCatalog": "搜索模型、服务商和开发者…", + "filterModels": "筛选模型", + "filterProviders": "筛选服务商", + "filterDevelopers": "筛选开发者", + "filterListings": "筛选服务商模型", + "clear": "清除", + "all": "全部", + "openWeights": "开放权重", + "openLabel": "开放", + "closedLabel": "封闭", + "modalities": "模态", + "tools": "工具调用", + "reasoning": "推理", + "cache": "缓存", + "yes": "是", + "no": "否", + "price": "价格", + "minimumPrice": "各服务商公开的最低基础输入价与输出价,以美元/百万 Token 计。", + "sdk": "SDK / npm", + "docsLink": "文档", + "latestRelease": "最新发布", + "descriptionLabel": "简介", + "menu": "菜单", + "close": "关闭", + "copy": "复制", + "copied": "已复制", + "copyFailed": "复制失败", + "loading": "加载中…", + "loadFailed": "无法加载此条目。", + "searchFailed": "无法加载搜索索引。", + "retry": "重试", + "noResults": "未找到结果。", + "results": "条结果", + "navigate": "移动", + "select": "打开", + "dismiss": "关闭", + "matches": "匹配", + "status": "状态", + "activeStatus": "可用", + "deprecatedStatus": "已弃用", + "license": "许可证", + "maxInput": "最大输入", + "maxOutput": "最大输出", + "knowledge": "知识截止", + "capabilities": "能力", + "specifications": "规格", + "links": "链接", + "architecture": "架构", + "languages": "语言支持", + "json": "原始 JSON", + "website": "网站", + "score": "分数", + "metric": "指标", + "dataset": "数据集", + "protocols": "API 协议", + "batchTier": "批处理/服务等级", + "inputRate": "输入 $/百万", + "outputRate": "输出 $/百万", + "cacheRate": "缓存读取 $/百万", + "providerModelId": "服务商模型 ID", + "viewModels": "查看模型", + "text": "文本", + "pdf": "PDF", + "modalityImage": "图像", + "modalityAudio": "音频", + "modalityVideo": "视频", + "tableScroll": "横向滚动查看更多列", + "unknownValue": "–", + "batch": "批处理", + "webSearch": "网页搜索", + "typesLabel": "类型" } diff --git a/apps/site/src/pages/404.astro b/apps/site/src/pages/404.astro index 9c0b619e..19e50b57 100644 --- a/apps/site/src/pages/404.astro +++ b/apps/site/src/pages/404.astro @@ -1,13 +1,22 @@ +--- +import '../styles/catalogue.css'; +--- - + + Page not found · LMSpeed Models - -

    Page not found

    - Open the model and provider catalog + + +
    +

    Page not found

    + Browse models +
    diff --git a/apps/site/src/pages/[...directory].astro b/apps/site/src/pages/[...directory].astro new file mode 100644 index 00000000..346b43bb --- /dev/null +++ b/apps/site/src/pages/[...directory].astro @@ -0,0 +1,14 @@ +--- +import type { GetStaticPaths, InferGetStaticPropsType } from 'astro'; +import Catalogue from '../components/Catalogue.astro'; +import { localePath, locales, sections } from '../lib/catalogue'; + +export const getStaticPaths = (() => + locales.flatMap(locale => sections.map(section => ({ + params: { directory: localePath(locale, section).slice(1) || undefined }, + props: { locale, section }, + })))) satisfies GetStaticPaths; + +const { locale, section } = Astro.props as InferGetStaticPropsType; +--- + diff --git a/apps/site/src/pages/index.astro b/apps/site/src/pages/index.astro deleted file mode 100644 index 3cf4985c..00000000 --- a/apps/site/src/pages/index.astro +++ /dev/null @@ -1,4 +0,0 @@ ---- -import Catalogue from '../components/Catalogue.astro'; ---- - diff --git a/apps/site/src/pages/llms-full.txt.ts b/apps/site/src/pages/llms-full.txt.ts index 480fe512..918e9a85 100644 --- a/apps/site/src/pages/llms-full.txt.ts +++ b/apps/site/src/pages/llms-full.txt.ts @@ -1,4 +1,4 @@ -import { localePath, locales, messages, siteUrl } from '../lib/catalogue'; +import { locales, markdownPath, messages, siteUrl } from '../lib/catalogue'; export const GET = () => new Response( @@ -6,7 +6,7 @@ export const GET = () => > Each catalog lists the complete set of models and providers and links to their v2 cards and shards. Credit LMSpeed and retain original field sources. -${locales.map((locale) => `- [${messages[locale].title}](${siteUrl}${localePath(locale)}index.md)`).join('\n')} +${locales.map((locale) => `- [${messages[locale].title}](${siteUrl}${markdownPath(locale)})`).join('\n')} `, { headers: { diff --git a/apps/site/src/pages/ru/index.astro b/apps/site/src/pages/ru/index.astro deleted file mode 100644 index bb234c89..00000000 --- a/apps/site/src/pages/ru/index.astro +++ /dev/null @@ -1,4 +0,0 @@ ---- -import Catalogue from '../../components/Catalogue.astro'; ---- - diff --git a/apps/site/src/pages/search.json.ts b/apps/site/src/pages/search.json.ts new file mode 100644 index 00000000..731c30fa --- /dev/null +++ b/apps/site/src/pages/search.json.ts @@ -0,0 +1,3 @@ +import { searchIndex } from '../lib/directory-data'; + +export const GET = () => Response.json(searchIndex()); diff --git a/apps/site/src/pages/sitemap.xml.ts b/apps/site/src/pages/sitemap.xml.ts index d0b4da4c..07a9d861 100644 --- a/apps/site/src/pages/sitemap.xml.ts +++ b/apps/site/src/pages/sitemap.xml.ts @@ -1,17 +1,20 @@ -import { localePath, locales, siteUrl } from '../lib/catalogue'; +import { localePath, locales, sections, siteUrl } from '../lib/catalogue'; export const GET = () => { - const alternates = [ - ...locales.map( - (locale) => - ``, - ), - ``, - ].join(''); - const urls = locales.map( - (locale) => - `${siteUrl}${localePath(locale)}${alternates}`, - ); + const urls = sections.flatMap((section) => { + const href = (locale: (typeof locales)[number]) => + `${siteUrl}${localePath(locale, section)}`; + const alternates = [ + ...locales.map( + (locale) => + ``, + ), + ``, + ].join(''); + return locales.map( + (locale) => `${href(locale)}${alternates}`, + ); + }); return new Response( `${urls.join('')}`, { headers: { 'content-type': 'application/xml' } }, diff --git a/apps/site/src/pages/zh/index.astro b/apps/site/src/pages/zh/index.astro deleted file mode 100644 index b1ca1ee1..00000000 --- a/apps/site/src/pages/zh/index.astro +++ /dev/null @@ -1,4 +0,0 @@ ---- -import Catalogue from '../../components/Catalogue.astro'; ---- - diff --git a/apps/site/src/styles/catalogue.css b/apps/site/src/styles/catalogue.css index a7e4eb74..0cb64f74 100644 --- a/apps/site/src/styles/catalogue.css +++ b/apps/site/src/styles/catalogue.css @@ -1,56 +1,98 @@ :root { - font-family: "Noto Sans Variable", "PingFang SC", sans-serif; + color-scheme: light dark; + font-family: "Noto Sans Variable", system-ui, -apple-system, sans-serif; font-synthesis: none; - --background: #fff; - --foreground: #171717; - --muted: #f7f7f6; - --muted-foreground: #696860; - --border: #e7e7e4; - --primary: #2778c1; - --soft-primary: #f2f7fd; - color: var(--foreground); - background: var(--background); - font-size: 16px; - color-scheme: light; + font-variant-numeric: tabular-nums; + font-size: 14px; + color: var(--ink); + background: var(--paper); + --mono: "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace; + --paper: #fff; + --panel: #f6f7f9; + --line: #dfe3e9; + --hairline: #edf0f3; + --ink: #1c2431; + --secondary: #4d5868; + --muted: #606d7e; + --accent: #1b55bd; + --accent-button: #2058bf; + --accent-soft: #edf3ff; + --positive: #21734d; + --positive-soft: #e8f4ed; + --selection: #eef4ff; + --backdrop: #25344859; + --rail: clamp(12px, 1.25vw, 20px); } + +@media (prefers-color-scheme: dark) { + :root { + --paper: #151a22; + --panel: #1c232e; + --line: #333d4d; + --hairline: #252e3b; + --ink: #edf1f7; + --secondary: #bec9d8; + --muted: #a0aec1; + --accent: #a2bfff; + --accent-button: #245abe; + --accent-soft: #253b62; + --positive: #95d8af; + --positive-soft: #20392d; + --selection: #202f48; + --backdrop: #080b12a3; + } +} + * { box-sizing: border-box; } body { margin: 0; -} -code, -kbd { - font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + display: flex; + flex-direction: column; + height: 100svh; + overflow: hidden; } button, input, select { font: inherit; + color: inherit; } -button, -a, -select, -input { - touch-action: manipulation; +button { + cursor: pointer; } a { color: inherit; text-decoration: none; } a:hover { - color: var(--primary); + color: var(--accent); +} +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +h1, +h2, +h3, +p, +dl, +dd, +ul { + margin: 0; } -button { - cursor: pointer; +code, +kbd, +.mono, +.numeric, +.date { + font-family: var(--mono); + font-variant-numeric: tabular-nums; } -button:focus-visible, -a:focus-visible, -input:focus-visible, -select:focus-visible, -.table-scroll:focus-visible { - outline: 2px solid var(--primary); - outline-offset: 3px; +svg { + flex: none; + display: block; } .sr-only { position: absolute; @@ -58,601 +100,1202 @@ select:focus-visible, height: 1px; padding: 0; margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); white-space: nowrap; + overflow: hidden; + clip-path: inset(50%); border: 0; } .skip { - position: absolute; - top: -5rem; - left: 1rem; - z-index: 5; - background: var(--background); - padding: 1rem; + position: fixed; + top: 8px; + left: var(--rail); + z-index: 10; + padding: 8px 12px; + background: var(--paper); + transform: translateY(-160%); } .skip:focus { - top: 1rem; + transform: none; } + .site-header { - height: 4.5rem; - border-bottom: 1px solid var(--border); - background: var(--background); -} -.header-inner { - height: 100%; - max-width: 100rem; - margin: auto; + position: sticky; + top: 0; + z-index: 4; + flex: 0 0 56px; display: flex; - align-items: center; justify-content: space-between; - padding: 0 2rem; - gap: 2rem; -} -.brand { + align-items: center; + gap: 14px; + padding: 0 var(--rail); + border-bottom: 1px solid var(--line); + background: var(--paper); +} +.identity, +.header-actions, +.directory-links, +.locales { display: flex; align-items: center; - gap: 0.625rem; - font-size: 1.125rem; - font-weight: 600; - letter-spacing: -0.025em; - white-space: nowrap; } -.brand img { - border-radius: 0.375rem; +.identity { + gap: 12px; + min-width: 0; } -.brand-section { - font-size: 0.75rem; - font-weight: 500; - letter-spacing: 0; - color: var(--muted-foreground); - border-left: 1px solid var(--border); - margin-left: 0.5rem; - padding-left: 1rem; +.header-actions { + gap: 9px; + flex: none; } -.site-header nav { - display: flex; - align-items: center; - gap: 2rem; - font-size: 0.875rem; - color: var(--muted-foreground); +.brand { + font-size: 15px; + font-weight: 790; + letter-spacing: -0.035em; + flex: none; + white-space: nowrap; } -.site-header nav a { - padding: 1.625rem 0; +.brand span { + font-weight: 620; + color: var(--accent); } -.header-actions { - display: flex; - align-items: center; - gap: 1rem; - font-size: 0.8125rem; +.slash { + width: 1px; + height: 15px; + background: var(--muted); + opacity: 0.55; + transform: rotate(20deg); + flex: none; } -.language select { - border: 0; - background: var(--background); - color: var(--muted-foreground); - font-size: 0.75rem; - padding: 0.5rem; +.tagline { + font-size: 12px; + color: var(--muted); + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; } -.icon-button { - width: 2rem; - height: 2rem; - background: none; - border: 0; - color: var(--muted-foreground); - font-size: 1.25rem; +.directory-links { + gap: 2px; } -.github-link { +.directory-links a, +.locales a { + border-radius: 4px; + padding: 6px 9px; + font-size: 12px; + font-weight: 560; + color: var(--secondary); white-space: nowrap; } -main { - max-width: 100rem; - margin: auto; - padding: 3rem 2rem 0; +.locales { + gap: 2px; } -.page-heading { - display: flex; - justify-content: space-between; - gap: 2rem; +.locales a { + padding-inline: 6px; + font-size: 11px; +} +.desktop-locales { + border-left: 1px solid var(--line); + padding-left: 8px; +} +.button, +.icon-button, +.quiet { + display: inline-flex; align-items: center; - margin-bottom: 1.5rem; + justify-content: center; + gap: 6px; + min-height: 31px; + padding: 4px 9px; + border: 1px solid var(--line); + border-radius: 5px; + background: var(--paper); + font-size: 12px; + font-weight: 570; + color: var(--secondary); + white-space: nowrap; } -h1 { - font-size: 1.75rem; - line-height: 1.2; - letter-spacing: -0.01em; - font-weight: 500; - margin: 0; +.icon-button { + flex: none; + width: 32px; + padding: 0; +} +.github-link { + border-color: transparent; +} +.primary { + background: var(--accent-button); + border-color: var(--accent-button); + color: white; } -.page-heading p { - font-size: 0.875rem; - line-height: 1.625; - color: var(--muted-foreground); - margin: 0.75rem 0 0; - max-width: 48rem; -} -.primary-button { - background: var(--primary); - color: #fff; - border-radius: 0.625rem; - padding: 0.75rem 1rem; - font-size: 0.8125rem; - font-weight: 500; +.search-trigger { + min-width: 116px; + justify-content: flex-start; +} +kbd { + display: inline-flex; + justify-content: center; + min-width: 19px; + border: 1px solid var(--line); + border-radius: 4px; + padding: 1px 4px; + color: var(--muted); + background: var(--panel); + font-size: 10px; + line-height: 1.45; white-space: nowrap; } -.primary-button:hover { - color: #fff; - background: #1b64ae; + +.search-trigger kbd { + margin-inline-start: auto; } -.data-meta { - display: flex; - gap: 0.625rem; - align-items: center; - font-size: 0.75rem; - color: var(--muted-foreground); - margin-bottom: 2rem; - flex-wrap: wrap; +.mobile-trigger { + display: none; } -.catalogue { - border: 1px solid var(--border); - border-radius: 0.875rem; - overflow: hidden; - scroll-margin-top: 1rem; + +.page-scroll { + min-height: 0; + min-width: 0; + flex: 1; + display: flex; + flex-direction: column; } .toolbar { + flex: 0 0 auto; + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px 20px; + padding: 11px var(--rail); + background: var(--paper); + border-bottom: 1px solid var(--line); +} +.toolbar-line, +.filter-selects, +.quick-filters { display: flex; align-items: center; - gap: 0.5rem; - flex-wrap: wrap; - padding: 1rem; - background: var(--background); - border-bottom: 1px solid var(--border); + gap: 7px; + min-width: 0; +} +.directory-count { + margin-right: 5px; + white-space: nowrap; + color: var(--muted); + font-size: 12px; +} +.directory-count strong { + font-family: var(--mono); + color: var(--ink); + font-weight: 650; } -.search-field { +.filter-search { display: flex; align-items: center; - gap: 0.625rem; + gap: 6px; + min-width: 0; + min-height: 32px; + padding-inline: 8px; + border: 1px solid var(--line); + border-radius: 5px; + color: var(--muted); + background: var(--paper); +} +.filter-search input { + min-width: 0; + width: 136px; flex: 1; - min-width: 15rem; - padding: 0 0.75rem; - border: 1px solid var(--border); - border-radius: 0.5rem; - height: 2.5rem; - color: var(--muted-foreground); -} -.search-field input { - width: 100%; + padding: 5px 0; + border: none; + outline: none; + background: transparent; + color: var(--ink); + font-size: 12px; +} +.filter-search input::placeholder { + color: var(--muted); + opacity: 1; +} +.filter-search:focus-within { + outline: 2px solid var(--accent); + outline-offset: 1px; +} +.filter-selects label { min-width: 0; - font-size: 0.8125rem; +} +.filter-selects select { + width: 100%; + max-width: 146px; + min-height: 32px; + border: 1px solid var(--line); + border-radius: 5px; + padding: 4px 6px; + color: var(--secondary); + background: var(--paper); + font-size: 12px; +} +.quiet { border: 0; - outline: 0; + min-height: 32px; background: transparent; - color: var(--foreground); } -.search-field:focus-within { - border-color: var(--primary); - box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary) 15%, transparent); +.button:hover, +.icon-button:hover, +.quiet:hover { + color: var(--accent); + background: var(--panel); } -.search-field kbd { - white-space: nowrap; - font-size: 0.625rem; - border: 1px solid var(--border); - border-radius: 0.25rem; - padding: 0.125rem 0.25rem; -} -.filter select { - max-width: 12rem; - height: 2.5rem; - border: 1px solid var(--border); - border-radius: 0.5rem; - background: var(--background); - color: var(--foreground); - font-size: 0.75rem; - padding: 0 1.5rem 0 0.625rem; -} -.reset-button { +.primary:hover { + background: #16489f; + color: white; +} + +.quick-filters { + gap: 4px; + flex-wrap: wrap; + justify-content: flex-end; +} +.pill { + display: inline-flex; + align-items: center; + gap: 5px; + min-height: 26px; + border: 1px solid transparent; + border-radius: 4px; background: transparent; - border: 0; - color: var(--muted-foreground); - font-size: 0.75rem; - padding: 0.625rem; - min-height: 2.5rem; + color: var(--secondary); + padding: 3px 7px; + font-size: 11.5px; + font-weight: 580; + white-space: nowrap; } +.weight-filter { + margin-left: 2px; + cursor: pointer; +} + +.pill:hover { + background: var(--panel); +} +.pill[aria-pressed="true"], +.weight-filter:has(:checked) { + border-color: var(--line); + color: var(--accent); + background: var(--accent-soft); +} +.weight-filter input { + margin: 0; + accent-color: var(--accent-button); +} + .table-scroll { + flex: 1; + min-height: 0; overflow: auto; - max-height: 66vh; - min-height: 15rem; - position: relative; - scrollbar-width: thin; + overscroll-behavior: contain; +} +.table-scroll:focus-visible { + outline-offset: -2px; } table { width: 100%; border-collapse: separate; border-spacing: 0; - font-size: 0.75rem; - line-height: 1.5; + text-align: left; +} +.directory-table { + font-size: 12px; +} +.models table { + min-width: 1220px; + table-layout: fixed; +} +.col-model { + width: var(--model-column, 19.5%); +} +.col-developer { + width: var(--developer-column, 12.5%); +} +.col-providers { + width: var(--providers-column, 6.7%); +} +.col-parameters { + width: 7.8%; +} +.col-context { + width: 6.2%; +} +.col-output { + width: 6%; +} +.col-modalities { + width: 9%; +} +.col-tools { + width: 4.5%; +} +.col-reasoning { + width: 6.6%; +} +.col-weights { + width: 5.9%; +} +.col-price { + width: var(--price-column, 9%); +} +.col-released { + width: var(--released-column, 6.3%); } -thead { +.column-label { + min-width: 0; + overflow-wrap: anywhere; + white-space: normal; +} +.models td.rate { + overflow: hidden; + text-overflow: ellipsis; +} +.glyph-library { + position: absolute; + width: 0; + height: 0; +} + +.providers table, +.developers table { + min-width: 960px; +} +thead th { position: sticky; top: 0; z-index: 2; -} -thead th { - background: var(--muted); - border-bottom: 1px solid var(--border); - font-weight: 500; - text-align: left; + background: var(--panel); + border-right: 1px solid var(--line); + border-bottom: 1px solid var(--line); + color: var(--secondary); + font-size: 10px; + font-weight: 690; + letter-spacing: 0.035em; + text-transform: uppercase; white-space: nowrap; - padding: 0.875rem 1rem; } -thead th:has(button) { - padding: 0; +thead th:where(:last-child) { + border-right: 0; } thead button { display: flex; align-items: center; - gap: 1rem; - background: transparent; - color: var(--muted-foreground); - border: 0; - font-size: 0.6875rem; - padding: 0.875rem 1rem; + justify-content: space-between; + gap: 4px; width: 100%; - text-align: left; + min-height: 36px; + padding: 4px 7px; + border: 0; + background: transparent; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-transform: inherit; + text-align: inherit; +} +thead th[aria-sort] { + color: var(--accent); + background: var(--accent-soft); } .sort-icon { - font-size: 0.75rem; - opacity: 0.5; -} -th[aria-sort="descending"] button, -th[aria-sort="ascending"] button { - color: var(--foreground); -} -tbody th, -tbody td { - background: var(--background); - border-bottom: 1px solid var(--border); - padding: 0.875rem 1rem; - text-align: left; - vertical-align: middle; - white-space: nowrap; - font-weight: 400; + flex: none; + color: var(--muted); + font: 12px var(--mono); + opacity: 0.65; } +[aria-sort] .sort-icon { + flex: none; + color: var(--accent); + opacity: 1; +} +tbody td, tbody th { - min-width: 16rem; - max-width: 23rem; - position: sticky; - left: 0; - z-index: 1; + border-bottom: 1px solid var(--hairline); + border-right: 1px solid var(--hairline); + background: var(--paper); + padding: 7px 9px; + color: var(--secondary); + font-weight: 400; +} +tbody tr:hover > *, +tbody tr:focus-within > * { + background: var(--selection); +} +tr[data-entry] { + cursor: pointer; +} +.directory-table :where(tbody th:first-child) { + padding-left: var(--rail); +} +.numeric { + text-align: right; +} +.date { + white-space: nowrap; +} +thead .numeric { + font-family: inherit; + font-size: 10px; +} +thead :where(th.numeric) button { + flex-direction: row-reverse; +} +.directory-table tbody .numeric, +.directory-table tbody .date { + white-space: nowrap; + font-size: 11.5px; +} + +.entity-link { + display: block; + min-width: 0; +} +.entity-with-logo { + display: flex; + align-items: center; + gap: 8px; +} +.entity-with-logo > span:last-child { + min-width: 0; +} +.entity-name { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--ink); + font-size: 13px; + font-weight: 635; +} +a:hover .entity-name { + color: var(--accent); +} +.entity-id { + display: block; + margin-top: 2px; + color: var(--muted); + font-size: 10.5px; + overflow-wrap: anywhere; +} +.directory-table .entity-id { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.developer-link, +.external-link { + display: inline-flex; + align-items: center; + gap: 6px; +} +.developer-link { + max-width: 155px; +} +.developer-link > span:last-child, +.truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.developer-link > span:last-child { + min-width: 0; } -thead th:first-child { +.truncate { + max-width: 0; +} +.providers td.truncate { + width: 18%; +} +.developers td.truncate { + width: 46%; +} +.logo { + display: inline-grid; + place-items: center; + flex: none; + background: #fff; + border: 1px solid #e0e4eb; + border-radius: 5px; + padding: 2px; +} +.logo img { + display: block; + object-fit: contain; +} +.entity-with-logo .logo { + padding: 3px; +} +.modalities, +.chips { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} +.modalities { + flex-wrap: nowrap; +} +.modality { + flex: none; + display: inline-grid; + place-items: center; + width: 19px; + height: 19px; + border: 1px solid var(--line); + border-radius: 4px; + font: 10px var(--mono); +} +.chip, +.open-status { + display: inline-block; + width: fit-content; + border: 1px solid var(--line); + border-radius: 4px; + padding: 2px 5px; + font-size: 10px; + font-weight: 550; + white-space: nowrap; +} +.open-status { + background: var(--positive-soft); + border-color: transparent; + color: var(--positive); +} +.empty-state { position: sticky; left: 0; - z-index: 3; - min-width: 16rem; + padding: 18px var(--rail); + color: var(--muted); } -tbody tr:hover td, -tbody tr:hover th { - background: var(--muted); +.directory-footer, +.dialog-foot { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px 15px; + padding: 8px var(--rail); + border-top: 1px solid var(--line); + font-size: 11px; + color: var(--muted); + background: var(--paper); +} +.directory-footer a, +.dialog-foot a { + display: flex; + align-items: center; + gap: 3px; +} +.price-hint { + margin-right: auto; } -.model-cell { +.scroll-hint { + display: none; +} + +dialog { + color: var(--ink); + background: var(--paper); + border: 1px solid var(--line); + border-radius: 10px; + padding: 0; + width: min(660px, calc(100% - 24px)); + max-width: none; + max-height: calc(100svh - 24px); + overflow: hidden; + box-shadow: + 0 16px 64px #070c1738, + 0 4px 14px #070c1724; +} +dialog[open] { + display: flex; + flex-direction: column; +} +dialog::backdrop { + background: var(--backdrop); +} +.dialog-head, +.drawer-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + min-height: 50px; + padding: 8px 15px; + border-bottom: 1px solid var(--line); +} +.dialog-head h2 { + font-size: 15px; +} +.dialog-head .icon-button, +.drawer-bar .icon-button { + border-color: transparent; +} +.dialog-head .icon-button:hover, +.drawer-bar .icon-button:hover { + border-color: var(--line); +} +.search-dialog { + width: min(610px, calc(100% - 24px)); + margin: min(13svh, 106px) auto auto; + max-height: min(530px, 78svh); +} +.palette-field { display: flex; align-items: center; - gap: 0.75rem; + gap: 11px; + padding: 12px 15px; + border-bottom: 1px solid var(--line); + color: var(--muted); } -.model-cell > div { +.palette-field input { min-width: 0; + width: 100%; + border: 0; + background: transparent; + color: var(--ink); + padding: 5px 0; + font-size: 16px; + outline: 0; +} +.palette-field input::placeholder { + color: var(--muted); + opacity: 1; +} +.escape-key { + flex: none; + border: 0; + padding: 0; + border-radius: 4px; + background: none; +} +.palette-scroll { + min-height: 0; + overflow: auto; + overscroll-behavior: contain; + padding: 4px 7px 7px; } -.model-cell a { - font-size: 0.8125rem; - font-weight: 500; +#palette-status { + padding: 8px; + color: var(--muted); + font-size: 11px; } -.model-id { +#palette-retry { + margin-left: 8px; +} +.palette-option { + display: grid; + grid-template-columns: 30px minmax(0, 1fr) auto; + gap: 9px; + align-items: center; + padding: 7px 8px; + border: 1px solid transparent; + border-radius: 5px; + color: var(--ink); +} +.palette-option .logo { + min-height: 30px; +} +.palette-option:hover, +.palette-option[aria-selected="true"] { + color: var(--ink); + background: var(--accent-soft); +} +.palette-option[aria-selected="true"] { + border-color: var(--line); +} +.palette-label strong, +.palette-label code { display: block; - color: var(--muted-foreground); - font-family: ui-monospace, SFMono-Regular, Menlo, monospace; - font-size: 0.625rem; - margin-top: 0.125rem; - max-width: 19rem; overflow: hidden; + white-space: nowrap; text-overflow: ellipsis; } -.number { - font-variant-numeric: tabular-nums; +.palette-label strong { + font-weight: 630; +} +.palette-label code { + margin-top: 2px; + font-size: 11px; + color: var(--muted); } -.table-footer { +mark { + color: var(--ink); + background: #ffcb667a; + border-radius: 2px; +} +.palette-foot { display: flex; - justify-content: space-between; align-items: center; + gap: 8px 14px; flex-wrap: wrap; - gap: 0.5rem 1rem; - padding: 0.875rem 1rem; - font-size: 0.6875rem; - color: var(--muted-foreground); - background: var(--background); + padding: 8px 15px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: 11px; } -.empty-state { - text-align: center; - padding: 4rem 1.5rem; - color: var(--muted-foreground); + +.help-content { + overflow: auto; + padding: 16px; +} +.help-content > p { + margin-bottom: 12px; + color: var(--secondary); +} +.sdk-tabs { + display: flex; + gap: 4px; + flex-wrap: wrap; + border-bottom: 1px solid var(--line); +} +.sdk-tabs button { + border: 0; + border-bottom: 2px solid transparent; + padding: 6px 8px; + color: var(--secondary); + background: transparent; + font-size: 12px; +} +thead button:hover { + background: var(--accent-soft); + color: var(--accent); +} +thead button:focus-visible { + outline-offset: -2px; } -.empty-state h2 { - font-size: 1rem; - font-weight: 500; - color: var(--foreground); +.sdk-tabs button[aria-selected="true"] { + border-color: var(--accent); + color: var(--accent); + font-weight: 650; } -.empty-state p { - font-size: 0.875rem; +.sdk-tabs button:hover { + background: var(--panel); } -.docs-section { +.sdk-panel { + margin-top: 12px; display: grid; - grid-template-columns: 1fr 1.25fr; - gap: 4rem; - padding: 3rem 0; - margin-top: 1rem; -} -.docs-section h2 { - font-size: 1.25rem; - font-weight: 500; - letter-spacing: -0.01em; + gap: 8px; +} +.code-block { + display: flex; + align-items: start; + justify-content: space-between; + gap: 8px; + border: 1px solid var(--line); + border-radius: 5px; + padding: 8px; + background: var(--panel); +} +.code-block pre { + min-width: 0; margin: 0; + padding: 4px; + overflow: auto; + font-size: 11.5px; + line-height: 1.6; } -.docs-section p { - font-size: 0.875rem; - color: var(--muted-foreground); - line-height: 1.625; - max-width: 32rem; +.copy { + min-height: 25px; + font-size: 10px; } -.docs-section > div > a { - font-size: 0.75rem; - color: var(--primary); +.mobile-dialog { + width: min(330px, 100%); + height: 100svh; + max-height: none; + margin: 0 0 0 auto; + border-radius: 0; } -.code-examples details { - border-bottom: 1px solid var(--border); - font-size: 0.8125rem; +.mobile-content { + display: grid; + justify-items: stretch; + gap: 10px; + padding: 15px; + overflow: auto; } -.code-examples summary { - cursor: pointer; - padding: 0.875rem 0; - font-weight: 500; +.mobile-content .directory-links { + display: grid; + gap: 4px; + padding-bottom: 10px; + border-bottom: 1px solid var(--line); } -.code-examples pre { - padding: 0.75rem 1rem; - margin: 0 0 1rem; - border-radius: 0.5rem; - background: var(--muted); - font-size: 0.75rem; - line-height: 1.8; +.mobile-content :where(.directory-links) a { + padding: 9px; + font-size: 14px; +} +.mobile-content .button { + justify-content: flex-start; +} +.mobile-content .locales { + margin-top: 4px; +} + +.detail-dialog { + width: min(780px, 100%); + height: 100svh; + max-height: none; + margin: 0 0 0 auto; + border-radius: 0; + border-width: 0 0 0 1px; +} +.drawer-bar { + justify-content: flex-end; + flex: none; + background: var(--panel); + padding-inline: 20px; +} +.drawer-kind { + margin-right: auto; + font: 11px var(--mono); + font-weight: 650; + letter-spacing: 0.07em; + text-transform: uppercase; + color: var(--muted); +} +.drawer-body { + min-height: 0; overflow: auto; - white-space: pre-wrap; + padding: 19px 20px 32px; + overscroll-behavior: contain; +} +.drawer-heading { + display: flex; + align-items: flex-start; + gap: 12px; + margin-bottom: 13px; +} +.drawer-heading > div { + min-width: 0; +} +.drawer-heading .logo { + margin-top: 2px; + padding: 7px; + border-radius: 7px; +} +.drawer-heading h2 { + font-size: clamp(23px, 4vw, 30px); + line-height: 1.15; + font-weight: 720; overflow-wrap: anywhere; } -footer { - border-top: 1px solid var(--border); - max-width: 100rem; - padding: 1.5rem 2rem; - margin: auto; +.identity-line { display: flex; - justify-content: space-between; - gap: 1rem; - color: var(--muted-foreground); - font-size: 0.75rem; + align-items: center; + flex-wrap: wrap; + gap: 4px 8px; + margin-top: 5px; + color: var(--muted); } -.footer-links { +.identity-line code { + overflow-wrap: anywhere; + font-size: 12px; +} +.detail-description { + margin: 12px 0; + color: var(--secondary); + font-size: 13px; + line-height: 1.6; +} +.drawer-links { display: flex; - gap: 1.5rem; + flex-wrap: wrap; + gap: 6px 11px; + margin-block: 10px 13px; + font-size: 12px; } -.dark { - --background: #171717; - --foreground: #f5f5f5; - --muted: #222; - --muted-foreground: #a4a39d; - --border: #323231; - --soft-primary: #102541; - color-scheme: dark; +.linked-entities a { + display: flex; + align-items: center; + gap: 5px; + padding: 4px 7px; + border: 1px solid var(--line); + border-radius: 5px; + font-size: 12px; +} +.drawer-links a, +.resource-list a, +.listing-name, +.detail-table-scroll td a { + color: var(--accent); + text-decoration: underline; + text-decoration-color: color-mix(in srgb, var(--accent) 44%, transparent); + text-underline-offset: 3px; } -@media (prefers-color-scheme: dark) { - :root:not(.light) { - --background: #171717; - --foreground: #f5f5f5; - --muted: #222; - --muted-foreground: #a4a39d; - --border: #323231; - --soft-primary: #102541; - color-scheme: dark; - } -} -@media (max-width: 900px) { - .header-inner, - main, - footer { - padding-left: 1.25rem; - padding-right: 1.25rem; - } - .site-header nav { - gap: 1rem; - } - .header-actions { - gap: 0.5rem; +.fact-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 1px; + margin-block: 12px; + padding: 1px; + background: var(--paper); + border-radius: 5px; + overflow: hidden; + outline: 1px solid var(--line); + outline-offset: -1px; +} +.fact-grid > div { + min-width: 0; + background: var(--paper); + padding: 9px 10px; + box-shadow: 0 0 0 1px var(--line); +} +.fact-grid dt { + color: var(--muted); + font-size: 10px; + font-weight: 620; + text-transform: uppercase; +} +.fact-grid dd { + margin-top: 4px; + font: 12px / 1.5 var(--mono); + overflow-wrap: anywhere; +} +.drawer-section { + margin-top: 19px; +} +.drawer-section h3 { + margin-bottom: 8px; + font-size: 13px; + font-weight: 720; +} +.drawer-section .fact-grid { + grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)); +} +.drawer-section .fact-grid dd { + color: var(--secondary); +} +.resource-list { + display: grid; + gap: 5px; + padding-left: 17px; + font-size: 12px; + overflow-wrap: anywhere; +} +.resource-list code, +.resource-list small { + color: var(--muted); + font-size: 11px; +} +.linked-entities { + display: flex; + flex-wrap: wrap; + gap: 6px; + list-style: none; + padding: 0; +} +.drawer-links a:hover, +.resource-list a:hover, +.listing-name:hover { + text-decoration-color: currentColor; +} +.linked-entities a:hover { + background: var(--panel); +} +.detail-table-scroll { + overflow: auto; + max-height: 440px; + border: 1px solid var(--line); + border-radius: 5px; +} +.detail-table-scroll:focus-visible { + outline-offset: -2px; +} +.detail-table-scroll table { + min-width: 100%; + width: max-content; + font-size: 12px; +} +.detail-table-scroll th, +.detail-table-scroll td { + max-width: 230px; +} +.detail-table-scroll td { + white-space: nowrap; +} +.detail-table-scroll thead th { + padding: 8px; +} +.detail-table-scroll thead th:has(button) { + padding: 0; +} + +.directory-table :where(thead th:first-child button) { + padding-left: var(--rail); +} + +.detail-table-scroll th:first-child button { + padding-left: 9px; +} +.detail-table-scroll tbody tr:last-child > * { + border-bottom: 0; +} +.listing-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-block: 17px 8px; +} +.listing-count, +.listing-note { + color: var(--muted); + font-size: 11px; +} +.listing-note { + margin-top: 8px; +} + +:lang(ru) .models table { + min-width: 1370px; +} +.directory-links a:hover, +.locales a:hover { + background: var(--panel); + color: var(--ink); +} +.directory-links [aria-current], +.locales [aria-current] { + color: var(--accent); + background: var(--accent-soft); +} +tbody td:last-child { + border-right: 0; +} +:is(.providers, .developers) .directory-table th:first-child { + min-width: 204px; + width: 26%; + max-width: 0; +} + +@media (max-width: 1320px) { + .toolbar:has(.quick-filters) { + flex-wrap: wrap; } - .docs-section { - gap: 2rem; + .quick-filters { + justify-content: flex-start; } - .brand-section { +} + +@media (max-width: 1100px) { + .tagline, + .slash { display: none; } } -@media (max-width: 600px) { - .site-header { - height: 4rem; - } - .header-inner { - gap: 0.75rem; - } - .site-header nav { + +@media (max-width: 767px) { + .desktop-nav, + .github-link, + .header-help, + .desktop-locales, + .search-trigger kbd, + .filter-search kbd { display: none; } - .github-link { - font-size: 0.75rem; + .mobile-trigger { + display: inline-flex; } - .brand { - font-size: 1rem; - gap: 0.5rem; + .search-trigger { + min-width: auto; } - .brand img { - height: 1.75rem; - width: 1.75rem; + .site-header { + gap: 6px; } - main { - padding-top: 2rem; + .header-actions { + gap: 6px; } - .page-heading { - align-items: flex-start; - gap: 1rem; - flex-direction: column; + .toolbar, + .toolbar-line { + width: 100%; } - h1 { - font-size: 1.5rem; + .toolbar { + gap: 7px; + padding-block: 8px; } - .primary-button { - align-self: flex-start; + .toolbar-line { + flex-wrap: wrap; } - .data-meta { - row-gap: 0.375rem; - margin-bottom: 1.5rem; + .directory-count { + margin: 0; } - .toolbar { - padding: 0.75rem; - gap: 0.5rem; + .toolbar-line > .filter-search { + flex: 1; } - .search-field { - flex-basis: 100%; - min-width: 0; + .filter-selects { + order: 1; + flex: 0 0 100%; } - .filter { + .filter-selects label { flex: 1; - min-width: 0; } - .filter select { - width: 100%; + .filter-selects select { max-width: none; - padding-left: 0.5rem; - font-size: 0.6875rem; } - .reset-button { - padding: 0.5rem; + .quick-filters { + gap: 3px; } - .table-scroll { - max-height: 65vh; + .pill { + padding-inline: 6px; } - tbody th, - thead th:first-child { - min-width: 12rem; - max-width: 13rem; + .directory-table { + table-layout: fixed; } - tbody th, - tbody td { - padding: 0.75rem; + .models { + --model-column: 151px; + --developer-column: 117px; + --providers-column: 7.9%; + --price-column: 11.8%; + --released-column: 10%; } - .model-id { - max-width: 9rem; + .providers th:nth-child(3) { + width: 218px; } - .model-cell { - gap: 0.5rem; + .developers th:last-child { + width: 285px; } - .model-cell a { - font-size: 0.75rem; + :is(.providers, .developers) .directory-table th:first-child { + width: 172px; + min-width: 172px; + max-width: none; } - .docs-section { - grid-template-columns: 1fr; - gap: 1rem; - padding: 2rem 0; + .directory-table tr > :first-child { + position: sticky; + left: 0; + z-index: 1; + box-shadow: 3px 0 3px -3px #4f5d7794; } - footer { - flex-direction: column; - line-height: 1.6; + .directory-table thead tr > :first-child { + z-index: 3; } - .footer-links { - gap: 1rem; + .directory-footer { + gap: 6px 8px; } -} - -@media (max-width: 600px) { - .filter { - flex: 1 1 calc(50% - 0.5rem); + .scroll-hint { + display: inline; + margin-right: auto; + } + .price-hint { + display: none; } - .reset-button { - flex: 1 1 calc(50% - 0.5rem); - text-align: left; + .drawer-bar { + padding-inline: 12px; } - .model-cell a { - display: block; - max-width: 10rem; - overflow: hidden; - text-overflow: ellipsis; + .drawer-body { + padding: 14px 12px 22px; } - .model-cell { - min-width: 0; + .fact-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); } } -.catalogue-tabs { - display: flex; - gap: 1.25rem; - margin-bottom: 0.75rem; - border-bottom: 1px solid var(--border); -} -.catalogue-tabs a { - display: block; - padding: 0.625rem 0.25rem; - border-bottom: 2px solid transparent; - color: var(--muted-foreground); - font-size: 0.875rem; +[hidden] { + display: none; } -.catalogue-tabs a[aria-selected="true"] { - border-color: var(--primary); - color: var(--foreground); - font-weight: 600; -} -.catalogue + .catalogue { - margin-top: 1rem; -} -.model-cell img { - flex: 0 0 24px; - border-radius: 0.25rem; - background: #fff; - padding: 2px; -} -.cell-line { - display: block; -} -.cell-line > span { - color: var(--muted-foreground); -} -.wrapping { - min-width: 12rem; - max-width: 24rem; - white-space: normal; - overflow-wrap: anywhere; -} -.wrapping details { - margin-top: 0.25rem; -} -.wrapping summary { - cursor: pointer; - color: var(--muted-foreground); -} -.wrapping ul { - margin: 0.375rem 0 0; - padding-left: 1.1rem; -} -.api-links { - display: flex; - flex-wrap: wrap; - gap: 0.75rem; - font-size: 0.8125rem; -} -.api-links a, -.wrapping a { - text-decoration: underline; - text-underline-offset: 0.18em; + +.not-found { + display: grid; + justify-items: start; + gap: 14px; + padding: 32px var(--rail); } diff --git a/apps/site/wrangler.jsonc b/apps/site/wrangler.jsonc index 44361b48..d58ba896 100644 --- a/apps/site/wrangler.jsonc +++ b/apps/site/wrangler.jsonc @@ -5,7 +5,7 @@ "assets": { "directory": "./dist", "not_found_handling": "404-page", - "html_handling": "auto-trailing-slash" + "html_handling": "drop-trailing-slash" }, "routes": [ { diff --git a/scripts/validate-artifacts.ts b/scripts/validate-artifacts.ts index 4d72525d..18ac77cc 100644 --- a/scripts/validate-artifacts.ts +++ b/scripts/validate-artifacts.ts @@ -2,6 +2,13 @@ import assert from 'node:assert/strict'; import { readdir, readFile, stat } from 'node:fs/promises'; import { join, relative } from 'node:path'; import { gzipSync } from 'node:zlib'; +import { + localePath, + locales, + markdownPath, + sections, + siteUrl, +} from '../apps/site/src/lib/catalogue'; import { normalizedCatalogSchema } from '../packages/core/src/index'; import { artifacts, @@ -108,17 +115,87 @@ assertDeployment( expected.commit, ); +const htmlRoutes = new Set(['404.html']); +const sitemap = await read('sitemap.xml'); +for (const section of sections) { + for (const locale of locales) { + const path = localePath(locale, section); + const artifact = + path === '/' ? 'index.html' : `${path.slice(1)}/index.html`; + htmlRoutes.add(artifact); + const page = await read(artifact); + const canonical = `${siteUrl}${path}`; + assert( + page.includes(``), + `Invalid language for ${path}`, + ); + assert( + page.includes(`rel="canonical" href="${canonical}"`), + `Invalid canonical for ${path}`, + ); + assert( + page.includes(`property="og:url" content="${canonical}"`), + `Invalid Open Graph URL for ${path}`, + ); + assert( + page.includes( + `type="text/markdown" href="${siteUrl}${markdownPath(locale)}"`, + ), + ); + assert(sitemap.includes(`${canonical}`)); + for (const language of [...locales, 'x-default'] as const) { + const alternate = localePath( + language === 'x-default' ? 'en' : language, + section, + ); + const attributes = `hreflang="${language}" href="${siteUrl}${alternate}"`; + assert( + page.includes(attributes), + `Missing ${language} alternate for ${path}`, + ); + assert( + sitemap.includes(attributes), + `Missing sitemap alternate for ${path}`, + ); + } + } +} +assert.deepEqual( + new Set(files.filter((file) => file.endsWith('.html'))), + htmlRoutes, +); +assert.equal(sitemap.match(//g)?.length, htmlRoutes.size - 1); + +const search = await read('search.json'); +assert(gzipSync(search).length < 100_000, 'Search index exceeds 100 KB gzip'); +const searchItems: { kind: string; id: string; name: string }[] = + JSON.parse(search); +for (const [kind, records] of [ + ['model', artifacts.modelCards], + ['provider', artifacts.providerShards], + ['developer', artifacts.models.developers], +] as const) { + const entries = searchItems.filter((item) => item.kind === kind); + const expected = Object.entries(records).map( + ([id, { name }]) => [id, name] as const, + ); + assert.equal(entries.length, expected.length, `Invalid ${kind} search count`); + assert.deepEqual( + new Map(entries.map(({ id, name }) => [id, name])), + new Map(expected), + ); +} +assert.equal( + searchItems.length, + artifacts.api.counts.models + + artifacts.api.counts.providers + + artifacts.api.counts.developers, +); + for (const path of [ - 'index.html', - 'zh/index.html', - 'ru/index.html', - '404.html', - 'index.md', - 'zh/index.md', - 'ru/index.md', + ...locales.map((locale) => markdownPath(locale).slice(1)), 'llms.txt', 'llms-full.txt', - 'sitemap.xml', 'licenses/models-dev.txt', 'licenses/logos.txt', ]) @@ -127,6 +204,8 @@ for (const path of [ const sizes = Object.fromEntries( await Promise.all( [ + 'index.html', + 'search.json', 'v2/api.json', 'v2/models.json', 'v2/index.json', @@ -146,6 +225,7 @@ console.log( { buildHash: expected.buildHash, files: files.length, + htmlPages: htmlRoutes.size, providers: Object.keys(artifacts.providerShards).length, models: Object.keys(artifacts.modelCards).length, logos: Object.keys(artifacts.logos).length, diff --git a/tests/site.spec.ts b/tests/site.spec.ts index 88c65965..e8666c87 100644 --- a/tests/site.spec.ts +++ b/tests/site.spec.ts @@ -101,81 +101,276 @@ test('user discovers the schema, coverage, shared icons and localized markdown @ } }); -test('user filters models and opens the provider directory @site', async ({ +test('user compares and filters the desktop model directory @site', async ({ page, request, }) => { - // Given the English catalog is open. - await page.goto('/'); + // Given the English catalog is open in a desktop browser. + await page.setViewportSize({ width: 1440, height: 900 }); + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (message) => { + if (message.type() === 'error') errors.push(message.text()); + }); const { counts } = await (await request.get('/deployment.json')).json(); - // When the user combines keyword, developer, type and modality filters. - await page.getByRole('searchbox').fill('openai/gpt-5'); - await page - .getByRole('combobox', { name: 'Developer', exact: true }) - .selectOption('openai'); - await page - .getByRole('combobox', { name: 'Type', exact: true }) - .selectOption('chat'); - await page - .getByRole('combobox', { name: 'Modality', exact: true }) - .selectOption('text'); - // Then the matched model links to its card and the Providers tab lists the public API and price preview. - const model = page - .getByRole('row') - .filter({ has: page.getByRole('link', { name: 'GPT-5', exact: true }) }); - await expect(model).toBeVisible(); - await expect(model.locator('img')).toHaveAttribute( - 'src', - '/v2/logos/openai.svg', + await page.goto('/'); + const table = page.getByRole('table', { name: 'Models', exact: true }); + await expect(table.getByRole('row')).toHaveCount(counts.models + 1); + await capture(page, 'desktop-light'); + await page.emulateMedia({ colorScheme: 'dark' }); + await capture(page, 'desktop-dark'); + // When the reader sorts by context and applies a keyword and type filter. + const context = table.getByRole('columnheader', { name: 'Context' }); + await context.getByRole('button').click(); + await expect(context).toHaveAttribute('aria-sort', 'descending'); + const first = table.getByRole('row').nth(1); + const highest = await first.getByRole('cell').nth(3).textContent(); + await context.getByRole('button').click(); + await expect(context).toHaveAttribute('aria-sort', 'ascending'); + const lowest = await first.getByRole('cell').nth(3).textContent(); + expect(Number((highest ?? '').replaceAll(',', ''))).toBeGreaterThan( + Number((lowest ?? '').replaceAll(',', '')), ); + await page + .getByRole('searchbox', { name: 'Filter models' }) + .fill('openai/gpt-5'); + await page.getByRole('button', { name: 'Chat', exact: true }).click(); + // Then GPT-5 remains visible, clearing restores all rows, and the page fits without errors. await expect( - model.getByRole('link', { name: 'GPT-5', exact: true }), - ).toHaveAttribute('href', '/v2/models/openai/gpt-5.json'); - await page.getByRole('searchbox').fill('missing-catalog-entry'); - await expect(page.getByRole('status')).toContainText(`0 / ${counts.models}`); - await page.getByRole('button', { name: 'Reset filters' }).click(); - await expect(model).toBeVisible(); - await page.getByRole('tab', { name: 'Models' }).focus(); - await page.keyboard.press('ArrowRight'); - await expect( - page.getByRole('tab', { name: 'Providers', selected: true }), - ).toBeFocused(); + table.getByRole('link', { name: 'GPT-5', exact: true }), + ).toBeVisible(); + await page.getByRole('button', { name: 'Clear', exact: true }).click(); + await expect(table.getByRole('row')).toHaveCount(counts.models + 1); + await expectViewport(page, 1440); + expect( + await page + .getByRole('region', { name: 'Models' }) + .evaluate((element) => element.scrollWidth - element.clientWidth), + ).toBe(0); + expect(errors).toEqual([]); +}); + +test('user finds a model with the command palette and opens its shard @site', async ({ + page, +}) => { + // Given the directory opens without requesting the GPT-5 card. + const requests: string[] = []; + page.on('request', (request) => + requests.push(new URL(request.url()).pathname), + ); + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto('/'); + expect(requests).not.toContain('/v2/models/openai/gpt-5.json'); + // When the reader opens Search, enters the canonical ID and navigates with the keyboard. + await page.keyboard.press('Meta+k'); + const palette = page.getByRole('dialog', { name: 'Search' }); + const query = palette.getByRole('combobox'); + await expect(query).toBeFocused(); + await query.fill('openai/gpt-5'); + await expect(palette.getByRole('option').first()).toContainText( + 'openai/gpt-5', + ); + await expect(palette.locator('mark').first()).toBeVisible(); + await capture(page, 'search'); + await query.press('ArrowDown'); + await query.press('ArrowUp'); + const shard = page.waitForResponse((response) => + response.url().endsWith('/v2/models/openai/gpt-5.json'), + ); + await query.press('Enter'); + expect((await shard).ok()).toBe(true); + // Then the detail opens at a shareable URL and Escape returns to the directory. + const detail = page.getByRole('dialog', { name: 'GPT-5', exact: true }); + await expect(detail.getByText('400,000', { exact: true })).toBeVisible(); await expect( - page.getByRole('tabpanel', { name: 'Providers' }).getByRole('row'), - ).toHaveCount(counts.providers + 1); - const provider = page + detail + .getByRole('heading', { name: 'Providers' }) + .locator('..') + .getByRole('link', { name: 'OpenAI', exact: true }), + ).toHaveAttribute('href', '/providers?provider=openai'); + expect(new URL(page.url()).searchParams.get('model')).toBe('openai/gpt-5'); + await capture(page, 'model-detail'); + await page.keyboard.press('Escape'); + await expect(detail).toBeHidden(); + expect(new URL(page.url()).searchParams.has('model')).toBe(false); + await page.getByRole('button', { name: 'Search', exact: true }).click(); + await expect(palette).toBeVisible(); +}); + +test('user opens provider rates and browses developers @site', async ({ + page, + request, +}) => { + // Given the reader starts on Models. + await page.goto('/'); + const { counts } = await (await request.get('/deployment.json')).json(); + // When the reader visits Providers and opens OpenAI. + const nav = page.getByRole('navigation', { name: 'Directories' }); + await nav.getByRole('link', { name: 'Providers' }).click(); + await expect(page).toHaveURL(/\/providers$/); + const providers = page.getByRole('table', { name: 'Providers', exact: true }); + await expect(providers.getByRole('row')).toHaveCount(counts.providers + 1); + const shard = page.waitForResponse((response) => + response.url().endsWith('/v2/providers/openai.json'), + ); + await providers.getByRole('link', { name: 'OpenAI', exact: true }).click(); + expect((await shard).ok()).toBe(true); + // Then the shard provides searchable pricing and Developers is a separate directory. + const detail = page.getByRole('dialog', { name: 'OpenAI', exact: true }); + await detail.getByRole('searchbox').fill('gpt-5'); + const rates = detail + .getByRole('table') .getByRole('row') - .filter({ has: page.getByRole('link', { name: 'OpenAI', exact: true }) }); - const openai = await (await request.get('/v2/providers/openai.json')).json(); - await expect(provider).toContainText(openai.api); - await expect(provider).toContainText('$'); - await page.getByText('JavaScript / TypeScript', { exact: true }).click(); + .filter({ + has: page.getByText('gpt-5', { exact: true }), + }); + await expect(rates).toContainText('$1.25'); + await expect(rates).toContainText('$10.00'); + await expect(rates).toContainText('$0.125'); + const output = detail.getByRole('columnheader', { + name: 'Output $/1M', + exact: true, + }); + await output.getByRole('button').click(); + await expect(output).toHaveAttribute('aria-sort', 'descending'); + await page.keyboard.press('Escape'); + await nav.getByRole('link', { name: 'Developers' }).click(); + await expect(page).toHaveURL(/\/developers$/); + const developers = page.getByRole('table', { + name: 'Developers', + exact: true, + }); + await expect(developers.getByRole('row')).toHaveCount(counts.developers + 1); + await developers.getByRole('link', { name: 'OpenAI', exact: true }).click(); + await expect( + page + .getByRole('dialog', { name: 'OpenAI' }) + .getByRole('link', { name: 'View models' }), + ).toHaveAttribute('href', '/?by=openai'); +}); + +test('user follows API and SDK quick starts @site', async ({ + page, + context, +}) => { + // Given the directory is open and the browser permits clipboard access. + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + await page.goto('/'); + // When the reader opens How to use and selects the SDK tabs. + await page.getByRole('button', { name: 'How to use' }).click(); + const help = page.getByRole('dialog', { name: 'How to use' }); + const panel = help.getByRole('tabpanel'); + await expect(panel).toContainText('/v2/api.json'); + await panel.getByRole('button', { name: 'Copy', exact: true }).click(); await expect( - page.getByText(/const model = await client.fetchModel/), + panel.getByRole('button', { name: 'Copied', exact: true }), ).toBeVisible(); + expect(await page.evaluate(() => navigator.clipboard.readText())).toContain( + '/v2/models/openai/gpt-5.json', + ); + // Then each tab shows the pinned install command, an on-demand example, and a way to copy it. + for (const [tab, version, example] of [ + ['JavaScript', '@lmspeed/models@0.2.0', 'fetchModel'], + ['Python', 'lmspeed-models==0.2.0', 'fetch_model'], + ['Rust', 'lmspeed-models@0.2.0', 'fetch_model'], + ['Go', 'github.com/lmspeed/models/sdk/go@v0.2.0', 'FetchModel'], + ]) { + await help.getByRole('tab', { name: tab, exact: true }).click(); + await expect(help.getByRole('tabpanel')).toContainText(version); + await expect(help.getByRole('tabpanel')).toContainText(example); + await expect( + help + .getByRole('tabpanel') + .getByRole('button', { name: 'Copy', exact: true }), + ).toHaveCount(2); + } }); -test('user switches language with filters and anchor on a narrow screen @site', async ({ +test('user switches languages on a shared detail URL from a narrow screen @site', async ({ page, + context, }) => { - // Given a Chinese page with an explicit filter at mobile width. + // Given the English model directory opens a shared GPT-5 detail link at 390 px. + await page.setViewportSize({ width: 390, height: 844 }); + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (message) => { + if (message.type() === 'error') errors.push(message.text()); + }); + const query = '?model=openai/gpt-5&utm_source=share#models'; + await page.goto('/'); + await capture(page, 'mobile'); + await page.goto(`/${query}`); + // When the reader switches the language from the detail to Chinese and then Russian. + for (const [language, path] of [ + ['中文', '/zh'], + ['RU', '/ru'], + ]) { + const dialog = page.getByRole('dialog', { name: 'GPT-5', exact: true }); + await dialog.getByRole('link', { name: language, exact: true }).click(); + await expect(page).toHaveURL( + (url) => url.pathname === path && url.search + url.hash === query, + ); + await expect(dialog).toBeVisible(); + await expectViewport(page, 390); + } + // Then both switches preserve the detail and URL state without saving a locale preference. + expect(await context.cookies()).toEqual([]); + expect(await page.evaluate(() => Object.keys(localStorage))).toEqual([]); + await page.keyboard.press('Escape'); await page.setViewportSize({ width: 360, height: 800 }); - await page.goto('/zh/?type=image#models'); - // When the reader chooses English. + await page.getByRole('button', { name: 'Меню', exact: true }).click(); await page - .getByRole('combobox', { name: '语言', exact: true }) - .selectOption('/'); - // Then the English route preserves the filter and anchor and fits the viewport. - await page.waitForURL( - (url) => - url.pathname === '/' && - url.searchParams.get('type') === 'image' && - url.hash === '#models', - ); - await expect( - page.getByRole('combobox', { name: 'Type', exact: true }), - ).toHaveValue('image'); + .getByRole('dialog', { name: 'Меню' }) + .getByRole('link', { name: 'Провайдеры' }) + .click(); + await expect(page).toHaveURL(/\/ru\/providers$/); + await expectViewport(page, 360); + expect(errors).toEqual([]); +}); + +async function expectViewport( + page: import('@playwright/test').Page, + width: number, +) { expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe( - 360, + width, + ); + expect(await page.evaluate(() => document.body.scrollWidth)).toBe(width); +} + +async function capture(page: import('@playwright/test').Page, name: string) { + if (process.env.MODELS_SITE_SCREENSHOTS === '1') { + await page.screenshot({ + path: `.tmp-verify/${name}.png`, + animations: 'disabled', + }); + } +} + +test('user searches other directories and follows an on-demand provider link @site', async ({ + page, +}) => { + // Given the global palette is available from the Developers directory. + await page.goto('/developers'); + await page.getByRole('button', { name: 'Search', exact: true }).click(); + const palette = page.getByRole('dialog', { name: 'Search' }); + const query = palette.getByRole('combobox'); + // When the reader searches for OpenAI across the catalog. + await query.fill('openai'); + const options = palette.getByRole('option'); + await expect(options.filter({ hasText: 'Developer' }).first()).toBeVisible(); + const provider = options.filter({ hasText: 'Provider' }).first(); + await expect(provider).toContainText('OpenAI'); + await provider.click(); + // Then the provider drawer opens and the same provider can be reached through a localized directory link. + await expect(page.getByRole('dialog', { name: 'OpenAI' })).toBeVisible(); + await page.goto('/zh/providers?provider=openai&ref=compare#providers'); + const drawer = page.getByRole('dialog', { name: 'OpenAI' }); + await expect(drawer.getByRole('table')).toBeVisible(); + await drawer.getByRole('link', { name: 'RU' }).click(); + await expect(page).toHaveURL( + /\/ru\/providers\?provider=openai&ref=compare#providers$/, ); + await expect(drawer.getByRole('table')).toBeVisible(); }); From 70a08a20cad1652a5c0f69eb02a4145a9615644e Mon Sep 17 00:00:00 2001 From: Nexmoe <16796652+nexmoe@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:49:55 +0800 Subject: [PATCH 2/2] fix: avoid duplicate catalog PR title and trailing newline in release notes --- .github/sync-models/publish.sh | 6 +++++- scripts/release/prepare.ts | 15 +++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/.github/sync-models/publish.sh b/.github/sync-models/publish.sh index 246ca78c..a6b240ac 100755 --- a/.github/sync-models/publish.sh +++ b/.github/sync-models/publish.sh @@ -86,7 +86,11 @@ if [[ $safe == false && -n $pr ]]; then [[ $(auto_enabled "$pr") == false ]] || fail "Auto-merge is still enabled for #$pr" fi -title="chore(sync): update $target catalog" +if [[ $target == catalog ]]; then + title="chore(sync): update model catalog" +else + title="chore(sync): update $target catalog" +fi tree=$("${git[@]}" write-tree) # Reuse an identical remote commit to avoid restarting CI on every scheduled run. remote=$("${git[@]}" ls-remote origin "refs/heads/$branch") diff --git a/scripts/release/prepare.ts b/scripts/release/prepare.ts index a2046ed8..ed90306b 100644 --- a/scripts/release/prepare.ts +++ b/scripts/release/prepare.ts @@ -93,10 +93,17 @@ try { } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } -const notes = `## ${version}\n\n${changes.map((change) => `- ${change.summary}`).join('\n')}\n\n`; -const existingNotes = previous.replace(/^# Changelog\r?\n(?:\r?\n)*/, ''); +const notes = `## ${version}\n\n${changes.map((change) => `- ${change.summary}`).join('\n')}\n`; +const existingNotes = previous + .replace(/^# Changelog\r?\n(?:\r?\n)*/, '') + .trim(); if (!existingNotes.startsWith(`## ${version}\n`)) - await writeFile('CHANGELOG.md', `# Changelog\n\n${notes}${existingNotes}`); + await writeFile( + 'CHANGELOG.md', + existingNotes + ? `# Changelog\n\n${notes}\n${existingNotes}\n` + : `# Changelog\n\n${notes}`, + ); await writeFile('release-notes.md', notes); for (const file of files) await unlink(`.changes/${file}`); run('git', [ @@ -127,7 +134,7 @@ if (!number) { title: `Release SDK ${version}`, head: branch, base: 'main', - body: `${notes}All four packages share schema major ${config.schemaVersion}. Publishing is bound to this PR's merged commit and immutable artifact manifest.`, + body: `${notes}\nAll four packages share schema major ${config.schemaVersion}. Publishing is bound to this PR's merged commit and immutable artifact manifest.`, }); number = pr.number; }