diff --git a/.agents/notes/implemented/architecture/2026-11-24-website-multilingual-i18n.md b/.agents/notes/archived/architecture/2026-11-24-website-multilingual-i18n.md similarity index 99% rename from .agents/notes/implemented/architecture/2026-11-24-website-multilingual-i18n.md rename to .agents/notes/archived/architecture/2026-11-24-website-multilingual-i18n.md index 1b0d4390..35d65e45 100644 --- a/.agents/notes/implemented/architecture/2026-11-24-website-multilingual-i18n.md +++ b/.agents/notes/archived/architecture/2026-11-24-website-multilingual-i18n.md @@ -1,6 +1,7 @@ # Agent Note: Website multilingual i18n architecture Status: implemented +Archived: 2026-11-25 ## Problem diff --git a/.agents/notes/archived/manifest.json b/.agents/notes/archived/manifest.json new file mode 100644 index 00000000..001cf669 --- /dev/null +++ b/.agents/notes/archived/manifest.json @@ -0,0 +1,6 @@ +{ + "version": 1, + "files": { + "archived/architecture/2026-11-24-website-multilingual-i18n.md": "sha256:a817821476844b7e520c4c4c29397a093ecfcb212ec63c38d2a7d47136b0062a" + } +} diff --git a/.agents/notes/implemented/architecture/2026-11-24-website-on-nsgo-website.md b/.agents/notes/implemented/architecture/2026-11-24-website-on-nsgo-website.md new file mode 100644 index 00000000..7f64aed4 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-24-website-on-nsgo-website.md @@ -0,0 +1,59 @@ +# Agent Note: The website on nsgo-website's demoscene look + +Status: implemented + +## Problem + +`apps/website` was a TanStack Start and React app of its own: about 5,000 lines of routing, a Vite content plugin, a hand-written HUD style and its own header, footer, docs frame and roadmap. Every NSGo project's site is now built from [nsgo-dev/nsgo-website](https://github.com/nsgo-dev/nsgo-website), an Astro integration over Starlight whose `look: 'demoscene'` and `example-game/` template are meant for game engines. Keeping a separate stack meant the game layer's site looked and behaved unlike its siblings and carried all of that code alone. + +## Decision + +`apps/website` is an Astro site using the `nsgo-website` integration in its demoscene look, with the template's frame and the project's own pages: + +- **Settings (`apps/website/site.config.ts`)**: the ten languages of `src/locales.ts`, the logo (NSGo's mark in its blue, `src/assets/logo.svg`, and in the look's amber on the dark theme, `src/assets/logo-dark.svg`), the header's navigation, 小莫's X account, the docs' sidebar from `src/content/groups.ts`, the roadmap of nsgo-dev/nsgo#1047 and the Apache-2.0 license. Words the settings need in every language come from `src/copy/.ts`. +- **Home page (`src/components/Home.astro`, `src/pages/index.astro`, `src/pages/[lang]/index.astro`)**: `home: false`, and the page is built from the package's demoscene components as `example-game/` does. Its own words are in `src/home/words.ts`; the package count is read from `docs/en/stability.md` and the code from `apps/website/snippets/` and `examples/fieldmedic`. +- **Docs read as they are**: `docs/en` and `docs/zh` stay GitHub-readable Markdown without frontmatter, as the Go tests and the README expect. `src/content.config.ts` wraps nsgo-website's `docsCollection()` loader so each entry's title is its first heading and its description, which goes only to meta tags, is its first paragraph. A Sätteri mdast plugin (`src/lib/markdown.ts`), which `src/lib/integration.ts` pushes onto Astro's default Markdown processor, drops that heading and rewrites `name.md` links to paths relative to the page, so a fallback page keeps its language, and other relative links to GitHub. Languages without docs get Starlight's English fallback. +- **Own pages (`src/pages/[...lang]/`)**: one file per page with a `[...lang]` rest parameter (`langPaths()` in `src/lib/paths.ts`) covers English at the root and nine languages under their codes. The playground and its examples (`src/lib/playground.ts`), the showcase, and the API reference (`src/lib/api.ts`, `src/lib/api-html.ts`, inside `StarlightPage` with the packages as its sidebar) are there; `src/pages/[file].json.ts` writes `api.json` and `src/pages/[file].txt.ts` `llms.txt` and `llms-full.txt` (`src/lib/llms.ts`). +- **Build-time contracts kept**: under `CI` a missing playground build or a failing `go run ./cmd/gameapi` fails the build; `scripts/check-api.ts` still checks every exported identifier's anchor on every language's page after `astro build`. + +The package's pieces are imported only from its public exports (`nsgo-website/components`, `/site`, `/content`, `/styles/*`); anything a second project would need belongs in nsgo-website, proposed there rather than patched here. + +## Pitfalls + +- **Sätteri, not remark**: Astro 7's default Markdown processor refuses `markdown.remarkPlugins` unless `@astrojs/markdown-remark` is installed, so the docs' plugin is a Sätteri plugin added to the processor in `astro:config:setup`. +- **Isolated installs**: the workspace's Bun links each package's dependencies under it, so `@astrojs/starlight` is a direct dependency of the site; Starlight's route entrypoints are resolved from the site's root. +- **Starlight's `Tabs` in an own page** bundles Sätteri's native binding into the prerender chunk, which then fails to load; the playground's source tabs are the page's own markup. +- **Pages run from `dist/.prerender`**, so `import.meta.url` says nothing of where the repository is; `src/lib/repo.ts` resolves it from `process.cwd()`, which Astro sets to the site's folder. +- **Starlight places sidebar links under the base and the page's language**: a custom sidebar's `link` is written as the first language has it (`/docs/api/x/`), never with `localePath()`. + +## Alternatives considered + +### Keep the TanStack Start site and restyle it + +It would have kept the playground, the API reference and the existing tests untouched. It was rejected because the user asked for nsgo-website's game version, and a restyled copy would still drift from every other NSGo site's header, footer, search, roadmap and share cards. + +### Add frontmatter to every Markdown page + +Starlight wants a `title` in each page's frontmatter, and adding it to 208 files would remove the loader wrapper and the heading-dropping plugin. It was rejected because the docs are read on GitHub and by `packages/game` tests, and they would then carry their title twice. + +### Show the first paragraph as nsgo-website's lead + +Setting `description` makes nsgo-website show it under the title as plain text. It was rejected because 30 pages have links in that paragraph; the paragraph stays in the body, styled as the lead in `src/styles/site.css`, and the description reaches only the meta tags. + +### Keep only English and Chinese, as the template does + +The template's two languages would have halved the build. It was rejected because the previous site served ten languages and their copy existed; the home page's new words were translated to all ten. + +## Consequences + +- Benefits: the frame, the light and dark themes, search, roadmap, share cards, language and theme handling come from nsgo-website and follow its updates; the site's own code is the home page, the playground, the showcase, the API reference and llms.txt. +- Costs: about 2,100 pages per build (the API reference alone is 100 packages × 10 languages), about 40 seconds locally; a new page of the site must exist under `src/pages/[...lang]/` to be in every language. +- Adding a language means adding it to `src/locales.ts`, a `src/copy/.ts`, the showcase's entries and `src/home/words.ts`. + +## Verification + +- `bun run test` runs `src/lib/llms.test.ts`, which checks that llms.txt and llms-full.txt list every page of `docs/en` with absolute links. +- `bun run typecheck` runs `astro check`; `bun run build` runs `astro build` and `scripts/check-api.ts`. +- A build with `BASE_PATH=/game/` was checked for internal links that lead nowhere: none. + +[Historical snapshot: Website multilingual i18n architecture](../../archived/architecture/2026-11-24-website-multilingual-i18n.md) diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 1cacfa89..3b8e2480 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -82,7 +82,7 @@ jobs: if: github.event_name != 'pull_request' uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: - path: apps/website/dist/client + path: apps/website/dist deploy: name: Deploy diff --git a/.gitignore b/.gitignore index aaebd950..6772a1d1 100644 --- a/.gitignore +++ b/.gitignore @@ -7,9 +7,7 @@ # The website's dependencies and build output node_modules/ /apps/website/dist/ -/apps/website/.output/ -/apps/website/.tanstack/ -/apps/website/src/routeTree.gen.ts +/apps/website/.astro/ # The playground's web builds of the examples (bun run playground) /apps/website/public/play/ # The agent notes board (bun run init-board, bun run bundle-board) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 765bf102..beafa29d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -54,11 +54,13 @@ From the repository root: ```sh bun install --frozen-lockfile bun run dev # local dev server -bun run typecheck # TypeScript check -bun run test # the build plugins' tests -bun run build # Vite build, prerender, and tsc --noEmit +bun run typecheck # astro check +bun run test # the site's own tests +bun run build # Astro build, then the API reference's anchor check ``` +The site is [Astro](https://astro.build) with [nsgo-website](https://github.com/nsgo-dev/nsgo-website) in its demoscene look: `apps/website/site.config.ts` holds its settings, `src/components/Home.astro` its home page, and the docs are read from `docs/en` and `docs/zh` as they are. `bun run --cwd apps/website share-cards` redraws the share images in `public/share/` after the site's title changes; it needs Chrome. + ## Coding conventions - **Standard library first.** Add no third-party Go dependencies where the standard library suffices. Packages should depend only on Go's standard library and NSGo's public API (`core`, `audio`, `gamepad`, etc.), so an app that does not import `game` links none of it. diff --git a/apps/website/astro.config.mjs b/apps/website/astro.config.mjs new file mode 100644 index 00000000..3a18a52f --- /dev/null +++ b/apps/website/astro.config.mjs @@ -0,0 +1,15 @@ +import { readFileSync } from 'node:fs'; +import { defineConfig } from 'astro/config'; +import nsgoWebsite from 'nsgo-website'; +import site from './site.config.ts'; +import { gameContent } from './src/lib/integration.ts'; + +// BASE_PATH is where the site is served from: "/" on its own domain, "/game/" on nsgo-dev.github.io. SITE_ORIGIN is the origin it is served at; the deploy sets both from GitHub Pages, and other builds use the custom domain in public/CNAME at its root. +const base = (process.env.BASE_PATH ?? '').trim() || '/'; +const origin = (process.env.SITE_ORIGIN ?? '').trim() || `https://${readFileSync(new URL('public/CNAME', import.meta.url), 'utf8').trim()}`; + +export default defineConfig({ + site: origin, + base, + integrations: [nsgoWebsite(site), gameContent()], +}); diff --git a/apps/website/package.json b/apps/website/package.json index 57c18073..2482bc9d 100644 --- a/apps/website/package.json +++ b/apps/website/package.json @@ -3,33 +3,24 @@ "private": true, "type": "module", "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit && bun scripts/check-api.ts", - "preview": "vite preview", + "dev": "astro dev --ignore-lock", + "build": "astro build && bun scripts/check-api.ts", + "preview": "astro preview", "test": "bun test", - "typecheck": "tsc --noEmit", - "playground": "bun scripts/build-playground.ts" + "playground": "bun scripts/build-playground.ts", + "share-cards": "nsgo-website-share-cards", + "typecheck": "astro check" }, "dependencies": { - "@tanstack/react-router": "1.170.46", - "@tanstack/react-start": "1.169.7", - "react": "19.3.1", - "react-dom": "19.3.1" + "@astrojs/starlight": "^0.43.1", + "astro": "^7.4.13", + "nsgo-website": "github:nsgo-dev/nsgo-website" }, "devDependencies": { - "@shikijs/rehype": "4.6.0", - "@types/node": "26.6.6", - "@types/react": "19.3.0", - "@types/react-dom": "19.3.0", - "@vitejs/plugin-react": "6.3.0", - "rehype-slug": "6.0.0", - "rehype-stringify": "10.0.1", + "@astrojs/check": "^0.9.12", "remark-gfm": "4.0.1", "remark-parse": "11.0.0", - "remark-rehype": "11.1.2", - "shiki": "4.6.0", - "typescript": "7.0.2", - "unified": "11.0.5", - "vite": "8.3.8" + "typescript": "^6", + "unified": "11.0.5" } } diff --git a/apps/website/plugins/content.ts b/apps/website/plugins/content.ts deleted file mode 100644 index dc3cd6b3..00000000 --- a/apps/website/plugins/content.ts +++ /dev/null @@ -1,743 +0,0 @@ -// Build-time content: the docs from the repository's Markdown in each language, the API reference from the Go packages' doc comments, the home page's Go snippets, the playground's example sources, and the roadmap from GitHub's API. Each is a virtual module the routes import, so the pages carry the result and nothing is read from the repository or fetched from GitHub in the browser. - -import { execFile } from 'node:child_process' -import { readdir, readFile, stat } from 'node:fs/promises' -import path from 'node:path' -import rehypeShiki from '@shikijs/rehype' -import rehypeSlug from 'rehype-slug' -import rehypeStringify from 'rehype-stringify' -import remarkGfm from 'remark-gfm' -import remarkParse from 'remark-parse' -import remarkRehype from 'remark-rehype' -import { codeToHtml } from 'shiki' -import { type Plugin as UnifiedPlugin, unified } from 'unified' -import type { Plugin } from 'vite' -import { PLAYGROUND_BUILDS, PLAYGROUND_IDS, type PlaygroundId, isPlaygroundId } from '../src/content/playground.ts' -import type { ApiPackage, ApiReference, ApiSummary, DocHeading, DocPackage, DocPage, PackageStatus, PlaygroundExample, PlaygroundFile, PlaygroundSource, Roadmap, RoadmapGroup, RoadmapIssue, RoadmapStage, Snippet } from '../src/content/types' -import { LANGS, type Lang, NON_DEFAULT_LANGS } from '../src/locales.ts' - -const REPO = 'nsgo-dev/game' -const PLAN = { repo: 'nsgo-dev/nsgo', number: 1047 } -const SNIPPETS: Snippet['id'][] = ['loop', 'sprite', 'sound'] -const THEMES = { light: 'github-light', dark: 'github-dark' } as const - -const modules = { - 'virtual:docs': loadDocsModule, - 'virtual:snippets': loadSnippetsModule, - 'virtual:roadmap': loadRoadmapModule, - 'virtual:playground': loadPlaygroundModule, -} as const -// Each playground example's sources are a module of their own, virtual:playground/, so a page loads only its example's. -const PLAYGROUND_SOURCE = 'virtual:playground/' -type ModuleId = keyof typeof modules - -// A package's page of the API reference is the module virtual:api/, which the reference's route imports on demand, so no page's script carries another package's API. -const API_MODULE = 'virtual:api' -const API_PACKAGE = `${API_MODULE}/` - -interface Context { - root: string - base: string - docsDir: string - snippetsDir: string - examplesDir: string - publicDir: string - // goModule is the directory of the Go module the API reference documents. - goModule: string -} - -export function siteContent(): Plugin { - let ctx: Context | undefined - // The client and server builds both load each module; the roadmap is fetched, and the API reference generated, once for both. - const cache = new Map>() - let api: Promise | undefined - const apiBuild = () => { - if (!ctx) throw new Error('the API reference was asked for before the config was resolved') - api ??= buildApi(ctx) - return api - } - return { - name: 'game-site-content', - configResolved(config) { - ctx = { - root: config.root, - base: config.base, - docsDir: path.resolve(config.root, '../../docs'), - snippetsDir: path.resolve(config.root, 'snippets'), - examplesDir: path.resolve(config.root, '../../examples'), - publicDir: config.publicDir, - goModule: path.resolve(config.root, '../../packages/game'), - } - }, - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url?.split('?')[0] !== `${server.config.base}${API_JSON}`) return next() - try { - const build = await apiBuild() - if (build.status !== 'ok') throw new Error(build.reason) - res.setHeader('Content-Type', 'application/json; charset=utf-8') - res.end(build.json) - } catch (error) { - next(error) - } - }) - }, - resolveId(id) { - if (id.startsWith(PLAYGROUND_SOURCE) && isPlaygroundId(id.slice(PLAYGROUND_SOURCE.length))) return `\0${id}` - if (id === API_MODULE || id.startsWith(API_PACKAGE)) return `\0${id}` - return id in modules ? `\0${id}` : undefined - }, - async generateBundle() { - // The JSON for agents is a file of the client's build, beside the pages. - if (this.environment.name !== 'client') return - const build = await apiBuild() - if (build.status === 'ok') this.emitFile({ type: 'asset', fileName: API_JSON, source: build.json }) - }, - async load(id) { - if (!id.startsWith('\0')) return undefined - const name = id.slice(1) - if (name.startsWith(PLAYGROUND_SOURCE) && ctx) { - const example = name.slice(PLAYGROUND_SOURCE.length) as PlaygroundId - const dir = path.join(ctx.examplesDir, example) - for (const file of await playgroundFiles(dir)) this.addWatchFile(path.join(dir, file)) - return loadPlaygroundSource(ctx, example) - } - if (name.startsWith(API_PACKAGE) && ctx) { - const build = await apiBuild() - const pkg = build.status === 'ok' ? build.packages.get(name.slice(API_PACKAGE.length)) : undefined - if (!pkg) throw new Error(`${name}: no such package`) - return `export default ${JSON.stringify(pkg)}` - } - if (name === API_MODULE && ctx) return loadApiModule(await apiBuild()) - if (!(name in modules) || !ctx) return undefined - const moduleId = name as ModuleId - if (moduleId === 'virtual:docs') { - for (const lang of LANGS) { - const dir = path.join(ctx.docsDir, lang) - for (const file of await optionalMarkdownFiles(dir)) this.addWatchFile(path.join(dir, file)) - } - } - if (moduleId === 'virtual:playground') { - // The line counts follow the sources, and a build made while the dev server runs shows up once its nsgo.json is written. - for (const id of PLAYGROUND_IDS) { - const dir = path.join(ctx.examplesDir, id) - for (const file of await playgroundFiles(dir)) this.addWatchFile(path.join(dir, file)) - this.addWatchFile(path.join(ctx.publicDir, PLAYGROUND_BUILDS, id, 'nsgo.json')) - } - } - if (moduleId === 'virtual:snippets') { - for (const snippet of SNIPPETS) this.addWatchFile(path.join(ctx.snippetsDir, `${snippet}.go.txt`)) - } - let code = cache.get(moduleId) - if (!code || moduleId !== 'virtual:roadmap') { - code = modules[moduleId](ctx) - cache.set(moduleId, code) - } - return code - }, - } -} - -// ---- Docs ---- - -// Sidebar order for the docs; any additional pages sort alphabetically after these. -const DOC_ORDER = [ - 'index.md', - 'getting-started.md', - 'playground.md', - 'packages.md', - 'stability.md', - 'loop.md', - 'sprite.md', - 'sound.md', - '3d-models-blender.md', - 'shipping.md', - 'cli.md', - 'cli-reference.md', -] as const - -// markdownFiles lists dir's Markdown files, those in DOC_ORDER first and the rest alphabetically. -export async function markdownFiles(dir: string): Promise { - const files = (await readdir(dir)).filter((f) => f.endsWith('.md')) - const rankOf = (file: string) => { - const idx = DOC_ORDER.indexOf(file as (typeof DOC_ORDER)[number]) - return idx >= 0 ? idx : Number.MAX_SAFE_INTEGER - } - return files.sort((a, b) => rankOf(a) - rankOf(b) || a.localeCompare(b)) -} - -// optionalMarkdownFiles returns dir's Markdown files, or [] when a locale has no docs// directory yet. -async function optionalMarkdownFiles(dir: string): Promise { - try { - return await markdownFiles(dir) - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [] - throw error - } -} - -function escapeRegExp(value: string): string { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -} - -// localizeDocLinks rewrites rendered internal docs links (href="docs/...") on a fallback English page so navigation stays in lang. -export function localizeDocLinks(html: string, lang: Lang, base: string): string { - if (lang === 'en') return html - const pattern = new RegExp(`(]*\\shref=")(${escapeRegExp(base)}docs\\/)`, 'g') - return html.replace(pattern, `$1${base}${lang}/docs/`) -} - -// Each language lists English's pages in English's order, its own translation where docs//.md exists, and English otherwise. -// Only files that actually exist on disk are rendered and bundled; fallback locales reuse English's rendered pages with localized internal links so adding languages does not multiply build time or bundle size. -async function loadDocsModule(ctx: Context): Promise { - const englishFiles = await markdownFiles(path.join(ctx.docsDir, 'en')) - const packages = await readStability(ctx) - const english: DocPage[] = [] - for (const file of englishFiles) { - const source = await readFile(path.join(ctx.docsDir, 'en', file), 'utf8') - const slug = file.slice(0, -'.md'.length) - english.push({ ...(await renderDoc(slug, source, { lang: 'en', from: 'en' }, ctx)), packages: packages.get(slug) ?? [] }) - } - const translated: Partial>> = {} - for (const lang of NON_DEFAULT_LANGS) { - const own = new Set(await optionalMarkdownFiles(path.join(ctx.docsDir, lang))) - if (own.size === 0) continue - const bySlug: Record = {} - for (const file of englishFiles) { - if (!own.has(file)) continue - const source = await readFile(path.join(ctx.docsDir, lang, file), 'utf8') - const slug = file.slice(0, -'.md'.length) - bySlug[slug] = { ...(await renderDoc(slug, source, { lang, from: lang }, ctx)), packages: packages.get(slug) ?? [] } - } - if (Object.keys(bySlug).length > 0) translated[lang] = bySlug - } - const linkSource = `(]*\\shref=")(?:${escapeRegExp(ctx.base)}docs\\/)` - return `const base = ${JSON.stringify(ctx.base)} -const english = ${JSON.stringify(english)} -const translated = ${JSON.stringify(translated)} -const linkPattern = new RegExp(${JSON.stringify(linkSource)}, 'g') -function localize(html, lang) { - return html.replace(linkPattern, '$1' + base + lang + '/docs/') -} -const cache = new Map([['en', english]]) -function docsFor(lang) { - let list = cache.get(lang) - if (!list) { - const own = Object.hasOwn(translated, lang) ? translated[lang] : undefined - list = english.map((page) => (own && Object.hasOwn(own, page.slug) ? own[page.slug] : { ...page, fallback: true, html: localize(page.html, lang) })) - cache.set(lang, list) - } - return list -} -export const docs = new Proxy({}, { - get(_, prop) { - return typeof prop === 'string' ? docsFor(prop) : undefined - }, -})` -} - -// A row of the package table in docs/en/stability.md: the package, its status, and the page that is its guide, if any. A test in packages/game keeps the table complete and the Chinese one equal to it. -const STABILITY_ROW = /^\| `([^`]+)` \| (Stable|Experimental) \| (?:\[[^\]]+\]\(([a-z0-9-]+)\.md\))? ?\|$/ - -// readStability reads each package's status from docs/en/stability.md, by the slug of its guide. -async function readStability(ctx: Context): Promise> { - const source = await readFile(path.join(ctx.docsDir, 'en', 'stability.md'), 'utf8') - const bySlug = new Map() - let rows = 0 - for (const line of source.split('\n')) { - const m = STABILITY_ROW.exec(line) - if (!m) continue - rows++ - const [, pkg = '', status = '', slug] = m - if (!slug) continue - const list = bySlug.get(slug) ?? [] - list.push({ path: pkg, status: status.toLowerCase() as PackageStatus }) - bySlug.set(slug, list) - } - if (rows === 0) throw new Error('docs/en/stability.md has no package rows') - return bySlug -} - -// MdNode is the part of an mdast node this file reads and writes. -interface MdNode { - type: string - children?: MdNode[] - url?: string - depth?: number - value?: string -} - -// lang is the language the page is shown in, from the one its Markdown is written in: the two differ when lang has no translation of it. -async function renderDoc(slug: string, source: string, { lang, from }: { lang: Lang; from: Lang }, ctx: Context): Promise> { - const meta = { title: slug, description: '' } - const headings: DocHeading[] = [] - const file = await unified() - .use(remarkParse) - .use(remarkGfm) - .use(docTransform(meta, lang, from, ctx) as UnifiedPlugin) - .use(remarkRehype) - .use(rehypeSlug) - .use(collectHeadings(headings) as UnifiedPlugin) - // The language class names the block in its editor pane's title bar. - .use(rehypeShiki, { themes: THEMES, defaultColor: false, addLanguageClass: true }) - .use(rehypeStringify) - .process(source) - return { slug, title: meta.title, description: meta.description, html: String(file), headings, fallback: from !== lang, source: `docs/${from}/${slug}.md` } -} - -// HastNode is the part of a hast node collectHeadings reads. -interface HastNode { - type: string - tagName?: string - properties?: { id?: unknown } - value?: string - children?: HastNode[] -} - -// collectHeadings records each h2 and h3 with the id rehype-slug gave it, for the page's contents list. -function collectHeadings(headings: DocHeading[]) { - return () => (tree: HastNode) => { - const visit = (node: HastNode) => { - if (node.type === 'element' && (node.tagName === 'h2' || node.tagName === 'h3') && typeof node.properties?.id === 'string') { - headings.push({ depth: node.tagName === 'h2' ? 2 : 3, id: node.properties.id, text: hastText(node) }) - return - } - for (const child of node.children ?? []) visit(child) - } - visit(tree) - } -} - -function hastText(node: HastNode): string { - if (node.type === 'text') return node.value ?? '' - return (node.children ?? []).map(hastText).join('') -} - -// docTransform takes the first heading out as the page's title and its first paragraph as its description, and points the Markdown's links at the site's docs routes in lang or at the files on GitHub. -function docTransform(meta: { title: string; description: string }, lang: Lang, from: Lang, ctx: Context) { - return () => (tree: MdNode) => { - const children = tree.children ?? [] - const h1 = children.findIndex((n) => n.type === 'heading' && n.depth === 1) - if (h1 >= 0) { - meta.title = textOf(children[h1]!) - children.splice(h1, 1) - } - const paragraph = children.find((n) => n.type === 'paragraph') - if (paragraph) meta.description = textOf(paragraph) - walk(tree, (node) => { - if ((node.type === 'link' || node.type === 'definition') && node.url) node.url = rewriteLink(node.url, lang, from, ctx.base) - }) - } -} - -// rewriteLink points a link of a page written in from at the site's docs route in lang, below base (a path such as "/game/", or an origin and path for an absolute address), or at the file on GitHub. A link to another page stays in lang, so a Chinese page, or the English one shown in its place, links to Chinese pages. -export function rewriteLink(url: string, lang: Lang, from: Lang, base: string): string { - if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('#') || url.startsWith('//')) return url - const [target = '', hash = ''] = url.split(/(?=#)/) - if (target.endsWith('.md') && !target.includes('/')) { - const slug = target.slice(0, -'.md'.length) - return `${base}${lang === 'en' ? '' : `${lang}/`}docs/${slug === 'index' ? '' : `${slug}/`}${hash}` - } - // Anything else is a file or directory of the repository, relative to the Markdown's directory, docs//. - const repoPath = path.posix.normalize(path.posix.join('docs', from, target)) - return `https://github.com/${REPO}/blob/main/${repoPath}${hash}` -} - -function walk(node: MdNode, visit: (node: MdNode) => void) { - visit(node) - for (const child of node.children ?? []) walk(child, visit) -} - -function textOf(node: MdNode): string { - if (node.value !== undefined) return node.value - return (node.children ?? []).map(textOf).join('') -} - -// ---- API reference ---- - -// The reference is what cmd/gameapi in the Go module writes: run with -html for the pages, which show each doc comment as HTML, and without it for API_JSON, the JSON published for agents. Without Go, a local build shows the reference as unavailable; a deploy needs it. - -const API_JSON = 'api.json' - -type ApiBuild = - | { status: 'ok'; json: string; summaries: ApiSummary[]; packages: Map } - | { status: 'unavailable'; reason: string } - -async function buildApi(ctx: Context): Promise { - try { - const [html, json] = await Promise.all([gameapi(ctx, ['-html']), gameapi(ctx, [])]) - const ref = JSON.parse(html) as ApiReference - const packages = new Map() - const summaries: ApiSummary[] = [] - for (const pkg of ref.packages) { - // The pages show the doc comments as HTML, so the text of each is left out of their scripts. - packages.set(pkg.page, JSON.parse(JSON.stringify(pkg, (key, value) => (key === 'doc' ? undefined : value))) as ApiPackage) - summaries.push({ importPath: pkg.importPath, name: pkg.name, page: pkg.page, synopsis: pkg.synopsis, platforms: pkg.platforms ?? [] }) - } - console.info(`[api] ${ref.packages.length} packages of ${ref.module}`) - return { status: 'ok', json, summaries, packages } - } catch (error) { - const reason = error instanceof Error ? error.message : String(error) - if (process.env.CI) throw new Error(`api: ${reason}`) - console.warn(`[api] skipped: ${reason}`) - return { status: 'unavailable', reason } - } -} - -function gameapi(ctx: Context, args: string[]): Promise { - return new Promise((resolve, reject) => { - execFile('go', ['run', './cmd/gameapi', ...args], { cwd: ctx.goModule, maxBuffer: 256 << 20 }, (error, stdout, stderr) => { - if (error) reject(new Error(`go run ./cmd/gameapi ${args.join(' ')}: ${stderr.trim() || error.message}`)) - else resolve(stdout) - }) - }) -} - -// virtual:api lists the packages and imports each one's page module on demand. -function loadApiModule(build: ApiBuild): string { - if (build.status !== 'ok') return `export const api = ${JSON.stringify({ status: 'unavailable', reason: build.reason })}\nexport const loadApiPackage = async () => undefined` - const loaders = build.summaries.map((s) => ` ${JSON.stringify(s.page)}: () => import(${JSON.stringify(API_PACKAGE + s.page)}),`).join('\n') - return `export const api = ${JSON.stringify({ status: 'ok', packages: build.summaries })} -const loaders = { -${loaders} -} -export async function loadApiPackage(page) { - const load = Object.hasOwn(loaders, page) ? loaders[page] : undefined - return load ? (await load()).default : undefined -}` -} - -// ---- Snippets ---- - -async function loadSnippetsModule(ctx: Context): Promise { - const snippets: Snippet[] = [] - for (const id of SNIPPETS) { - const code = await readFile(path.join(ctx.snippetsDir, `${id}.go.txt`), 'utf8') - snippets.push({ id, html: await codeToHtml(code.trimEnd(), { lang: 'go', themes: THEMES, defaultColor: false }) }) - } - return `export const snippets = ${JSON.stringify(snippets)}` -} - -// ---- Playground ---- - -// playgroundFiles are the files an example's source tabs show: its main package's Go files, main.go first, without its tests, then its nsgo.yaml. -async function playgroundFiles(dir: string): Promise { - const entries = await readdir(dir, { withFileTypes: true }) - const names = entries.filter((e) => e.isFile()).map((e) => e.name) - const goFiles = names.filter((n) => n.endsWith('.go') && !n.endsWith('_test.go')).sort((a, b) => Number(b === 'main.go') - Number(a === 'main.go') || a.localeCompare(b)) - if (goFiles.length === 0) throw new Error(`playground: ${dir} has no Go files`) - return names.includes('nsgo.yaml') ? [...goFiles, 'nsgo.yaml'] : goFiles -} - -const lineCount = (code: string) => code.split('\n').length - -// loadPlaygroundModule lists each example's files and the size of the web build public/play// holds. A deploy must not publish a playground that runs nothing, so in CI a missing build fails the site's build; a local build goes on and its page says how to make one. -async function loadPlaygroundModule(ctx: Context): Promise { - const examples: PlaygroundExample[] = [] - const missing: string[] = [] - for (const id of PLAYGROUND_IDS) { - const dir = path.join(ctx.examplesDir, id) - const files: PlaygroundFile[] = [] - for (const name of await playgroundFiles(dir)) files.push({ name, lines: lineCount((await readFile(path.join(dir, name), 'utf8')).trimEnd()) }) - const wasm = await playgroundWasmSize(path.join(ctx.publicDir, PLAYGROUND_BUILDS, id)) - if (wasm === 0) missing.push(id) - examples.push({ id, files, built: wasm > 0, wasm }) - } - if (missing.length) { - const reason = `no web build of ${missing.join(', ')} in public/${PLAYGROUND_BUILDS}/; run bun run playground` - if (process.env.CI) throw new Error(`playground: ${reason}`) - console.warn(`[playground] ${reason}`) - } - const loaders = PLAYGROUND_IDS.map((id) => `${JSON.stringify(id)}: () => import(${JSON.stringify(PLAYGROUND_SOURCE + id)})`).join(', ') - return `export const examples = ${JSON.stringify(examples)}\nexport const sources = { ${loaders} }` -} - -// playgroundWasmSize is the size in bytes of the WebAssembly the web build in dir runs, as its nsgo.json names it, or 0 when dir holds no usable build. -async function playgroundWasmSize(dir: string): Promise { - let manifest: string - try { - manifest = await readFile(path.join(dir, 'nsgo.json'), 'utf8') - } catch { - return 0 - } - // A build that is present but broken counts as missing, so a local build warns and goes on instead of dying, and CI still fails it through the missing-build check in loadPlaygroundModule. - try { - const { wasm } = JSON.parse(manifest) as { wasm?: unknown } - if (typeof wasm !== 'string' || wasm === '') throw new Error('nsgo.json names no wasm') - return (await stat(path.join(dir, wasm))).size - } catch (err) { - console.warn(`[playground] ignoring the build in ${dir}: ${err instanceof Error ? err.message : String(err)}`) - return 0 - } -} - -async function loadPlaygroundSource(ctx: Context, id: PlaygroundId): Promise { - const dir = path.join(ctx.examplesDir, id) - const source: PlaygroundSource = { files: [] } - for (const name of await playgroundFiles(dir)) { - const code = (await readFile(path.join(dir, name), 'utf8')).trimEnd() - const lang = name.endsWith('.go') ? 'go' : 'yaml' - source.files.push({ name, lines: lineCount(code), html: await codeToHtml(code, { lang, themes: THEMES, defaultColor: false }) }) - } - return `export const files = ${JSON.stringify(source.files)}` -} - -// ---- Roadmap ---- - -// The roadmap is the issue tree under the plan, read with GitHub's GraphQL API: the plan's sub-issues are its stages, a stage's sub-issues its areas, and everything below an area is listed under it. A level of the tree is one request for up to 100 issues, so a build takes a handful of requests rather than one per issue. GraphQL needs a token; without GITHUB_TOKEN a local build shows the roadmap as unavailable. - -const GRAPHQL_URL = 'https://api.github.com/graphql' -// Up to 100 issues a request asks for the sub-issues of, and up to 100 sub-issues for each: 10,000 nodes, well inside GitHub's limit of 500,000. -const PAGE = 100 - -const ISSUE_FIELDS = `fragment IssueFields on Issue { id number title state url repository { nameWithOwner } subIssuesSummary { total } }` -const SUB_ISSUES = `subIssues(first: ${PAGE}) { pageInfo { hasNextPage endCursor } nodes { ...IssueFields } }` - -interface GqlPageInfo { - hasNextPage: boolean - endCursor: string | null -} - -interface GqlIssue { - id: string - number: number - title: string - state: 'OPEN' | 'CLOSED' - url: string - repository: { nameWithOwner: string } - subIssuesSummary: { total: number } -} - -interface GqlConnection { - pageInfo: GqlPageInfo - nodes: T[] -} - -type GqlStage = GqlIssue & { body: string; subIssues: GqlConnection } - -// TreeNode is an issue of the plan's tree with the sub-issues read so far. -interface TreeNode { - id: string - issue: RoadmapIssue - // total is how many sub-issues GitHub says the issue has. - total: number - children: TreeNode[] -} - -async function loadRoadmapModule(): Promise { - let roadmap: Roadmap - try { - roadmap = await fetchRoadmap() - } catch (error) { - const reason = error instanceof Error ? error.message : String(error) - // A deploy must not replace the roadmap with an empty one; a local build goes on without it. - if (process.env.CI) throw new Error(`roadmap: ${reason}`) - console.warn(`[roadmap] skipped: ${reason}`) - roadmap = { status: 'unavailable', reason } - } - return `export const roadmap = ${JSON.stringify(roadmap)}` -} - -async function fetchRoadmap(): Promise { - const token = process.env.GITHUB_TOKEN - if (!token) throw new Error('GITHUB_TOKEN is not set, and GitHub’s GraphQL API needs a token') - const client = new GraphQL(token) - const [stages, gameIssues] = await Promise.all([fetchTree(client), fetchGameIssues(client)]) - const planned = new Set() - const roadmapStages = stages.map((stage, index) => { - const built = buildStage(stage, index) - for (const node of descendants(stage.node)) planned.add(issueKey(node.issue)) - return built - }) - const unplanned = gameIssues.filter((issue) => !planned.has(issueKey(issue))).sort((a, b) => a.number - b.number) - console.info(`[roadmap] ${client.requests} GraphQL requests; ${roadmapStages.map((s) => `stage ${s.number} ${s.closed}/${s.open + s.closed}`).join(', ')}; ${unplanned.length} unplanned`) - return { status: 'ok', fetchedAt: new Date().toISOString(), stages: roadmapStages, unplanned } -} - -// fetchTree reads the plan's stages with their bodies and two levels below them in one request, then each further level, a request per 100 issues that have sub-issues. -async function fetchTree(client: GraphQL): Promise<{ node: TreeNode; body: string }[]> { - const data = await client.query<{ repository: { issue: { subIssues: GqlConnection } | null } }>( - `query($owner: String!, $name: String!, $number: Int!) { - repository(owner: $owner, name: $name) { - issue(number: $number) { - subIssues(first: ${PAGE}) { pageInfo { hasNextPage endCursor } nodes { ...IssueFields body ${SUB_ISSUES} } } - } - } - } - ${ISSUE_FIELDS}`, - { owner: PLAN.repo.split('/')[0], name: PLAN.repo.split('/')[1], number: PLAN.number }, - ) - const plan = data.repository.issue - if (!plan) throw new Error(`${PLAN.repo}#${PLAN.number} was not found`) - if (plan.subIssues.pageInfo.hasNextPage) throw new Error(`${PLAN.repo}#${PLAN.number} has more than ${PAGE} stages`) - // Issues whose sub-issues are still to be read, and those with more pages of them. - let pending: TreeNode[] = [] - const more: { node: TreeNode; after: string }[] = [] - const attach = (node: TreeNode, connection: GqlConnection) => { - for (const raw of connection.nodes) { - const child = treeNode(raw) - node.children.push(child) - if (child.total > 0) pending.push(child) - } - if (connection.pageInfo.hasNextPage && connection.pageInfo.endCursor) more.push({ node, after: connection.pageInfo.endCursor }) - } - const stages = plan.subIssues.nodes.map((raw) => { - const node = treeNode(raw) - attach(node, raw.subIssues) - return { node, body: raw.body } - }) - while (pending.length || more.length) { - const level = pending - pending = [] - for (let i = 0; i < level.length; i += PAGE) { - const batch = level.slice(i, i + PAGE) - const result = await client.query<{ nodes: ({ id: string; subIssues: GqlConnection } | null)[] }>( - `query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id ${SUB_ISSUES} } } } - ${ISSUE_FIELDS}`, - { ids: batch.map((node) => node.id) }, - ) - result.nodes.forEach((raw, j) => { - if (raw) attach(batch[j]!, raw.subIssues) - }) - } - // An issue with more than 100 sub-issues reads the rest a page at a time. - for (const { node, after } of more.splice(0)) { - const result = await client.query<{ node: { subIssues: GqlConnection } | null }>( - `query($id: ID!, $after: String!) { node(id: $id) { ... on Issue { subIssues(first: ${PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ...IssueFields } } } } } - ${ISSUE_FIELDS}`, - { id: node.id, after }, - ) - if (result.node) attach(node, result.node.subIssues) - } - } - return stages -} - -// fetchGameIssues reads every issue of the game's repository, to list those in no stage. -async function fetchGameIssues(client: GraphQL): Promise { - const [owner, name] = REPO.split('/') - const issues: RoadmapIssue[] = [] - let after: string | null = null - do { - const data: { repository: { issues: GqlConnection> } } = await client.query( - `query($owner: String!, $name: String!, $after: String) { - repository(owner: $owner, name: $name) { - issues(first: ${PAGE}, after: $after, orderBy: { field: CREATED_AT, direction: ASC }) { - pageInfo { hasNextPage endCursor } - nodes { number title state url repository { nameWithOwner } } - } - } - }`, - { owner, name, after }, - ) - const page = data.repository.issues - for (const raw of page.nodes) issues.push(toIssue(raw)) - after = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null - } while (after) - return issues -} - -function treeNode(raw: GqlIssue): TreeNode { - return { id: raw.id, issue: toIssue(raw), total: raw.subIssuesSummary.total, children: [] } -} - -function toIssue(raw: Pick): RoadmapIssue { - return { repo: raw.repository.nameWithOwner, number: raw.number, title: raw.title, state: raw.state === 'CLOSED' ? 'closed' : 'open', url: raw.url } -} - -function issueKey(issue: RoadmapIssue): string { - return `${issue.repo}#${issue.number}` -} - -// descendants lists the issues below node, depth first in GitHub's order. -function descendants(node: TreeNode): TreeNode[] { - return node.children.flatMap((child) => [child, ...descendants(child)]) -} - -const STAGE_TITLE = /^Games stage (\d+):\s*(.+)$/i - -// buildStage turns a stage's subtree into areas: each sub-issue with sub-issues of its own is an area listing everything below it, and the rest share one group after them. -function buildStage({ node, body }: { node: TreeNode; body: string }, index: number): RoadmapStage { - const match = STAGE_TITLE.exec(node.issue.title) - const title = match ? match[2]! : node.issue.title - const stage: RoadmapStage = { - number: match ? Number(match[1]) : index + 1, - title: title.charAt(0).toUpperCase() + title.slice(1), - description: stageDescription(body), - url: node.issue.url, - groups: [], - open: 0, - closed: 0, - } - const single: RoadmapGroup = { epic: null, area: '', items: [], open: 0, closed: 0 } - for (const child of node.children) { - if (child.children.length === 0) { - single.items.push({ ...child.issue, depth: 0 }) - single[child.issue.state]++ - continue - } - const group: RoadmapGroup = { epic: child.issue, area: areaName(child.issue.title), items: [], open: 0, closed: 0 } - group[child.issue.state]++ - const visit = (parent: TreeNode, depth: 0 | 1) => { - for (const item of parent.children) { - group.items.push({ ...item.issue, depth }) - group[item.issue.state]++ - visit(item, 1) - } - } - visit(child, 0) - stage.groups.push(group) - } - if (single.items.length) stage.groups.push(single) - for (const group of stage.groups) { - stage.open += group.open - stage.closed += group.closed - } - return stage -} - -// areaName is an epic's title up to its colon, without a leading tag such as "[Feature]": "Input: named actions…" is Input. -function areaName(title: string): string { - const untagged = title.replace(/^\[[^\]]*\]\s*/, '') - const colon = untagged.indexOf(':') - return colon > 0 ? untagged.slice(0, colon) : untagged -} - -// stageDescription is the first paragraph of the stage issue's Context section, or of its body, without the sentence naming the plan it belongs to. -function stageDescription(body: string): string { - const text = body.replace(/\r\n/g, '\n') - const context = /^#{1,6}\s*Context\s*\n([\s\S]*?)(?=^#{1,6}\s|$(?![\s\S]))/im.exec(text) - const paragraphs = (context ? context[1]! : text).split(/\n\s*\n/).map((p) => p.trim().replace(/\s*\n\s*/g, ' ')) - const first = paragraphs.find((p) => p && !p.startsWith('#')) ?? '' - return first - .replace(/^A stage of [\w/-]*#\d+\.\s*/i, '') - .replace(/`([^`]*)`/g, '$1') - .replace(/\*\*([^*]+)\*\*/g, '$1') -} - -class GraphQL { - requests = 0 - constructor(private readonly token: string) {} - - async query(query: string, variables: Record): Promise { - this.requests++ - const res = await fetch(GRAPHQL_URL, { - method: 'POST', - headers: { - Authorization: `Bearer ${this.token}`, - 'Content-Type': 'application/json', - 'User-Agent': 'game-website-build', - }, - body: JSON.stringify({ query, variables }), - signal: AbortSignal.timeout(30_000), - }) - if (!res.ok) { - const hint = res.status === 403 || res.status === 429 ? ' (rate limited)' : '' - throw new Error(`GraphQL answered ${res.status} ${res.statusText}${hint}`) - } - const json = (await res.json()) as { data?: T; errors?: { message: string }[] } - if (json.errors?.length) throw new Error(`GraphQL: ${json.errors.map((e) => e.message).join('; ')}`) - if (!json.data) throw new Error('GraphQL answered without data') - return json.data - } -} diff --git a/apps/website/public/favicon.svg b/apps/website/public/favicon.svg new file mode 100644 index 00000000..0cc166b8 --- /dev/null +++ b/apps/website/public/favicon.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/apps/website/public/share/de.png b/apps/website/public/share/de.png new file mode 100644 index 00000000..56c1dc7b Binary files /dev/null and b/apps/website/public/share/de.png differ diff --git a/apps/website/public/share/en.png b/apps/website/public/share/en.png new file mode 100644 index 00000000..92e90908 Binary files /dev/null and b/apps/website/public/share/en.png differ diff --git a/apps/website/public/share/es.png b/apps/website/public/share/es.png new file mode 100644 index 00000000..66995493 Binary files /dev/null and b/apps/website/public/share/es.png differ diff --git a/apps/website/public/share/fr.png b/apps/website/public/share/fr.png new file mode 100644 index 00000000..fa44c5f7 Binary files /dev/null and b/apps/website/public/share/fr.png differ diff --git a/apps/website/public/share/ja.png b/apps/website/public/share/ja.png new file mode 100644 index 00000000..9bb6fe5c Binary files /dev/null and b/apps/website/public/share/ja.png differ diff --git a/apps/website/public/share/ko.png b/apps/website/public/share/ko.png new file mode 100644 index 00000000..4a5df3ef Binary files /dev/null and b/apps/website/public/share/ko.png differ diff --git a/apps/website/public/share/pt.png b/apps/website/public/share/pt.png new file mode 100644 index 00000000..9762e729 Binary files /dev/null and b/apps/website/public/share/pt.png differ diff --git a/apps/website/public/share/ru.png b/apps/website/public/share/ru.png new file mode 100644 index 00000000..4b416dec Binary files /dev/null and b/apps/website/public/share/ru.png differ diff --git a/apps/website/public/share/zh-tw.png b/apps/website/public/share/zh-tw.png new file mode 100644 index 00000000..62c89ea4 Binary files /dev/null and b/apps/website/public/share/zh-tw.png differ diff --git a/apps/website/public/share/zh.png b/apps/website/public/share/zh.png new file mode 100644 index 00000000..3f460290 Binary files /dev/null and b/apps/website/public/share/zh.png differ diff --git a/apps/website/scripts/check-api.ts b/apps/website/scripts/check-api.ts index acee84f1..49f1ff73 100644 --- a/apps/website/scripts/check-api.ts +++ b/apps/website/scripts/check-api.ts @@ -3,12 +3,12 @@ import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' import path from 'node:path' -import type { ApiFunc, ApiReference, ApiValue } from '../src/content/types' +import type { ApiFunc, ApiReference, ApiValue } from '../src/content/types.ts' import { LANGS } from '../src/locales.ts' const langs = LANGS -const dist = path.resolve(import.meta.dirname, '../dist/client') +const dist = path.resolve(import.meta.dirname, '../dist') const json = path.join(dist, 'api.json') if (!existsSync(json)) { diff --git a/apps/website/site.config.ts b/apps/website/site.config.ts new file mode 100644 index 00000000..5d6e9619 --- /dev/null +++ b/apps/website/site.config.ts @@ -0,0 +1,66 @@ +// The site's settings, for the nsgo-website integration and the share-cards command, in the demoscene look of its game template. The home page is the site's own (src/components/Home.astro); every fact on it comes from the repository's README, docs and code. +import { readdirSync } from 'node:fs'; +import { defineSite } from 'nsgo-website/config'; +import type { SidebarItem } from 'nsgo-website/config'; +import { copies } from './src/copy.ts'; +import { groupDocs, type GroupKey } from './src/content/groups.ts'; +import { LANGS, type Lang } from './src/locales.ts'; + +const repo = 'https://github.com/nsgo-dev/game'; + +// per gives a word in each of the site's languages from the copy files. +const per = (pick: (copy: (typeof copies)[Lang]) => string) => Object.fromEntries(LANGS.map((l) => [l, pick(copies[l])])) as Record; + +// The docs' sidebar: every page of docs/en in the groups of src/content/groups.ts, then the API reference, which the site builds from the Go packages. +const pages = readdirSync(new URL('../../docs/en/', import.meta.url)) + .filter((f) => f.endsWith('.md')) + .map((f) => ({ slug: f.slice(0, -'.md'.length) })) + .sort((a, b) => a.slug.localeCompare(b.slug)); +const sidebar: SidebarItem[] = [ + ...groupDocs(pages).map(({ key, items }) => ({ + label: per((c) => c.docs.groups[key as GroupKey]), + collapsed: key !== 'guides', + items: items.map((p) => (p.slug === 'index' ? 'docs' : `docs/${p.slug}`)), + })), + { label: per((c) => c.docs.reference), items: [{ label: per((c) => c.api.nav), link: '/docs/api/' }] }, +]; + +export default defineSite({ + languages: [...LANGS], + name: 'NSGo Game', + title: per((c) => c.site.title), + description: per((c) => c.site.description), + // NSGo's mark, in its blue on the light theme and in the look's amber on the dark. + logo: './src/assets/logo.svg', + logoDark: './src/assets/logo-dark.svg', + favicon: '/favicon.svg', + appleTouchIcon: '/apple-touch-icon.png', + look: 'demoscene', + repo, + path: 'apps/website', + editLink: false, + nav: [ + 'docs', + { label: per((c) => c.nav.playground), href: 'playground/' }, + { label: per((c) => c.nav.showcase), href: 'showcase/' }, + 'roadmap', + 'community', + 'feedback', + ], + accounts: [{ label: '小莫', note: '@suzukaze_haduki', href: 'https://x.com/suzukaze_haduki', icon: 'x.com', avatar: './src/assets/avatars/houko.png' }], + docs: { dir: '../../docs', sidebar }, + roadmap: { + owner: 'nsgo-dev', + name: 'nsgo', + tracking: 1047, + description: per((c) => c.roadmap.description), + }, + footer: { + copyright: '© 2026 NSGo', + license: { label: 'Apache-2.0', href: `${repo}/blob/main/LICENSE` }, + }, + home: false, + customCss: ['./src/styles/site.css'], + // The Kubai icons of the home page's sections (src/components/Home.astro). + icons: ['file-code', 'file-diff', 'files', 'gamepad', 'trophy', 'network', 'cube', 'terminal', 'accessibility'], +}); diff --git a/apps/website/src/assets/avatars/houko.png b/apps/website/src/assets/avatars/houko.png new file mode 100644 index 00000000..4c525245 Binary files /dev/null and b/apps/website/src/assets/avatars/houko.png differ diff --git a/apps/website/src/assets/logo-dark.svg b/apps/website/src/assets/logo-dark.svg index 66c8764d..0cc166b8 100644 --- a/apps/website/src/assets/logo-dark.svg +++ b/apps/website/src/assets/logo-dark.svg @@ -1,9 +1,9 @@ - - + + - + diff --git a/apps/website/src/assets/logo-light.svg b/apps/website/src/assets/logo.svg similarity index 100% rename from apps/website/src/assets/logo-light.svg rename to apps/website/src/assets/logo.svg diff --git a/apps/website/src/components/ApiView.tsx b/apps/website/src/components/ApiView.tsx deleted file mode 100644 index 6bcf9533..00000000 --- a/apps/website/src/components/ApiView.tsx +++ /dev/null @@ -1,406 +0,0 @@ -import { Fragment, type ReactNode, useEffect, useRef } from 'react' -import { api } from 'virtual:api' -import type { ApiFunc, ApiIdent, ApiPackage, ApiSummary, ApiType, ApiValue } from '../content/types' -import { copies } from '../copy' -import { htmlLang, type Lang, pageHead, useLang } from '../i18n' -import { GITHUB_URL } from '../links' -import { Icon } from './Icon' -import { LocaleLink } from './LocaleLink' - -const NARROW = '(max-width: 820px)' -const FOLD_SCRIPT = `if (matchMedia('${NARROW}').matches) document.querySelector('.docs__nav').open = false;` - -// The Go module's directory in the repository, which a declaration's file is relative to. -const MODULE_DIR = 'packages/game' - -// The ids of a package page's sections, as pkg.go.dev names them; an exported identifier starts with a capital letter, so none is one of these. -const SECTION = { overview: 'pkg-overview', index: 'pkg-index', consts: 'pkg-constants', vars: 'pkg-variables', funcs: 'pkg-functions', types: 'pkg-types' } as const - -export function apiIndexHead(lang: Lang) { - const copy = copies[lang].api - return pageHead(lang, 'docs/api/', `${copy.title} — ${copy.titleSuffix}`, copy.description) -} - -export function apiPackageHead(lang: Lang, pkg: ApiPackage | undefined) { - if (!pkg) return {} - return pageHead(lang, `docs/api/${pkg.page}/`, `${pkg.name} — ${copies[lang].api.titleSuffix}`, pkg.synopsis) -} - -// apiPage is a package page's path from a splat, which may end in the slash every page's address does. -export const apiPage = (splat: string | undefined) => (splat ?? '').replace(/\/+$/, '') - -// groupPackages puts the packages at the module's top level first, then those below each directory, such as tooling/, under it. -function groupPackages(packages: ApiSummary[]): { dir: string; items: ApiSummary[] }[] { - const groups = new Map() - for (const pkg of packages) { - const slash = pkg.page.indexOf('/') - const dir = slash < 0 ? '' : pkg.page.slice(0, slash) - groups.set(dir, [...(groups.get(dir) ?? []), pkg]) - } - return [...groups].map(([dir, items]) => ({ dir, items })).sort((a, b) => (a.dir === '' ? -1 : b.dir === '' ? 1 : a.dir.localeCompare(b.dir))) -} - -function groupTitle(lang: Lang, dir: string): string { - const copy = copies[lang].api - if (dir === '') return copy.packages - return dir === 'tooling' ? copy.tooling : dir -} - -function PackageLink({ lang, page, children, className }: { lang: Lang; page: string; children: ReactNode; className?: string }) { - return ( - - {children} - - ) -} - -// ApiLayout is the docs' layout for the reference: its packages beside the article, and the article's contents on the other side. -function ApiLayout({ children, toc, page }: { children: ReactNode; toc?: { id: string; text: string; depth: 2 | 3 }[]; page?: string }) { - const lang = useLang() - const copy = copies[lang] - const nav = useRef(null) - useEffect(() => { - if (nav.current && matchMedia(NARROW).matches) nav.current.open = false - }, [page]) - const packages = api.status === 'ok' ? api.packages : [] - return ( -
-