diff --git a/apps/apidocs-astro/astro.config.mjs b/apps/apidocs-astro/astro.config.mjs index 7fa83c9..fea8ca8 100644 --- a/apps/apidocs-astro/astro.config.mjs +++ b/apps/apidocs-astro/astro.config.mjs @@ -6,7 +6,17 @@ import { apidocs } from "@elide/apidocs/astro/integration"; import { defineConfig } from "astro/config"; import { guidesPlugin } from "./scripts/guides.mjs"; -const theme = { extends: "elide" }; +// Each site's top bar switches between the sample's documentation sites, with its own marked as current. +const theme = current => ({ + extends: "elide", + links: { + header: [ + { label: "User guide", url: "/guides/", current: current === "guides" }, + { label: "Java API", url: "/java/2.0/", current: current === "java" }, + { label: "Kotlin API", url: "/kotlin/", current: current === "kotlin" }, + ], + }, +}); export default defineConfig({ adapter: cloudflare(), @@ -15,10 +25,10 @@ export default defineConfig({ integrations: [ apidocs({ sites: [ - { base: "/java/2.0/", model: "./src/models/java.ts", theme, version: "2.0" }, - { base: "/java/main/", model: "./src/models/java.ts", theme, version: "main" }, - { base: "/kotlin/", model: "./src/models/kotlin.ts", theme }, - { base: "/guides/", model: "./src/generated/guides.json", theme }, + { base: "/java/2.0/", model: "./src/models/java.ts", theme: theme("java"), version: "2.0" }, + { base: "/java/main/", model: "./src/models/java.ts", theme: theme("java"), version: "main" }, + { base: "/kotlin/", model: "./src/models/kotlin.ts", theme: theme("kotlin") }, + { base: "/guides/", model: "./src/generated/guides.json", theme: theme("guides") }, ], versions: "./src/versions.ts", }), diff --git a/apps/apidocs-astro/test/browser.test.ts b/apps/apidocs-astro/test/browser.test.ts index cb6a1ad..7e10524 100644 --- a/apps/apidocs-astro/test/browser.test.ts +++ b/apps/apidocs-astro/test/browser.test.ts @@ -3,8 +3,8 @@ * top bar and navigator, the page behaviors across navigations, server islands, JavaScript off, reduced motion, * layout stability, axe, and head metadata against the static renderer. * - * Builds the app and starts wrangler dev on port 5191 unless APIDOCS_ASTRO_URL names a running server. Needs a - * Playwright 1.65 Chromium (PLAYWRIGHT_BROWSERS_PATH). + * Builds the app and starts wrangler dev on port 5191 (APIDOCS_ASTRO_PORT picks another) unless APIDOCS_ASTRO_URL + * names a running server. Needs a Playwright 1.65 Chromium (PLAYWRIGHT_BROWSERS_PATH). */ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { type ChildProcess, spawn, spawnSync } from "node:child_process"; @@ -17,7 +17,7 @@ import { type Browser, type BrowserContextOptions, chromium, type Page } from "p const app = fileURLToPath(new URL("..", import.meta.url)); const require = createRequire(import.meta.url); -const PORT = 5191; +const PORT = Number(process.env.APIDOCS_ASTRO_PORT ?? 5191); let origin = process.env.APIDOCS_ASTRO_URL?.replace(/\/$/, "") ?? `http://127.0.0.1:${PORT}`; let server: ChildProcess | undefined; let browser: Browser; @@ -155,10 +155,50 @@ describe("the persisted top bar and navigator", () => { await page.context().close(); }); - test("the index links follow the page", async () => { + test("the navigator's index links follow the page", async () => { const { page } = await open(TYPE); - await follow(page, '.topbar-nav a[href="/java/2.0/packages"]'); - expect(await page.locator('.topbar-nav [aria-current="page"]').getAttribute("href")).toBe("/java/2.0/packages"); + expect(await page.locator('.nav-reference [aria-current="page"]').count()).toBe(0); + await follow(page, '.nav-reference a[href="/java/2.0/packages"]'); + expect(await page.locator('.nav-reference [aria-current="page"]').getAttribute("href")).toBe("/java/2.0/packages"); + await follow(page, '.nav-reference a[href="/java/2.0/index-all"]'); + expect(await page.locator('.nav-reference [aria-current="page"]').getAttribute("href")).toBe("/java/2.0/index-all"); + expect(await page.locator('.sidebar [aria-current="page"]').count()).toBe(1); + await page.context().close(); + }); + + test("the suite switcher marks the current site, within a site and after moving to another", async () => { + const { page, documents } = await open(TYPE); + const current = () => page.locator('.suites-row a[aria-current="true"]').textContent(); + expect(await current()).toBe("Java API"); + expect(await page.locator('.suites-row a[aria-current="true"]').getAttribute("href")).toBe("/java/2.0/"); + await follow(page, `.sidebar a[href="${OTHER}"]`); + expect(await current()).toBe("Java API"); + expect(await page.locator(".suites").getAttribute("data-fit")).toBe("row"); + await follow(page, '.suites-row a[href="/kotlin/"]'); + expect(new URL(page.url()).pathname).toBe("/kotlin/"); + expect(await current()).toBe("Kotlin API"); + expect(await page.locator('.suites-row a[aria-current="true"]').getAttribute("href")).toBe("/kotlin/"); + expect(await page.locator(".suites").getAttribute("data-fit")).toBe("row"); + await follow(page, '.suites-row a[href="/guides/"]'); + expect(await current()).toBe("User guide"); + // The guides-only site has its overview as a guide, so the navigator lists no index links. + expect(await page.locator(".nav-reference, .nav-index").count()).toBe(0); + expect(documents).toEqual([]); + await page.context().close(); + }); + + test("on a phone the switcher leaves the bar, and the drawer lists the sites first", async () => { + const { page } = await open(TYPE, { viewport: { width: 360, height: 700 } }); + expect(await page.locator(".suites").getAttribute("data-fit")).toBe("none"); + expect(await page.locator(".suites-row").isVisible()).toBe(false); + await page.locator(".nav-button").click(); + const first = page.locator(".sidebar > :first-child"); + expect(await first.evaluate(e => e.classList.contains("nav-suites"))).toBe(true); + expect(await first.locator("a").allTextContents()).toEqual(["User guide", "Java API", "Kotlin API"]); + // After a navigation the drawer's blocks keep their order around the kept filter field. + await follow(page, `.sidebar a[href="${OTHER}"]`); + expect(await page.locator(".sidebar > :first-child").evaluate(e => e.classList.contains("nav-suites"))).toBe(true); + expect(await page.locator(".sidebar > :nth-child(2)").evaluate(e => e.classList.contains("nav-filter"))).toBe(true); await page.context().close(); }); @@ -331,6 +371,48 @@ describe("layout stability", () => { }); }); +describe("the top bar", () => { + /** packages/apidocs/test/topbar.test.ts topBarProblems, for the app's own pages: what wraps, overflows or is cut off. */ + const problems = (page: Page) => page.evaluate(() => { + const bar = document.querySelector(".topbar")!; + const box = bar.getBoundingClientRect(); + const found: string[] = []; + if (bar.scrollWidth > bar.clientWidth) found.push(`the bar scrolls: ${bar.scrollWidth} > ${bar.clientWidth}`); + const shown = (e: Element) => { + for (let n: Element | null = e; n && n !== bar.parentElement; n = n.parentElement) { + const s = getComputedStyle(n); + if (s.display === "none" || s.visibility === "hidden" || n.classList.contains("visually-hidden")) return false; + } + return true; + }; + for (const e of bar.querySelectorAll("*")) { + if (e.matches(".suites-fit, .suites-probe") || e.closest(".search-results, .suite-list, .version-list, script") || !shown(e)) continue; + const r = e.getBoundingClientRect(); + if ((r.width === 0 && r.height === 0) || r.bottom < 0) continue; + const s = getComputedStyle(e); + const name = `${e.tagName.toLowerCase()}.${typeof e.className === "string" ? e.className.split(" ")[0] : ""}`; + if (r.left < box.left - 0.5 || r.right > box.right + 0.5 || r.top < box.top - 0.5 || r.bottom > box.bottom + 0.5) found.push(`${name} lies outside the bar`); + if (s.overflowX !== "visible" && e.scrollWidth > e.clientWidth + 1 && s.textOverflow !== "ellipsis" && !(e instanceof HTMLInputElement)) found.push(`${name} is cut off`); + } + return found; + }); + + for (const path of [TYPE, "/kotlin/org/example/kgeo/Geometry", "/guides/guides/getting-started"]) { + test(`${path}: nothing wraps, overflows or is cut off from 320 to 1600px`, async () => { + const { page } = await open(path, { viewport: { width: 1600, height: 600 } }); + await page.waitForSelector(".topbar"); + const found: string[] = []; + for (let width = 320; width <= 1600; width += 20) { + await page.setViewportSize({ width, height: 600 }); + await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))); + for (const problem of await problems(page)) found.push(`${width}px: ${problem}`); + } + expect(found).toEqual([]); + await page.context().close(); + }, 120_000); + } +}); + describe("server islands", () => { test("the version menu lists the versions and opens the same page in another one", async () => { const { page, documents } = await open("/java/main/com/example/geo/Circle"); @@ -395,7 +477,7 @@ describe("reduced motion", () => { describe("accessibility", () => { for (const colorScheme of ["light", "dark"] as const) { - for (const path of [TYPE, "/java/2.0/guides/concepts", "/java/2.0/index-all", "/java/main/com/example/geo/", "/guides/"]) { + for (const path of [TYPE, "/java/2.0/guides/concepts", "/java/2.0/index-all", "/java/main/com/example/geo/", "/guides/", "/kotlin/org/example/kgeo/ShapeParseException", "/java/2.0/nope"]) { test(`${path} in ${colorScheme} has no axe violations`, async () => { const { page } = await open(path, { colorScheme }); await page.waitForLoadState("networkidle"); @@ -423,9 +505,10 @@ describe("metadata", () => { const head = html.split("")[1]!.split("")[0]!; return { title: /(.*?)<\/title>/.exec(head)?.[1], - meta: [...head.matchAll(/<meta (?:name|property)="(description|keywords|generator|apidocs:[a-z]+|og:[a-z_]+|twitter:card)" content="([^"]*)"\/?>/g)].map(m => [m[1], m[1] === "og:url" ? map(m[2]!) : m[2]]), + meta: [...head.matchAll(/<meta (?:name|property)="(description|keywords|generator|apidocs:[a-z]+|og:[a-z_]+|twitter:card)" content="([^"]*)"\/?>/g)].map(m => [m[1], m[1] === "og:url" ? map(m[2]!) : m[1] === "og:image" ? "(the social image)" : m[2]]), links: [...head.matchAll(/<link rel="(canonical|alternate|index)"[^>]*? href="([^"]*)"/g)].map(m => [m[1], map(m[2]!)]), - jsonLd: JSON.parse(/<script type="application\/ld\+json">(.*?)<\/script>/.exec(head)![1]!, (key, value) => (["url", "item", "contentUrl"].includes(key) ? map(value) : value)), + // The social image is the app's bundled file, not the static site's assets/social/. + jsonLd: JSON.parse(/<script type="application\/ld\+json">(.*?)<\/script>/.exec(head)![1]!, (key, value) => (key === "url" && /\.png$/.test(value) ? "(the social image)" : ["url", "item", "contentUrl"].includes(key) ? map(value) : value)), }; }; expect(metadata(served, u => u)).toEqual(metadata(staticHtml, u => mapUrl(u, ctx))); @@ -440,4 +523,23 @@ describe("metadata", () => { expect(redirect.headers.get("location")).toBe("/java/2.0/com/example/geo/Circle"); expect((await at("/java/2.0/com/example/geo/Nope")).status).toBe(404); }); + + test("the social image is served, and a missing page is the site's not-found page, as HTML or Markdown", async () => { + const html = await (await fetch(`${origin}/java/2.0/`)).text(); + const image = /<meta property="og:image" content="([^"]*)"/.exec(html)![1]!; + expect(image).toMatch(new RegExp(`^${origin}/_astro/`)); + const png = await fetch(image); + expect(png.status).toBe(200); + expect(png.headers.get("content-type")).toBe("image/png"); + const missing = await fetch(`${origin}/java/2.0/com/example/geo/Nope`); + expect(missing.status).toBe(404); + const page = await missing.text(); + expect(page).toContain("<h1>Not found</h1>"); + expect(page).toContain('<a href="/java/2.0/packages">Packages</a>'); + expect(page).toContain('<meta name="robots" content="noindex"/>'); + const md = await fetch(`${origin}/java/2.0/com/example/geo/Nope`, { headers: { accept: "text/markdown" } }); + expect(md.status).toBe(404); + expect(md.headers.get("content-type")).toContain("text/markdown"); + expect(await md.text()).toContain("Start at the [overview](/java/2.0/index.md)"); + }); }); diff --git a/bun.lock b/bun.lock index d2ffe5b..3948017 100644 --- a/bun.lock +++ b/bun.lock @@ -159,6 +159,7 @@ "node-html-parser": "6.1.13", "playwright": "^1.65.0", "postcss": "8.5.32", + "sharp": "^0.35.5", "typescript": "^7.0.2", "vite": "^8.3.6", "yaml": "2.9.1", diff --git a/packages/apidocs/AUDITS.md b/packages/apidocs/AUDITS.md index 8a67190..9412ac9 100644 --- a/packages/apidocs/AUDITS.md +++ b/packages/apidocs/AUDITS.md @@ -43,8 +43,9 @@ the score below; the CSS row is the share of the nine mechanical good-css rules Lighthouse 13.6.0 (pinned) runs programmatically in the Chromium that Playwright installs, through chrome-launcher, once per page and form factor (mobile is Lighthouse's default config; desktop uses `desktop-config.js`). It audits the module -overview, the package page with the most types, the smallest type page with real content, and the largest type page -(`ShapeCatalog.html` in the Java sample; `dev/elide/kotlin/api/Ir.html` in the Komodo model). Each run's JSON and HTML +overview, the package page with the most types, the smallest type page with real content, the largest type page +(`ShapeCatalog.html` in the Java sample; `dev/elide/kotlin/api/Ir.html` in the Komodo model), and a guide page +(`guides/getting-started.html` when there is one). Each run's JSON and HTML report, and a summary of the failing weighted audits with their values, are in `lighthouse/`. The pages are served the way a static host would serve them: brotli or gzip, `Cache-Control: public, max-age=31536000` @@ -83,6 +84,16 @@ Ora's partial-credit thresholds are not all published, and the values used are i Agentic's own display groups checks as Essential (80 points), Recommended (20) and Bonus (5); that grouping per site type is not published, so the audit reports Ora's score. +The text the token budget and the content checks measure is what a reader gets: `<pre>` is parsed like any other +element, so a highlighted signature counts as its text, not its markup. (Earlier versions of the audit counted the +markup inside `<pre>`, which made the largest Java sample page read as 175,174 characters; parsed, it was 102,861, +and with each member's summary sentence drawn once it is 89,287.) Built sites get the run's date as the theme's +`lastModified`, as the doclet passes its build date. + +The static host profile cannot pass `agent-friendly-404` in full: a missing page gets the site's `404.html` with a +404 status (1 of 2), but answering `Accept: text/markdown` with `404.md` is content negotiation, which a static +host does not do. `--host agent` does it, as the Astro integration's route does. + Each finding names an owner: `page` (markup, CSS, client script), `output` (files the renderer writes: llms.txt, sitemap.xml, robots.txt, 404 pages, JSON-LD content) or `host` (status codes, headers, negotiation). `--host agent` serves each page's `.md` twin for `Accept: text/markdown` with `Vary: Accept` and adds Link headers, to show the score @@ -106,3 +117,19 @@ everything pressable (approximated: every `:hover` selector has a matching `:act `prefers-reduced-motion: no-preference`, named transition properties without `all` or `ease-in` and at most 300 ms, `overflow: clip` over `hidden`, and the declarations the skill leaves out on purpose. The 47 entries need judgment about where they apply, so each gets a `review` row in the report with what the stylesheet shows; a person settles it. + +A declaration may be a noted exception to one rule: a `/* good-css exception (rule-id): reason */` comment before it +in its rule, or before its rule, takes it out of that rule's count, and the report lists it. Each one is a choice +the pages need, kept on purpose: + +| Rule | Where | Why | +| --- | --- | --- | +| `motion-properties` | the load bar's two animations | It shows progress, not a change of state: a 6s ease-out so a slow page still shows movement, and 420ms for the arriving page to finish it. Both stay inside `prefers-reduced-motion: no-preference`. | +| `overflow-clip` | `.product`, `.suite-label`, `.result-context`, `.nav-label`, `.toc a` | `overflow: hidden` so `text-overflow: ellipsis` shows in every target browser (Safari before 16 has no `clip`). | +| `overflow-clip` | `.member-brief` | WebKit clamps lines with `-webkit-line-clamp` only under `overflow: hidden`. | +| `fluid-clamp` | where the navigator becomes a drawer (860px): the drawer's padding, the switcher's margin, the search field without its key hint, the drawer's sites block, one-column facts, the summary table as blocks; and the content's padding when the navigator is hidden | Layout changes, not a size stepped at a breakpoint: each value belongs to a different arrangement of the page. | +| `fluid-clamp` | the Elide preset's title and declaration-specimen sizes | The preset sets its type in exact pixels so JetBrains Mono's characters are a whole number of pixels wide: 30px and 15px, 25px and 13.3333px where the navigator is a drawer. A fluid size between them would put the characters off the pixel grid. It is written as a token switch in the preset's CSS. | + +Fluid sizes are custom properties at the top of `apidocs.css` (`--apidocs-gutter`, `--apidocs-content-top`, and so +on): the narrow value at 480px wide and below, the wide one from 1000px, a straight line between. They cover spacing, +and the title and specimen sizes of the neutral (fallback) type scale; the scale tokens themselves stay exact. diff --git a/packages/apidocs/README.md b/packages/apidocs/README.md index 8ed3159..fcf58e8 100644 --- a/packages/apidocs/README.md +++ b/packages/apidocs/README.md @@ -25,8 +25,27 @@ the network. ## Output Every page has an `.html` and an `.md` twin: `index`, `<package/path>/index` and `<package/path>/<Type>`, with nested -types as `Outer.Inner`. The root also holds `llms.txt`, `llms-full.txt`, `api.json`, `element-list` and `assets/`. -With a theme `baseUrl` it also has `sitemap.xml`, and pages carry canonical links. Every link is relative and names +types as `Outer.Inner`. The root also holds `llms.txt`, `llms-full.txt`, `api.json`, `element-list`, `404.html` and +`404.md`, and `assets/`. With a theme `baseUrl` it also has `sitemap.xml`, and pages carry canonical links. + +- **Markdown twins** open with YAML frontmatter: `title`, `description`, `kind` (module, package, a type's kind, + guide, index), `id`, `module`, `version`, and `canonical` (the HTML page's URL) when the site's address is known. + Values are double-quoted, with `<`, `>` and `&` as `\u` escapes. `llms-full.txt` joins the twins without it, and + "copy as Markdown" copies the page without it. +- **`404.html` and `404.md`** are what a static host (GitHub Pages, Netlify, Cloudflare Pages) serves for a missing + URL: the page shell with links to the overview, the indexes and `llms.txt`, marked `noindex`. A host serves them at + any depth, so with a `baseUrl` their links start from it (`<base href>` in the HTML); without one, they work for + missing pages at the site's root only. Neither is listed in `llms.txt` or `sitemap.xml`. +- **`llms.txt`** has a "When to use this" section: the theme's `whenToUse` (Markdown), or one sentence from the + module's name, version and description. +- **`sitemap.xml`** gives every URL a `lastmod` when the theme has `lastModified` (a W3C date such as `2026-11-21`): + the runner's and the guides command's `--last-modified` set it. The renderer never reads the clock. +- **Link previews**: with a theme `socialImage` (`{ asset or url, width, height, alt }`), pages carry `og:image`, its + size and alt text, and a large Twitter card. Both presets have one, 1200 by 630, generated by + `scripts/gen-social.ts` into `artwork/` (Elide's dark lockup on its dark surface; the neutral preset's mark); + `socialImage: null` leaves it out. +- **JSON-LD**: every page's item has a `url` (absolute with a `baseUrl`, else relative); the overview's lists the + guides and packages as `hasPart`. Every link is relative and names its file. Scripts are classic. Search reads `assets/search-index.js`, which assigns a global, so nothing uses `fetch`. With JavaScript off, pages keep all their content; only search, the theme switch, copy buttons and table-of-contents tracking go away. @@ -163,6 +182,41 @@ The stylesheet reads only `--apidocs-*` custom properties; `tokens` sets them wi `elide` maps the tokens to `@elide/tokens` and takes its logo from `@elide/brand`. A theme can also set `logo` (SVG markup for light and dark), `favicon`, `fonts` and `footer`. +Colors are written as `oklch()`: the neutral defaults, converted exactly from their former hex values, and the Elide +preset's, converted from `@elide/tokens` when the preset loads (`src/color.ts`; each is the same 8-bit color). A theme +may use any CSS color. The stylesheet uses logical properties, so a page laid out right to left (`dir="rtl"`) mirrors. +Spacing grows with the screen (`--apidocs-gutter` and the other fluid tokens at the top of the stylesheet); the type +scale stays exact, and a theme that sets its type in exact pixels sets `size-title` and `size-specimen` too, as the +Elide preset does. + +### The top bar and the navigator + +The top bar holds what belongs to the whole site: the navigator toggle, the brand, the version (or an Astro app's +version menu), a switcher between sibling documentation sites, search and the theme switch. The module's indexes +(Overview, Packages, All types, Index, Deprecated, as many as the site has) are at the top of the navigator, under the +filter: one line of links when there are at most two, else rows under "Reference", the current one marked. + +`links.header` lists the sibling sites, such as a user guide, a developer guide and the API reference, in the order +the switcher shows them. Mark the entry that is this site with `"current": true`; without one, the entry whose URL is +the site's own root (`""`, `"./"`, `"index.html"`, or the theme's `baseUrl`) is current. The current entry links to +this site's overview. With no entries, or only this site, there is no switcher. Put other links, such as a +repository, in `links.footer`. Relative URLs in both lists are resolved from the site's root; a path that starts with +`/` and an absolute URL are written as given. + +```json +{ "links": { "header": [ + { "label": "User guide", "url": "https://example.com/user/" }, + { "label": "API reference", "url": "https://example.com/api/", "current": true } +] } } +``` + +The switcher shows the sites as a row when the bar has room for it, else as one menu button that names the current +site and opens the list (a `<details>` menu that works without JavaScript; Escape and a click elsewhere close it). +Where the navigator is a drawer (860px and narrower), the drawer lists the sites first, and the bar shows the row +only when it fits. Nothing in the bar wraps, overflows or is cut off at any width from 320px: the search field +narrows first, then the switcher gives way, then the product name ends in an ellipsis. The browser's layout makes +the choice with no width written down; `src/styles/apidocs.css` (the top bar section) has the details. + ## Astro `@elide/apidocs/astro` serves the same pages from an Astro app (Astro 7), rendered on request or from models the app @@ -206,7 +260,10 @@ same functions from `@elide/apidocs/astro/helpers`): those three; everything else renders alone. - `prefersMarkdown(accept)`, `linkHeader(base, page)` and `notFound(base, title, accept)`: serve a page's Markdown twin at its URL to a client that asks for Markdown, point at the other forms in a `Link` header, and answer a - missing page with directions. + missing page with directions when the app has no model to render. +- The not-found page: `<ApidocsPage page="404">` (with a 404 status) is the static `404.html` in the Astro form, and + `notFoundText(model, base, theme?)` its Markdown, with links under the base. `resolvePage` never resolves a path + to it. The integration's route answers a missing path with both, by the Accept header. - `<VersionSelect versions current path />` and `<VersionNotice versions current path />`: a version menu for the top bar and a "not the latest release" line, each a fixed box (see "Server islands"). A `Version` is `{ id, label?, base, channel?: "release" | "prerelease" | "development", latest? }`. @@ -216,8 +273,8 @@ same functions from `@elide/apidocs/astro/helpers`): The search island is Preact: the app needs `@astrojs/preact`. `apidocs()` adds it (and keeps one copy of Preact), so an app that renders on request adds `apidocs()` with no sites. An app that also uses React gives each renderer `include` -patterns. Astro bundles the stylesheet, the client script and the Elide preset's fonts as hashed files under -`/_astro/`; a theme's tokens are inlined. Nothing under `assets/` needs copying unless a theme names its own fonts, +patterns. Astro bundles the stylesheet, the client script, the Elide preset's fonts and the presets' social images +as hashed files under `/_astro/`; a theme's tokens are inlined. `og:image` names the bundled image, absolute. Nothing under `assets/` needs copying unless a theme names its own fonts, which resolve to `assets/fonts/...` under the base. Keep the parsed model object between requests (per version, say): the site structure and each page's data are @@ -326,7 +383,7 @@ cached for a year. | --- | --- | | Search | A Preact island, `client:idle`, in the top bar. Loads `assets/search-index.json` on first focus or keystroke; opens results through the router. The top bar persists, so it hydrates once per site. | | Theme switch, navigator toggle and `[`, copy buttons, copy as Markdown, member expand and collapse, open-on-hash, list filters, "On this page" tracking, menus | The static page's functions (`src/client/behaviors.tsx`), started on `astro:page-load` and stopped on `astro:before-swap` through one `AbortController` per page: no listener outlives its page. | -| Top bar and navigator | `transition:persist`, keyed by the site's base: across pages of one site they are the same elements, so the navigator keeps its scroll position and filter text without a script restoring them. Before each swap the client moves the new page's index links and navigator rows into them. | +| Top bar and navigator | `transition:persist`, keyed by the site's base: across pages of one site they are the same elements, so the navigator keeps its scroll position and filter text without a script restoring them. Before each swap the client moves the new page's suite switcher and navigator blocks (the sites, the indexes with the current one marked, guides, packages and types) into them, around the kept filter field, and applies the kept filter text to the new rows. A top bar from another site is sized before it paints. | | Theme and `data-js` | The head script sets them on first load; the client carries them to each new page's `<html>`, whose attributes the router replaces. | | Load bar | Starts on `astro:before-preparation`, finishes on arrival, clears if the navigation is aborted. | | Page transition | The router's view transition, with the static stylesheet's `::view-transition` rules: the content fades and rises 6px, the top bar and navigator do not move. The browser's cross-document transitions are off on Astro pages, so the two never both run. With reduced motion nothing animates. | @@ -343,7 +400,7 @@ The sample app, `apps/apidocs-astro`, serves the Java sample at `/java/2.0/` and bun run apidocs:astro:dev # astro dev on http://127.0.0.1:5190/ bun run apidocs:astro:build bun run apidocs:astro:preview # wrangler dev on http://127.0.0.1:5190/ -bun run --cwd apps/apidocs-astro test # builds, serves on 5191, and drives it in Chromium +bun run --cwd apps/apidocs-astro test # builds, serves on 5191 (APIDOCS_ASTRO_PORT), and drives it in Chromium ``` Astro 7 runs `astro dev` in the background when it detects an AI agent; set `ASTRO_DEV_BACKGROUND=1` to keep it in the @@ -363,7 +420,8 @@ The dev server renders pages with the production `render()` and the same compone `/site/<model>/<preset>/`. Editing a component, the stylesheet, a theme preset, a sample or the `--model` file reloads the page. In dev, the islands run as a module; the built pages load the `defer` bundle instead. The bar at the top is for development only and is not part of any output. It switches the model (Java sample, Kotlin sample, the -`--model` file), the theme preset, light or dark, the viewport width, and JavaScript off for the current page. +`--model` file), the theme preset, the number of sibling sites in the switcher (none, 1, 3 or 5), light or dark, the +viewport width, and JavaScript off for the current page. To check the portable output in the same loop, build it exactly as the doclet will: @@ -394,9 +452,11 @@ page that shows it, and says how to add one. - the Markdown importer (`test/import.test.ts`): each construct, the diagnostics fixture (`test/fixtures/guides-errors`), hostile Markdown and SVG, copied-file rules, the sample suite as a guides-only site through the output checker, the CLI, and Komodo's two suites when this package sits inside Komodo; -- in Chromium, a site built with `dist/runner.mjs` opened from `file://` with JavaScript on and off, and axe on the - page shell in light and dark; the same for the Markdown sample suite built with `apidocs guides` - (`test/guides-browser.test.ts`). Locally, point `PLAYWRIGHT_BROWSERS_PATH` at a Playwright 1.65 browser directory, or +- in Chromium, a site built with `dist/runner.mjs` opened from `file://` with JavaScript on and off, and axe on every + page kind in light and dark; the same for the Markdown sample suite built with `apidocs guides` + (`test/guides-browser.test.ts`); and the top bar (`test/topbar.test.ts`) at every width from 320 to 1600px in steps + of 20, in the static and the Astro markup, with zero to five sibling sites, with and without a version menu, and + with a long product name: nothing wraps, overflows or is cut off, and the switcher's menu and layout stability. Locally, point `PLAYWRIGHT_BROWSERS_PATH` at a Playwright 1.65 browser directory, or install one with `bunx playwright install chromium`. - the Astro helpers (`test/astro.test.ts`): every page and text file of every sample resolves in both URL forms and renders as the static renderer does, head metadata equals the static page's apart from the URL form, and hostile diff --git a/packages/apidocs/artwork/social-elide.png b/packages/apidocs/artwork/social-elide.png new file mode 100644 index 0000000..c14c3a8 Binary files /dev/null and b/packages/apidocs/artwork/social-elide.png differ diff --git a/packages/apidocs/artwork/social-neutral.png b/packages/apidocs/artwork/social-neutral.png new file mode 100644 index 0000000..bd3feaf Binary files /dev/null and b/packages/apidocs/artwork/social-neutral.png differ diff --git a/packages/apidocs/package.json b/packages/apidocs/package.json index 6325499..25946d5 100644 --- a/packages/apidocs/package.json +++ b/packages/apidocs/package.json @@ -25,6 +25,7 @@ "apidocs": "./src/cli.ts" }, "files": [ + "artwork", "dist", "schema", "src", @@ -57,6 +58,7 @@ "axe-core": "4.14.0", "chrome-launcher": "1.2.3", "lighthouse": "13.6.0", + "sharp": "^0.35.5", "mdast-util-from-markdown": "2.1.0", "mdast-util-gfm": "3.1.0", "micromark-extension-gfm": "3.0.0", diff --git a/packages/apidocs/samples/FEATURES.md b/packages/apidocs/samples/FEATURES.md index acdcb15..f657642 100644 --- a/packages/apidocs/samples/FEATURES.md +++ b/packages/apidocs/samples/FEATURES.md @@ -16,7 +16,7 @@ doclet's flavor. `kotlin` is `samples/kotlin.ts`, the Dokka plugin's flavor. `re | Record with documented components (`#param-radius`) | java | `com/example/geo/Circle.html` | | Enum with a deprecated constant | java, kotlin | `com/example/geo/Units.html`, `org/example/kgeo/LengthUnit.html` | | Annotation interface with element defaults | java, kotlin | `com/example/geo/Measured.html`, `org/example/kgeo/experimental/ExperimentalGeometry.html` | -| Exception (grouped under Exceptions) | java | `com/example/geo/GeometryException.html` | +| Exception (grouped under Exceptions, with the exception glyph): `java.lang.Throwable`, and Kotlin's `kotlin/Throwable` DRI | java, kotlin | `com/example/geo/GeometryException.html`, `org/example/kgeo/ShapeParseException.html` | | Nested types, two levels deep, in breadcrumbs and navigation | java | `com/example/geo/Shapes.Builder.Option.html` | | Generics with bounds and wildcards | java | `com/example/geo/Shapes.html#largest(java.util.Collection)` | | Constructors | java, kotlin | `com/example/geo/Circle.html`, `org/example/kgeo/Point.html` | diff --git a/packages/apidocs/samples/kotlin.ts b/packages/apidocs/samples/kotlin.ts index e637c9e..b5f5de9 100644 --- a/packages/apidocs/samples/kotlin.ts +++ b/packages/apidocs/samples/kotlin.ts @@ -69,6 +69,23 @@ const rect: Type = type({ doc: doc("An axis-aligned rectangle."), since: "1.0", }, "kotlin"); +// An exception: its ancestors are Kotlin's, by Dokka DRI (kotlin/Exception, kotlin/Throwable), so the navigator and +// the package list group it under Exceptions with the exception glyph. +const parseError: Type = type({ + id: dri(K, "ShapeParseException"), name: "ShapeParseException", kind: "class", modifiers: ["public"], + signature: tk(kw("class"), " ", nm("ShapeParseException"), "(", prm("message"), ": ", STRING, ") : ", std("Exception"), "(", prm("message"), ")"), + superclass: [std("Exception")], + ancestors: [ + { id: dri("kotlin", "Exception"), url: "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-exception/" }, + { id: dri("kotlin", "Throwable"), url: "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-throwable/" }, + { id: dri("kotlin", "Any"), url: "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-any/" }, + ], + members: [ + f(`${K}/ShapeParseException`, { name: "ShapeParseException", kind: "constructor", params: [{ name: "message", type: [STRING], doc: "what could not be read" }], doc: "Creates the exception with its message." }), + ], + doc: doc("Thrown when text does not describe a shape."), since: "2.1", +}, "kotlin"); + const meters: Type = type({ id: dri(K, "Meters"), name: "Meters", kind: "class", modifiers: ["public", "value"], annotations: [[an("@JvmInline", dri("kotlin.jvm", "JvmInline"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.jvm/-jvm-inline/")]], @@ -254,7 +271,7 @@ const packages: Package[] = [ { id: K, name: K, since: "1.0", doc: doc({ body: [P("Shapes and measurements in Kotlin."), UL("Shapes: [[org.example.kgeo/Shape///PointingToDeclaration/|Shape]] and its subclasses.", "Extensions on shapes, such as `scaled`; see [[guide:concepts#extensions|Extensions]]."), P("The [[guide:concepts|Concepts]] guide explains how these fit together.")] }), - types: [circle, companion, geometry, lengthUnit, meters, metric, point, rect, shape], + types: [circle, companion, geometry, lengthUnit, meters, metric, point, rect, shape, parseError], typeAliases: [ { id: `${K}/ShapeList///PointingToDeclaration/`, name: "ShapeList", signature: tk(kw("typealias"), " ", nm("ShapeList"), " = ", list(t("Shape"))), target: list(t("Shape")), doc: doc("A list of shapes."), since: "1.0" }, { id: `${K}/Transform///PointingToDeclaration/`, name: "Transform", typeParams: [{ name: "T", doc: blocks("the value type") }], signature: tk(kw("typealias"), " ", nm("Transform"), "<", tp("T"), "> = (", tp("T"), ") -> ", tp("T")), target: tk("(", tp("T"), ") -> ", tp("T")), doc: doc("A function from a value to a value of the same type."), since: "1.1" }, diff --git a/packages/apidocs/scripts/assets.ts b/packages/apidocs/scripts/assets.ts index ced65ea..e767209 100644 --- a/packages/apidocs/scripts/assets.ts +++ b/packages/apidocs/scripts/assets.ts @@ -1,6 +1,6 @@ /** - * Completes dist/: the stylesheet, the fonts the Elide preset names, the - * runner, and the JSON Schema, beside the two bundles Vite wrote. + * Completes dist/: the stylesheet, the fonts and social image the Elide preset + * names, the runner, and the JSON Schema, beside the two bundles Vite wrote. */ import { copyFileSync, mkdirSync } from "node:fs"; import { createRequire } from "node:module"; @@ -10,6 +10,9 @@ import { elide } from "../src/presets/elide"; const require = createRequire(import.meta.url); const pkg = (path: string) => fileURLToPath(new URL(`../${path}`, import.meta.url)); mkdirSync(pkg("dist/assets/fonts"), { recursive: true }); +mkdirSync(pkg("dist/assets/social"), { recursive: true }); +copyFileSync(pkg("artwork/social-elide.png"), pkg("dist/assets/social/elide.png")); +copyFileSync(pkg("artwork/social-neutral.png"), pkg("dist/assets/social/neutral.png")); copyFileSync(pkg("src/styles/apidocs.css"), pkg("dist/assets/apidocs.css")); copyFileSync(pkg("src/runner.mjs"), pkg("dist/runner.mjs")); copyFileSync(pkg("schema/apidocs-1.schema.json"), pkg("dist/apidocs-1.schema.json")); diff --git a/packages/apidocs/scripts/audit.ts b/packages/apidocs/scripts/audit.ts index 3ec9a39..0d7685d 100644 --- a/packages/apidocs/scripts/audit.ts +++ b/packages/apidocs/scripts/audit.ts @@ -83,7 +83,8 @@ for (const input of inputs) { const dir = join(reportDir, "sites", input.name); const server = serve(dir, host); servers.push(server); - const theme = { ...extraTheme, extends: extraTheme.extends ?? input.preset, ...(args.includes("--no-base-url") ? {} : { baseUrl: server.url }) }; + // The build's date, as the doclet passes it (--last-modified): the audit may read the clock; the renderer never does. + const theme = { lastModified: new Date().toISOString().slice(0, 10), ...extraTheme, extends: extraTheme.extends ?? input.preset, ...(args.includes("--no-base-url") ? {} : { baseUrl: server.url }) }; const stats = renderSite({ model: input.model, theme, out: dir, work: join(reportDir, "work", input.name) }); const prefer = flag("page") ?? (modelPath ? "dev/elide/kotlin/api/Ir.html" : undefined); sites.push({ name: input.name, dir, url: server.url, pages: representativePages(dir, prefer) }); @@ -117,12 +118,12 @@ try { const which = flag("lighthouse-sites") ?? "first"; const lhSites = which === "all" ? sites : [sites.find(s => s.name.endsWith("-elide")) ?? sites[0]!]; const at = (site: Site, page: string) => (site.urlOf ? site.urlOf(page) : site.url + page); - console.log(` lighthouse: ${lhSites.length} site(s) x 4 pages x ${formFactors.length} form factors ...`); + console.log(` lighthouse: ${lhSites.length} site(s) x 5 pages x ${formFactors.length} form factors ...`); const lh = await startLighthouse(); try { for (const site of lhSites) { - const { overview, package: pkg, smallType, largestType } = site.pages; - for (const page of [...new Set([overview, pkg, smallType, largestType])]) { + const { overview, package: pkg, smallType, largestType, guide } = site.pages; + for (const page of [...new Set([overview, pkg, smallType, largestType, ...(guide ? [guide] : [])])]) { for (const formFactor of formFactors) { const base = reportPath(reportDir, site.name, page, formFactor); const t = Date.now(); diff --git a/packages/apidocs/scripts/audit/agentic.ts b/packages/apidocs/scripts/audit/agentic.ts index 465b9df..10495a1 100644 --- a/packages/apidocs/scripts/audit/agentic.ts +++ b/packages/apidocs/scripts/audit/agentic.ts @@ -393,7 +393,8 @@ export async function agenticAudit(site: Site, options: AgenticOptions = {}): Pr set("markdown-link-alternate", { score: s, max: 1, status: statusOf(s, 1), evidence: `${advertised}/${rows.length} pages advertise a Markdown twin; ${rows.length - bad.length} of them resolve to Markdown.`, where: bad.slice(0, 5) }); const index = await get(`${site.url}index.md`); const twins = pages.filter(p => existsSync(join(site.dir, p.replace(/\.html$/, ".md")))); - const okIndex = index.status === 200 && /markdown/.test(index.type ?? "") && /^#/.test(index.text.trimStart()); + // A heading first, after the frontmatter that markdown-frontmatter asks for. + const okIndex = index.status === 200 && /markdown/.test(index.text && (index.type ?? "")) && /^#/.test(index.text.replace(/^---\n[\s\S]*?\n---\n/, "").trimStart()); const sf = okIndex ? (twins.length === pages.length ? 2 : 1) : 0; set("markdown-url-fallback", { score: sf, max: 2, status: statusOf(sf, 2), evidence: `/index.md: ${index.status} ${index.type ?? ""}; ${twins.length}/${pages.length} pages have a .md twin at the same path.` }); const mdFiles = pages.map(p => p.replace(/\.html$/, ".md")).filter(p => existsSync(join(site.dir, p))); diff --git a/packages/apidocs/scripts/audit/build.ts b/packages/apidocs/scripts/audit/build.ts index 73fef83..f0ca4b2 100644 --- a/packages/apidocs/scripts/audit/build.ts +++ b/packages/apidocs/scripts/audit/build.ts @@ -61,14 +61,16 @@ export function listFiles(dir: string): string[] { /** * The module overview, the package page with the most types, the smallest and - * the largest type page by HTML size, and every page. `prefer` names a page + * the largest type page by HTML size, a guide page (getting-started when there is one), and every page. `prefer` names a page * to use as the largest type page when it exists (dev/elide/kotlin/api/Ir.html * for the Komodo model). */ export function representativePages(dir: string, prefer?: string): RepresentativePages { const html = listFiles(dir).filter(f => f.endsWith(".html") && !f.startsWith("assets/") && f !== "404.html"); const packages = html.filter(f => f.endsWith("/index.html")); - const types = html.filter(f => !f.endsWith("index.html")); + // Type pages only: not package pages, guides, or the index pages (packages, types, index-all, deprecated) at the root. + const types = html.filter(f => !f.endsWith("index.html") && !f.startsWith("guides/") && f.includes("/")); + const guides = html.filter(f => f.startsWith("guides/")).sort(); const size = (f: string) => statSync(join(dir, f)).size; const typeCount = (pkgPage: string) => { const prefix = pkgPage.slice(0, -"index.html".length); @@ -79,5 +81,5 @@ export function representativePages(dir: string, prefer?: string): Representativ const largest = prefer && types.includes(prefer) ? prefer : bySize.at(-1) ?? "index.html"; // The smallest type page that still documents something: skip pages under 2 KB of text (empty annotation types). const small = bySize.find(f => readFileSync(join(dir, f), "utf8").length > 4000) ?? bySize[0] ?? "index.html"; - return { overview: "index.html", package: pkg, smallType: small, largestType: largest, all: html }; + return { overview: "index.html", package: pkg, smallType: small, largestType: largest, ...(guides.length ? { guide: guides.find(g => /getting-started/.test(g)) ?? guides[0] } : {}), all: html }; } diff --git a/packages/apidocs/scripts/audit/css.ts b/packages/apidocs/scripts/audit/css.ts index 45ee138..5ec2cd9 100644 --- a/packages/apidocs/scripts/audit/css.ts +++ b/packages/apidocs/scripts/audit/css.ts @@ -12,7 +12,7 @@ * * The score is the share of the mechanical rules with no violation. */ -import postcss, { type AtRule, type Declaration, type Rule } from "postcss"; +import postcss, { type AtRule, type ChildNode, type Comment, type Declaration, type Rule } from "postcss"; import type { Finding, Status } from "./types"; export interface Stylesheet { @@ -31,8 +31,13 @@ interface Decl { context: string[]; prop: string; value: string; + /** Rules this declaration is a noted exception to: a "good-css exception (rule-id): reason" comment before it in its rule, or before its rule. */ + exceptions: string[]; } +const EXCEPTION = /good-css exception \(([a-z-]+)\)/g; +const exceptionIds = (text: string) => [...text.matchAll(EXCEPTION)].map(m => m[1]!); + export interface CssReport { score: number; rules: Finding[]; @@ -58,7 +63,11 @@ export function readDeclarations(sheets: Stylesheet[]): Decl[] { else if (p.type === "rule") selector = `${(p as Rule).selector.replace(/\s+/g, " ")} ${selector}`; if (p.type === "atrule") context.unshift(`@${(p as AtRule).name} ${(p as AtRule).params}`.trim()); } - out.push({ sheet: sheet.path, line: decl.source?.start?.line ?? 0, selector: selector || "(at-rule)", context, prop: decl.prop.toLowerCase(), value: decl.value }); + const exceptions: string[] = []; + for (let n: ChildNode | undefined = decl.prev(); n; n = n.prev()) if (n.type === "comment") exceptions.push(...exceptionIds((n as Comment).text)); + const before = decl.parent && decl.parent.type === "rule" ? (decl.parent as Rule).prev() : undefined; + if (before?.type === "comment") exceptions.push(...exceptionIds((before as Comment).text)); + out.push({ sheet: sheet.path, line: decl.source?.start?.line ?? 0, selector: selector || "(at-rule)", context, prop: decl.prop.toLowerCase(), value: decl.value, exceptions }); }); } return out; @@ -70,10 +79,14 @@ export function cssAudit(sheets: Stylesheet[]): CssReport { const at = (d: Decl) => `${d.sheet}:${d.line} ${d.selector.slice(0, 70)} { ${d.prop}: ${d.value.slice(0, 60)} }`; const files = (list: Decl[]) => [...new Set(list.map(d => sourceOf(d.sheet)))].join(", ") || undefined; const rules: Finding[] = []; - const rule = (id: string, name: string, violations: Decl[], evidence: string, fix: string, source = SKILL, extra: string[] = []) => { + const rule = (id: string, name: string, found: Decl[], evidence: string, fix: string, source = SKILL, extra: string[] = []) => { + // A declaration the stylesheet notes as an exception to this rule, with its reason, is reported but does not fail it. + const violations = found.filter(d => !d.exceptions.includes(id)); + const excepted = found.filter(d => d.exceptions.includes(id)); + const noted = excepted.length ? ` ${excepted.length} noted exception(s) in the stylesheet: ${excepted.map(d => `${d.selector.slice(0, 40)} { ${d.prop} }`).join("; ")}.` : ""; rules.push({ rule: id, name, owner: "page", status: violations.length || extra.length ? "fail" : "pass", - evidence: violations.length || extra.length ? `${violations.length + extra.length} ${evidence}` : "No violations.", + evidence: (violations.length || extra.length ? `${violations.length + extra.length} ${evidence}` : "No violations.") + noted, where: [...extra, ...violations.map(at)].slice(0, 8), file: files(violations) ?? (extra.length ? sheets[0]?.source : undefined), fix: violations.length || extra.length ? fix : undefined, source, }); }; diff --git a/packages/apidocs/scripts/audit/html.ts b/packages/apidocs/scripts/audit/html.ts index 3ef525d..b37071d 100644 --- a/packages/apidocs/scripts/audit/html.ts +++ b/packages/apidocs/scripts/audit/html.ts @@ -45,7 +45,9 @@ const SKIP = new Set(["script", "style", "template", "svg"]); const INSTRUCTION = /\b(ignore (all |any )?(previous|prior|above) instructions|you are (an? )?(ai|assistant|language model)|as an ai|system prompt|disregard (the|all|previous)|do not tell the user)\b/i; export function readPage(html: string): PageFacts { - const root = parse(html, { comment: false, blockTextElements: { script: true, style: true, pre: true, textarea: true } }); + // Scripts, styles and textareas hold raw text; <pre> is parsed like any element, so the markup of a highlighted + // signature counts as the text it shows, not as its tags. + const root = parse(html, { comment: false, blockTextElements: { script: true, style: true, textarea: true } }); const doc = root.querySelector("html") ?? root; const head = root.querySelector("head"); const body = root.querySelector("body") ?? root; diff --git a/packages/apidocs/scripts/audit/remote.ts b/packages/apidocs/scripts/audit/remote.ts index d5ec0c4..0aa9e0f 100644 --- a/packages/apidocs/scripts/audit/remote.ts +++ b/packages/apidocs/scripts/audit/remote.ts @@ -71,6 +71,7 @@ export async function mirrorSite(name: string, url: string, dir: string): Promis // The smallest type page with real content, and the largest, as representativePages chooses them. smallType: bySize.find(f => size(f) > 4000) ?? bySize[0] ?? "index.html", largestType: bySize.at(-1) ?? "index.html", + ...(all.some(f => f.startsWith("guides/")) ? { guide: all.filter(f => f.startsWith("guides/")).sort().find(g => /getting-started/.test(g)) ?? all.filter(f => f.startsWith("guides/")).sort()[0] } : {}), all, }, }; diff --git a/packages/apidocs/scripts/audit/types.ts b/packages/apidocs/scripts/audit/types.ts index a67d3a7..f996edf 100644 --- a/packages/apidocs/scripts/audit/types.ts +++ b/packages/apidocs/scripts/audit/types.ts @@ -71,6 +71,8 @@ export interface RepresentativePages { package: string; smallType: string; largestType: string; + /** A guide page, when the site has guides. */ + guide?: string; /** Every HTML page, for the checks that read all of them. */ all: string[]; } diff --git a/packages/apidocs/scripts/dev.ts b/packages/apidocs/scripts/dev.ts index 3dd0a84..8d6a166 100644 --- a/packages/apidocs/scripts/dev.ts +++ b/packages/apidocs/scripts/dev.ts @@ -40,12 +40,24 @@ const require = createRequire(import.meta.url); type Output = Record<string, string | { asset: string }>; const cache = new Map<string, Output>(); -async function site(server: ViteDevServer, model: string, preset: string): Promise<Output> { - const key = `${model}/${preset}`; +/** Sibling sites for the suite switcher, as a theme's header links: the dev bar shows none, one, three or five. */ +const SUITES = [ + { label: "User guide", url: "https://example.com/user/" }, + { label: "Developer guide", url: "https://example.com/developer/" }, + { label: "API reference", url: "index.html", current: true }, + { label: "Kotlin API", url: "https://example.com/kotlin/" }, + { label: "Release notes", url: "https://example.com/notes/" }, +]; + +async function site(server: ViteDevServer, model: string, presetAndSuites: string): Promise<Output> { + const key = `${model}/${presetAndSuites}`; const cached = cache.get(key); if (cached) return cached; const { render } = await server.ssrLoadModule("/src/render.tsx"); - const theme = { extends: preset === "elide" ? "elide" : "neutral" }; + // "elide" or "elide.3": the preset, and how many sibling sites the switcher lists. + const [preset, count] = presetAndSuites.split("."); + const header = count === "1" ? [SUITES[0]!] : count === "3" ? SUITES.slice(0, 3) : count === "5" ? SUITES : []; + const theme = { extends: preset === "elide" ? "elide" : "neutral", links: { header } }; if (suites[model]) { const { suiteSite } = await server.ssrLoadModule("/src/import/suite.ts"); const { formatDiagnostic } = await server.ssrLoadModule("/src/import/markdown.ts"); @@ -85,6 +97,7 @@ const DEV_SCRIPTS = '<script type="module" src="/@vite/client"></script><script function asset(name: string): { body: Buffer | string; type: string } { if (name === "apidocs.css") return { body: readFileSync(resolve(root, "src/styles/apidocs.css"), "utf8"), type: "text/css" }; + if (name.startsWith("social/")) return { body: readFileSync(resolve(root, `artwork/social-${name.slice("social/".length)}`)), type: "image/png" }; if (name.startsWith("fonts/")) { const file = name.slice("fonts/".length); return { body: readFileSync(require.resolve(`@fontsource-variable/${file.replace(/-latin-.*$/, "")}/files/${file}`)), type: "font/woff2" }; @@ -117,6 +130,7 @@ function shell(): string { <strong>@elide/apidocs dev</strong> <label>Model <select id="model">${models.map(m => `<option value="${m}">${label(m)}</option>`).join("")}</select></label> <label>Theme <select id="preset"><option value="neutral">neutral (default)</option><option value="elide">elide</option></select></label> + <label>Sites <select id="suites"><option value="0">none</option><option value="1">1</option><option value="3">3</option><option value="5">5</option></select></label> <label>Mode <select id="mode"><option value="system">system</option><option value="light">light</option><option value="dark">dark</option></select></label> <label>Width <select id="width"><option value="100%">full</option><option value="1440px">1440</option><option value="1180px">1180</option><option value="1024px">1024</option><option value="820px">820</option><option value="390px">390 (phone)</option></select></label> <label><input type="checkbox" id="nojs"> JavaScript off</label> @@ -125,10 +139,11 @@ function shell(): string { <div class="stage"><iframe id="frame" title="Rendered page"></iframe></div> <script> const $ = id => document.getElementById(id); - const state = Object.assign({ model: "java", preset: "neutral", mode: "system", width: "100%", page: "index.html", nojs: false }, + const state = Object.assign({ model: "java", preset: "neutral", suites: "0", mode: "system", width: "100%", page: "index.html", nojs: false }, JSON.parse(sessionStorage.getItem("apidocs-dev") || "{}")); const frame = $("frame"); - const src = () => "/site/" + state.model + "/" + state.preset + "/" + state.page + (state.nojs ? "?nojs" : ""); + const site = () => state.preset + (state.suites === "0" ? "" : "." + state.suites); + const src = () => "/site/" + state.model + "/" + site() + "/" + state.page + (state.nojs ? "?nojs" : ""); function save() { sessionStorage.setItem("apidocs-dev", JSON.stringify(state)); } function load() { frame.src = src(); $("direct").href = src(); save(); } function applyMode() { @@ -137,7 +152,7 @@ function shell(): string { if (state.mode === "system") html.removeAttribute("data-theme"); else html.setAttribute("data-theme", state.mode); } catch (e) {} } - for (const key of ["model", "preset", "mode", "width"]) { + for (const key of ["model", "preset", "suites", "mode", "width"]) { $(key).value = state[key]; $(key).addEventListener("change", () => { state[key] = $(key).value; @@ -153,7 +168,7 @@ function shell(): string { frame.addEventListener("load", () => { try { const path = frame.contentWindow.location.pathname; - const prefix = "/site/" + state.model + "/" + state.preset + "/"; + const prefix = "/site/" + state.model + "/" + site() + "/"; if (path.startsWith(prefix)) { state.page = path.slice(prefix.length); $("direct").href = src(); save(); } } catch (e) {} applyMode(); diff --git a/packages/apidocs/scripts/gen-social.ts b/packages/apidocs/scripts/gen-social.ts new file mode 100644 index 0000000..4523776 --- /dev/null +++ b/packages/apidocs/scripts/gen-social.ts @@ -0,0 +1,38 @@ +/** + * Generates the presets' link-preview images, at 1200 by 630 as Open Graph expects: + * - artwork/social-elide.png: the dark lockup from @elide/brand, centered on the Elide preset's dark surface; + * - artwork/social-neutral.png: the neutral preset's favicon mark, unbranded, on its light page color. + * Committed, so builds need no image tooling; run it again when the artwork changes. + * + * bun scripts/gen-social.ts + */ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { neutral } from "@elide/tokens"; +import { neutral as neutralTheme } from "../src/theme"; +import sharp from "sharp"; + +const require = createRequire(import.meta.url); +const lockup = readFileSync(require.resolve("@elide/brand/assets/svg/elide-full-blend-dark.svg"), "utf8"); +const [, , w, h] = /viewBox="([\d.\s]+)"/.exec(lockup)![1]!.trim().split(/\s+/).map(Number) as [number, number, number, number]; +const WIDTH = 1200; +const HEIGHT = 630; +const LOGO = 520; +const logoHeight = Math.round((LOGO * h) / w); +const logo = await sharp(Buffer.from(lockup), { density: 600 }).resize(LOGO, logoHeight).png().toBuffer(); +const out = fileURLToPath(new URL("../artwork/social-elide.png", import.meta.url)); +await sharp({ create: { width: WIDTH, height: HEIGHT, channels: 3, background: neutral[950] } }) + .composite([{ input: logo, left: Math.round((WIDTH - LOGO) / 2), top: Math.round((HEIGHT - logoHeight) / 2) }]) + .png({ compressionLevel: 9 }) + .toFile(out); +console.log(`wrote ${out}`); + +const markSize = 168; +const mark = await sharp(Buffer.from(neutralTheme.favicon!), { density: 1200 }).resize(markSize, markSize).png().toBuffer(); +const plain = fileURLToPath(new URL("../artwork/social-neutral.png", import.meta.url)); +await sharp({ create: { width: WIDTH, height: HEIGHT, channels: 3, background: "#fbfcfd" } }) + .composite([{ input: mark, left: (WIDTH - markSize) / 2, top: (HEIGHT - markSize) / 2 }]) + .png({ compressionLevel: 9 }) + .toFile(plain); +console.log(`wrote ${plain}`); diff --git a/packages/apidocs/src/astro/ApidocsPage.astro b/packages/apidocs/src/astro/ApidocsPage.astro index 8628376..83d86f9 100644 --- a/packages/apidocs/src/astro/ApidocsPage.astro +++ b/packages/apidocs/src/astro/ApidocsPage.astro @@ -15,7 +15,7 @@ import "../styles/apidocs.css"; import "./apidocs-astro.css"; import type { Model } from "../model"; import type { Theme } from "../theme"; -import { bundledFonts } from "./fonts"; +import { bundledAssets, bundledFonts } from "./fonts"; import { renderPage } from "./render"; import Search from "./Search"; @@ -32,7 +32,7 @@ interface Props { const { model, page, theme, site } = Astro.props; const base = Astro.props.base.endsWith("/") ? Astro.props.base : `${Astro.props.base}/`; const baseUrl = new URL(base, site ?? Astro.site ?? Astro.url.origin).href; -const parts = renderPage(model, page, theme, { base, baseUrl, fontUrl: asset => bundledFonts[asset] ?? `${base}assets/${asset}` }); +const parts = renderPage(model, page, theme, { base, baseUrl, fontUrl: asset => bundledFonts[asset] ?? `${base}assets/${asset}`, assetUrl: asset => bundledAssets[asset] ?? `${base}assets/${asset}` }); --- <html lang="en" data-root={base}> <head> diff --git a/packages/apidocs/src/astro/Route.astro b/packages/apidocs/src/astro/Route.astro index 90b4406..37fcf9f 100644 --- a/packages/apidocs/src/astro/Route.astro +++ b/packages/apidocs/src/astro/Route.astro @@ -7,8 +7,8 @@ import { sites, versions } from "virtual:@elide/apidocs/sites"; import ApidocsPage from "./ApidocsPage.astro"; import { resolvePage } from "./resolve"; -import { linkHeader, notFound, prefersMarkdown } from "./http"; -import { renderText } from "./text"; +import { linkHeader, prefersMarkdown } from "./http"; +import { notFoundText, renderText } from "./text"; import VersionIsland from "./VersionIsland.astro"; import VersionNotice from "./VersionNotice.astro"; import VersionSelect from "./VersionSelect.astro"; @@ -29,15 +29,23 @@ if (resolved.kind === "markdown" || resolved.kind === "file") { return new Response(text.body, { headers: { "content-type": text.contentType } }); } const accept = Astro.request.headers.get("accept"); -if (resolved.kind === "missing") return notFound(site.base, site.model.module.name, accept); -const page = resolved.page; +// A missing page is the site's not-found page, as the static output's 404.html and 404.md are: Markdown for a client +// that asks for it, else the page shell with the way back. +if (resolved.kind === "missing" && prefersMarkdown(accept)) { + return new Response(notFoundText(site.model, site.base, theme), { status: 404, headers: { "content-type": "text/markdown; charset=utf-8", vary: "Accept", "cache-control": "public, max-age=60" } }); +} +if (resolved.kind === "missing") { + Astro.response.status = 404; + Astro.response.headers.set("cache-control", "public, max-age=60"); +} +const page = resolved.kind === "missing" ? "404" : resolved.page; // One URL, two forms: a request that prefers Markdown gets the page's twin. -if (prefersMarkdown(accept)) { +if (resolved.kind === "page" && prefersMarkdown(accept)) { const text = renderText(site.model, `${page}.md`, theme)!; return new Response(text.body, { headers: { "content-type": text.contentType, vary: "Accept", link: linkHeader(site.base, page) } }); } Astro.response.headers.set("vary", "Accept"); -Astro.response.headers.set("link", linkHeader(site.base, page)); +if (resolved.kind === "page") Astro.response.headers.set("link", linkHeader(site.base, page)); const here = site.version ? versions.find(v => v.id === site.version) : undefined; const latest = latestRelease(versions); --- diff --git a/packages/apidocs/src/astro/apidocs-astro.css b/packages/apidocs/src/astro/apidocs-astro.css index 9ab41b8..126ba79 100644 --- a/packages/apidocs/src/astro/apidocs-astro.css +++ b/packages/apidocs/src/astro/apidocs-astro.css @@ -38,7 +38,7 @@ details.version-menu > .version-current:active, .version-list a:active { backgro position: absolute; inset-inline-start: -1px; inset-block-start: calc(100% + 6px); z-index: 12; min-inline-size: 12rem; margin: 0; padding: 4px; list-style: none; background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); - border-radius: calc(var(--apidocs-radius) + 2px); box-shadow: 0 12px 32px -12px rgb(0 0 0 / 0.28); + border-radius: calc(var(--apidocs-radius) + 2px); box-shadow: 0 12px 32px -12px oklch(0% 0 none / 0.28); line-height: 1.5; } .version-list a { diff --git a/packages/apidocs/src/astro/client.ts b/packages/apidocs/src/astro/client.ts index 6cd9c82..bb40534 100644 --- a/packages/apidocs/src/astro/client.ts +++ b/packages/apidocs/src/astro/client.ts @@ -7,11 +7,12 @@ * - carries the theme choice and the boot script's marks (data-js, data-emoji) to the new page's <html>, whose * attributes the router replaces; * - updates the top bar and the navigator, which the router keeps (transition:persist) so the navigator keeps - * its scroll position and filter text: the index links' current page, and the navigator's rows for the new - * page, leaving the filter field in place; + * its scroll position and filter text: the suite switcher's links, and the navigator's blocks for the new page + * (the sites, the indexes with the current one marked, the guides, packages and types), leaving the filter field + * in place; * - runs the load bar from astro:before-preparation and finishes it on arrival. */ -import { pageBehaviors, saveNavigatorScroll, siteRoot } from "../client/behaviors"; +import { filterRows, NAV_FILTERED_ROWS, pageBehaviors, saveNavigatorScroll, siteRoot } from "../client/behaviors"; import { pathUnder } from "./versions"; /** The <html> attributes the page's own scripts set, which the router's swap would drop. */ @@ -47,9 +48,10 @@ function refreshPersisted(newDocument: Document) { const next = newDocument.querySelector<HTMLElement>(`[${PERSIST}="${CSS.escape(kept.getAttribute(PERSIST)!)}"]`); if (!next) continue; if (kept.matches(".topbar")) { - const nav = kept.querySelector(".topbar-nav"); - const fresh = next.querySelector(".topbar-nav"); - if (nav && fresh) nav.replaceWith(document.importNode(fresh, true)); + // The suite switcher marks the site, which a persisted top bar keeps; its links are refreshed all the same. + const suites = kept.querySelector(".suites"); + const fresh = next.querySelector(".suites"); + if (suites && fresh) suites.replaceWith(document.importNode(fresh, true)); } else if (kept.matches(".sidebar")) { refreshNavigator(kept, next); } @@ -59,15 +61,31 @@ function refreshPersisted(newDocument: Document) { function refreshNavigator(kept: HTMLElement, next: HTMLElement) { const focused = kept.contains(document.activeElement) ? (document.activeElement as HTMLAnchorElement).getAttribute?.("href") : null; const top = kept.scrollTop; - for (const child of [...kept.children]) if (!child.matches(".nav-filter")) child.remove(); - for (const child of [...next.children]) if (!child.matches(".nav-filter")) kept.append(document.importNode(child, true)); + // Every block but the filter field is the new page's, in the new page's order around the kept field. + const filter = kept.querySelector<HTMLElement>(":scope > .nav-filter"); + for (const child of [...kept.children]) if (child !== filter) child.remove(); + let afterFilter = false; + for (const child of [...next.children]) { + if (child.matches(".nav-filter")) { + afterFilter = true; + if (!filter) kept.append(document.importNode(child, true)); + continue; + } + const node = document.importNode(child, true); + if (filter && !afterFilter) kept.insertBefore(node, filter); + else kept.append(node); + } + // The kept filter text applies to the new rows now, before the scroll position is put back, so the rows above it + // take the same space as before. + const query = filter?.querySelector("input")?.value; + if (query?.trim()) filterRows(kept, NAV_FILTERED_ROWS, query); kept.scrollTop = top; // Keyboard users who chose a row stay on it. if (focused) kept.querySelector<HTMLElement>(`a[href="${CSS.escape(focused)}"]`)?.focus({ preventScroll: true }); // The current page's row comes into view if it is out of it, as on a first load. const current = kept.querySelector<HTMLElement>('[aria-current="page"]'); if (current && (current.offsetTop < kept.scrollTop || current.offsetTop > kept.scrollTop + kept.clientHeight - 40)) { - kept.scrollTop = Math.max(0, current.offsetTop - kept.clientHeight / 3); + kept.scrollTop = window.apidocsNavTop?.(kept, current) ?? Math.max(0, current.offsetTop - kept.clientHeight / 3); } kept.dataset.scrollTop = String(kept.scrollTop); } @@ -106,6 +124,8 @@ document.addEventListener("astro:before-swap", event => { }); document.addEventListener("astro:after-swap", () => { + // A top bar from another site arrives without its script having run: size its suite switcher before it paints. + window.apidocsFitSuites?.(); // Where the router cannot move an element without detaching it (no Element.moveBefore), the navigator loses // its scroll position in the move: put it back before the new page paints. const nav = document.querySelector<HTMLElement>(`.sidebar[${PERSIST}]`); diff --git a/packages/apidocs/src/astro/fonts.ts b/packages/apidocs/src/astro/fonts.ts index 434713a..09d5113 100644 --- a/packages/apidocs/src/astro/fonts.ts +++ b/packages/apidocs/src/astro/fonts.ts @@ -1,11 +1,18 @@ /** - * The Elide preset's font files, bundled by Vite: each URL names the file's content hash, so a host can cache it + * The Elide preset's font files and the presets' social images, bundled by Vite: each URL names the file's content hash, so a host can cache it * for a year. A theme font that is not here is served from the site's assets/ (see assetFile). */ import jetbrainsItalic from "@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-wght-italic.woff2?url"; import jetbrainsNormal from "@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-wght-normal.woff2?url"; +import elideSocial from "../../artwork/social-elide.png?url"; +import neutralSocial from "../../artwork/social-neutral.png?url"; export const bundledFonts: Record<string, string> = { "fonts/jetbrains-mono-latin-wght-normal.woff2": jetbrainsNormal, "fonts/jetbrains-mono-latin-wght-italic.woff2": jetbrainsItalic, }; + +export const bundledAssets: Record<string, string> = { + "social/elide.png": elideSocial, + "social/neutral.png": neutralSocial, +}; diff --git a/packages/apidocs/src/astro/helpers.ts b/packages/apidocs/src/astro/helpers.ts index 6752027..859c5b7 100644 --- a/packages/apidocs/src/astro/helpers.ts +++ b/packages/apidocs/src/astro/helpers.ts @@ -5,6 +5,6 @@ export { renderPage, type PageParts, type RenderOptions } from "./render"; export { type Resolved, resolvePage, sitePaths, textFiles } from "./resolve"; export { linkHeader, notFound, prefersMarkdown } from "./http"; -export { prepareTheme, renderText, searchEntries, type TextFile } from "./text"; +export { notFoundText, prepareTheme, renderText, searchEntries, type TextFile } from "./text"; export { assertBase, fileUrl, isBaseRelative, mapUrl, pageUrl, rewriteHtml } from "./urls"; export { latestRelease, pathUnder, type Version, versionLabel } from "./versions"; diff --git a/packages/apidocs/src/astro/http.ts b/packages/apidocs/src/astro/http.ts index 48bbe13..5cd7c28 100644 --- a/packages/apidocs/src/astro/http.ts +++ b/packages/apidocs/src/astro/http.ts @@ -38,7 +38,8 @@ function escapeHtml(s: string): string { export function notFound(base: string, title: string, accept: string | null | undefined): Response { const headers = { vary: "Accept", "cache-control": "public, max-age=60" }; if (prefersMarkdown(accept)) { - const body = `# Not found\n\nThere is no such page in ${title}. Start at the [overview](${base}index.md), or read [llms.txt](${base}llms.txt), which lists every page.\n`; + // The wording of the static renderer's 404.md (notFoundMarkdown), which a route with the model sends instead. + const body = `# Not found\n\nThere is no such page in ${title}. Start at the [overview](${base}index.md), or read [llms.txt](${base}llms.txt), which lists every page as Markdown.\n`; return new Response(body, { status: 404, headers: { ...headers, "content-type": "text/markdown; charset=utf-8" } }); } const name = escapeHtml(title); diff --git a/packages/apidocs/src/astro/index.ts b/packages/apidocs/src/astro/index.ts index 6fe3a47..11fef4f 100644 --- a/packages/apidocs/src/astro/index.ts +++ b/packages/apidocs/src/astro/index.ts @@ -9,6 +9,6 @@ export { type ApidocsOptions, type ApidocsSite, apidocs } from "./integration"; export { renderPage, type PageParts, type RenderOptions } from "./render"; export { type Resolved, resolvePage, sitePaths, textFiles } from "./resolve"; export { linkHeader, notFound, prefersMarkdown } from "./http"; -export { prepareTheme, renderText, searchEntries, type TextFile } from "./text"; +export { notFoundText, prepareTheme, renderText, searchEntries, type TextFile } from "./text"; export { assertBase, fileUrl, isBaseRelative, mapUrl, pageUrl, rewriteHtml } from "./urls"; export { latestRelease, pathUnder, type Version, versionLabel } from "./versions"; diff --git a/packages/apidocs/src/astro/pages.tsx b/packages/apidocs/src/astro/pages.tsx index c3ab9b4..5444c91 100644 --- a/packages/apidocs/src/astro/pages.tsx +++ b/packages/apidocs/src/astro/pages.tsx @@ -5,10 +5,10 @@ */ import type { VNode } from "preact"; import { DeprecatedPage, IndexAllPage, PackagesIndexPage, TypesIndexPage } from "../indexes"; -import { deprecatedIndexMarkdown, guideMarkdown, indexAllMarkdown, indexMarkdown, packageMarkdown, packagesIndexMarkdown, typeMarkdown, typesIndexMarkdown } from "../markdown"; +import { deprecatedIndexMarkdown, frontmatter, guideMarkdown, guideTwin, indexAllMarkdown, indexMarkdown, indexTwin, moduleTwin, NOT_FOUND, notFoundMarkdown, packageMarkdown, packagesIndexMarkdown, packageTwin, type TwinMeta, typeMarkdown, typesIndexMarkdown, typeTwin } from "../markdown"; import type { Model } from "../model"; import { GuidePage } from "../narrative"; -import { IndexPage, PackagePage, TypePage } from "../pages"; +import { IndexPage, NotFoundPage, PackagePage, TypePage } from "../pages"; import { SCHEMA } from "../render"; import { buildSite, DEPRECATED_PAGE, INDEX, INDEX_ALL_PAGE, indexPages, PACKAGES_PAGE, packagePage, type Site, TYPES_PAGE, typePage } from "../site"; import type { SymbolMode } from "../symbols"; @@ -18,12 +18,15 @@ export interface SitePage { page: string; language: string; html: () => VNode; - markdown: (symbols: SymbolMode) => string; + /** The Markdown twin, its frontmatter naming `canonical` as the page's URL when given. */ + markdown: (symbols: SymbolMode, canonical?: string) => string; } interface Built { site: Site; pages: Map<string, SitePage>; + /** The page for a missing URL ("404"): rendered like a page, but never resolved from a path. */ + notFound: SitePage; } const built = new WeakMap<Model, Built>(); @@ -34,33 +37,40 @@ export function siteOf(model: Model): Built { if (!entry) { if (model.schema !== SCHEMA) throw new Error(`Expected an ${SCHEMA} model, got ${JSON.stringify(model.schema)}`); const site = buildSite(model); - entry = { site, pages: new Map(sitePages(site).map(p => [p.page, p])) }; + entry = { site, pages: new Map(sitePages(site).map(p => [p.page, p])), notFound: notFoundPage(site) }; built.set(model, entry); } return entry; } +/** The not-found page, with links from the site's base (`root`, given when its Markdown is rendered). */ +function notFoundPage(site: Site): SitePage { + return { page: NOT_FOUND, language: site.language, html: () => <NotFoundPage />, markdown: (_, root) => frontmatter(site, { title: "Not found", kind: "notfound" }) + notFoundMarkdown(site, root ?? "", indexPages(site)) }; +} + /** Every page, in render()'s order: the overview, the guides, each package and its types, the index pages. */ function sitePages(site: Site): SitePage[] { const pages: SitePage[] = []; - pages.push({ page: INDEX, language: site.language, html: () => <IndexPage />, markdown: s => indexMarkdown(site, s) }); + const twin = (meta: TwinMeta, body: (s: SymbolMode) => string) => (s: SymbolMode, canonical?: string) => frontmatter(site, meta, canonical) + body(s); + pages.push({ page: INDEX, language: site.language, html: () => <IndexPage />, markdown: twin(moduleTwin(site), s => indexMarkdown(site, s)) }); for (const entry of site.guides) { // The overview guide is the index page. if (entry.page === INDEX) continue; - pages.push({ page: entry.page, language: site.language, html: () => <GuidePage entry={entry} />, markdown: s => guideMarkdown(site, entry, s) }); + pages.push({ page: entry.page, language: site.language, html: () => <GuidePage entry={entry} />, markdown: twin(guideTwin(entry), s => guideMarkdown(site, entry, s)) }); } for (const pkg of site.packages) { - pages.push({ page: packagePage(pkg), language: site.language, html: () => <PackagePage pkg={pkg} />, markdown: s => packageMarkdown(site, pkg, s) }); + pages.push({ page: packagePage(pkg), language: site.language, html: () => <PackagePage pkg={pkg} />, markdown: twin(packageTwin(pkg), s => packageMarkdown(site, pkg, s)) }); for (const type of pkg.types ?? []) { - pages.push({ page: typePage(pkg, type), language: type.language, html: () => <TypePage type={type} />, markdown: s => typeMarkdown(site, type, s) }); + pages.push({ page: typePage(pkg, type), language: type.language, html: () => <TypePage type={type} />, markdown: twin(typeTwin(type), s => typeMarkdown(site, type, s)) }); } } for (const { page } of indexPages(site)) { const lang = site.language; - if (page === PACKAGES_PAGE) pages.push({ page, language: lang, html: () => <PackagesIndexPage />, markdown: s => packagesIndexMarkdown(site, s) }); - if (page === TYPES_PAGE) pages.push({ page, language: lang, html: () => <TypesIndexPage />, markdown: s => typesIndexMarkdown(site, s) }); - if (page === INDEX_ALL_PAGE) pages.push({ page, language: lang, html: () => <IndexAllPage />, markdown: s => indexAllMarkdown(site, s) }); - if (page === DEPRECATED_PAGE) pages.push({ page, language: lang, html: () => <DeprecatedPage />, markdown: s => deprecatedIndexMarkdown(site, s) }); + // The same titles and summaries as render()'s llms.txt entries for these pages. + if (page === PACKAGES_PAGE) pages.push({ page, language: lang, html: () => <PackagesIndexPage />, markdown: twin(indexTwin("Packages", "Packages: every package with its summary and type counts."), s => packagesIndexMarkdown(site, s)) }); + if (page === TYPES_PAGE) pages.push({ page, language: lang, html: () => <TypesIndexPage />, markdown: twin(indexTwin("All types", "All types: every type, nested ones too, by name."), s => typesIndexMarkdown(site, s)) }); + if (page === INDEX_ALL_PAGE) pages.push({ page, language: lang, html: () => <IndexAllPage />, markdown: twin(indexTwin("Index", "Index: every declaration from A to Z."), s => indexAllMarkdown(site, s)) }); + if (page === DEPRECATED_PAGE) pages.push({ page, language: lang, html: () => <DeprecatedPage />, markdown: twin(indexTwin("Deprecated", "Deprecated: everything deprecated, for removal first."), s => deprecatedIndexMarkdown(site, s)) }); } return pages; } diff --git a/packages/apidocs/src/astro/render.tsx b/packages/apidocs/src/astro/render.tsx index 4abee76..3270fa4 100644 --- a/packages/apidocs/src/astro/render.tsx +++ b/packages/apidocs/src/astro/render.tsx @@ -19,6 +19,11 @@ export interface RenderOptions { baseUrl?: string; /** Where a theme font file is served, from its asset path ("fonts/inter.woff2"). Defaults to the site's assets/. */ fontUrl?: (asset: string) => string; + /** + * Where the theme's social image (an asset path, "social/elide.png") is served, as a path or URL; it is made + * absolute against baseUrl for og:image. Defaults to the site's assets/. + */ + assetUrl?: (asset: string) => string; } export interface PageParts { @@ -47,13 +52,18 @@ function between(html: string, open: string, close: string): string { /** Renders one page of a model (a page path from resolvePage) into the pieces of an Astro document. */ export function renderPage(model: Model, page: string, themeInput: Theme | string | undefined, options: RenderOptions): PageParts { - const { site, pages } = siteOf(model); - const entry = pages.get(page); + const { site, pages, notFound } = siteOf(model); + // "404" is the not-found page: an app renders it for a missing path (with a 404 status), never resolves a path to it. + const entry = page === notFound.page ? notFound : pages.get(page); if (!entry) throw new Error(`apidocs: no page ${JSON.stringify(page)} in ${model.module.name}`); const base = options.base.endsWith("/") ? options.base : `${options.base}/`; assertBase(base); const input = typeof themeInput === "string" ? (JSON.parse(themeInput) as Theme) : (themeInput ?? {}); - const theme = prepareTheme({ ...input, baseUrl: input.baseUrl ?? options.baseUrl }); + const prepared = prepareTheme({ ...input, baseUrl: input.baseUrl ?? options.baseUrl }); + // The social image's asset is wherever the app serves it (Vite bundles the Elide preset's), as an absolute URL. + const image = prepared.socialImage; + const imageAt = image?.asset && !image.url && options.assetUrl ? options.assetUrl(image.asset) : undefined; + const theme = imageAt && image ? { ...prepared, socialImage: { ...image, url: prepared.baseUrl ? new URL(imageAt, prepared.baseUrl).href : imageAt } } : prepared; const ctx: PageContext = { site, theme, page, language: entry.language }; const render = (node: preact.VNode) => rewriteHtml( diff --git a/packages/apidocs/src/astro/text.ts b/packages/apidocs/src/astro/text.ts index 075edd3..fd56b72 100644 --- a/packages/apidocs/src/astro/text.ts +++ b/packages/apidocs/src/astro/text.ts @@ -5,12 +5,21 @@ * Astro form. */ import type { Model } from "../model"; -import { render, safeTheme, searchIndex } from "../render"; +import { render, safeTheme, searchIndex, sitemap } from "../render"; import { resolveTheme, type Theme, themeCss } from "../theme"; import type { Entry } from "../client/search"; import { siteOf } from "./pages"; import { fileUrl, pageUrl } from "./urls"; +/** + * The not-found page as Markdown, with links under the site's base path: what a server sends a client that asks for + * Markdown at a missing URL. The same text as the static renderer's 404.md. + */ +export function notFoundText(model: Model, base: string, themeInput?: Theme | string): string { + return siteOf(model).notFound.markdown(prepareTheme(themeInput).symbols ?? "utf", base); +} + + /** A theme with its preset applied and its URLs checked, as render() uses it. Accepts the theme as JSON text. */ export function prepareTheme(input: Theme | string | undefined): Theme { return safeTheme(resolveTheme(typeof input === "string" ? JSON.parse(input) : input)); @@ -75,7 +84,11 @@ export function renderText(model: Model, path: string, themeInput?: Theme | stri const { site, pages } = siteOf(model); const theme = prepareTheme(themeInput); const body = ((): string | undefined => { - if (path.endsWith(".md")) return pages.get(path.slice(0, -".md".length))?.markdown(theme.symbols ?? "utf"); + if (path.endsWith(".md")) { + const page = path.slice(0, -".md".length); + // The frontmatter's canonical URL is the page's, in the Astro form. + return pages.get(page)?.markdown(theme.symbols ?? "utf", theme.baseUrl ? theme.baseUrl + pageUrl(page) : undefined); + } switch (path) { case "llms.txt": case "llms-full.txt": @@ -96,16 +109,10 @@ export function renderText(model: Model, path: string, themeInput?: Theme | stri case "assets/favicon.svg": return theme.favicon; case "sitemap.xml": - return theme.baseUrl ? sitemap(theme.baseUrl, [...pages.keys()]) : undefined; + return theme.baseUrl ? sitemap(theme.baseUrl, [...pages.keys()].map(pageUrl), theme.lastModified) : undefined; default: return undefined; } })(); return body === undefined ? undefined : { body, contentType: contentType(path) }; } - -function sitemap(base: string, pages: string[]): string { - const escape = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); - const urls = pages.map(p => ` <url><loc>${escape(base + pageUrl(p))}</loc></url>`).join("\n"); - return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`; -} diff --git a/packages/apidocs/src/astro/urls.ts b/packages/apidocs/src/astro/urls.ts index b91fb86..5116f31 100644 --- a/packages/apidocs/src/astro/urls.ts +++ b/packages/apidocs/src/astro/urls.ts @@ -125,7 +125,7 @@ function mapPath(pathWithRest: string): string { } const ATTR = /(\s(?:href|src|data-copy-markdown)=")([^"]*)(")/g; -const META_CONTENT = /(<meta property="og:url" content=")([^"]*)(")/g; +const META_CONTENT = /(<meta property="og:(?:url|image)" content=")([^"]*)(")/g; const JSON_LD = /(<script type="application\/ld\+json">)([\s\S]*?)(<\/script>)/g; /** The JSON-LD keys whose values are URLs. */ const URL_KEYS = new Set(["url", "item", "contentUrl"]); diff --git a/packages/apidocs/src/cli.ts b/packages/apidocs/src/cli.ts index d022787..07dc724 100644 --- a/packages/apidocs/src/cli.ts +++ b/packages/apidocs/src/cli.ts @@ -3,17 +3,17 @@ * The apidocs command line. One command so far: * * apidocs guides --src <suite dir> --id <suite id> --title <site title> --out <output dir> - * [--theme <theme.json>] [--version <string>] [--base-url <url with trailing slash>] + * [--theme <theme.json>] [--version <string>] [--base-url <url with trailing slash>] [--last-modified <date>] * [--source-link <template with {path} and {line}>] [--source-root <repo-relative suite path>] * [--link <prefix>=<target> ...] [--include-drafts] [--warn-only] [--assets <dir>] * * It imports a Markdown suite (src/import/markdown.ts), renders it as a guides-only site and writes the site into - * --out: HTML pages and their Markdown twins, llms.txt, llms-full.txt, api.json (the guides-only model), the search + * --out: HTML pages and their Markdown twins, 404.html and 404.md, llms.txt, llms-full.txt, api.json (the guides-only model), the search * index, the assets and the suite's images. Diagnostics go to stderr as file:line: message, with paths as given to * --src. It exits 1 when there is an error (unless --warn-only), 2 on bad arguments, and prints one JSON line of * counts on success. It writes into --out without deleting what is already there. * - * The stylesheet and fonts come from the sources; the client script from dist/assets/apidocs.js, which is built + * The stylesheet, fonts and social images come from the sources; the client script from dist/assets/apidocs.js, which is built * first when it is missing or older than src/client. --assets takes every asset from a directory instead. */ import { spawnSync } from "node:child_process"; @@ -26,7 +26,7 @@ import { suiteSite } from "./import/suite"; import type { Theme } from "./theme"; const USAGE = `usage: apidocs guides --src <suite dir> --id <suite id> --title <site title> --out <output dir> - [--theme <theme.json>] [--version <string>] [--base-url <url/>] [--source-link <template>] + [--theme <theme.json>] [--version <string>] [--base-url <url/>] [--last-modified <date>] [--source-link <template>] [--source-root <path>] [--link <prefix>=<target> ...] [--include-drafts] [--warn-only] [--assets <dir>]`; const pkg = fileURLToPath(new URL("..", import.meta.url)); @@ -40,7 +40,7 @@ interface Args { flags: Set<string>; } -const VALUED = new Set(["src", "id", "title", "out", "theme", "version", "base-url", "source-link", "source-root", "assets"]); +const VALUED = new Set(["src", "id", "title", "out", "theme", "version", "base-url", "last-modified", "source-link", "source-root", "assets"]); const FLAGS = new Set(["include-drafts", "warn-only"]); function parseArgs(argv: string[]): Args { @@ -95,6 +95,8 @@ function assetSource(name: string, assets: string | undefined): string { const file = name.slice("fonts/".length); return require.resolve(`@fontsource-variable/${file.replace(/-latin-.*$/, "")}/files/${file}`); } + // The presets' link-preview images (scripts/gen-social.ts). + if (/^social\/[a-z]+\.png$/.test(name)) return join(pkg, `artwork/social-${name.slice("social/".length)}`); throw new Error(`no source for the asset ${name}`); } @@ -107,6 +109,7 @@ function guides(argv: string[]): number { if (!existsSync(src) || !statSync(src).isDirectory()) throw new UsageError(`--src ${args.values.get("src")} is not a directory`); const themePath = args.values.get("theme"); const theme: Theme = themePath ? JSON.parse(readFileSync(resolve(cwd, themePath), "utf8")) : {}; + if (args.values.get("last-modified")) theme.lastModified = args.values.get("last-modified")!; const assetsDir = args.values.get("assets") ? resolve(cwd, args.values.get("assets")!) : undefined; const warnOnly = args.flags.has("warn-only"); const opt = (key: string) => args.values.get(key); @@ -159,7 +162,8 @@ function guides(argv: string[]): number { bytes += file.data.byteLength; count++; } - const pages = Object.keys(site.output).filter(p => p.endsWith(".html")).length; + // The site's pages: the not-found page is not one of them. + const pages = Object.keys(site.output).filter(p => p.endsWith(".html") && p !== "404.html").length; process.stdout.write(JSON.stringify({ files: count, bytes, pages, guides: site.model.module.guides?.length ?? 0, drafts: site.result.drafts.length, errors: 0, warnings }) + "\n"); return 0; } diff --git a/packages/apidocs/src/client/behaviors.tsx b/packages/apidocs/src/client/behaviors.tsx index 36d051e..452acd2 100644 --- a/packages/apidocs/src/client/behaviors.tsx +++ b/packages/apidocs/src/client/behaviors.tsx @@ -261,19 +261,17 @@ export function navigatorScroll(signal?: AbortSignal) { const nav = document.querySelector<HTMLElement>(".sidebar"); if (!nav) return; const key = navScrollKey(); - let restored = false; try { const saved = window.sessionStorage.getItem(key); - if (saved) { - nav.scrollTop = Number(saved); - restored = true; - } + if (saved) nav.scrollTop = Number(saved); } catch { /* storage blocked */ } const currentLink = nav.querySelector<HTMLElement>('[aria-current="page"]'); - if (currentLink && (!restored || currentLink.offsetTop < nav.scrollTop || currentLink.offsetTop > nav.scrollTop + nav.clientHeight)) { - nav.scrollTop = Math.max(0, currentLink.offsetTop - nav.clientHeight / 3); + // Only when the current row is out of view, as the head script does: a navigator moved for no reason leaves its top + // rows half under the filter field. + if (currentLink && (currentLink.offsetTop < nav.scrollTop || currentLink.offsetTop > nav.scrollTop + nav.clientHeight - 40)) { + nav.scrollTop = window.apidocsNavTop?.(nav, currentLink) ?? Math.max(0, currentLink.offsetTop - nav.clientHeight / 3); } saveNavigatorScroll(signal); } @@ -293,22 +291,33 @@ export function saveNavigatorScroll(signal?: AbortSignal) { // ---- List filters: narrow the navigator, or the page rail and the member summary, to rows that match. +/** Marks the rows under `scope` that do not contain the query (case-insensitive), and opens folds while filtering. */ +export function filterRows(scope: Element, rowSelector: string, rawQuery: string) { + const query = rawQuery.trim().toLowerCase(); + for (const fold of scope.querySelectorAll<HTMLDetailsElement>("details")) if (query) fold.open = true; + for (const row of scope.querySelectorAll<HTMLElement>(rowSelector)) { + const hit = !query || (row.textContent ?? "").toLowerCase().includes(query); + row.toggleAttribute("data-filtered-out", !hit); + } +} + +/** The navigator rows its filter narrows: types and guides. The sites, the indexes and the packages always stay. */ +export const NAV_FILTERED_ROWS = ".nav-section[data-nav-filterable] .nav-list > li"; + export function listFilter(boxSelector: string, rowSelector: string, also: string | undefined, signal?: AbortSignal) { const box = document.querySelector<HTMLElement>(boxSelector); const input = box?.querySelector<HTMLInputElement>("input"); if (!box || !input) return; box.hidden = false; const apply = () => { - const query = input.value.trim().toLowerCase(); - const scope = box.parentElement!; - for (const fold of scope.querySelectorAll<HTMLDetailsElement>("details")) if (query) fold.open = true; - for (const row of scope.querySelectorAll<HTMLElement>(rowSelector)) { - const hit = !query || (row.textContent ?? "").toLowerCase().includes(query); - row.toggleAttribute("data-filtered-out", !hit); - } + filterRows(box.parentElement!, rowSelector, input.value); if (also) { + const query = input.value.trim().toLowerCase(); for (const row of document.querySelectorAll<HTMLElement>(also)) { - const hit = !query || (row.querySelector("summary, th")?.textContent ?? "").toLowerCase().includes(query); + const head = row.querySelector("summary, th"); + // A member row's summary sentence is drawn from an attribute (MemberDetail), so it is read from there too. + const text = `${head?.textContent ?? ""} ${head?.querySelector("[data-brief]")?.getAttribute("data-brief") ?? ""}`; + const hit = !query || text.toLowerCase().includes(query); row.toggleAttribute("data-filtered-out", !hit); } } @@ -343,7 +352,8 @@ export function copyMarkdown(signal?: AbortSignal) { request.onload = async () => { if (request.status < 200 || request.status >= 300) return fail(); try { - await navigator.clipboard.writeText(request.responseText); + // The page's text, as a reader pastes it: without the frontmatter that describes it to programs. + await navigator.clipboard.writeText(request.responseText.replace(/^---\n[\s\S]*?\n---\n\n?/, "")); } catch { return fail(); } @@ -360,8 +370,8 @@ export function copyMarkdown(signal?: AbortSignal) { // ---- Menus built on <details>: close on Escape and on a click elsewhere. -/** The menus this closes: the page's formats menu, and a site's version menu. */ -const MENUS = "details.formats-menu[open], details.version-menu[open]"; +/** The menus this closes: the page's formats menu, the suite menu, and a site's version menu. */ +const MENUS = "details.formats-menu[open], details.suite-menu[open], details.version-menu[open]"; export function menus(signal?: AbortSignal) { const open = () => document.querySelectorAll<HTMLDetailsElement>(MENUS); @@ -377,6 +387,35 @@ export function menus(signal?: AbortSignal) { }, { signal }); } +// ---- The suite switcher: the layout alone shows its row or its menu (SuiteSwitcher in chrome.tsx). The top bar's +// script (SUITES_BOOT) also sizes it to what it shows, and hides the other from assistive technology and the +// keyboard; this runs that again whenever the tools' width changes, and closes the menu when the row takes its place. + +declare global { + interface Window { + apidocsFitSuites?: () => void; + /** Where the navigator scrolls to show a row (NAV_BOOT in chrome.tsx). */ + apidocsNavTop?: (nav: HTMLElement, row: HTMLElement) => number; + } +} + +export function suiteSwitcher(signal?: AbortSignal) { + const box = document.querySelector<HTMLElement>(".suites"); + const tools = box?.parentElement; + if (!box || !tools || !window.apidocsFitSuites || !("ResizeObserver" in window)) return; + const fit = () => { + window.apidocsFitSuites?.(); + const menu = box.querySelector<HTMLDetailsElement>("details.suite-menu"); + if (menu?.open && box.dataset.fit !== "menu") menu.open = false; + }; + // At once, for a top bar the client router has just put in place, and then whenever the tools' width changes. + fit(); + const observer = new ResizeObserver(fit); + observer.observe(tools); + document.fonts?.addEventListener("loadingdone", fit, { signal }); + signal?.addEventListener("abort", () => observer.disconnect(), { once: true }); +} + // ---- Leaving for another page of this site: start the load bar; the next page finishes it. export function leaving(signal?: AbortSignal) { @@ -463,7 +502,8 @@ export function pageBehaviors(signal?: AbortSignal) { copyMarkdown(signal); members(signal); menus(signal); - // Types only: packages stay, so the way to another package is never filtered away. - listFilter("[data-nav-filter]", ".nav-section:not(:first-of-type) .nav-list > li", undefined, signal); + suiteSwitcher(signal); + // Types and guides only: the sites, the indexes and the packages stay, so the way to another one is never filtered away. + listFilter("[data-nav-filter]", NAV_FILTERED_ROWS, undefined, signal); listFilter("[data-toc-filter]", ".toc-entries > li", ".members > details.member", signal); } diff --git a/packages/apidocs/src/color.ts b/packages/apidocs/src/color.ts new file mode 100644 index 0000000..d67506e --- /dev/null +++ b/packages/apidocs/src/color.ts @@ -0,0 +1,77 @@ +/** + * sRGB hex colors as CSS oklch(), precisely enough that a browser draws the same 8-bit color: lightness to 0.001%, + * chroma to 0.00001 and hue to 0.001 degree keep every channel within half a step (0.5/255) of the original, so it + * rounds back to it (test/color.test.ts checks every color the stylesheet and the presets use, and a random sample). + * A gray, with no chroma at that precision, is written with a hue of none. Björn Ottosson's OKLab matrices, as CSS + * Color 4 uses them. + */ + +/** [r, g, b] in 0..1 from #rgb, #rrggbb or #rrggbbaa (alpha is returned separately). */ +export function parseHex(hex: string): { rgb: [number, number, number]; alpha: number } { + let h = hex.trim().replace(/^#/, ""); + if (h.length === 3 || h.length === 4) h = [...h].map(c => c + c).join(""); + if (!/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(h)) throw new Error(`Not a hex color: ${hex}`); + const n = (i: number) => parseInt(h.slice(i, i + 2), 16) / 255; + return { rgb: [n(0), n(2), n(4)], alpha: h.length === 8 ? n(6) : 1 }; +} + +const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); +const fromLinear = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055); + +/** OKLCH [L 0..1, C, H degrees] of an sRGB color. */ +export function srgbToOklch([r, g, b]: [number, number, number]): [number, number, number] { + const [lr, lg, lb] = [toLinear(r), toLinear(g), toLinear(b)]; + const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb); + const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb); + const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb); + const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s; + const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s; + const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s; + const C = Math.hypot(A, B); + const H = ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360; + return [L, C, H]; +} + +/** sRGB (0..1, unclamped) of an OKLCH color. */ +export function oklchToSrgb([L, C, H]: [number, number, number]): [number, number, number] { + const a = C * Math.cos((H * Math.PI) / 180); + const b = C * Math.sin((H * Math.PI) / 180); + const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3; + const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3; + const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3; + return [ + fromLinear(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), + fromLinear(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s), + fromLinear(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s), + ]; +} + +const trim = (n: number, digits: number) => String(Number(n.toFixed(digits))); + +/** The oklch() for a hex color, with an optional alpha (0..1) written as "/ a". */ +export function oklch(hex: string, alpha?: number): string { + const parsed = parseHex(hex); + const [L, C, H] = srgbToOklch(parsed.rgb); + const c = Number(C.toFixed(5)); + const a = alpha ?? parsed.alpha; + return `oklch(${trim(L * 100, 3)}% ${c === 0 ? "0" : trim(c, 5)} ${c === 0 ? "none" : trim(H, 3)}${a < 1 ? ` / ${trim(a, 3)}` : ""})`; +} + +/** The sRGB channels (0..1) an oklch() string written by oklch() stands for, to check a conversion. */ +export function parseOklch(css: string): { rgb: [number, number, number]; alpha: number } { + const m = /^oklch\(\s*([\d.]+)%\s+([\d.]+)\s+([\d.]+|none)(?:\s*\/\s*([\d.]+))?\s*\)$/.exec(css.trim()); + if (!m) throw new Error(`Not an oklch() color: ${css}`); + const rgb = oklchToSrgb([Number(m[1]) / 100, Number(m[2]), m[3] === "none" ? 0 : Number(m[3])]); + return { rgb, alpha: m[4] === undefined ? 1 : Number(m[4]) }; +} + +/** WCAG 2 relative luminance of an sRGB color (0..1 channels). */ +export function luminance([r, g, b]: [number, number, number]): number { + return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b); +} + +/** WCAG 2 contrast ratio of two sRGB colors. */ +export function contrast(a: [number, number, number], b: [number, number, number]): number { + const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number]; + return (x + 0.05) / (y + 0.05); +} diff --git a/packages/apidocs/src/components/chrome.tsx b/packages/apidocs/src/components/chrome.tsx index 2008363..13c56d3 100644 --- a/packages/apidocs/src/components/chrome.tsx +++ b/packages/apidocs/src/components/chrome.tsx @@ -11,7 +11,7 @@ import { createContext, type ComponentChildren } from "preact"; import { useContext } from "preact/hooks"; import { type PageContext, usePage } from "../context"; import type { Package, Type } from "../model"; -import { INDEX, guideNav, indexPages, isAbsolute, isThrowable, packagePage, relative, rootOf, typePage } from "../site"; +import { INDEX, guideNav, indexPages, isAbsolute, isThrowable, overviewGuide, packagePage, relative, rootOf, type Site, typePage } from "../site"; import { typeGroups } from "../structure"; import type { Theme } from "../theme"; import { SYMBOLS, sym } from "../symbols"; @@ -77,9 +77,21 @@ function logoWidth(svg: string, height: number): number | undefined { return w > 0 && h > 0 ? Math.round((height * w) / h) : undefined; } -/** Restores the navigator's scroll position as soon as it is parsed, so it never jumps after paint. */ +/** + * Where the navigator scrolls to show the current row: about a third of the way down, at a position where no row + * lies partly under the sticky filter field, which covers the navigator's top once it is scrolled (a row half under + * the field is a link with part of it covered). It picks the scroll position nearest the third whose field sits over + * a gap between rows (a heading, the space between sections), with the current row still in view; at the top + * nothing is under the field. Defined once, as a global the page's scripts call (apidocsNavTop), and used at once to + * restore the navigator's position before it is painted. + */ const NAV_BOOT = - '(function(){var n=document.getElementById("apidocs-nav");if(!n)return;try{var k="apidocs-nav:"+new URL(document.documentElement.getAttribute("data-root")||"./",location.href).pathname;var s=sessionStorage.getItem(k);if(s)n.scrollTop=+s}catch(e){}var c=n.querySelector(\'[aria-current="page"]\');if(c&&(c.offsetTop<n.scrollTop||c.offsetTop>n.scrollTop+n.clientHeight-40))n.scrollTop=Math.max(0,c.offsetTop-n.clientHeight/3)})()'; + 'window.apidocsNavTop=function(n,c){var m=n.scrollHeight-n.clientHeight,w=Math.max(0,Math.min(c.offsetTop-n.clientHeight/3,m)),i=n.querySelector(".nav-filter input"),' + + 'a=i?i.offsetTop:0,z=i?a+i.offsetHeight:0,best=0,end=0;' + + 'Array.prototype.forEach.call(n.querySelectorAll(".nav-row"),function(r){if(!r.offsetHeight)return;var t=r.offsetTop,s=t-z;' + + 'if(t-end>=z-a&&s>=0&&s<=m&&end<=s+a&&c.offsetTop>=s+z&&c.offsetTop+c.offsetHeight<=s+n.clientHeight&&Math.abs(s-w)<Math.abs(best-w))best=s;end=Math.max(end,t+r.offsetHeight)});' + + 'return best};' + + '(function(){var n=document.getElementById("apidocs-nav");if(!n)return;try{var k="apidocs-nav:"+new URL(document.documentElement.getAttribute("data-root")||"./",location.href).pathname;var s=sessionStorage.getItem(k);if(s)n.scrollTop=+s}catch(e){}var c=n.querySelector(\'[aria-current="page"]\');if(c&&(c.offsetTop<n.scrollTop||c.offsetTop>n.scrollTop+n.clientHeight-40))n.scrollTop=apidocsNavTop(n,c)})()'; /** * Preloads the upright font files, so they are ready at first paint. Done from the head script, not with link @@ -100,6 +112,22 @@ const SPECULATION = JSON.stringify({ prerender: [{ where: { selector_matches: "a[href$='.html']:not([href*='://']), a[href*='.html#']:not([href*='://'])" }, eagerness: "moderate" }], }); +/** + * Sizes the suite switcher before first paint, and again whenever the script calls it (on resize). The layout + * alone already shows the row or the menu (see SuiteSwitcher); this gives the switcher exactly the width of what it + * shows, so a menu leaves no empty space for the search field, and takes the switcher out of a drawer layout's bar + * when its row does not fit. The room it measures is what the tools would leave it with the search field at its + * narrowest, so the decision never depends on the switcher's own width. + */ +export const SUITES_BOOT = + 'window.apidocsFitSuites=function(){var b=document.querySelector(".suites");if(!b)return;var t=b.parentElement,g=parseFloat(getComputedStyle(t).columnGap)||0,' + + 'a=t.clientWidth-(parseFloat(getComputedStyle(b).marginInlineStart)||0),r=0,l=b.querySelectorAll(".suites-ghost"),f=b.querySelector(".suites-floor"),' + + // The search field's floor beside a switcher (a length in rem or px), not its floor once the switcher has left. + 'm=getComputedStyle(t).getPropertyValue("--apidocs-search-floor").trim(),q=parseFloat(m)*(/rem$/.test(m)?parseFloat(getComputedStyle(document.documentElement).fontSize):1)||0;' + + 'Array.prototype.forEach.call(t.querySelectorAll(".search,.theme-switch,.search-fallback"),function(e){var c=getComputedStyle(e);if(c.display==="none")return;a-=g+(e.classList.contains("search")?q:e.getBoundingClientRect().width)});' + + 'Array.prototype.forEach.call(l,function(e){r+=e.getBoundingClientRect().width});r+=(parseFloat(getComputedStyle(l[0].parentElement).columnGap)||0)*(l.length-1)+1;' + + 'var s=r<=a?"row":matchMedia("(min-width:861px)").matches?"menu":"none";b.setAttribute("data-fit",s);b.style.setProperty("--apidocs-suites-width",(s==="row"?r:f.getBoundingClientRect().width)+"px")};apidocsFitSuites()'; + /** Applies a stored "navigator hidden" choice on a wide screen, before the navigator is painted. */ const NAV_STATE_BOOT = 'try{if(matchMedia("(min-width:861px)").matches&&localStorage.getItem("apidocs-nav")==="closed")document.getElementById("apidocs-nav-toggle").checked=true}catch(e){}'; @@ -116,7 +144,7 @@ export interface ShellProps { } export interface PageMeta { - kind: "module" | "package" | "type" | "guide"; + kind: "module" | "package" | "type" | "guide" | "index" | "notfound"; /** The declaration's stable id. */ id?: string; package?: string; @@ -161,7 +189,8 @@ export function headData(ctx: PageContext, props: Pick<ShellProps, "title" | "de const root = rootOf(page); const name = page.split("/").pop()!; const product = theme.productName ?? site.model.module.name; - const canonical = theme.baseUrl ? `${theme.baseUrl}${page}.html` : undefined; + // The not-found page is served at every missing URL: it names no canonical one. + const canonical = theme.baseUrl && meta?.kind !== "notfound" ? `${theme.baseUrl}${page}.html` : undefined; const m = site.model.module; const at = (path: string, fromRoot: boolean) => (theme.baseUrl ? `${theme.baseUrl}${fromRoot ? path : `${page.slice(0, page.lastIndexOf("/") + 1)}${path}`}` : `${fromRoot ? root : ""}${path}`); const formats: Formats = { @@ -171,17 +200,31 @@ export function headData(ctx: PageContext, props: Pick<ShellProps, "title" | "de model: at("api.json", true), }; const keywords = [...new Set([...(meta?.keywords ?? []), m.name, ...(m.languages ?? []).map(languageName), ...(site.packages.length ? ["API reference"] : [])])].filter(Boolean); + // Another page's URL in the graph: absolute under the base URL, else relative to this page, as the breadcrumbs are. + const pageUrl = (target: string) => (theme.baseUrl ? `${theme.baseUrl}${target}.html` : relative(page, target, ".html")); + const image = socialImageUrl(theme, root); const graph = { "@context": "https://schema.org", "@graph": [ { ...jsonLd, "@context": undefined, + url: pageUrl(page), headline: title, inLanguage: "en", keywords: keywords.join(", "), encoding: [{ "@type": "MediaObject", encodingFormat: "text/markdown", contentUrl: formats.markdown, name: "This page as Markdown" }], ...(m.version ? { version: m.version } : {}), + ...(image ? { image: { "@type": "ImageObject", url: image, width: theme.socialImage!.width, height: theme.socialImage!.height, caption: theme.socialImage!.alt } } : {}), + // The overview lists what the site holds: the guides, then the packages. + ...(page === INDEX && (site.guides.length > 0 || site.packages.length > 0) + ? { + hasPart: [ + ...site.guides.filter(g => g.page !== INDEX).map(g => ({ "@type": "TechArticle", name: g.guide.title, url: pageUrl(g.page) })), + ...site.packages.map(pkg => ({ "@type": "APIReference", name: pkg.name || "(default package)", url: pageUrl(packagePage(pkg)) })), + ], + } + : {}), }, ...(crumbs.length > 1 ? [{ @@ -223,7 +266,16 @@ export function headData(ctx: PageContext, props: Pick<ShellProps, "title" | "de { property: "og:description", content: description }, { property: "og:site_name", content: product }, ...(canonical ? [{ property: "og:url", content: canonical }] : []), - { name: "twitter:card", content: "summary" }, + ...(image + ? [ + { property: "og:image", content: image }, + { property: "og:image:width", content: String(theme.socialImage!.width) }, + { property: "og:image:height", content: String(theme.socialImage!.height) }, + { property: "og:image:alt", content: theme.socialImage!.alt }, + ] + : []), + { name: "twitter:card", content: image ? "summary_large_image" : "summary" }, + ...(meta?.kind === "notfound" ? [{ name: "robots", content: "noindex" }] : []), ]; // The same content for programs and AI agents: this page as Markdown, the index, the whole reference, the model. const links: HeadData["links"] = [ @@ -236,6 +288,18 @@ export function headData(ctx: PageContext, props: Pick<ShellProps, "title" | "de return { title, description, keywords, product, canonical, meta: tags, links, formats, jsonLd: graph }; } +/** + * Where the theme's social image is: its URL as given, else its asset under the base URL (absolute, as Open Graph + * wants) or, without one, relative to the page. Undefined without an image. + */ +export function socialImageUrl(theme: Theme, root: string): string | undefined { + const image = theme.socialImage; + if (!image) return undefined; + if (image.url) return image.url; + if (!image.asset) return undefined; + return theme.baseUrl ? `${theme.baseUrl}assets/${image.asset}` : `${root}assets/${image.asset}`; +} + /** The head's metadata elements: charset and viewport, title, meta tags, canonical, alternates and index. */ export function HeadMeta({ head }: { head: HeadData }) { return ( @@ -266,6 +330,8 @@ export function Shell({ title, description, crumbs, toc, jsonLd, meta, children return ( <html lang="en" data-root={root || "./"}> <head> + {/* A host serves the not-found page at any depth: with the site's address known, its links resolve from the root. */} + {meta?.kind === "notfound" && theme.baseUrl && !astro && <base href={theme.baseUrl} />} <HeadMeta head={head} /> {/* Astro bundles the stylesheet and inlines the theme's tokens itself. */} {!astro && <link rel="stylesheet" href={`${root}assets/apidocs.css`} />} @@ -275,7 +341,7 @@ export function Shell({ title, description, crumbs, toc, jsonLd, meta, children <script dangerouslySetInnerHTML={{ __html: astro ? THEME_BOOT : THEME_BOOT + fontPreload(theme.fonts, root) }} /> {!astro && <script defer src={`${root}assets/apidocs.js`} />} {/* Hold first paint until the content element is parsed, so a page transition starts from real content. */} - <link rel="expect" href={`${name}.html#content`} {...({ blocking: "render" } as object)} /> + <link rel="expect" href={meta?.kind === "notfound" ? "#content" : `${name}.html#content`} {...({ blocking: "render" } as object)} /> {/* On a server, start loading and rendering a page of this site when a link to it is hovered or pressed. Astro pages navigate with its client router and prefetch instead. */} {!astro && <script type="speculationrules" dangerouslySetInnerHTML={{ __html: SPECULATION }} />} @@ -284,7 +350,8 @@ export function Shell({ title, description, crumbs, toc, jsonLd, meta, children <body> <div class="loadbar" aria-hidden="true" /> {meta?.kind === "guide" && <div class="readbar" aria-hidden="true" />} - <a class="skip" href={`${name}.html#content`}>Skip to content</a> + {/* The not-found page is served at whatever URL was missing, so its skip link names no file. */} + <a class="skip" href={meta?.kind === "notfound" ? "#content" : `${name}.html#content`}>Skip to content</a> <TopBar /> <div class="layout"> <Navigation /> @@ -338,9 +405,13 @@ export function SearchField({ apiLabel = true }: { apiLabel?: boolean }) { } /** - * The top bar: the navigator toggle, the brand, the module's version, the index pages, search, the theme's - * links and the theme switch. One checkbox toggles the navigator with no script: it hides it on a wide screen - * and shows it on a narrow one. + * The top bar holds what belongs to the whole site: the navigator toggle, the brand, the module's version (or an + * Astro app's version menu), the switcher between sibling documentation sites, search and the theme switch. The + * module's indexes (overview, packages, types, A to Z, deprecated) are in the navigator. One checkbox toggles the + * navigator with no script: it hides it on a wide screen and shows it on a narrow one. + * + * Nothing in the bar wraps, overflows or is cut off at any width from 320px; the stylesheet's top-bar section says + * in what order its parts give way. */ export function TopBar() { const { site, theme, page } = usePage(); @@ -362,29 +433,109 @@ export function TopBar() { <img class="logo logo-dark" src={`${root}assets/logo-${theme.logo.dark ? "dark" : "light"}.svg`} alt={theme.logo.alt ?? ""} height={22} width={logoWidth(theme.logo.dark ?? theme.logo.light, 22)} /> </> )} - <span class="product">{product}</span> + <span class="product" title={product}>{product}</span> </a> {astro ? <HoleMark name="topbar" /> : <ModuleVersion />} - <nav class="topbar-nav" aria-label="Indexes"> - <a href={relative(page, INDEX, ".html")} aria-current={page === INDEX ? "page" : undefined}>Overview</a> - {indexPages(site).map(entry => ( - <a key={entry.page} href={relative(page, entry.page, ".html")} aria-current={page === entry.page ? "page" : undefined}>{entry.label}</a> - ))} - </nav> <div class="topbar-tools"> + <SuiteSwitcher /> {site.packages.length > 0 && <a class="search-fallback" href={`${relative(page, INDEX, ".html")}#all-types`}>All types</a>} {astro ? <HoleMark name="search" /> : <SearchField apiLabel={site.packages.length > 0} />} - {(theme.links?.header ?? []).map(link => <a key={link.url} class="topbar-link" href={hrefFor(page, link.url)}>{link.label}</a>)} <button type="button" class="theme-switch" data-theme-switch data-js-only aria-label="Color theme: system"> {/* The drawn icon everywhere; a sun or a moon where the platform's emoji are good (data-emoji). */} <span aria-hidden="true" class="theme-icon" /> <span aria-hidden="true" class="theme-emoji" /> </button> </div> + {suites(theme, page).length > 0 && <script dangerouslySetInnerHTML={{ __html: SUITES_BOOT }} />} </header> ); } +/** + * One sibling documentation site, as the switcher and the navigator list it. The current site is marked with + * aria-current="true", not "page": its link goes to the site's overview, which is rarely the page being read. + */ +export interface Suite { + label: string; + /** The link from the page being rendered. */ + href: string; + /** Whether this is the site being rendered. */ + current: boolean; +} + +/** + * The sibling documentation sites from the theme's header links, linked from a page, with the current one + * marked: the entry with `current: true`, else the one whose URL is this site's own root (see ThemeLink). The + * current entry links to this site's overview. Empty when there is nothing to switch to: no links, or only this site. + */ +export function suites(theme: Theme, page: string): Suite[] { + const links = theme.links?.header ?? []; + const marked = links.some(link => link.current); + const isOwnRoot = (url: string) => { + if (["", "./", ".", "index.html", "./index.html"].includes(url.trim())) return true; + if (!theme.baseUrl) return false; + try { + const at = new URL(url, theme.baseUrl).href; + return at === theme.baseUrl || at === `${theme.baseUrl}index.html`; + } catch { + return false; + } + }; + let found = false; + const list = links.map(link => { + const current = !found && (marked ? !!link.current : isOwnRoot(link.url)); + found ||= current; + return { label: link.label, href: current ? relative(page, INDEX, ".html") : hrefFor(page, link.url), current }; + }); + return list.some(entry => !entry.current) ? list : []; +} + +/** The label of the suite menu's button: the current site, or a word for the set when no entry is current. */ +function currentSuiteLabel(list: Suite[]): string { + return list.find(entry => entry.current)?.label ?? "Documentation"; +} + +const CHEVRON = <svg class="icon" viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path d="M4 6.25 8 10.25l4-4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" /></svg>; + +/** + * The switcher between sibling documentation sites: a row of the sites with the current one marked when the bar + * has room for it, else one menu button that names the current site and opens the list. The browser's layout + * decides, with no script and no width written down anywhere: the hidden copies of the labels (.suites-fit) are a + * wrapping row whose height says whether the labels fit on one line, and that height places the visible row or + * the menu (see "Suite switcher" in apidocs.css). The script only hides the one out of view from assistive + * technology and the keyboard. Where the navigator is a drawer, the drawer lists the sites first, and the bar shows + * the row only when it fits. + */ +export function SuiteSwitcher() { + const { theme, page } = usePage(); + const list = suites(theme, page); + if (!list.length) return null; + const label = currentSuiteLabel(list); + return ( + <div class="suites"> + <div class="suites-fit"> + {/* Empty and zero-wide, so that even a first label wider than the switcher moves to a second line. */} + <span class="suites-probe" aria-hidden="true" /> + {list.map((entry, i) => <span key={i} class="suites-ghost" data-current={entry.current ? "" : undefined} aria-hidden="true">{entry.label}</span>)} + <nav class="suites-row" aria-label="Documentation"> + {list.map((entry, i) => <a key={i} href={entry.href} aria-current={entry.current ? "true" : undefined}>{entry.label}</a>)} + </nav> + <details class="suite-menu"> + <summary class="suite-current" aria-label={`${label}: other documentation`} title="Other documentation"> + <span class="suite-label">{label}</span> + {CHEVRON} + </summary> + <ul class="suite-list"> + {list.map((entry, i) => <li key={i}><a href={entry.href} aria-current={entry.current ? "true" : undefined}>{entry.label}</a></li>)} + </ul> + </details> + </div> + {/* The menu button's width, so the bar keeps room for it. */} + <span class="suites-floor" aria-hidden="true"><span>{label}</span>{CHEVRON}</span> + </div> + ); +} + /** The row above the page's title: where the page is, and its other forms. */ export function PageTools({ crumbs, canonical, title }: { crumbs: Crumb[]; canonical: string | undefined; title: string }) { const { page } = usePage(); @@ -412,7 +563,7 @@ export function Footer() { <a href={`${root}api.json`}>api.json</a> </p> {(theme.links?.footer ?? []).length > 0 && ( - <p class="footer-links">{theme.links!.footer!.map(link => <a key={link.url} href={link.url}>{link.label}</a>)}</p> + <p class="footer-links">{theme.links!.footer!.map(link => <a key={link.url} href={hrefFor(page, link.url)}>{link.label}</a>)}</p> )} </footer> ); @@ -559,7 +710,7 @@ export function kindGlyph(type: Type): { letter: string; tone: string } { * hundreds of nested types does not repeat them on every page. */ export function Navigation() { - const { site, page } = usePage(); + const { site, theme, page } = usePage(); const current = currentType(site.types, page); const currentPkg = current ? site.types.get(current.id)!.pkg : site.packages.find(pkg => packagePage(pkg) === page); const prefix = sharedPrefix(site.packages.map(pkg => pkg.name)); @@ -567,16 +718,45 @@ export function Navigation() { for (let t: Type | undefined = current; t; t = t.enclosing ? site.types.get(t.enclosing)?.type : undefined) chain.add(t.id); const tops = (currentPkg?.types ?? []).filter(t => !t.enclosing); const guides = guideNav(site, page); + const sites = suites(theme, page); + const indexes = navIndexes(site, page); return ( <nav class="sidebar" id="apidocs-nav" aria-label={site.packages.length ? "Packages and types" : "Guides"} {...persistAttr(useVariant(), "apidocs-nav")}> - {site.packages.length > 0 && ( + {/* Shown only where the navigator is a drawer: there the top bar may have no room for the switcher. */} + {sites.length > 0 && ( + <section class="nav-section nav-suites"> + <h2 class="nav-heading"><span>Documentation</span></h2> + <ul class="nav-list"> + {sites.map((entry, i) => ( + <li key={i}><a class="nav-row" href={entry.href} aria-current={entry.current ? "true" : undefined}><span class="nav-label">{entry.label}</span></a></li> + ))} + </ul> + </section> + )} + {(site.packages.length > 0 || site.guides.length > 0) && ( <div class="nav-filter" data-nav-filter data-js-only> - <label class="visually-hidden" for="apidocs-nav-filter">Filter this list</label> + <label class="visually-hidden" for="apidocs-nav-filter">{site.packages.length ? "Filter types and guides" : "Filter guides"}</label> <input id="apidocs-nav-filter" type="search" placeholder="Filter" autocomplete="off" spellcheck={false} /> </div> )} + {indexes.length > 0 && (indexes.length <= NAV_INDEX_ROW_MAX + ? ( + <ul class="nav-index" aria-label="Indexes"> + {indexes.map(entry => <li key={entry.page}><a href={entry.href} aria-current={entry.current ? "page" : undefined}>{entry.label}</a></li>)} + </ul> + ) + : ( + <section class="nav-section nav-reference"> + <h2 class="nav-heading"><span>Reference</span></h2> + <ul class="nav-list"> + {indexes.map(entry => ( + <li key={entry.page}><a class="nav-row" href={entry.href} aria-current={entry.current ? "page" : undefined}><span class="nav-label">{entry.label}</span></a></li> + ))} + </ul> + </section> + ))} {guides.groups.length > 0 && ( - <section class="nav-section nav-guides"> + <section class="nav-section nav-guides" data-nav-filterable> <h2 class="nav-heading"><span>Guides</span></h2> {guides.groups.map((group, i) => ( <div key={i} class="nav-group"> @@ -620,7 +800,7 @@ export function Navigation() { </ul> </section>} {currentPkg && typeGroups(tops).map(group => ( - <section key={group.id} class="nav-section"> + <section key={group.id} class="nav-section" data-nav-filterable> <h2 class="nav-heading"><span>{group.title}</span></h2> <NavTypes types={group.types} pkg={currentPkg} chain={chain} /> </section> @@ -629,6 +809,31 @@ export function Navigation() { ); } +/** + * The most index links that share one line at the navigator's narrowest width: 223px of line at 16.5rem, less the + * padding. Measured in Chromium at both presets' type scales (13px and 13.33px): all five links (Overview, Packages, + * All types, Index, Deprecated) need 357-364px, any four 264-309px, any three 223-238px, which leaves no room on the + * narrowest line; two fit with room to spare. More than two are rows under "Reference", never a wrapped line. + */ +export const NAV_INDEX_ROW_MAX = 2; + +/** One of the module's index pages, as the navigator lists it. */ +export interface NavIndex { + page: string; + label: string; + href: string; + current: boolean; +} + +/** + * The module's index pages, from a page: the overview (unless the navigator already lists it as the overview + * guide), then the index pages this site has. A guides-only site has few or none. + */ +export function navIndexes(site: Site, page: string): NavIndex[] { + const entries = [...(overviewGuide(site) ? [] : [{ page: INDEX, label: "Overview" }]), ...indexPages(site)]; + return entries.map(entry => ({ ...entry, href: relative(page, entry.page, ".html"), current: entry.page === page })); +} + function NavTypes({ types, pkg, chain }: { types: Type[]; pkg: Package; chain: Set<string> }) { const { site, page } = usePage(); const mixed = (site.model.module.languages ?? []).length > 1; @@ -714,7 +919,10 @@ export function Toc({ items, filterLabel }: { items: TocItem[]; filterLabel: str ); } -/** A link to an absolute URL or a page, for theme links. */ +/** + * A theme link from a page: an absolute URL or a path from the server's root ("/docs/") as given, and a relative + * URL resolved from the site's root, so it works from a page at any depth. + */ export function hrefFor(page: string, url: string): string { - return isAbsolute(url) ? url : relative(page, url, ""); + return isAbsolute(url) || url.startsWith("/") ? url : relative(page, url, ""); } diff --git a/packages/apidocs/src/components/declaration.tsx b/packages/apidocs/src/components/declaration.tsx index fed5b5c..09d6dc5 100644 --- a/packages/apidocs/src/components/declaration.tsx +++ b/packages/apidocs/src/components/declaration.tsx @@ -174,8 +174,11 @@ export function MemberDetail({ member, summary }: { member: Member; summary?: Co <summary class="member-row"> <svg class="member-chevron" viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path d="M6 3.75 10.25 8 6 12.25" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" /></svg> <span class="member-sig">{summary ?? <code class="summary-sig">{member.name}</code>}</span> - <span class="member-brief"> - {brief || (!member.implicit && <span class="undocumented">No description.</span>)} + {/* The summary sentence is the first sentence of the entry inside, which carries it as text: the row draws it + from the attribute, so a page with hundreds of members does not hold each sentence twice. It is still in + the row's accessible name, and find-in-page finds it in the entry, opening the row. */} + <span class="member-brief" data-brief={brief || undefined}> + {!brief && !member.implicit && <span class="undocumented">No description.</span>} </span> <span class="member-marks"> {noted && <span class="member-noted" title="Has an API note"><svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><circle cx="8" cy="8" r="6.25" /><path d="M8 4.6v3.9" /><path d="M8 11.1v.01" /></svg><span class="visually-hidden">Has an API note</span></span>} diff --git a/packages/apidocs/src/indexes.tsx b/packages/apidocs/src/indexes.tsx index 3038c69..baf4a0e 100644 --- a/packages/apidocs/src/indexes.tsx +++ b/packages/apidocs/src/indexes.tsx @@ -22,8 +22,8 @@ function IndexShell({ page, title, description, toc, children }: { page: string; description={description} crumbs={crumbs} toc={toc} - meta={{ kind: "module", keywords }} - jsonLd={{ "@context": "https://schema.org", "@type": "CollectionPage", name: `${title} of ${m.name}`, description, url: `${page}.html` }} + meta={{ kind: "index", keywords }} + jsonLd={{ "@context": "https://schema.org", "@type": "CollectionPage", name: `${title} of ${m.name}`, description }} > <header class="page-head"> <h1>{title}</h1> diff --git a/packages/apidocs/src/markdown.ts b/packages/apidocs/src/markdown.ts index 8754c3f..e8f8a90 100644 --- a/packages/apidocs/src/markdown.ts +++ b/packages/apidocs/src/markdown.ts @@ -383,3 +383,78 @@ export function deprecatedIndexMarkdown(site: Site, symbols: SymbolMode = "utf") } return join(parts); } + +// ---- Frontmatter and the not-found page. + +/** What a Markdown twin's frontmatter says about its page. */ +export interface TwinMeta { + title: string; + description?: string; + /** module, package, a type's kind word (class, interface, ...), guide, index or notfound. */ + kind: string; + /** The declaration's or guide's stable id. */ + id?: string; +} + +/** + * A twin's YAML frontmatter: title, description, kind, id, module, version and, when the site's address is known, + * the HTML page's canonical URL. Every value is a double-quoted YAML string (JSON's escaping is YAML's). + */ +export function frontmatter(site: Site, meta: TwinMeta, canonical?: string): string { + const m = site.model.module; + const fields: [string, string | undefined][] = [ + ["title", meta.title], ["description", meta.description || undefined], ["kind", meta.kind], ["id", meta.id], + ["module", m.name], ["version", m.version], ["canonical", canonical], + ]; + // Angle brackets and ampersands as \u escapes (YAML reads them as JSON does), so a reader that shows frontmatter as + // text, and one that renders it as Markdown, gets no markup from a title. + const value = (v: string) => JSON.stringify(v).replace(/[<>&]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`); + return `---\n${fields.filter(([, v]) => v !== undefined && v !== "").map(([k, v]) => `${k}: ${value(v!)}`).join("\n")}\n---\n\n`; +} + +/** A twin without its frontmatter: what llms-full.txt joins, and what "copy as Markdown" copies. */ +export function stripFrontmatter(md: string): string { + return md.replace(/^---\n[\s\S]*?\n---\n\n?/, ""); +} + +const flat = (text: string) => text.replace(/\s+/g, " ").trim(); + +/** The overview's frontmatter. */ +export function moduleTwin(site: Site): TwinMeta { + const m = site.model.module; + const overview = overviewGuide(site); + return { title: overview?.guide.title ?? m.name, description: summaryText(m.doc) || flat(inlineText(overview?.guide.summary)) || undefined, kind: "module", id: overview?.guide.id }; +} + +export function packageTwin(pkg: Package): TwinMeta { + return { title: pkg.name || "(default package)", description: summaryText(pkg.doc), kind: "package", id: pkg.id }; +} + +export function typeTwin(type: Type): TwinMeta { + return { title: type.name, description: summaryText(type.doc), kind: typeKindWord(type), id: type.id }; +} + +export function guideTwin(entry: GuideEntry): TwinMeta { + return { title: entry.guide.title, description: flat(inlineText(entry.guide.summary)), kind: "guide", id: entry.guide.id }; +} + +export function indexTwin(title: string, description: string): TwinMeta { + return { title, description, kind: "index" }; +} + +/** The page path of the not-found page (404.html, 404.md). It is not linked from anywhere and not in llms.txt or the sitemap. */ +export const NOT_FOUND = "404"; + +/** + * The not-found page as Markdown. `root` is where the site's files are: the site's absolute URL when known (a host + * serves 404.md for a missing path at any depth), a base path, or "" for links relative to the site's root. + */ +export function notFoundMarkdown(site: Site, root: string, indexes: { page: string; label: string }[]): string { + const name = esc(site.model.module.name); + const lines = [ + "# Not found", + `There is no such page in ${name}. Start at the [overview](${root}index.md), or read [llms.txt](${root}llms.txt), which lists every page as Markdown.`, + ]; + if (indexes.length) lines.push(indexes.map(entry => `- [${esc(entry.label)}](${root}${entry.page}.md)`).join("\n")); + return join(lines); +} diff --git a/packages/apidocs/src/narrative.tsx b/packages/apidocs/src/narrative.tsx index 73970ca..3353581 100644 --- a/packages/apidocs/src/narrative.tsx +++ b/packages/apidocs/src/narrative.tsx @@ -52,9 +52,9 @@ export function GuidePage({ entry, children, extraToc = [] }: { entry: GuideEntr const jsonLd = { "@context": "https://schema.org", "@type": "TechArticle", + name: g.title, headline: g.title, description, - ...(theme.baseUrl ? { url: `${theme.baseUrl}${page}.html` } : {}), isPartOf: { "@type": "SoftwareSourceCode", name: m.name, ...(m.version ? { version: m.version } : {}) }, }; const nav = guideNav(site, page); diff --git a/packages/apidocs/src/pages.tsx b/packages/apidocs/src/pages.tsx index efb9aef..89181ec 100644 --- a/packages/apidocs/src/pages.tsx +++ b/packages/apidocs/src/pages.tsx @@ -1,7 +1,7 @@ /** The three page kinds: the module overview, a package, and a type. */ import { usePage } from "./context"; import type { Member, Package, Token, Type } from "./model"; -import { INDEX, overviewGuide, packagePage, refLabel, relative, resolve, typePage } from "./site"; +import { INDEX, indexPages, overviewGuide, packagePage, refLabel, relative, resolve, rootOf, typePage } from "./site"; import { compactTokens, memberGroups, memberTitle, summaryText, typeGroups, typeKindWord } from "./structure"; import { Badge, Blocks, Inlines, Signature, TokenList } from "./components/doc"; import type { Crumb, TocItem } from "./components/chrome"; @@ -25,11 +25,34 @@ function jsonLd(name: string, description: string, kind: string) { description, programmingLanguage: (m.languages ?? []).map(l => l[0]!.toUpperCase() + l.slice(1)), about: kind, - ...(theme.baseUrl ? { url: `${theme.baseUrl}${page}.html` } : {}), isPartOf: { "@type": "SoftwareSourceCode", name: m.name, ...(m.version ? { version: m.version } : {}) }, }; } +// ---- The page a host serves for a missing URL (404.html). + +export function NotFoundPage() { + const { site, page } = usePage(); + const m = site.model.module; + const description = `There is no such page in ${m.name}.`; + const links = [{ page: INDEX, label: "Overview" }, ...indexPages(site)]; + return ( + <Shell title={`Not found (${moduleTitle()})`} description={description} crumbs={[]} toc={[]} jsonLd={{ "@context": "https://schema.org", "@type": "WebPage", name: "Not found", description }} + meta={{ kind: "notfound" }}> + <header class="page-head"> + <h1>Not found</h1> + </header> + <div class="prose"> + <p>There is no such page in {m.name}. It may have moved, or the link may be wrong. Search above, or start from one of these:</p> + <ul> + {links.map(link => <li key={link.page}><a href={relative(page, link.page, ".html")}>{link.label}</a></li>)} + <li><a href={`${rootOf(page)}llms.txt`}>llms.txt</a>, every page as Markdown</li> + </ul> + </div> + </Shell> + ); +} + // ---- The module overview. export function IndexPage() { diff --git a/packages/apidocs/src/presets/elide.ts b/packages/apidocs/src/presets/elide.ts index bab3be3..4dea28d 100644 --- a/packages/apidocs/src/presets/elide.ts +++ b/packages/apidocs/src/presets/elide.ts @@ -3,10 +3,22 @@ * and @elide/brand artwork. Branding lives here and in theme files only; the * components never name Elide. */ -import { code, neutral, purple, status, syntax, syntaxLight } from "@elide/tokens"; +import { code as codeHex, neutral as neutralHex, purple as purpleHex, status as statusHex, syntax as syntaxHex, syntaxLight as syntaxLightHex } from "@elide/tokens"; +import { oklch } from "../color"; import type { Theme } from "../theme"; import { logoDark, logoLight, mark } from "./elide-artwork"; +// @elide/tokens has its colors as hex; the pages write them as oklch(), converted exactly (src/color.ts), so each +// is the same 8-bit color. +const inOklch = <T extends Record<string | number, string>>(scale: T): { [K in keyof T]: string } => + Object.fromEntries(Object.entries(scale).map(([k, v]) => [k, oklch(v)])) as { [K in keyof T]: string }; +const neutral = inOklch(neutralHex); +const purple = inOklch(purpleHex); +const status = inOklch(statusHex); +const syntax = inOklch(syntaxHex); +const syntaxLight = inOklch(syntaxLightHex); +const code = inOklch(codeHex); + const LATIN = "U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD"; const MONO = @@ -16,6 +28,8 @@ export const elide: Theme = { name: "elide", logo: { light: logoLight, dark: logoDark, alt: "Elide" }, favicon: mark, + // The dark lockup on the dark surface, 1200 by 630 (scripts/gen-social.ts). + socialImage: { asset: "social/elide.png", width: 1200, height: 630, alt: "The Elide logo on a dark background" }, // JetBrains Mono for code and for every type and member name; the reader's system fonts for prose and // headings. The files hold Latin only, and the unicode-range says so, so a symbol or an emoji goes straight to // the system font chosen for it. @@ -25,7 +39,12 @@ export const elide: Theme = { ], // A local monospace font scaled to JetBrains Mono's width, for the moment before the web font is ready, so // text takes the same space either way. - css: '@font-face{font-family:"Apidocs Mono Fallback";src:local("Consolas");size-adjust:109.1%}', + // The title and the declaration specimen keep exact sizes, set in JetBrains Mono: 30px and 15px, 25px and 13.3333px + // where the navigator is a drawer. A fluid size between them would put the characters off the pixel grid. + css: + '@font-face{font-family:"Apidocs Mono Fallback";src:local("Consolas");size-adjust:109.1%}\n' + + "/* good-css exception (fluid-clamp): exact type sizes for JetBrains Mono, stepped where the navigator becomes a drawer. */\n" + + "@media (max-width:860px){:root:root{--apidocs-size-title:25px;--apidocs-size-specimen:13.3333px}}", tokens: { light: { "font-mono": MONO, @@ -38,10 +57,12 @@ export const elide: Theme = { "size-xl": "20px", "size-2xl": "25px", "size-3xl": "30px", + "size-title": "30px", + "size-specimen": "15px", // Code inside 15px prose: 13.3333px, the same 8px grid as code blocks. "code-scale": "0.8889em", bg: neutral[50], - surface: "#ffffff", + surface: oklch("#ffffff"), subtle: neutral[100], fg: neutral[950], muted: neutral[600], diff --git a/packages/apidocs/src/render.tsx b/packages/apidocs/src/render.tsx index 9d7a8a4..b06e533 100644 --- a/packages/apidocs/src/render.tsx +++ b/packages/apidocs/src/render.tsx @@ -8,10 +8,10 @@ import { renderToString } from "preact-render-to-string"; import { DeprecatedPage, IndexAllPage, PackagesIndexPage, TypesIndexPage } from "./indexes"; import { Ctx, type PageContext } from "./context"; -import { deprecatedIndexMarkdown, guideMarkdown, indexAllMarkdown, indexMarkdown, packageMarkdown, packagesIndexMarkdown, typeMarkdown, typesIndexMarkdown } from "./markdown"; +import { deprecatedIndexMarkdown, frontmatter, guideMarkdown, guideTwin, indexAllMarkdown, indexMarkdown, indexTwin, moduleTwin, NOT_FOUND, notFoundMarkdown, packageMarkdown, packagesIndexMarkdown, packageTwin, stripFrontmatter, typeMarkdown, typesIndexMarkdown, typeTwin } from "./markdown"; import type { Model } from "./model"; import { GuidePage } from "./narrative"; -import { IndexPage, PackagePage, TypePage } from "./pages"; +import { IndexPage, NotFoundPage, PackagePage, TypePage } from "./pages"; import { buildSite, DEPRECATED_PAGE, INDEX, INDEX_ALL_PAGE, indexPages, isThrowable, overviewGuide, PACKAGES_PAGE, packagePage, type Site, TYPES_PAGE, typePage } from "./site"; import { inlineText, summaryText, typeKindWord } from "./structure"; import { type SymbolKey, type SymbolMode, typeSymbolKey, withSym } from "./symbols"; @@ -38,6 +38,8 @@ export function render(modelInput: Model | string, themeInput?: Theme | string): const out: Output = {}; const pages: ListedPage[] = []; const symbols = theme.symbols ?? "utf"; + // A Markdown twin's canonical URL is its HTML page's, when the site's address is known. + const canonical = (page: string) => (theme.baseUrl ? `${theme.baseUrl}${page}.html` : undefined); const html = (page: string, language: string, node: preact.VNode) => { const ctx: PageContext = { site, theme, page, language }; @@ -45,7 +47,7 @@ export function render(modelInput: Model | string, themeInput?: Theme | string): }; html(INDEX, site.language, <IndexPage />); - out[`${INDEX}.md`] = indexMarkdown(site, symbols); + out[`${INDEX}.md`] = frontmatter(site, moduleTwin(site), canonical(INDEX)) + indexMarkdown(site, symbols); pages.push({ page: INDEX, title: `${model.module.name} overview`, summary: overviewSummary(site), symbol: "module" }); // Guides come right after the overview in llms-full.txt: agents should read them before the reference. The // overview guide is the index page, already written. @@ -53,18 +55,18 @@ export function render(modelInput: Model | string, themeInput?: Theme | string): for (const entry of site.guides) { if (entry.page === INDEX) continue; html(entry.page, site.language, <GuidePage entry={entry} />); - out[`${entry.page}.md`] = guideMarkdown(site, entry, symbols); + out[`${entry.page}.md`] = frontmatter(site, guideTwin(entry), canonical(entry.page)) + guideMarkdown(site, entry, symbols); guides.push({ page: entry.page, title: entry.guide.title, summary: oneLine(inlineText(entry.guide.summary)), symbol: "guide" }); } for (const pkg of site.packages) { const page = packagePage(pkg); html(page, site.language, <PackagePage pkg={pkg} />); - out[`${page}.md`] = packageMarkdown(site, pkg, symbols); + out[`${page}.md`] = frontmatter(site, packageTwin(pkg), canonical(page)) + packageMarkdown(site, pkg, symbols); pages.push({ page, title: `Package ${pkg.name}`, summary: summaryText(pkg.doc), symbol: "package" }); for (const type of pkg.types ?? []) { const tpage = typePage(pkg, type); html(tpage, type.language, <TypePage type={type} />); - out[`${tpage}.md`] = typeMarkdown(site, type, symbols); + out[`${tpage}.md`] = frontmatter(site, typeTwin(type), canonical(tpage)) + typeMarkdown(site, type, symbols); pages.push({ page: tpage, title: `${type.name} (${typeKindWord(type)} in ${pkg.name})`, summary: summaryText(type.doc), symbol: typeSymbolKey(type.kind, isThrowable(type)) }); } } @@ -73,7 +75,7 @@ export function render(modelInput: Model | string, themeInput?: Theme | string): const indexes: ListedPage[] = []; const indexPage = (page: string, title: string, summary: string, node: preact.VNode, markdown: string) => { html(page, site.language, node); - out[`${page}.md`] = markdown; + out[`${page}.md`] = frontmatter(site, indexTwin(title, `${title}: ${summary}.`), canonical(page)) + markdown; indexes.push({ page, title, summary, symbol: "module" }); }; for (const { page } of indexPages(site)) { @@ -83,8 +85,13 @@ export function render(modelInput: Model | string, themeInput?: Theme | string): if (page === DEPRECATED_PAGE) indexPage(page, "Deprecated", "everything deprecated, for removal first", <DeprecatedPage />, deprecatedIndexMarkdown(site, symbols)); } - out["llms.txt"] = llms(site, pages, guides, symbols, indexes); - out["llms-full.txt"] = [pages[0]!, ...guides, ...pages.slice(1)].map(p => `<!-- ${p.page}.md -->\n${out[`${p.page}.md`]}`).join("\n"); + // What a host serves for a missing URL: the page shell with the way back, and its Markdown form. + html(NOT_FOUND, site.language, <NotFoundPage />); + out[`${NOT_FOUND}.md`] = frontmatter(site, { title: "Not found", kind: "notfound" }) + notFoundMarkdown(site, theme.baseUrl ?? "", indexPages(site)); + + out["llms.txt"] = llms(site, pages, guides, symbols, indexes, theme.whenToUse); + // The twins without their frontmatter: in one file, each starts at the comment that names it. + out["llms-full.txt"] = [pages[0]!, ...guides, ...pages.slice(1)].map(p => `<!-- ${p.page}.md -->\n${stripFrontmatter(out[`${p.page}.md`] as string)}`).join("\n"); out["api.json"] = JSON.stringify(model); // Javadoc's element-list: a module line first when the packages belong to a named JPMS module, as -link expects. // A guides-only site has no packages for -link to find, so it has no element-list. @@ -97,7 +104,8 @@ export function render(modelInput: Model | string, themeInput?: Theme | string): if (theme.logo?.light) out["assets/logo-light.svg"] = theme.logo.light; if (theme.logo?.dark) out["assets/logo-dark.svg"] = theme.logo.dark; if (theme.favicon) out["assets/favicon.svg"] = theme.favicon; - if (theme.baseUrl) out["sitemap.xml"] = sitemap(theme.baseUrl, [pages[0]!, ...guides, ...pages.slice(1), ...indexes].map(p => p.page)); + if (theme.socialImage?.asset) out[`assets/${theme.socialImage.asset}`] = { asset: theme.socialImage.asset }; + if (theme.baseUrl) out["sitemap.xml"] = sitemap(theme.baseUrl, [pages[0]!, ...guides, ...pages.slice(1), ...indexes].map(p => `${p.page}.html`), theme.lastModified); return out; } @@ -114,11 +122,29 @@ export function safeTheme(theme: Theme): Theme { }); const base = theme.baseUrl && /^https?:\/\//i.test(safeUrl(theme.baseUrl) ?? "") ? theme.baseUrl : undefined; const source = theme.sourceLink && safeUrl(theme.sourceLink.replace(/\{(path|line|ref)\}/g, "x")) ? theme.sourceLink : undefined; - return { ...theme, links: { header: links(theme.links?.header), footer: links(theme.links?.footer) }, baseUrl: base, sourceLink: source }; + return { + ...theme, + links: { header: links(theme.links?.header), footer: links(theme.links?.footer) }, + baseUrl: base, + sourceLink: source, + socialImage: safeSocialImage(theme.socialImage), + lastModified: theme.lastModified && W3C_DATE.test(theme.lastModified) ? theme.lastModified : undefined, + }; +} + +/** A W3C date or date-time, as sitemap.xml's lastmod takes it: 2026-11-21, or with a time and a zone. */ +const W3C_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/; + +/** The social image when it is usable: an absolute http(s) URL, or an asset path with no way out of assets/. */ +function safeSocialImage(image: Theme["socialImage"]): Theme["socialImage"] | undefined { + if (!image || !(image.width > 0) || !(image.height > 0)) return undefined; + const url = image.url && /^https?:\/\//i.test(safeUrl(image.url) ?? "") ? image.url : undefined; + const asset = image.asset && /^[a-z0-9][a-z0-9._/-]*\.(png|jpe?g|webp)$/i.test(image.asset) && !image.asset.split("/").includes("..") ? image.asset : undefined; + return url || asset ? { ...image, url, asset } : undefined; } /** llms.txt (llmstxt.org): what the module is, the guides, then every reference page, each with its summary. */ -function llms(site: Site, pages: ListedPage[], guides: ListedPage[], symbols: SymbolMode, indexes: ListedPage[] = []): string { +function llms(site: Site, pages: ListedPage[], guides: ListedPage[], symbols: SymbolMode, indexes: ListedPage[] = [], whenToUse?: string): string { const m = site.model.module; const guidesOnly = site.packages.length === 0 && site.guides.length > 0; // Names and summaries are untrusted text: Markdown escapes keep their angle brackets and brackets literal. @@ -130,6 +156,10 @@ function llms(site: Site, pages: ListedPage[], guides: ListedPage[], symbols: Sy "Each page below is Markdown; the HTML page of the same name has the same content. llms-full.txt has every page in one file, and api.json is the apidocs/1 model.", "", ); + // For an agent deciding whether this is the reference it needs: the theme's words, or one sentence from the module's. + const what = guidesOnly ? "documentation" : "API reference"; + const summary = overviewSummary(site); + lines.push("## When to use this", "", whenToUse?.trim() || `Use this ${what} when you write, read or review code that uses ${md(m.name)}${m.version ? ` ${md(m.version)}` : ""}.${summary ? ` ${md(summary)}` : ""}`, ""); lines.push( "## Overview", "", `- [${withSym(symbols, "module", md(m.name))}](index.md): ${guidesOnly ? "the overview" : "packages and types"}`, @@ -192,8 +222,10 @@ export function searchIndex(site: Site): string { return `window.apidocsSearch=${JSON.stringify(items).replace(/</g, "\\u003c")};\n`; } -function sitemap(base: string, pages: string[]): string { - const urls = pages.map(p => ` <url><loc>${escapeXml(base + p + ".html")}</loc></url>`).join("\n"); +/** sitemap.xml: each URL (relative to base), with the theme's lastModified as every entry's lastmod when there is one. */ +export function sitemap(base: string, paths: string[], lastModified?: string): string { + const lastmod = lastModified ? `<lastmod>${escapeXml(lastModified)}</lastmod>` : ""; + const urls = paths.map(p => ` <url><loc>${escapeXml(base + p)}</loc>${lastmod}</url>`).join("\n"); return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`; } diff --git a/packages/apidocs/src/runner.mjs b/packages/apidocs/src/runner.mjs index 4923b55..94de90e 100644 --- a/packages/apidocs/src/runner.mjs +++ b/packages/apidocs/src/runner.mjs @@ -5,9 +5,11 @@ * directory in their jars and start it with an external JavaScript runtime * (Bun or Node); it needs nothing else and never touches the network. * - * runner.mjs --bundle render.js --assets assets/ --model api.json [--theme theme.json] [--source-ref ref] --out site/ + * runner.mjs --bundle render.js --assets assets/ --model api.json [--theme theme.json] [--source-ref ref] + * [--last-modified 2026-11-21] --out site/ * - * --source-ref sets the theme's sourceRef: the {ref} in its source-link template. + * --source-ref sets the theme's sourceRef: the {ref} in its source-link template. --last-modified sets the + * theme's lastModified, sitemap.xml's lastmod: the build's date, which the renderer never reads from a clock. * * Input and output go through files, so output size is not limited by a pipe. * On success it prints one JSON line, {"files":N,"bytes":N,"renderMs":N}, and @@ -48,6 +50,7 @@ try { const model = readFileSync(options.model, "utf8"); const theme = options.theme ? JSON.parse(readFileSync(options.theme, "utf8")) : {}; if (options["source-ref"]) theme.sourceRef = options["source-ref"]; + if (options["last-modified"]) theme.lastModified = options["last-modified"]; const started = performance.now(); const files = api.render(model, theme); const renderMs = Math.round(performance.now() - started); diff --git a/packages/apidocs/src/site.ts b/packages/apidocs/src/site.ts index e53680c..de72c6f 100644 --- a/packages/apidocs/src/site.ts +++ b/packages/apidocs/src/site.ts @@ -294,9 +294,15 @@ export function refLabel(site: Site, ref: Ref): string { return tail.slice(tail.lastIndexOf(".", tail.indexOf("(") < 0 ? tail.length : tail.indexOf("(")) + 1).replace(/\$/g, "."); } -/** Whether a type is an exception: its superclass chain reaches java.lang.Throwable. */ +/** + * The ids Throwable has in the models: the doclet's binary name, and the Dokka DRIs of Kotlin's Throwable and of the + * Java class as a Kotlin model reaches it. + */ +const THROWABLE = new Set(["java.lang.Throwable", "kotlin/Throwable///PointingToDeclaration/", "java.lang/Throwable///PointingToDeclaration/"]); + +/** Whether a type is an exception: its superclass chain reaches Throwable, by id (a name that merely contains "Throwable" does not count). */ export function isThrowable(type: Type): boolean { - return (type.ancestors ?? []).some(a => a.id === "java.lang.Throwable") || type.id === "java.lang.Throwable"; + return THROWABLE.has(type.id) || (type.ancestors ?? []).some(a => THROWABLE.has(a.id)); } /** Tokens as plain text. */ diff --git a/packages/apidocs/src/styles/apidocs.css b/packages/apidocs/src/styles/apidocs.css index 4263232..8f9444c 100644 --- a/packages/apidocs/src/styles/apidocs.css +++ b/packages/apidocs/src/styles/apidocs.css @@ -28,114 +28,129 @@ --apidocs-code-scale: 0.9em; --apidocs-tracking-display: -0.015em; --apidocs-tracking-caps: 0.04em; - --apidocs-bg: #fbfcfd; - --apidocs-surface: #ffffff; - --apidocs-subtle: #f2f4f7; - --apidocs-fg: #161a21; - --apidocs-muted: #4f5766; - --apidocs-faint: #5f6775; - --apidocs-rule: #e1e4ea; - --apidocs-rule-strong: #c7ccd6; - --apidocs-accent: #0f6e7a; - --apidocs-accent-soft: rgb(15 110 122 / 0.08); - --apidocs-link: #0c5f6b; - --apidocs-focus: #0f6e7a; - --apidocs-note-api: #0f6e7a; - --apidocs-note-api-soft: rgb(15 110 122 / 0.08); - --apidocs-note-spec: #2d55a8; - --apidocs-note-spec-soft: rgb(45 85 168 / 0.07); - --apidocs-note-impl: #5f6775; - --apidocs-note-impl-soft: rgb(22 26 33 / 0.03); - --apidocs-deprecated: #a8321f; - --apidocs-deprecated-soft: rgb(168 50 31 / 0.07); - --apidocs-nullable: #8a5300; - --apidocs-non-null: #2b6b3a; - --apidocs-code-bg: #f3f5f8; - --apidocs-code-fg: #1d2430; - --apidocs-syn-comment: #5f6775; - --apidocs-syn-keyword: #7a3196; - --apidocs-syn-string: #1c6d45; - --apidocs-syn-number: #9a4a00; - --apidocs-syn-type: #0c5f6b; - --apidocs-syn-function: #2b4db3; - --apidocs-syn-annotation: #8a5300; - --apidocs-syn-param: #8c1f4f; + --apidocs-bg: oklch(99.059% 0.0017 247.839); + --apidocs-surface: oklch(100% 0 none); + --apidocs-subtle: oklch(96.648% 0.00454 258.325); + --apidocs-fg: oklch(21.685% 0.01509 261.617); + --apidocs-muted: oklch(45.541% 0.02655 263.037); + --apidocs-faint: oklch(51.195% 0.0243 261.702); + --apidocs-rule: oklch(91.83% 0.00875 264.52); + --apidocs-rule-strong: oklch(84.433% 0.01492 264.488); + --apidocs-accent: oklch(49.4% 0.08141 208.54); + --apidocs-accent-soft: oklch(49.4% 0.08141 208.54 / 0.08); + --apidocs-link: oklch(44.632% 0.07384 210.379); + --apidocs-focus: oklch(49.4% 0.08141 208.54); + --apidocs-note-api: oklch(49.4% 0.08141 208.54); + --apidocs-note-api-soft: oklch(49.4% 0.08141 208.54 / 0.08); + --apidocs-note-spec: oklch(46.754% 0.14115 262.814); + --apidocs-note-spec-soft: oklch(46.754% 0.14115 262.814 / 0.07); + --apidocs-note-impl: oklch(51.195% 0.0243 261.702); + --apidocs-note-impl-soft: oklch(21.685% 0.01509 261.617 / 0.03); + --apidocs-deprecated: oklch(49.291% 0.15737 31.846); + --apidocs-deprecated-soft: oklch(49.291% 0.15737 31.846 / 0.07); + --apidocs-nullable: oklch(49.402% 0.10925 66.906); + --apidocs-non-null: oklch(47.294% 0.10194 148.797); + --apidocs-code-bg: oklch(96.948% 0.00454 258.325); + --apidocs-code-fg: oklch(25.906% 0.02487 261.09); + --apidocs-syn-comment: oklch(51.195% 0.0243 261.702); + --apidocs-syn-keyword: oklch(46.111% 0.16624 315.205); + --apidocs-syn-string: oklch(47.612% 0.10049 157.022); + --apidocs-syn-number: oklch(50.112% 0.12797 52.531); + --apidocs-syn-type: oklch(44.632% 0.07384 210.379); + --apidocs-syn-function: oklch(45.846% 0.16697 265.949); + --apidocs-syn-annotation: oklch(49.402% 0.10925 66.906); + --apidocs-syn-param: oklch(43.405% 0.14897 358.998); --apidocs-radius: 6px; --apidocs-topbar: 52px; + /* Sizes that grow with the screen: the narrow value at 480px wide and below, the wide one from 1000px, a straight + line between. Spacing only, and two sizes of the fallback type scale: a theme whose type is set to exact pixels + (the Elide preset's JetBrains Mono, whose characters are then a whole number of pixels wide) sets those two to + its own sizes, and the scale tokens above stay exact. */ + --apidocs-gutter: clamp(16px, 5.385vw - 0.656rem, 44px); + --apidocs-content-top: clamp(18px, 1.923vw + 0.585rem, 28px); + --apidocs-content-bottom: clamp(72px, 4.615vw + 3.323rem, 96px); + --apidocs-topbar-pad: clamp(12px, 1.538vw + 0.308rem, 20px); + --apidocs-topbar-gap: clamp(10px, 0.769vw + 0.421rem, 14px); + --apidocs-tools-gap: clamp(10px, 0.385vw + 0.544rem, 12px); + --apidocs-specimen-pad-block: clamp(14px, 0.769vw + 0.687rem, 18px); + --apidocs-specimen-pad-inline: clamp(16px, 1.154vw + 0.697rem, 22px); + /* A page's title and its declaration specimen. */ + --apidocs-size-title: clamp(var(--apidocs-size-2xl), 1.154vw + 1.231rem, var(--apidocs-size-3xl)); + --apidocs-size-specimen: clamp(var(--apidocs-size-sm), 0.385vw + 0.744rem, var(--apidocs-size-md)); } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { color-scheme: dark; - --apidocs-bg: #0f1216; - --apidocs-surface: #151920; - --apidocs-subtle: #1a1f27; - --apidocs-fg: #e6e8ec; - --apidocs-muted: #a3abb8; - --apidocs-faint: #8f98a6; - --apidocs-rule: #262c35; - --apidocs-rule-strong: #3a414d; - --apidocs-accent: #5cc6d0; - --apidocs-accent-soft: rgb(92 198 208 / 0.1); - --apidocs-link: #6fd0d9; - --apidocs-focus: #5cc6d0; - --apidocs-note-api: #5cc6d0; - --apidocs-note-api-soft: rgb(92 198 208 / 0.1); - --apidocs-note-spec: #8fb0f0; - --apidocs-note-spec-soft: rgb(143 176 240 / 0.09); - --apidocs-note-impl: #8f98a6; - --apidocs-note-impl-soft: rgb(230 232 236 / 0.03); - --apidocs-deprecated: #f08a78; - --apidocs-deprecated-soft: rgb(240 138 120 / 0.1); - --apidocs-nullable: #e3b25c; - --apidocs-non-null: #7cc98d; - --apidocs-code-bg: #141920; - --apidocs-code-fg: #d9dde3; - --apidocs-syn-comment: #8a93a1; - --apidocs-syn-keyword: #d09be6; - --apidocs-syn-string: #8fd1a6; - --apidocs-syn-number: #f0b47a; - --apidocs-syn-type: #6fd0d9; - --apidocs-syn-function: #9ab5ff; - --apidocs-syn-annotation: #e3b25c; - --apidocs-syn-param: #f09ac0; + --apidocs-bg: oklch(18.079% 0.00953 255.642); + --apidocs-surface: oklch(21.25% 0.01517 261.609); + --apidocs-subtle: oklch(23.785% 0.01713 259.757); + --apidocs-fg: oklch(93.061% 0.00581 264.531); + --apidocs-muted: oklch(73.897% 0.0208 260.165); + --apidocs-faint: oklch(67.698% 0.02312 259.192); + --apidocs-rule: oklch(29.114% 0.01854 258.368); + --apidocs-rule-strong: oklch(37.364% 0.02265 261.232); + --apidocs-accent: oklch(76.813% 0.09823 203.685); + --apidocs-accent-soft: oklch(76.813% 0.09823 203.685 / 0.1); + --apidocs-link: oklch(80.181% 0.09233 203.396); + --apidocs-focus: oklch(76.813% 0.09823 203.685); + --apidocs-note-api: oklch(76.813% 0.09823 203.685); + --apidocs-note-api-soft: oklch(76.813% 0.09823 203.685 / 0.1); + --apidocs-note-spec: oklch(75.722% 0.0996 263.17); + --apidocs-note-spec-soft: oklch(75.722% 0.0996 263.17 / 0.09); + --apidocs-note-impl: oklch(67.698% 0.02312 259.192); + --apidocs-note-impl-soft: oklch(93.061% 0.00581 264.531 / 0.03); + --apidocs-deprecated: oklch(73.872% 0.12799 30.977); + --apidocs-deprecated-soft: oklch(73.872% 0.12799 30.977 / 0.1); + --apidocs-nullable: oklch(79.118% 0.11843 79.713); + --apidocs-non-null: oklch(77.004% 0.115 150.059); + --apidocs-code-bg: oklch(21.154% 0.01586 256.82); + --apidocs-code-fg: oklch(89.621% 0.00927 258.337); + --apidocs-syn-comment: oklch(66.055% 0.02327 259.192); + --apidocs-syn-keyword: oklch(76.528% 0.11869 315.718); + --apidocs-syn-string: oklch(80.46% 0.09072 155.262); + --apidocs-syn-number: oklch(81.27% 0.10204 64.602); + --apidocs-syn-type: oklch(80.181% 0.09233 203.396); + --apidocs-syn-function: oklch(78.123% 0.11032 268.427); + --apidocs-syn-annotation: oklch(79.118% 0.11843 79.713); + --apidocs-syn-param: oklch(78.337% 0.11238 351.953); } } :root[data-theme="dark"] { color-scheme: dark; - --apidocs-bg: #0f1216; - --apidocs-surface: #151920; - --apidocs-subtle: #1a1f27; - --apidocs-fg: #e6e8ec; - --apidocs-muted: #a3abb8; - --apidocs-faint: #8f98a6; - --apidocs-rule: #262c35; - --apidocs-rule-strong: #3a414d; - --apidocs-accent: #5cc6d0; - --apidocs-accent-soft: rgb(92 198 208 / 0.1); - --apidocs-link: #6fd0d9; - --apidocs-focus: #5cc6d0; - --apidocs-note-api: #5cc6d0; - --apidocs-note-api-soft: rgb(92 198 208 / 0.1); - --apidocs-note-spec: #8fb0f0; - --apidocs-note-spec-soft: rgb(143 176 240 / 0.09); - --apidocs-note-impl: #8f98a6; - --apidocs-note-impl-soft: rgb(230 232 236 / 0.03); - --apidocs-deprecated: #f08a78; - --apidocs-deprecated-soft: rgb(240 138 120 / 0.1); - --apidocs-nullable: #e3b25c; - --apidocs-non-null: #7cc98d; - --apidocs-code-bg: #141920; - --apidocs-code-fg: #d9dde3; - --apidocs-syn-comment: #8a93a1; - --apidocs-syn-keyword: #d09be6; - --apidocs-syn-string: #8fd1a6; - --apidocs-syn-number: #f0b47a; - --apidocs-syn-type: #6fd0d9; - --apidocs-syn-function: #9ab5ff; - --apidocs-syn-annotation: #e3b25c; - --apidocs-syn-param: #f09ac0; + --apidocs-bg: oklch(18.079% 0.00953 255.642); + --apidocs-surface: oklch(21.25% 0.01517 261.609); + --apidocs-subtle: oklch(23.785% 0.01713 259.757); + --apidocs-fg: oklch(93.061% 0.00581 264.531); + --apidocs-muted: oklch(73.897% 0.0208 260.165); + --apidocs-faint: oklch(67.698% 0.02312 259.192); + --apidocs-rule: oklch(29.114% 0.01854 258.368); + --apidocs-rule-strong: oklch(37.364% 0.02265 261.232); + --apidocs-accent: oklch(76.813% 0.09823 203.685); + --apidocs-accent-soft: oklch(76.813% 0.09823 203.685 / 0.1); + --apidocs-link: oklch(80.181% 0.09233 203.396); + --apidocs-focus: oklch(76.813% 0.09823 203.685); + --apidocs-note-api: oklch(76.813% 0.09823 203.685); + --apidocs-note-api-soft: oklch(76.813% 0.09823 203.685 / 0.1); + --apidocs-note-spec: oklch(75.722% 0.0996 263.17); + --apidocs-note-spec-soft: oklch(75.722% 0.0996 263.17 / 0.09); + --apidocs-note-impl: oklch(67.698% 0.02312 259.192); + --apidocs-note-impl-soft: oklch(93.061% 0.00581 264.531 / 0.03); + --apidocs-deprecated: oklch(73.872% 0.12799 30.977); + --apidocs-deprecated-soft: oklch(73.872% 0.12799 30.977 / 0.1); + --apidocs-nullable: oklch(79.118% 0.11843 79.713); + --apidocs-non-null: oklch(77.004% 0.115 150.059); + --apidocs-code-bg: oklch(21.154% 0.01586 256.82); + --apidocs-code-fg: oklch(89.621% 0.00927 258.337); + --apidocs-syn-comment: oklch(66.055% 0.02327 259.192); + --apidocs-syn-keyword: oklch(76.528% 0.11869 315.718); + --apidocs-syn-string: oklch(80.46% 0.09072 155.262); + --apidocs-syn-number: oklch(81.27% 0.10204 64.602); + --apidocs-syn-type: oklch(80.181% 0.09233 203.396); + --apidocs-syn-function: oklch(78.123% 0.11032 268.427); + --apidocs-syn-annotation: oklch(79.118% 0.11843 79.713); + --apidocs-syn-param: oklch(78.337% 0.11238 351.953); } /* ---- Base ---- */ @@ -159,12 +174,11 @@ html { font-synthesis: none; font-variant-ligatures: none; font-kerning: normal; - text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; text-size-adjust: 100%; - scroll-padding-top: calc(var(--apidocs-topbar) + 16px); + scroll-padding-block-start: calc(var(--apidocs-topbar) + 16px); /* The page keeps its width whether or not it scrolls, so moving between short and long pages shifts nothing. */ scrollbar-gutter: stable; } @@ -172,37 +186,41 @@ html { body { margin: 0; min-height: 100vh; font-size: var(--apidocs-size-md); } a { color: var(--apidocs-link); text-decoration: none; } -a:hover { text-decoration: underline; text-underline-offset: 2px; } +@media (hover: hover) and (pointer: fine) { a:hover { text-decoration: underline; text-underline-offset: 2px; } } +a:active { text-decoration: underline; text-underline-offset: 2px; } :focus-visible { outline: 2px solid var(--apidocs-focus); outline-offset: 2px; border-radius: 3px; } code, kbd, pre { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-code-scale); font-variant-ligatures: none; } +/* Code reads left to right on a right-to-left page too. Only there: isolating inline code moves line breaks. */ +code:dir(rtl), kbd:dir(rtl), pre:dir(rtl) { direction: ltr; unicode-bidi: isolate; } :not(pre) > code { background: var(--apidocs-subtle); border-radius: 4px; - padding: 0.08em 0.32em; + padding-block: 0.08em; padding-inline: 0.32em; overflow-wrap: anywhere; } a > code { color: inherit; } -.prose a, .callout a, .fact dd a, td a:not(.type-link), .lede a, .inherited-list a, .see-list a { +.prose a, .callout a, .fact dd a, td a:not(.type-link), .lede a, .inherited-list a, .see-list a, .index-summary a { text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px; text-decoration-color: color-mix(in srgb, currentColor 45%, transparent); } -.prose a:hover, .callout a:hover, .fact dd a:hover, td a:not(.type-link):hover, .lede a:hover, .inherited-list a:hover, .see-list a:hover { text-decoration-color: currentColor; } +@media (hover: hover) and (pointer: fine) { .prose a:hover, .callout a:hover, .fact dd a:hover, td a:not(.type-link):hover, .lede a:hover, .inherited-list a:hover, .see-list a:hover, .index-summary a:hover { text-decoration-color: currentColor; } } +.prose a:active, .callout a:active, .fact dd a:active, td a:not(.type-link):active, .lede a:active, .inherited-list a:active, .see-list a:active, .index-summary a:active { text-decoration-color: currentColor; } .summary-sig a { text-decoration: none; } h1, h2, h3, h4 { font-family: var(--apidocs-font-display); line-height: 1.2; margin: 0; text-wrap: balance; } p, li, dd { text-wrap: pretty; } .visually-hidden { - position: absolute; width: 1px; height: 1px; overflow: hidden; + position: absolute; width: 1px; height: 1px; overflow: clip; clip-path: inset(50%); white-space: nowrap; } .skip { - position: absolute; left: 12px; top: -60px; z-index: 20; - background: var(--apidocs-surface); padding: 8px 12px; border: 1px solid var(--apidocs-rule-strong); + position: absolute; inset-inline-start: 12px; inset-block-start: -60px; z-index: 20; + background: var(--apidocs-surface); padding-block: 8px; padding-inline: 12px; border: 1px solid var(--apidocs-rule-strong); } -.skip:focus { top: 8px; } +.skip:focus-visible { inset-block-start: 8px; } /* Labels, counts, marks and controls are furniture, not content: a selection skips them, so copying a name or a paragraph gives that text and nothing else. */ @@ -212,18 +230,31 @@ p, li, dd { text-wrap: pretty; } /* ---- Top bar ---- */ +/* + * The bar holds the site's controls on one line at every width from 320px. As it narrows, its parts give way in + * this order, and nothing wraps, overflows or is cut off: + * 1. The search field narrows, from 19rem to 10rem (to 5rem where the navigator is a drawer). + * 2. The suite switcher's row gives way to its menu button. Where the navigator is a drawer, the switcher leaves + * the bar instead: the drawer lists the sites first. + * 3. The product name ends in an ellipsis; its title keeps the whole name. The logo never shrinks. + * Where the navigator is a drawer (860px and below), the module's name and version are not in the bar at all. + * Flexbox does the ordering. .topbar-tools has a flex basis of 0: it grows into what the brand leaves and squeezes + * the brand only once it is at its own minimum. Inside it, the search field also starts from 0 and grows (to 19rem) + * only into space the switcher's row does not need, and the switcher is the one part that shrinks. + */ .topbar { - position: sticky; top: 0; z-index: 10; + position: sticky; inset-block-start: 0; z-index: 10; height: var(--apidocs-topbar); - display: flex; align-items: center; gap: 14px; - padding: 0 20px; + display: flex; align-items: center; gap: var(--apidocs-topbar-gap); + padding-inline: var(--apidocs-topbar-pad); background: color-mix(in srgb, var(--apidocs-bg) 92%, transparent); backdrop-filter: blur(8px); - border-bottom: 1px solid var(--apidocs-rule); + border-block-end: 1px solid var(--apidocs-rule); } -.brand { display: flex; align-items: center; gap: 10px; color: var(--apidocs-fg); font-weight: 650; white-space: nowrap; } -.brand:hover { text-decoration: none; } -.logo { height: 22px; width: auto; display: block; } +.brand { flex: 0 1 auto; min-width: 0; display: flex; align-items: center; gap: 10px; color: var(--apidocs-fg); font-weight: 650; white-space: nowrap; } +@media (hover: hover) and (pointer: fine) { .brand:hover { text-decoration: none; } } +.brand:active { text-decoration: none; } +.logo { flex: none; height: 22px; width: auto; display: block; } .logo-dark { display: none; } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .logo-light { display: none; } @@ -231,52 +262,100 @@ p, li, dd { text-wrap: pretty; } } :root[data-theme="dark"] .logo-light { display: none; } :root[data-theme="dark"] .logo-dark { display: block; } -.product { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-lg); letter-spacing: 0; } -.module-version { color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* good-css exception (overflow-clip): hidden, not clip, so the ellipsis shows in every target browser, Safari before 16 among them. */ +.product { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-lg); letter-spacing: 0; } +.module-version { flex: none; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); white-space: nowrap; } .version { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-sm); } -/* The module's indexes, as Javadoc has them: overview, packages, types, A to Z, deprecated. */ -.topbar-nav { display: flex; align-items: center; gap: 2px; margin-left: 10px; min-width: 0; font-size: var(--apidocs-size-sm); user-select: none; -webkit-user-select: none; } -.topbar-nav a { padding: 5px 9px; border-radius: var(--apidocs-radius); color: var(--apidocs-muted); white-space: nowrap; } -.topbar-nav a:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); text-decoration: none; } -.topbar-nav a[aria-current="page"] { color: var(--apidocs-accent); background: var(--apidocs-accent-soft); font-weight: 600; } -@media (max-width: 1100px) { .topbar-nav, .topbar-link { display: none; } } -.topbar-tools { margin-left: auto; display: flex; align-items: center; gap: 12px; min-width: 0; } -.topbar-link { color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); } - -.search { position: relative; display: block; } +.topbar-tools { --apidocs-search-floor: 10rem; flex: 1 1 0; display: flex; align-items: center; gap: var(--apidocs-tools-gap); } +.topbar-tools > .search-fallback, .topbar-tools > .theme-switch { flex: none; } +.search-fallback { margin-inline-start: auto; } + +/* The suite switcher (SuiteSwitcher in chrome.tsx). .suites-fit holds hidden copies of the labels in a wrapping + row: 32px tall when they fit on one line, 64px or more when they do not. The visible row and the menu are placed + from that height, scaled up so the one that does not apply sits far above the page: the row at the top when the + labels fit, the menu when they do not. No width is written down anywhere: the browser's layout decides. The + hidden copy of the menu button (.suites-floor) keeps the bar from squeezing the switcher below the button. */ +.suites { flex: 0 1 auto; height: 32px; margin-inline-start: 10px; font-size: var(--apidocs-size-sm); user-select: none; -webkit-user-select: none; } +.suites-fit { position: relative; display: flex; flex-wrap: wrap; column-gap: 2px; pointer-events: none; } +.suites-probe { width: 0; height: 32px; margin-inline-end: -2px; } +.suites-ghost { display: flex; align-items: center; height: 32px; padding-block: 0; padding-inline: 9px; white-space: nowrap; visibility: hidden; } +.suites-ghost[data-current] { font-weight: 600; } +.suites-row, .suite-menu { pointer-events: auto; } +.suites-row { position: absolute; inset-inline-start: 0; inset-block-start: calc((32px - 100%) * 1000); display: flex; align-items: center; height: 32px; max-width: 100%; overflow: clip; column-gap: 2px; } +.suites-row a { padding-block: 5px; padding-inline: 9px; border-radius: var(--apidocs-radius); color: var(--apidocs-muted); white-space: nowrap; } +@media (hover: hover) and (pointer: fine) { .suites-row a:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); text-decoration: none; } } +.suites-row a:active { color: var(--apidocs-fg); background: var(--apidocs-subtle); text-decoration: none; } +.suites-row a[aria-current="true"] { color: var(--apidocs-accent); background: var(--apidocs-accent-soft); font-weight: 600; } +.suite-menu { position: absolute; inset-inline-start: 0; inset-inline-end: 0; inset-block-start: min(0px, calc((100% - 64px) * 1000)); height: 32px; } +.suite-current, .suites-floor { display: flex; align-items: center; gap: 4px; padding-block: 0; padding-inline: 9px 7px; border: 1px solid transparent; white-space: nowrap; } +.suite-current { + width: fit-content; max-width: 100%; height: 30px; margin-block-start: 1px; + border-color: var(--apidocs-rule-strong); border-radius: var(--apidocs-radius); + color: var(--apidocs-fg); list-style: none; cursor: pointer; +} +.suite-current::-webkit-details-marker { display: none; } +.suite-current .icon { flex: none; vertical-align: 0; color: var(--apidocs-muted); } +/* good-css exception (overflow-clip): hidden, not clip, so the ellipsis shows in every target browser, Safari before 16 among them. */ +.suite-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.suite-menu[open] > .suite-current { background: var(--apidocs-subtle); } +@media (hover: hover) and (pointer: fine) { .suite-current:hover { background: var(--apidocs-subtle); } } +.suite-current:active { background: var(--apidocs-subtle); } +.suites-floor { width: max-content; height: 0; overflow: clip; visibility: hidden; } +/* With the script (SUITES_BOOT in chrome.tsx), the switcher is as wide as what it shows, and the one out of view is + hidden from assistive technology and the keyboard too. */ +.suites[data-fit] { flex: 0 1 var(--apidocs-suites-width); } +.suites[data-fit="row"] { min-width: 0; } +/* Out of the bar, but still laid out, so the script can measure its labels the next time: no width, no gap, unseen. */ +.suites[data-fit="none"] { flex: 0 0 0; min-width: 0; margin-inline-end: calc(-1 * var(--apidocs-tools-gap)); overflow: clip; visibility: hidden; } +.suites[data-fit="row"] .suite-menu, .suites[data-fit="menu"] .suites-row { visibility: hidden; } +.suite-list { + position: absolute; inset-inline-start: -1px; inset-block-start: calc(100% + 6px); z-index: 12; + min-width: 12rem; margin: 0; padding: 4px; list-style: none; + background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); + border-radius: calc(var(--apidocs-radius) + 2px); box-shadow: 0 12px 32px -12px oklch(0% 0 none / 0.28); + line-height: 1.5; +} +.suite-list a { display: block; padding-block: 5px; padding-inline: 10px; border-radius: 4px; color: var(--apidocs-fg); white-space: nowrap; } +@media (hover: hover) and (pointer: fine) { .suite-list a:hover { background: var(--apidocs-subtle); text-decoration: none; } } +.suite-list a:active { background: var(--apidocs-subtle); text-decoration: none; } +.suite-list a[aria-current="true"] { color: var(--apidocs-accent); font-weight: 600; } + +.search { position: relative; display: block; flex: 1000 1 0; min-width: var(--apidocs-search-floor); max-width: 19rem; margin-inline-start: auto; } .search input { - width: 19rem; max-width: 46vw; + width: 100%; text-overflow: ellipsis; font: inherit; font-size: var(--apidocs-size-sm); color: var(--apidocs-fg); background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); border-radius: var(--apidocs-radius); - padding: 6px 30px 6px 10px; + padding-block: 6px; padding-inline: 10px 30px; } .search input:focus-visible { outline: 2px solid var(--apidocs-focus); outline-offset: 0; border-color: transparent; } .search-key { - position: absolute; right: 8px; top: 50%; transform: translateY(-50%); + position: absolute; inset-inline-end: 8px; inset-block-start: 50%; transform: translateY(-50%); font-size: var(--apidocs-size-xs); color: var(--apidocs-faint); - border: 1px solid var(--apidocs-rule-strong); border-radius: 4px; padding: 0 5px; line-height: 1.4; + border: 1px solid var(--apidocs-rule-strong); border-radius: 4px; padding-block: 0; padding-inline: 5px; line-height: 1.4; } .search-results { - position: absolute; right: 0; top: calc(100% + 6px); + position: absolute; inset-inline-end: 0; inset-block-start: calc(100% + 6px); width: min(34rem, 92vw); max-height: min(70vh, 34rem); overflow: auto; margin: 0; padding: 4px; list-style: none; background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); border-radius: var(--apidocs-radius); - box-shadow: 0 12px 32px -12px rgb(0 0 0 / 0.28); + box-shadow: 0 12px 32px -12px oklch(0% 0 none / 0.28); } .search-results li a { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 12px; - padding: 7px 10px; border-radius: 4px; color: var(--apidocs-fg); + padding-block: 7px; padding-inline: 10px; border-radius: 4px; color: var(--apidocs-fg); } -.search-results li a:hover { text-decoration: none; } +@media (hover: hover) and (pointer: fine) { .search-results li a:hover { text-decoration: none; } } +.search-results li a:active { text-decoration: none; } .search-results li[aria-selected="true"] a { background: var(--apidocs-accent-soft); } .result-label { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-sm); overflow-wrap: anywhere; } .result-label mark { background: none; color: var(--apidocs-accent); font-weight: 700; } -.result-kind { color: var(--apidocs-faint); font-size: var(--apidocs-size-sm); text-align: right; } +.result-kind { color: var(--apidocs-faint); font-size: var(--apidocs-size-sm); text-align: end; } +/* good-css exception (overflow-clip): hidden, not clip, so the ellipsis shows in every target browser, Safari before 16 among them. */ .result-context { grid-column: 1 / -1; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .search-empty { padding: 10px; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); } @@ -304,10 +383,10 @@ html[data-emoji] .theme-switch[data-mode="dark"] .theme-emoji::before { content: display: grid; grid-template-columns: 17.5rem minmax(0, 1fr) 15.5rem; max-width: 104rem; - margin: 0 auto; + margin-block: 0; margin-inline: auto; } .sidebar, .toc { - position: sticky; top: var(--apidocs-topbar); + position: sticky; inset-block-start: var(--apidocs-topbar); align-self: start; height: calc(100vh - var(--apidocs-topbar)); overflow: auto; @@ -315,65 +394,78 @@ html[data-emoji] .theme-switch[data-mode="dark"] .theme-emoji::before { content: scrollbar-width: thin; font-size: var(--apidocs-size-sm); line-height: 1.5; } -.sidebar { padding: 14px 10px 40px 14px; border-right: 1px solid var(--apidocs-rule); } -.content { padding: 28px 44px 96px; min-width: 0; } +.sidebar { padding-block: 14px 40px; padding-inline: 14px 10px; border-inline-end: 1px solid var(--apidocs-rule); } +.content { padding-block: var(--apidocs-content-top) var(--apidocs-content-bottom); padding-inline: var(--apidocs-gutter); min-width: 0; } .content > * { max-width: 62rem; } -.toc { padding: 28px 16px 40px 4px; } +.toc { padding-block: 28px 40px; padding-inline: 4px 16px; } /* The navigator: flat one-line rows. Nothing wraps; a row truncates and its title has the full name. */ .nav-button { display: grid; place-items: center; width: 32px; height: 32px; flex: none; cursor: pointer; - margin-left: -6px; border-radius: var(--apidocs-radius); color: var(--apidocs-muted); + margin-inline-start: -6px; border-radius: var(--apidocs-radius); color: var(--apidocs-muted); } -.nav-button:hover { background: var(--apidocs-subtle); color: var(--apidocs-fg); } +@media (hover: hover) and (pointer: fine) { .nav-button:hover { background: var(--apidocs-subtle); color: var(--apidocs-fg); } } +.nav-button:active { background: var(--apidocs-subtle); color: var(--apidocs-fg); } .nav-button svg { display: block; fill: none; stroke: currentColor; stroke-width: 1.4; stroke-linejoin: round; } .nav-toggle:focus-visible + script + .nav-button, .nav-toggle:focus-visible + .nav-button { outline: 2px solid var(--apidocs-focus); outline-offset: 2px; } /* Wide screens: checked hides the navigator and gives its column to the content. No animation: the page is laid out once. */ @media (min-width: 861px) { body:has(.nav-toggle:checked) .layout { grid-template-columns: minmax(0, 1fr) 15.5rem; } body:has(.nav-toggle:checked) .layout .sidebar { display: none; } - body:has(.nav-toggle:checked) .layout .content { padding-left: max(44px, calc((100% - 62rem) / 2)); } + /* good-css exception (fluid-clamp): a layout, not a size step: with the navigator hidden, the text is centered. */ + body:has(.nav-toggle:checked) .layout .content { padding-inline-start: max(var(--apidocs-gutter), calc((100% - 62rem) / 2)); } } @media (min-width: 861px) and (max-width: 1240px) { body:has(.nav-toggle:checked) .layout { grid-template-columns: minmax(0, 1fr); } } -.nav-section + .nav-section { margin-top: 18px; } +.nav-section + .nav-section { margin-block-start: 18px; } .nav-heading { display: flex; align-items: baseline; gap: 8px; - margin: 0 0 4px; padding: 0 8px; + margin-block: 0 4px; margin-inline: 0; padding-block: 0; padding-inline: 8px; font-family: var(--apidocs-font-sans); font-size: var(--apidocs-size-xs); font-weight: 650; letter-spacing: var(--apidocs-tracking-caps); text-transform: uppercase; color: var(--apidocs-faint); } /* The shared package prefix is a row of its own; the packages hang from it, each starting with the dot that joins them. */ .nav-prefix { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-sm); color: var(--apidocs-muted); } -.nav-list.nav-suffixes { margin-left: 15px; padding-left: 4px; border-left: 1px solid var(--apidocs-rule-strong); } +.nav-list.nav-suffixes { margin-inline-start: 15px; padding-inline-start: 4px; border-inline-start: 1px solid var(--apidocs-rule-strong); } .nav-dot { color: var(--apidocs-faint); } .nav-list { list-style: none; margin: 0; padding: 0; } .nav-row { display: flex; align-items: center; gap: 8px; - height: 28px; padding: 0 8px; border-radius: 5px; + height: 28px; padding-block: 0; padding-inline: 8px; border-radius: 5px; color: var(--apidocs-fg); white-space: nowrap; } -.nav-row:hover { background: var(--apidocs-subtle); text-decoration: none; } +@media (hover: hover) and (pointer: fine) { .nav-row:hover { background: var(--apidocs-subtle); text-decoration: none; } } +.nav-row:active { background: var(--apidocs-subtle); text-decoration: none; } +/* good-css exception (overflow-clip): hidden, not clip, so the ellipsis shows in every target browser, Safari before 16 among them. */ .nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; } .nav-package .nav-label { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-sm); } .nav-count { flex: none; font-size: var(--apidocs-size-xs); font-variant-numeric: tabular-nums; color: var(--apidocs-faint); } .nav-row[data-open] { font-weight: 600; } .nav-package[data-open] { color: var(--apidocs-accent); } .nav-package[data-open] .nav-dot { color: inherit; opacity: 0.6; } -.nav-row[aria-current="page"] { background: var(--apidocs-accent-soft); color: var(--apidocs-accent); font-weight: 600; } -.nav-row[aria-current="page"] .nav-count { color: inherit; } -.nav-nested { margin: 1px 0 4px 15px; padding-left: 6px; border-left: 1px solid var(--apidocs-rule); } -.nav-filter, .toc-filter { margin: 0 0 12px; } +.nav-row[aria-current="page"], .nav-row[aria-current="true"] { background: var(--apidocs-accent-soft); color: var(--apidocs-accent); font-weight: 600; } +.nav-row[aria-current] .nav-count { color: inherit; } +.nav-nested { margin-block: 1px 4px; margin-inline: 15px 0; padding-inline-start: 6px; border-inline-start: 1px solid var(--apidocs-rule); } +/* The sites, first in the drawer only: on a wide screen the top bar's switcher has them. */ +.nav-suites { display: none; } +/* The module's indexes: one line of links when they fit the narrowest navigator (NAV_INDEX_ROW_MAX in chrome.tsx), + else rows under "Reference". */ +.nav-index { display: flex; gap: 2px; margin-block: 0 14px; margin-inline: 0; padding: 0; list-style: none; font-size: var(--apidocs-size-sm); white-space: nowrap; user-select: none; -webkit-user-select: none; } +.nav-index a { display: block; padding-block: 3px; padding-inline: 8px; border-radius: 5px; color: var(--apidocs-muted); } +@media (hover: hover) and (pointer: fine) { .nav-index a:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); text-decoration: none; } } +.nav-index a:active { color: var(--apidocs-fg); background: var(--apidocs-subtle); text-decoration: none; } +.nav-index a[aria-current="page"] { color: var(--apidocs-accent); background: var(--apidocs-accent-soft); font-weight: 600; } +.nav-filter, .toc-filter { margin-block: 0 12px; margin-inline: 0; } .nav-filter { - position: sticky; top: -14px; z-index: 1; - margin: -14px -10px 10px -14px; padding: 14px 10px 8px 14px; + position: sticky; inset-block-start: -14px; z-index: 1; + margin-block: -14px 10px; margin-inline: -14px -10px; padding-block: 14px 8px; padding-inline: 14px 10px; background: var(--apidocs-bg); } .nav-filter input, .toc-filter input { width: 100%; font: inherit; font-size: var(--apidocs-size-sm); color: var(--apidocs-fg); background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); - border-radius: var(--apidocs-radius); padding: 5px 9px; + border-radius: var(--apidocs-radius); padding-block: 5px; padding-inline: 9px; } .nav-filter input:focus-visible, .toc-filter input:focus-visible { outline: 2px solid var(--apidocs-focus); outline-offset: 0; border-color: transparent; } [data-filtered-out] { display: none !important; } @@ -393,44 +485,47 @@ html[data-emoji] .theme-switch[data-mode="dark"] .theme-emoji::before { content: .glyph[data-tone="object"] { --glyph: var(--apidocs-syn-keyword); } .glyph[data-tone="exception"] { --glyph: var(--apidocs-deprecated); } .glyph[data-tone="guide"] { --glyph: var(--apidocs-accent); font-family: var(--apidocs-font-system); } -.nav-subheading { margin: 8px 0 2px; padding: 0 8px; font-size: var(--apidocs-size-xs); color: var(--apidocs-faint); user-select: none; -webkit-user-select: none; } +.nav-subheading { margin-block: 8px 2px; margin-inline: 0; padding-block: 0; padding-inline: 8px; font-size: var(--apidocs-size-xs); color: var(--apidocs-faint); user-select: none; -webkit-user-select: none; } .glyph-large { width: 28px; height: 28px; border-radius: 7px; font-size: var(--apidocs-size-md); } /* "On this page": sections with counts; long sections fold. */ -.toc-title { margin: 0 0 10px; padding-left: 12px; color: var(--apidocs-faint); font-weight: 650; font-size: var(--apidocs-size-xs); letter-spacing: var(--apidocs-tracking-caps); text-transform: uppercase; } -.toc-filter { padding-left: 12px; } +.toc-title { margin-block: 0 10px; margin-inline: 0; padding-inline-start: 12px; color: var(--apidocs-faint); font-weight: 650; font-size: var(--apidocs-size-xs); letter-spacing: var(--apidocs-tracking-caps); text-transform: uppercase; } +.toc-filter { padding-inline-start: 12px; } .toc-list, .toc-entries { list-style: none; margin: 0; padding: 0; } -.toc-section + .toc-section { margin-top: 2px; } +.toc-section + .toc-section { margin-block-start: 2px; } .toc-head { display: flex; align-items: baseline; gap: 8px; } .toc-head a { flex: 1; } +/* good-css exception (overflow-clip): hidden, not clip, so the ellipsis shows in every target browser, Safari before 16 among them. */ .toc a { - display: block; min-width: 0; padding: 3px 0 3px 12px; - border-left: 2px solid transparent; color: var(--apidocs-muted); + display: block; min-width: 0; padding-block: 3px; padding-inline: 12px 0; + border-inline-start: 2px solid transparent; color: var(--apidocs-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .toc-head a { color: var(--apidocs-fg); font-weight: 550; } -.toc a:hover { color: var(--apidocs-fg); text-decoration: none; } -.toc a[aria-current="true"] { color: var(--apidocs-accent); border-left-color: var(--apidocs-accent); } +@media (hover: hover) and (pointer: fine) { .toc a:hover { color: var(--apidocs-fg); text-decoration: none; } } +.toc a:active { color: var(--apidocs-fg); text-decoration: none; } +.toc a[aria-current="true"] { color: var(--apidocs-accent); border-inline-start-color: var(--apidocs-accent); } .toc-count { flex: none; font-size: var(--apidocs-size-xs); font-variant-numeric: tabular-nums; color: var(--apidocs-faint); } -.toc-entries { margin: 0 0 6px; } -.toc-entries a { padding-left: 22px; font-size: var(--apidocs-size-sm); } +.toc-entries { margin-block: 0 6px; margin-inline: 0; } +.toc-entries a { padding-inline-start: 22px; font-size: var(--apidocs-size-sm); } .toc code { background: none; padding: 0; font-size: 1em; } .toc-more > summary { - list-style: none; cursor: pointer; padding: 2px 0 4px 22px; + list-style: none; cursor: pointer; padding-block: 2px 4px; padding-inline: 22px 0; font-size: var(--apidocs-size-sm); color: var(--apidocs-faint); } .toc-more > summary::-webkit-details-marker { display: none; } -.toc-more > summary:hover { color: var(--apidocs-fg); } +@media (hover: hover) and (pointer: fine) { .toc-more > summary:hover { color: var(--apidocs-fg); } } +.toc-more > summary:active { color: var(--apidocs-fg); } .toc-more[open] > summary { display: none; } .toc-more > .toc-entries { max-height: 55vh; overflow: auto; scrollbar-width: thin; } /* The row above the title: where you are, and the page's other forms. */ -.page-tools { display: flex; align-items: center; gap: 12px; min-height: 30px; margin-bottom: 14px; } +.page-tools { display: flex; align-items: center; gap: 12px; min-height: 30px; margin-block-end: 14px; } .page-tools .crumbs { flex: 1; min-width: 0; } .page-tools .crumbs ol { margin: 0; } /* The formats control: a mark and an arrow in one quiet pill. */ .formats { - display: flex; align-items: stretch; flex: none; margin-left: auto; position: relative; height: 30px; + display: flex; align-items: stretch; flex: none; margin-inline-start: auto; position: relative; height: 30px; border: 1px solid var(--apidocs-rule-strong); border-radius: var(--apidocs-radius); background: var(--apidocs-surface); color: var(--apidocs-muted); user-select: none; -webkit-user-select: none; @@ -438,73 +533,76 @@ html[data-emoji] .theme-switch[data-mode="dark"] .theme-emoji::before { content: .formats-main, .formats-menu > summary { display: grid; place-items: center; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; } -.formats-main { width: 36px; border-radius: calc(var(--apidocs-radius) - 1px) 0 0 calc(var(--apidocs-radius) - 1px); } -.formats-menu > summary { width: 28px; height: 100%; list-style: none; border-left: 1px solid var(--apidocs-rule); border-radius: 0 calc(var(--apidocs-radius) - 1px) calc(var(--apidocs-radius) - 1px) 0; } +.formats-main { width: 36px; border-radius: 0; border-start-start-radius: calc(var(--apidocs-radius) - 1px); border-end-start-radius: calc(var(--apidocs-radius) - 1px); } +.formats-menu > summary { width: 28px; height: 100%; list-style: none; border-inline-start: 1px solid var(--apidocs-rule); border-radius: 0; border-start-end-radius: calc(var(--apidocs-radius) - 1px); border-end-end-radius: calc(var(--apidocs-radius) - 1px); } .formats-menu > summary::-webkit-details-marker { display: none; } -.formats-main:hover, .formats-menu > summary:hover, .formats-menu[open] > summary { color: var(--apidocs-fg); background: var(--apidocs-subtle); } +.formats-menu[open] > summary { color: var(--apidocs-fg); background: var(--apidocs-subtle); } +@media (hover: hover) and (pointer: fine) { .formats-main:hover, .formats-menu > summary:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); } } +.formats-main:active, .formats-menu > summary:active { color: var(--apidocs-fg); background: var(--apidocs-subtle); } .formats-main .formats-done { display: none; color: var(--apidocs-non-null); } .formats-main[data-copied] .icon-markdown { display: none; } .formats-main[data-copied] .formats-done { display: block; } .formats-main .icon { vertical-align: 0; } .formats-list { - position: absolute; right: -1px; top: calc(100% + 6px); z-index: 8; width: max-content; min-width: 16rem; + position: absolute; inset-inline-end: -1px; inset-block-start: calc(100% + 6px); z-index: 8; width: max-content; min-width: 16rem; margin: 0; padding: 4px; list-style: none; background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); - border-radius: calc(var(--apidocs-radius) + 2px); box-shadow: 0 12px 32px -12px rgb(0 0 0 / 0.28); + border-radius: calc(var(--apidocs-radius) + 2px); box-shadow: 0 12px 32px -12px oklch(0% 0 none / 0.28); font-size: var(--apidocs-size-sm); line-height: 1.5; } -.formats-list a { display: flex; align-items: baseline; justify-content: space-between; gap: 20px; padding: 5px 10px; border-radius: 4px; color: var(--apidocs-fg); } -.formats-list a:hover { background: var(--apidocs-subtle); text-decoration: none; } +.formats-list a { display: flex; align-items: baseline; justify-content: space-between; gap: 20px; padding-block: 5px; padding-inline: 10px; border-radius: 4px; color: var(--apidocs-fg); } +@media (hover: hover) and (pointer: fine) { .formats-list a:hover { background: var(--apidocs-subtle); text-decoration: none; } } +.formats-list a:active { background: var(--apidocs-subtle); text-decoration: none; } .formats-list code { background: none; padding: 0; } .formats-list small { color: var(--apidocs-faint); font-size: var(--apidocs-size-xs); } -.formats-sep { margin-top: 4px; padding-top: 4px; border-top: 1px solid var(--apidocs-rule); } +.formats-sep { margin-block-start: 4px; padding-block-start: 4px; border-block-start: 1px solid var(--apidocs-rule); } .icon { display: inline-block; vertical-align: -0.125em; } /* A language's mark. */ .lang { display: inline-flex; align-items: center; gap: 5px; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); white-space: nowrap; user-select: none; } .lang .icon { flex: none; vertical-align: 0; } -.lang[data-lang="kotlin"] .icon { color: var(--apidocs-lang-kotlin, #7f52ff); } -.lang[data-lang="java"] .icon { color: var(--apidocs-lang-java, #c9601a); } +.lang[data-lang="kotlin"] .icon { color: var(--apidocs-lang-kotlin, oklch(58.775% 0.24128 288.635)); } +.lang[data-lang="java"] .icon { color: var(--apidocs-lang-java, oklch(60.725% 0.15353 48.401)); } .nav-row .lang, .type-link .lang { flex: none; } -.crumbs ol { list-style: none; display: flex; flex-wrap: wrap; gap: 4px; margin: 0 0 18px; padding: 0; font-size: var(--apidocs-size-sm); color: var(--apidocs-muted); } -.crumbs li + li::before { content: "/"; margin-right: 4px; color: var(--apidocs-rule-strong); } +.crumbs ol { list-style: none; display: flex; flex-wrap: wrap; gap: 4px; margin-block: 0 18px; margin-inline: 0; padding: 0; font-size: var(--apidocs-size-sm); color: var(--apidocs-muted); } +.crumbs li + li::before { content: "/"; margin-inline-end: 4px; color: var(--apidocs-rule-strong); } .crumbs a { color: var(--apidocs-muted); } .footer { - border-top: 1px solid var(--apidocs-rule); - padding: 20px 24px 32px; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); - max-width: 94rem; margin: 0 auto; + border-block-start: 1px solid var(--apidocs-rule); + padding-block: 20px 32px; padding-inline: 24px; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); + max-width: 94rem; margin-block: 0; margin-inline: auto; } -.footer p { margin: 0 0 6px; } +.footer p { margin-block: 0 6px; margin-inline: 0; } .footer-links { display: flex; gap: 16px; flex-wrap: wrap; } /* ---- Page head and the declaration specimen ---- */ -.page-head { margin-bottom: 16px; } -.page-head h1 { font-size: var(--apidocs-size-3xl); font-weight: 650; letter-spacing: var(--apidocs-tracking-display); overflow-wrap: anywhere; } +.page-head { margin-block-end: 16px; } +.page-head h1 { font-size: var(--apidocs-size-title); font-weight: 650; letter-spacing: var(--apidocs-tracking-display); overflow-wrap: anywhere; } /* The tile and the name share one line box and one center line, whatever fonts they come from. */ .page-head h1[data-kind] { display: flex; align-items: center; gap: 12px; font-family: var(--apidocs-font-mono); letter-spacing: 0; font-weight: 700; line-height: 36px; } @supports (text-box: trim-both cap alphabetic) { .page-head h1 { text-box: trim-both cap alphabetic; } .page-head h1[data-kind] { line-height: 1; } - .page-head .page-meta { margin-top: 14px; } + .page-head .page-meta { margin-block-start: 14px; } } .page-head h1 code { background: none; padding: 0; font-size: calc(var(--apidocs-code-scale) * 0.92); } -.page-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin: 8px 0 0; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); } +.page-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin-block: 8px 0; margin-inline: 0; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); } .kind-word { font-weight: 600; color: var(--apidocs-fg); } .lede { font-size: var(--apidocs-size-lg); color: var(--apidocs-muted); } .sig { position: relative; } .sig pre { - margin: 12px 0; padding: 10px 14px; + margin-block: 12px; margin-inline: 0; padding-block: 10px; padding-inline: 14px; background: var(--apidocs-code-bg); color: var(--apidocs-code-fg); border-radius: var(--apidocs-radius); overflow-x: auto; font-size: var(--apidocs-size-sm); line-height: 1.5; } .sig-large pre { - margin: 18px 0 20px; padding: 18px 22px; - font-size: var(--apidocs-size-md); line-height: 1.6; + margin-block: 18px 20px; margin-inline: 0; padding-block: var(--apidocs-specimen-pad-block); padding-inline: var(--apidocs-specimen-pad-inline); + font-size: var(--apidocs-size-specimen); line-height: 1.6; border: 1px solid var(--apidocs-rule); border-radius: calc(var(--apidocs-radius) + 4px); } @@ -517,26 +615,29 @@ html[data-emoji] .theme-switch[data-mode="dark"] .theme-emoji::before { content: .tk-l { color: var(--apidocs-syn-string); } .tk-p { color: var(--apidocs-syn-param); } a.tk-t, a.tk-a { text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 30%, transparent); text-underline-offset: 3px; } -a.tk-t:hover, a.tk-a:hover { text-decoration-color: currentColor; } +@media (hover: hover) and (pointer: fine) { a.tk-t:hover, a.tk-a:hover { text-decoration-color: currentColor; } } +a.tk-t:active, a.tk-a:active { text-decoration-color: currentColor; } .copy { - position: absolute; top: 6px; right: 6px; + position: absolute; inset-block-start: 6px; inset-inline-end: 6px; font: inherit; font-size: var(--apidocs-size-xs); line-height: 1; - padding: 5px 7px; + padding-block: 5px; padding-inline: 7px; color: var(--apidocs-muted); background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); border-radius: 4px; cursor: pointer; opacity: 0; } -.sig:hover .copy, .code-block:hover .copy, .copy:focus-visible, .copy[data-copied] { opacity: 1; } +.copy:focus-visible, .copy[data-copied] { opacity: 1; } +@media (hover: hover) and (pointer: fine) { .sig:hover .copy, .code-block:hover .copy { opacity: 1; } } +.sig:active .copy, .code-block:active .copy { opacity: 1; } @media (hover: none) { .copy { opacity: 1; } } -.lineage { display: grid; gap: 4px; margin: 0 0 22px; font-size: var(--apidocs-size-sm); } +.lineage { display: grid; gap: 4px; margin-block: 0 22px; margin-inline: 0; font-size: var(--apidocs-size-sm); } .lineage > div { display: grid; grid-template-columns: 10rem minmax(0, 1fr); gap: 12px; } .lineage dt { color: var(--apidocs-muted); } .lineage dd { margin: 0; min-width: 0; } .chain, .inline-list { list-style: none; display: flex; flex-wrap: wrap; gap: 2px 8px; margin: 0; padding: 0; } -.chain li + li::before { content: "\203A"; margin-right: 8px; color: var(--apidocs-faint); } +.chain li + li::before { content: "\203A"; margin-inline-end: 8px; color: var(--apidocs-faint); } .inline-list li:not(:last-child)::after { content: ","; color: var(--apidocs-faint); } /* ---- Badges, deprecation and notes ---- */ @@ -544,7 +645,7 @@ a.tk-t:hover, a.tk-a:hover { text-decoration-color: currentColor; } .badge { display: inline-block; font-size: var(--apidocs-size-xs); line-height: 1.5; font-weight: 550; - padding: 0 7px; border-radius: 999px; + padding-block: 0; padding-inline: 7px; border-radius: 999px; border: 1px solid var(--apidocs-rule-strong); color: var(--apidocs-muted); white-space: nowrap; } @@ -559,7 +660,7 @@ a.tk-t:hover, a.tk-a:hover { text-decoration-color: currentColor; } --tone: var(--apidocs-note-api); --tone-soft: var(--apidocs-note-api-soft); display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 0 12px; align-items: start; - margin: 16px 0; padding: 12px 18px 13px 12px; + margin-block: 16px; margin-inline: 0; padding-block: 12px 13px; padding-inline: 12px 18px; background: var(--tone-soft); border: 1px solid color-mix(in srgb, var(--tone) 16%, transparent); border-radius: calc(var(--apidocs-radius) + 4px); @@ -578,8 +679,8 @@ a.tk-t:hover, a.tk-a:hover { text-decoration-color: currentColor; } } .callout-aside { font-weight: 450; } .callout-body > p:not(.callout-label) { margin: 0; } -.callout-body > p:not(.callout-label) + p { margin-top: 0.5em; } -.callout-body > :last-child { margin-bottom: 0; } +.callout-body > p:not(.callout-label) + p { margin-block-start: 0.5em; } +.callout-body > :last-child { margin-block-end: 0; } .callout-implSpec { --tone: var(--apidocs-note-spec); --tone-soft: var(--apidocs-note-spec-soft); } .callout-implNote { --tone: var(--apidocs-note-impl); --tone-soft: transparent; border-color: var(--apidocs-rule-strong); } .callout-implNote .callout-icon { background: var(--apidocs-subtle); } @@ -595,22 +696,22 @@ a.tk-t:hover, a.tk-a:hover { text-decoration-color: currentColor; } /* ---- Prose and documentation content ---- */ .prose { max-width: 46rem; } -.prose p, .member p { margin: 0.6em 0; } -.prose ul, .prose ol, .member ul, .member ol { padding-left: 1.4em; margin: 0.6em 0; } -.prose li + li, .member li + li { margin-top: 0.2em; } +.prose p, .member p { margin-block: 0.6em; margin-inline: 0; } +.prose ul, .prose ol, .member ul, .member ol { padding-inline-start: 1.4em; margin-block: 0.6em; margin-inline: 0; } +.prose li + li, .member li + li { margin-block-start: 0.2em; } /* Guide images keep their aspect ratio inside the column; task-list items show their check box instead of a bullet. */ .prose img, .member img { max-width: 100%; height: auto; } -.prose li:has(> p:first-child > .task-check:first-child) { list-style: none; margin-left: -1.4em; } -.task-check { margin: 0 0.45em 0 0; vertical-align: -0.1em; accent-color: var(--apidocs-accent); } -.doc-heading { margin: 1.4em 0 0.4em; font-size: var(--apidocs-size-lg); font-weight: 650; } -blockquote { margin: 0.8em 0; padding: 2px 16px; border-left: 3px solid var(--apidocs-rule-strong); color: var(--apidocs-muted); } +.prose li:has(> p:first-child > .task-check:first-child) { list-style: none; margin-inline-start: -1.4em; } +.task-check { margin-block: 0; margin-inline: 0 0.45em; vertical-align: -0.1em; accent-color: var(--apidocs-accent); } +.doc-heading { margin-block: 1.4em 0.4em; margin-inline: 0; font-size: var(--apidocs-size-lg); font-weight: 650; } +blockquote { margin-block: 0.8em; margin-inline: 0; padding-block: 2px; padding-inline: 16px; border-inline-start: 3px solid var(--apidocs-rule-strong); color: var(--apidocs-muted); } .undocumented { color: var(--apidocs-faint); font-style: italic; } .inherited-from, .overrides, .default-value { color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); } .raw sup, .raw sub { line-height: 0; } -.code-block { position: relative; margin: 0.9em 0; } +.code-block { position: relative; margin-block: 0.9em; margin-inline: 0; } .code-block pre { - margin: 0; padding: 12px 16px; + margin: 0; padding-block: 12px; padding-inline: 16px; background: var(--apidocs-code-bg); color: var(--apidocs-code-fg); border-radius: var(--apidocs-radius); overflow-x: auto; font-size: var(--apidocs-size-sm); line-height: 1.5; @@ -624,83 +725,92 @@ blockquote { margin: 0.8em 0; padding: 2px 16px; border-left: 3px solid var(--ap .hl-f { color: var(--apidocs-syn-function); } .hl-p { color: var(--apidocs-syn-param); } -.table-scroll { overflow-x: auto; margin: 0.8em 0; } +.table-scroll { overflow-x: auto; margin-block: 0.8em; margin-inline: 0; } table { border-collapse: collapse; width: 100%; font-size: var(--apidocs-size-sm); line-height: 1.5; } -caption { text-align: left; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); padding-bottom: 6px; } -th, td { text-align: left; vertical-align: top; padding: 7px 12px 7px 0; border-bottom: 1px solid var(--apidocs-rule); } -thead th { color: var(--apidocs-muted); font-weight: 600; font-size: var(--apidocs-size-sm); border-bottom-color: var(--apidocs-rule-strong); } -.doc-table td, .doc-table th { padding-left: 10px; } +caption { text-align: start; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); padding-block-end: 6px; } +th, td { text-align: start; vertical-align: top; padding-block: 7px; padding-inline: 0 12px; border-block-end: 1px solid var(--apidocs-rule); } +thead th { color: var(--apidocs-muted); font-weight: 600; font-size: var(--apidocs-size-sm); border-block-end-color: var(--apidocs-rule-strong); } +.doc-table td, .doc-table th { padding-inline-start: 10px; } /* ---- Guides: prose pages beside the reference ---- */ .guide-kicker { - margin: 0 0 6px; font-size: var(--apidocs-size-xs); font-weight: 650; letter-spacing: var(--apidocs-tracking-caps); + margin-block: 0 6px; margin-inline: 0; font-size: var(--apidocs-size-xs); font-weight: 650; letter-spacing: var(--apidocs-tracking-caps); text-transform: uppercase; color: var(--apidocs-accent); user-select: none; -webkit-user-select: none; } -.guide-head h1 { font-size: var(--apidocs-size-3xl); } -.guide-summary { margin: 10px 0 0; max-width: 44rem; } +.guide-head h1 { font-size: var(--apidocs-size-title); } +.guide-summary { margin-block: 10px 0; margin-inline: 0; max-width: 44rem; } .guide-body { max-width: 46rem; } -.guide-body > .guide-intro > :first-child { margin-top: 0; } -.guide-section { margin-top: 36px; } -.guide-heading { position: relative; scroll-margin-top: calc(var(--apidocs-topbar) + 16px); } -h2.guide-heading { font-size: var(--apidocs-size-xl); font-weight: 650; margin: 0 0 10px; padding-bottom: 8px; border-bottom: 1px solid var(--apidocs-rule); } -h3.guide-heading { font-size: var(--apidocs-size-lg); font-weight: 650; margin: 26px 0 6px; } +.guide-body > .guide-intro > :first-child { margin-block-start: 0; } +.guide-section { margin-block-start: 36px; } +.guide-heading { position: relative; scroll-margin-block-start: calc(var(--apidocs-topbar) + 16px); } +h2.guide-heading { font-size: var(--apidocs-size-xl); font-weight: 650; margin-block: 0 10px; margin-inline: 0; padding-block-end: 8px; border-block-end: 1px solid var(--apidocs-rule); } +h3.guide-heading { font-size: var(--apidocs-size-lg); font-weight: 650; margin-block: 26px 6px; margin-inline: 0; } /* The section link sits in the margin and shows when the heading is pointed at or the link has focus. */ .heading-anchor { - position: absolute; right: 100%; top: 0; padding-right: 8px; + position: absolute; inset-inline-end: 100%; inset-block-start: 0; padding-inline-end: 8px; color: var(--apidocs-faint); font-family: var(--apidocs-font-mono); font-weight: 400; opacity: 0; text-decoration: none !important; user-select: none; -webkit-user-select: none; } -.guide-heading:hover .heading-anchor, .heading-anchor:focus-visible { opacity: 1; } -.heading-anchor:hover { color: var(--apidocs-accent); } +.heading-anchor:focus-visible { opacity: 1; } +@media (hover: hover) and (pointer: fine) { .guide-heading:hover .heading-anchor { opacity: 1; } } +.guide-heading:active .heading-anchor { opacity: 1; } +@media (hover: hover) and (pointer: fine) { .heading-anchor:hover { color: var(--apidocs-accent); } } +.heading-anchor:active { color: var(--apidocs-accent); } .guide-heading:target { color: var(--apidocs-accent); } -@media (hover: none) { .heading-anchor { position: static; opacity: 1; padding: 0 0 0 8px; } } +@media (hover: none) { .heading-anchor { position: static; opacity: 1; padding-block: 0; padding-inline: 8px 0; } } /* Previous and next: two quiet cards at the foot of a guide. */ -.guide-pager { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 56px; max-width: 46rem; } +.guide-pager { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-block-start: 56px; max-width: 46rem; } .guide-pager-link { - display: grid; gap: 2px; padding: 12px 16px; + display: grid; gap: 2px; padding-block: 12px; padding-inline: 16px; border: 1px solid var(--apidocs-rule-strong); border-radius: calc(var(--apidocs-radius) + 4px); color: var(--apidocs-fg); } -.guide-pager-link:hover { border-color: var(--apidocs-accent); background: var(--apidocs-accent-soft); text-decoration: none; } -.guide-next { grid-column: 2; text-align: right; } +@media (hover: hover) and (pointer: fine) { .guide-pager-link:hover { border-color: var(--apidocs-accent); background: var(--apidocs-accent-soft); text-decoration: none; } } +.guide-pager-link:active { border-color: var(--apidocs-accent); background: var(--apidocs-accent-soft); text-decoration: none; } +.guide-next { grid-column: 2; text-align: end; } .guide-pager-dir { font-size: var(--apidocs-size-xs); color: var(--apidocs-faint); user-select: none; -webkit-user-select: none; } .guide-pager-title { font-weight: 600; } /* Guides on the overview: cards. */ -.guide-group-title { font-size: var(--apidocs-size-sm); font-weight: 600; margin: 20px 0 0; color: var(--apidocs-muted); } -.guide-cards { list-style: none; margin: 12px 0 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 12px; } +.guide-group-title { font-size: var(--apidocs-size-sm); font-weight: 600; margin-block: 20px 0; margin-inline: 0; color: var(--apidocs-muted); } +.guide-cards { list-style: none; margin-block: 12px 0; margin-inline: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 12px; } .guide-card { - position: relative; padding: 14px 16px 15px; + position: relative; padding-block: 14px 15px; padding-inline: 16px; border: 1px solid var(--apidocs-rule-strong); border-radius: calc(var(--apidocs-radius) + 4px); background: var(--apidocs-surface); } -.guide-card:hover, .guide-card:focus-within { border-color: var(--apidocs-accent); } +.guide-card:focus-within { border-color: var(--apidocs-accent); } +@media (hover: hover) and (pointer: fine) { .guide-card:hover { border-color: var(--apidocs-accent); } } +.guide-card:active { border-color: var(--apidocs-accent); } .guide-card-link { color: var(--apidocs-fg); font-weight: 600; text-decoration: none !important; } .guide-card-link::after { content: ""; position: absolute; inset: 0; border-radius: inherit; } -.guide-card-summary { margin: 4px 0 0; font-size: var(--apidocs-size-sm); line-height: 1.5; color: var(--apidocs-muted); } +.guide-card-summary { margin-block: 4px 0; margin-inline: 0; font-size: var(--apidocs-size-sm); line-height: 1.5; color: var(--apidocs-muted); } /* How far through a guide the reader is: a hairline under the top bar, driven by scrolling alone. */ .readbar { display: none; } @supports (animation-timeline: scroll()) { .readbar { - display: block; position: fixed; z-index: 11; left: 0; right: 0; top: var(--apidocs-topbar); height: 2px; + display: block; position: fixed; z-index: 11; inset-inline-start: 0; inset-inline-end: 0; inset-block-start: var(--apidocs-topbar); height: 2px; background: var(--apidocs-accent); transform-origin: 0 50%; transform: scaleX(0); pointer-events: none; - animation: apidocs-read linear both; animation-timeline: scroll(root block); } + .readbar:dir(rtl) { transform-origin: 100% 50%; } + /* Driven by scrolling, not by time; reduced motion hides the bar. */ + @media (prefers-reduced-motion: no-preference) { .readbar { animation: apidocs-read linear both; animation-timeline: scroll(root block); } } } @keyframes apidocs-read { to { transform: scaleX(1); } } /* ---- Index pages ---- */ -.letter-bar { display: flex; flex-wrap: wrap; gap: 2px; margin: 18px 0 4px; font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-sm); user-select: none; -webkit-user-select: none; } +.letter-bar { display: flex; flex-wrap: wrap; gap: 2px; margin-block: 18px 4px; margin-inline: 0; font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-sm); user-select: none; -webkit-user-select: none; } .letter-bar a { display: grid; place-items: center; min-width: 28px; height: 28px; border-radius: var(--apidocs-radius); color: var(--apidocs-muted); } -.letter-bar a:hover { color: var(--apidocs-accent); background: var(--apidocs-accent-soft); text-decoration: none; } -.index-letter { margin-top: 28px; } -.index-letter > h2 { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-xl); padding-bottom: 6px; border-bottom: 1px solid var(--apidocs-rule-strong); } +@media (hover: hover) and (pointer: fine) { .letter-bar a:hover { color: var(--apidocs-accent); background: var(--apidocs-accent-soft); text-decoration: none; } } +.letter-bar a:active { color: var(--apidocs-accent); background: var(--apidocs-accent-soft); text-decoration: none; } +.index-letter { margin-block-start: 28px; } +.index-letter > h2 { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-xl); padding-block-end: 6px; border-block-end: 1px solid var(--apidocs-rule-strong); } .index-list { list-style: none; margin: 0; padding: 0; font-size: var(--apidocs-size-sm); line-height: 1.5; } -.index-entry { display: grid; grid-template-columns: minmax(0, 30%) minmax(0, 22%) minmax(0, 1fr); gap: 0 16px; align-items: baseline; padding: 7px 0; border-bottom: 1px solid var(--apidocs-rule); } +.index-entry { display: grid; grid-template-columns: minmax(0, 30%) minmax(0, 22%) minmax(0, 1fr); gap: 0 16px; align-items: baseline; padding-block: 7px; padding-inline: 0; border-block-end: 1px solid var(--apidocs-rule); } .index-name { font-family: var(--apidocs-font-mono); font-weight: 600; overflow-wrap: anywhere; } .index-where { color: var(--apidocs-muted); overflow-wrap: anywhere; } .index-summary { color: var(--apidocs-muted); } @@ -708,89 +818,108 @@ h3.guide-heading { font-size: var(--apidocs-size-lg); font-weight: 650; margin: /* ---- Sections, summaries and members ---- */ -.section { margin-top: 40px; } +.section { margin-block-start: 40px; } .section > h2 { font-size: var(--apidocs-size-xl); font-weight: 650; - padding-bottom: 8px; border-bottom: 1px solid var(--apidocs-rule-strong); - margin-bottom: 8px; + padding-block-end: 8px; border-block-end: 1px solid var(--apidocs-rule-strong); + margin-block-end: 8px; } -.section-tight { margin-top: 12px; } -.summary-group h3, .type-index h3, .inherited h3 { font-size: var(--apidocs-size-md); font-weight: 600; margin: 22px 0 2px; color: var(--apidocs-fg); } +.section-tight { margin-block-start: 12px; } +.summary-group h3, .type-index h3, .inherited h3 { font-size: var(--apidocs-size-md); font-weight: 600; margin-block: 22px 2px; margin-inline: 0; color: var(--apidocs-fg); } .type-index h3 code { background: none; padding: 0; } -table.summary th[scope="row"] { font-weight: 400; width: 44%; padding-right: 20px; } -table.summary tbody tr:hover { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } +table.summary th[scope="row"] { font-weight: 400; width: 44%; padding-inline-end: 20px; } +@media (hover: hover) and (pointer: fine) { table.summary tbody tr:hover { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } } +table.summary tbody tr:active { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } .summary-sig { background: none !important; padding: 0 !important; font-size: var(--apidocs-size-sm); overflow-wrap: anywhere; } .summary-sig a { font-weight: 650; } .type-link { display: inline-flex; align-items: center; gap: 8px; } .type-link code { background: none !important; padding: 0 !important; font-weight: 600; } .kind-cell { color: var(--apidocs-muted); white-space: nowrap; } tr.is-deprecated .summary-sig a { text-decoration: line-through; text-decoration-color: var(--apidocs-deprecated); } -td .badge { margin-right: 6px; } +td .badge { margin-inline-end: 6px; } /* A member is a disclosure: a row when closed, the full entry when open. Rows far from the viewport are not laid out or painted until they come near; find-in-page still searches them and opens the one it matches. */ .members-heading { display: flex; align-items: baseline; gap: 10px; } .members-count { font-size: var(--apidocs-size-sm); font-weight: 400; color: var(--apidocs-faint); user-select: none; -webkit-user-select: none; } .members-toggle { - margin-left: auto; font: inherit; font-size: var(--apidocs-size-xs); font-weight: 400; color: var(--apidocs-muted); - background: none; border: 0; padding: 2px 4px; border-radius: 4px; cursor: pointer; user-select: none; -webkit-user-select: none; + margin-inline-start: auto; font: inherit; font-size: var(--apidocs-size-xs); font-weight: 400; color: var(--apidocs-muted); + background: none; border: 0; padding-block: 2px; padding-inline: 4px; border-radius: 4px; cursor: pointer; user-select: none; -webkit-user-select: none; } -.members-toggle:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); } -.members > .member { border-bottom: 1px solid var(--apidocs-rule); content-visibility: auto; contain-intrinsic-size: auto 41px; } +@media (hover: hover) and (pointer: fine) { .members-toggle:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); } } +.members-toggle:active { color: var(--apidocs-fg); background: var(--apidocs-subtle); } +.members > .member { border-block-end: 1px solid var(--apidocs-rule); content-visibility: auto; contain-intrinsic-size: auto 41px; } /* A group's first rows can be in the first viewport, where a placeholder that differs from the real row by a few pixels would shift everything below it once the row is laid out: those render as usual. 24 rows fill any screen. */ .members > .member:nth-of-type(-n+24) { content-visibility: visible; } .member-row { display: grid; grid-template-columns: 12px minmax(0, 46%) minmax(0, 1fr) auto; gap: 0 12px; align-items: baseline; - padding: 9px 4px 9px 0; cursor: pointer; list-style: none; + padding-block: 9px; padding-inline: 0 4px; cursor: pointer; list-style: none; font-size: var(--apidocs-size-sm); line-height: 1.5; } .member-row::-webkit-details-marker { display: none; } -.member-row:hover { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } +@media (hover: hover) and (pointer: fine) { .member-row:hover { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } } +.member-row:active { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } .member-chevron { align-self: center; color: var(--apidocs-faint); } .member[open] > .member-row .member-chevron { transform: rotate(90deg); } +/* Right to left, a closed row points to the start of the line. */ +.member:not([open]) > .member-row .member-chevron:dir(rtl) { scale: -1 1; } .member[open] > .member-row { background: color-mix(in srgb, var(--apidocs-subtle) 60%, transparent); } .member[open] > .member-row .member-brief { visibility: hidden; } .member-sig { min-width: 0; } +.member-brief[data-brief]::before { content: attr(data-brief); } +/* good-css exception (overflow-clip): hidden, not clip: WebKit clamps lines with -webkit-line-clamp only under overflow: hidden. */ .member-brief { min-width: 0; color: var(--apidocs-muted); display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; } .member-marks { display: flex; align-items: center; gap: 8px; user-select: none; -webkit-user-select: none; } +/* A narrow page has no room for the signature and the sentence side by side: the sentence goes under the + signature, which then has the full line and breaks between words. */ +@media (max-width: 640px) { + .member-row { grid-template-columns: 12px minmax(0, 1fr) auto; grid-template-areas: "chevron sig marks" ". brief brief"; row-gap: 2px; } + .member-chevron { grid-area: chevron; align-self: start; margin-block-start: 5px; } + .member-sig { grid-area: sig; } + .member-marks { grid-area: marks; } + .member-brief { grid-area: brief; } + .member-sig .summary-sig { overflow-wrap: break-word; } + .member[open] > .member-row .member-brief { display: none; } +} .member-noted { display: inline-grid; color: var(--apidocs-note-api); } .member-noted svg { fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; } .member-key { font-weight: 650; color: var(--apidocs-link); } .member.is-deprecated .member-key { text-decoration: line-through; text-decoration-color: var(--apidocs-deprecated); } -.member-body { padding: 14px 0 22px 24px; } +.member-body { padding-block: 14px 22px; padding-inline: 24px 0; } /* Opening fades the entry in: opacity only, so nothing is laid out twice. */ -.member::details-content { opacity: 1; transition: opacity 140ms ease-out; } +.member::details-content { opacity: 1; } +@media (prefers-reduced-motion: no-preference) { .member::details-content { transition: opacity 140ms ease-out; } } @starting-style { .member[open]::details-content { opacity: 0; } } .member-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 12px; } .member-name { font-family: var(--apidocs-font-mono); font-size: var(--apidocs-size-lg); font-weight: 700; overflow-wrap: anywhere; } .member-name .anchor { color: var(--apidocs-fg); } .member-badges { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } .source-link { font-size: var(--apidocs-size-sm); color: var(--apidocs-faint); } -.member .prose { margin-top: 2px; } +.member .prose { margin-block-start: 2px; } -.facts { margin: 14px 0 0; } -.facts-title, .see .facts-title { font-family: var(--apidocs-font-sans); font-size: var(--apidocs-size-sm); font-weight: 650; color: var(--apidocs-muted); margin: 0 0 2px; } +.facts { margin-block: 14px 0; margin-inline: 0; } +.facts-title, .see .facts-title { font-family: var(--apidocs-font-sans); font-size: var(--apidocs-size-sm); font-weight: 650; color: var(--apidocs-muted); margin-block: 0 2px; margin-inline: 0; } .facts-list { margin: 0; } .fact { display: grid; grid-template-columns: minmax(9rem, 18rem) minmax(0, 1fr); gap: 2px 20px; - padding: 6px 0; border-top: 1px solid var(--apidocs-rule); + padding-block: 6px; padding-inline: 0; border-block-start: 1px solid var(--apidocs-rule); font-size: var(--apidocs-size-md); } -.fact:first-child { border-top: 0; } +.fact:first-child { border-block-start: 0; } .fact dt { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; min-width: 0; } .fact dd { margin: 0; min-width: 0; } -.fact dd p { margin: 0 0 0.4em; } +.fact dd p { margin-block: 0 0.4em; margin-inline: 0; } .fact-name { background: none !important; padding: 0 !important; font-weight: 700; } .fact-type { background: none !important; padding: 0 !important; color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); } .fact:target { background: var(--apidocs-accent-soft); } -.see { margin-top: 14px; } -.see-list { margin: 0; padding-left: 1.2em; } +.see { margin-block-start: 14px; } +.see-list { margin: 0; padding-inline-start: 1.2em; } -.inherited-list { margin: 2px 0 0; line-height: 1.9; font-size: var(--apidocs-size-sm); } +.inherited-list { margin-block: 2px 0; margin-inline: 0; line-height: 1.9; font-size: var(--apidocs-size-sm); } .member-head:target .member-name .anchor { color: var(--apidocs-accent); } -.member-head { scroll-margin-top: calc(var(--apidocs-topbar) + 56px); } +.member-head { scroll-margin-block-start: calc(var(--apidocs-topbar) + 56px); } /* ---- Small screens ---- */ @@ -799,24 +928,41 @@ td .badge { margin-right: 6px; } .toc, .toc-spacer { display: none; } } @media (max-width: 860px) { - html { font-size: 15px; } .layout { grid-template-columns: minmax(0, 1fr); } + /* The drawer fills the space under the bar and scrolls. Stretch, not the wide layout's start: an absolutely + positioned box aligned to the start takes its content's height and, taller than the screen, is moved up behind + the bar, where it cannot scroll. */ .sidebar { - display: none; position: fixed; z-index: 9; inset: var(--apidocs-topbar) 0 0 0; height: auto; - background: var(--apidocs-bg); border-right: 0; padding: 14px 12px 40px; + display: none; position: fixed; z-index: 9; inset-block: var(--apidocs-topbar) 0; inset-inline: 0; height: auto; align-self: stretch; + background: var(--apidocs-bg); border-inline-end: 0; + /* good-css exception (fluid-clamp): a layout, not a size step: the drawer's own padding, over the page. */ + padding-block: 14px 40px; padding-inline: 12px; } body:has(.nav-toggle:checked) .layout .sidebar { display: block; } - .content { padding: 18px 16px 72px; } - .topbar { padding: 0 12px; gap: 10px; } .module-version { display: none; } - .search input { width: 100%; max-width: 52vw; } - .page-head h1 { font-size: var(--apidocs-size-2xl); } - .sig-large pre { font-size: var(--apidocs-size-sm); padding: 14px 16px; } + /* The drawer lists the sites, so the switcher shows its row when it fits and leaves the bar when it does not. Once + it has left (or where there is none), the search field may narrow further, to 5rem. The tools' floor is then the + search field's narrowest, the theme switch and the gaps, not the switcher's labels. */ + .topbar-tools { min-width: calc(5rem + 32px + 2 * var(--apidocs-tools-gap)); } + /* good-css exception (fluid-clamp): a layout, not a size step: the switcher sits beside the search field here. */ + .suites { min-width: 0; margin-inline-start: 0; overflow: clip; } + .suite-menu, .suites-floor { display: none; } + .topbar-tools:not(:has(> .suites:not([data-fit="none"]))) .search { min-width: 5rem; } + .search-key { display: none; } + /* good-css exception (fluid-clamp): a layout, not a size step: no keyboard hint to leave room for. */ + .search input { padding-inline-end: 10px; } + /* good-css exception (fluid-clamp): a layout, not a size step: the sites are the drawer's first block. */ + .nav-suites { display: block; margin-block-end: 14px; } + /* good-css exception (fluid-clamp): see above. */ + .nav-suites + .nav-filter { margin-block-start: 0; } + /* good-css exception (fluid-clamp): a layout, not a size step: one column, so no gap between name and text. */ .lineage > div, .fact { grid-template-columns: minmax(0, 1fr); gap: 0; } table.summary th[scope="row"] { width: auto; } table.summary, table.summary tbody, table.summary tr, table.summary th, table.summary td { display: block; } table.summary thead { display: none; } - table.summary tr { padding: 8px 0; border-bottom: 1px solid var(--apidocs-rule); } + /* good-css exception (fluid-clamp): a layout, not a size step: the summary table's rows become blocks. */ + table.summary tr { padding-block: 8px; padding-inline: 0; border-block-end: 1px solid var(--apidocs-rule); } + /* good-css exception (fluid-clamp): see above. */ table.summary th, table.summary td { border: 0; padding: 0; } } @@ -827,7 +973,7 @@ td .badge { margin-right: 6px; } .layout { display: block; } .content { padding: 0; } .content > * { max-width: none; } - .sig pre, .code-block pre { white-space: pre-wrap; border: 1px solid #ccc; } + .sig pre, .code-block pre { white-space: pre-wrap; border: 1px solid oklch(84.522% 0 none); } .member::details-content { content-visibility: visible; display: block; } .members-toggle, .member-chevron { display: none; } .member { break-inside: avoid-page; } @@ -838,17 +984,21 @@ td .badge { margin-right: 6px; } arrives finishes it and lets it fade. The content cross-fades and rises a few pixels; the top bar and the navigator do not move. Only transform and opacity animate, so nothing is laid out again. */ .loadbar { - position: fixed; inset: 0 0 auto 0; height: 2px; z-index: 30; pointer-events: none; + position: fixed; inset-block: 0 auto; inset-inline: 0; height: 2px; z-index: 30; pointer-events: none; transform: translateX(-101%); opacity: 0; background: linear-gradient(90deg, transparent 0%, var(--apidocs-loadbar-tail, var(--apidocs-accent)) 55%, var(--apidocs-loadbar-head, var(--apidocs-accent)) 100%); } .loadbar::after { - content: ""; position: absolute; right: 0; top: -2px; width: 96px; height: 6px; border-radius: 3px; + content: ""; position: absolute; inset-inline-end: 0; inset-block-start: -2px; width: 96px; height: 6px; border-radius: 3px; background: linear-gradient(90deg, transparent, var(--apidocs-loadbar-head, var(--apidocs-accent))); filter: blur(3px); opacity: 0.9; } @media (prefers-reduced-motion: no-preference) { + /* good-css exception (motion-properties): the load bar shows progress, not a change of state. It eases out over 6s + so a slow page still shows movement, and the arriving page finishes it in 420ms: both longer than a 300ms UI + transition on purpose. */ html[data-leaving] .loadbar { opacity: 1; animation: apidocs-leave 6s cubic-bezier(0.08, 0.82, 0.17, 1) forwards; } + /* good-css exception (motion-properties): see above. */ html[data-arriving] .loadbar { animation: apidocs-arrive 420ms ease-out both; } } @keyframes apidocs-leave { from { transform: translateX(-101%); } to { transform: translateX(-12%); } } @@ -858,7 +1008,8 @@ td .badge { margin-right: 6px; } 100% { transform: translateX(0); opacity: 0; } } -@view-transition { navigation: auto; } +/* Cross-document transitions only where motion is welcome; with reduced motion a page simply loads. */ +@media (prefers-reduced-motion: no-preference) { @view-transition { navigation: auto; } } .topbar { view-transition-name: apidocs-topbar; } .sidebar { view-transition-name: apidocs-sidebar; } .content { view-transition-name: apidocs-content; } @@ -867,8 +1018,10 @@ td .badge { margin-right: 6px; } ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 120ms; } ::view-transition-old(apidocs-topbar), ::view-transition-old(apidocs-sidebar), ::view-transition-old(apidocs-loadbar) { display: none; } ::view-transition-new(apidocs-topbar), ::view-transition-new(apidocs-sidebar), ::view-transition-new(apidocs-loadbar) { animation: none; } -::view-transition-old(apidocs-content) { animation: apidocs-out 90ms ease-out both; } -::view-transition-new(apidocs-content) { animation: apidocs-in 180ms 40ms ease-out both; } +@media (prefers-reduced-motion: no-preference) { + ::view-transition-old(apidocs-content) { animation: apidocs-out 90ms ease-out both; } + ::view-transition-new(apidocs-content) { animation: apidocs-in 180ms 40ms ease-out both; } +} @keyframes apidocs-out { to { opacity: 0; } } @keyframes apidocs-in { from { opacity: 0; transform: translateY(6px); } } diff --git a/packages/apidocs/src/theme.ts b/packages/apidocs/src/theme.ts index 60e5e83..e1a0ed0 100644 --- a/packages/apidocs/src/theme.ts +++ b/packages/apidocs/src/theme.ts @@ -11,6 +11,13 @@ import type { SymbolMode } from "./symbols"; export interface ThemeLink { label: string; url: string; + /** + * In `links.header`: this entry is the site being rendered. Header links are the sibling documentation sites + * (a user guide, a developer guide, the API reference), shown as a switcher with the current one marked. When no + * entry sets it, the renderer marks the entry whose URL is this site's own root: "", "./", "index.html", or the + * theme's baseUrl. + */ + current?: boolean; } export interface FontFace { @@ -24,6 +31,19 @@ export interface FontFace { preload?: boolean; } +/** An image for link previews (Open Graph and Twitter cards). */ +export interface SocialImage { + /** A PNG or JPEG below the renderer's assets directory (social/elide.png), copied into the site's assets/. */ + asset?: string; + /** Or the image's absolute URL, used as given. */ + url?: string; + /** In pixels; Open Graph expects 1200 by 630. */ + width: number; + height: number; + /** What the image shows, for readers who cannot see it. */ + alt: string; +} + export interface Theme { /** A preset to start from. */ extends?: "neutral" | "elide"; @@ -39,6 +59,10 @@ export interface Theme { tokens?: { light?: Record<string, string>; dark?: Record<string, string> }; /** Font files the pages load. Families are set through the font-* tokens. */ fonts?: FontFace[]; + /** + * `header`: the sibling documentation sites, as a switcher in the top bar (see ThemeLink.current); other links, + * such as a repository, belong in `footer`. Relative URLs in both are resolved from the site's root. + */ links?: { header?: ThemeLink[]; footer?: ThemeLink[] }; /** Text at the foot of every page, such as a copyright line. */ footer?: string; @@ -55,11 +79,34 @@ export interface Theme { symbols?: SymbolMode; /** Whether a member's full documentation starts folded under its summary row ("collapsed", the default) or open. */ memberDetails?: "collapsed" | "expanded"; + /** + * The image link previews show. With one, pages carry og:image and a large Twitter card; without, neither. Both + * presets have one; null leaves the preset's out. + */ + socialImage?: SocialImage | null; + /** + * When the pages were built or last changed, as a W3C date (2026-11-21) or date-time: sitemap.xml's lastmod. + * The renderer never reads the clock; without this, the sitemap has no lastmod. + */ + lastModified?: string; + /** + * The text of llms.txt's "When to use this" section, Markdown, for an agent deciding whether to read on. Defaults + * to a sentence built from the module's name, version and description. + */ + whenToUse?: string; /** Extra CSS appended to the theme stylesheet. */ css?: string; } -export const neutral: Theme = { name: "neutral" }; +/** The neutral preset's favicon: braces on the default accent, so a browser asking for /favicon.ico finds an icon. */ +const NEUTRAL_FAVICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0f6e7a"/><path d="M13 8.5c-2.4 0-3 1-3 3V14c0 1.3-.7 2-2 2 1.3 0 2 .7 2 2v2.5c0 2 .6 3 3 3M19 8.5c2.4 0 3 1 3 3V14c0 1.3.7 2 2 2-1.3 0-2 .7-2 2v2.5c0 2-.6 3-3 3" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>'; + +export const neutral: Theme = { + name: "neutral", + favicon: NEUTRAL_FAVICON, + // The favicon's mark on the page color, 1200 by 630 (scripts/gen-social.ts). + socialImage: { asset: "social/neutral.png", width: 1200, height: 630, alt: "A pair of braces on a teal square" }, +}; const presets: Record<string, Theme> = { neutral, elide }; @@ -81,6 +128,7 @@ export function resolveTheme(input: Theme | undefined): Theme { header: theme.links?.header ?? base.links?.header, footer: theme.links?.footer ?? base.links?.footer, }, + socialImage: theme.socialImage === null ? undefined : (theme.socialImage ?? base.socialImage), css: [base.css, theme.css].filter(Boolean).join("\n") || undefined, }; } diff --git a/packages/apidocs/test/__snapshots__/import.test.ts.snap b/packages/apidocs/test/__snapshots__/import.test.ts.snap index 6d7ef11..b5dc54f 100644 --- a/packages/apidocs/test/__snapshots__/import.test.ts.snap +++ b/packages/apidocs/test/__snapshots__/import.test.ts.snap @@ -1,7 +1,17 @@ // Bun Snapshot v1, https://bun.sh/docs/test/snapshots exports[`guides-only site snapshots: index.md 1`] = ` -"# ⬢ Geo user guide +"--- +title: "Geo user guide" +description: "Measure and draw shapes with the Geo library, from installation to custom shapes." +kind: "module" +id: "guide:geo/index" +module: "Geo user guide" +version: "2.1.0" +canonical: "https://docs.example.com/geo/index.html" +--- + +# ⬢ Geo user guide Every page: [llms.txt](llms.txt), or all in one file: [llms-full.txt](llms-full.txt) @@ -36,7 +46,17 @@ Next: [Getting started](guides/getting-started.md) `; exports[`guides-only site snapshots: guides/getting-started.md 1`] = ` -"# ¶ Getting started +"--- +title: "Getting started" +description: "Install Geo, then measure your first shape." +kind: "guide" +id: "guide:geo/getting-started" +module: "Geo user guide" +version: "2.1.0" +canonical: "https://docs.example.com/geo/guides/getting-started.html" +--- + +# ¶ Getting started [Geo user guide](../index.md) · Every page: [llms.txt](../llms.txt) @@ -93,7 +113,17 @@ Next: [Concepts](concepts/index.md) `; exports[`guides-only site snapshots: guides/concepts/alerts.md 1`] = ` -"# ¶ Callouts +"--- +title: "Callouts" +description: "The five GitHub alerts, an explicit heading id and raw HTML." +kind: "guide" +id: "guide:geo/concepts/alerts" +module: "Geo user guide" +version: "2.1.0" +canonical: "https://docs.example.com/geo/guides/concepts/alerts.html" +--- + +# ¶ Callouts [Geo user guide](../../index.md) › [Concepts](index.md) · Every page: [llms.txt](../../llms.txt) @@ -140,7 +170,17 @@ Next: [Pictures](images.md) `; exports[`guides-only site snapshots: guides/concepts/images.md 1`] = ` -"# ¶ Pictures +"--- +title: "Pictures" +description: "Diagrams and screenshots, with their sizes known before they load." +kind: "guide" +id: "guide:geo/concepts/images" +module: "Geo user guide" +version: "2.1.0" +canonical: "https://docs.example.com/geo/guides/concepts/images.html" +--- + +# ¶ Pictures [Geo user guide](../../index.md) › [Concepts](index.md) · Every page: [llms.txt](../../llms.txt) @@ -165,7 +205,7 @@ Next: [Advanced topics](advanced/index.md) exports[`guides-only site snapshots: guides/concepts/alerts.html 1`] = ` "<!doctype html> -<html lang="en" data-root="../../"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>Callouts (Geo user guide 2.1.0)
Geo user guide2.1.0

Concepts

Callouts

The five GitHub alerts, an explicit heading id and raw HTML.

Before you start

Note

Measurements are exact for circles and polygons.

Tip

Reuse a Shapes.Builder to build many shapes.

Important

Shapes are immutable: every transform returns a new shape.

Warning

A polygon whose edges cross has no defined area.

Caution

Shapes.parse reads untrusted text: limit its input size.

It allocates one object per vertex.

A plain quote

Geometry is the art of correct reasoning from incorrectly drawn figures.

Raw HTML

Press Ctrl+C to copy. Water is H2O, and E = mc2.

+Callouts (Geo user guide 2.1.0)
Geo user guide2.1.0

Concepts

Callouts

The five GitHub alerts, an explicit heading id and raw HTML.

Before you start

Note

Measurements are exact for circles and polygons.

Tip

Reuse a Shapes.Builder to build many shapes.

Important

Shapes are immutable: every transform returns a new shape.

Warning

A polygon whose edges cross has no defined area.

Caution

Shapes.parse reads untrusted text: limit its input size.

It allocates one object per vertex.

A plain quote

Geometry is the art of correct reasoning from incorrectly drawn figures.

Raw HTML

Press Ctrl+C to copy. Water is H2O, and E = mc2.

Area
The size of the inside.

Back to the concepts.

diff --git a/packages/apidocs/test/__snapshots__/indexes.test.ts.snap b/packages/apidocs/test/__snapshots__/indexes.test.ts.snap index 4c61d64..30f382d 100644 --- a/packages/apidocs/test/__snapshots__/indexes.test.ts.snap +++ b/packages/apidocs/test/__snapshots__/indexes.test.ts.snap @@ -1,7 +1,15 @@ // Bun Snapshot v1, https://bun.sh/docs/test/snapshots exports[`index pages Markdown snapshots of the fixture's index pages: packages.md 1`] = ` -"# Packages +"--- +title: "Packages" +description: "Packages: every package with its summary and type counts." +kind: "index" +module: "fixture" +version: "1.0" +--- + +# Packages Every package of fixture. @@ -11,7 +19,15 @@ Every package of fixture. `; exports[`index pages Markdown snapshots of the fixture's index pages: types.md 1`] = ` -"# All types +"--- +title: "All types" +description: "All types: every type, nested ones too, by name." +kind: "index" +module: "fixture" +version: "1.0" +--- + +# All types Every type of fixture, nested ones too, by name. @@ -37,7 +53,15 @@ Every type of fixture, nested ones too, by name. `; exports[`index pages Markdown snapshots of the fixture's index pages: index-all.md 1`] = ` -"# Index +"--- +title: "Index" +description: "Index: every declaration from A to Z." +kind: "index" +module: "fixture" +version: "1.0" +--- + +# Index Every declaration of fixture, from A to Z. @@ -195,7 +219,15 @@ Every declaration of fixture, from A to Z. `; exports[`index pages Markdown snapshots of the fixture's index pages: deprecated.md 1`] = ` -"# Deprecated +"--- +title: "Deprecated" +description: "Deprecated: everything deprecated, for removal first." +kind: "index" +module: "fixture" +version: "1.0" +--- + +# Deprecated Everything deprecated in fixture; what will be removed comes first. diff --git a/packages/apidocs/test/__snapshots__/markdown.test.ts.snap b/packages/apidocs/test/__snapshots__/markdown.test.ts.snap index 7db7955..2f49107 100644 --- a/packages/apidocs/test/__snapshots__/markdown.test.ts.snap +++ b/packages/apidocs/test/__snapshots__/markdown.test.ts.snap @@ -1,7 +1,16 @@ // Bun Snapshot v1, https://bun.sh/docs/test/snapshots exports[`Markdown snapshots of the fixture: fixture/java/Geometry.md 1`] = ` -"# Geometry +"--- +title: "Geometry" +description: "Operations on shapes." +kind: "class" +id: "fixture.java.Geometry" +module: "fixture" +version: "1.0" +--- + +# Geometry [fixture](../../index.md) › [fixture.java](index.md) · Every page: [llms.txt](../../llms.txt) @@ -189,7 +198,16 @@ Finds a shape by name. `; exports[`Markdown snapshots of the fixture: fixture/java/Circle.md 1`] = ` -"# Circle +"--- +title: "Circle" +description: "A circle." +kind: "record" +id: "fixture.java.Circle" +module: "fixture" +version: "1.0" +--- + +# Circle [fixture](../../index.md) › [fixture.java](index.md) · Every page: [llms.txt](../../llms.txt) @@ -351,7 +369,16 @@ public @Nullable String label() `; exports[`Markdown snapshots of the fixture: fixture/java/io/ShapeReader.md 1`] = ` -"# ShapeReader +"--- +title: "ShapeReader" +description: "Reads shapes in their text form, one per line." +kind: "class" +id: "fixture.java.io.ShapeReader" +module: "fixture" +version: "1.0" +--- + +# ShapeReader [fixture](../../../index.md) › [fixture.java.io](index.md) · Every page: [llms.txt](../../../llms.txt) @@ -447,7 +474,14 @@ Overrides [\`close()\`](https://docs.oracle.com/en/java/javase/25/docs/api/java. `; exports[`Markdown snapshots of the fixture: index.md 1`] = ` -"# fixture 1.0 +"--- +title: "fixture" +kind: "module" +module: "fixture" +version: "1.0" +--- + +# fixture 1.0 Every page: [llms.txt](llms.txt), or all in one file: [llms-full.txt](llms-full.txt) @@ -491,6 +525,10 @@ exports[`Markdown snapshots of the fixture: llms.txt 1`] = ` Each page below is Markdown; the HTML page of the same name has the same content. llms-full.txt has every page in one file, and api.json is the apidocs/1 model. +## When to use this + +Use this API reference when you write, read or review code that uses fixture 1.0. + ## Overview - [fixture](index.md): packages and types diff --git a/packages/apidocs/test/__snapshots__/narrative.test.ts.snap b/packages/apidocs/test/__snapshots__/narrative.test.ts.snap index 5d4176c..ee691e4 100644 --- a/packages/apidocs/test/__snapshots__/narrative.test.ts.snap +++ b/packages/apidocs/test/__snapshots__/narrative.test.ts.snap @@ -1,7 +1,17 @@ // Bun Snapshot v1, https://bun.sh/docs/test/snapshots exports[`outputs guide page snapshots, HTML and Markdown: guides/concepts.md 1`] = ` -"# ¶ Concepts +"--- +title: "Concepts" +description: "Shapes, measuring and units: the ideas the reference pages assume." +kind: "guide" +id: "guide:concepts" +module: "geo" +version: "2.1.0" +canonical: "https://docs.example.com/guides/concepts.html" +--- + +# ¶ Concepts [geo](../index.md) › Guides · Every page: [llms.txt](../llms.txt) @@ -112,7 +122,17 @@ Next: [Migrating from 1.x](migrating-from-1x.md) `; exports[`outputs guide page snapshots, HTML and Markdown: guides/advanced/text-format.md 1`] = ` -"# ¶ The text format +"--- +title: "The text format" +description: "The grammar Shapes.parse reads, and how to read files of shapes." +kind: "guide" +id: "guide:advanced/text-format" +module: "geo" +version: "2.1.0" +canonical: "https://docs.example.com/guides/advanced/text-format.html" +--- + +# ¶ The text format [geo](../../index.md) › Advanced · Every page: [llms.txt](../../llms.txt) @@ -152,7 +172,7 @@ Previous: [Custom shapes](custom-shapes.md) exports[`outputs guide page snapshots, HTML and Markdown: guides/getting-started.html 1`] = ` " -Getting started (geo 2.1.0)
geo2.1.0
All types

Guide

Getting started

Add geo to a build and measure a first shape.

geo measures plane shapes: circles, polygons and shapes you build from them. This guide adds it to a build and runs a first program.

Install

geo needs Java 21 or later. With Gradle, add the dependency to build.gradle.kts:

dependencies {
+Getting started (geo 2.1.0)
geo2.1.0
All types

Guide

Getting started

Add geo to a build and measure a first shape.

geo measures plane shapes: circles, polygons and shapes you build from them. This guide adds it to a build and runs a first program.

Install

geo needs Java 21 or later. With Gradle, add the dependency to build.gradle.kts:

dependencies {
     implementation("com.example:geo:2.1.0")
 }

With Maven, add it to pom.xml:

<dependency>
   <groupId>com.example</groupId>
diff --git a/packages/apidocs/test/__snapshots__/render.test.ts.snap b/packages/apidocs/test/__snapshots__/render.test.ts.snap
index 02fa105..269ffd9 100644
--- a/packages/apidocs/test/__snapshots__/render.test.ts.snap
+++ b/packages/apidocs/test/__snapshots__/render.test.ts.snap
@@ -2,12 +2,12 @@
 
 exports[`render HTML snapshots: fixture/java/Geometry.html 1`] = `
 "
-Geometry (fixture 1.0)
fixture1.0
All types

Geometry

Javaclassin fixture.javasince 1.0null-marked

public final class Geometry
Inheritance
  1. Object
  2. Geometry

Operations on shapes.

Every method is pure: it never modifies its arguments. Thread safety: every method is safe to call concurrently.

  1. First, measure.

  2. Then compare, with compareTo.

Unit factors
UnitFactor
Units.METERS1.0
Units.FEET0.3048
Shape big = Geometry.largest(List.of(Circle.of(1), Rect.square(2)));
-double total = Geometry.totalArea(big, Circle.of(3));

Measure twice, cut once.

Edge cases

Text with an entity — a superscript kept as raw markup, a line
break, a hyperlink, and <angle brackets> as literal text.

Implementation note

Areas are computed in double precision.

See also

Nested types

NameKindDescription
LegacyclassMethods from before null markings; their nullness is unspecified.

Fields2

static int PRECISIONThe default number of significant digits: 6.

PRECISION

static
public static final int PRECISION

The default number of significant digits: 6.

Value

int
Constant: 6
static String NAMEThe library's name, "fixture", as tools report it.

NAME

static
public static final String NAME

The library's name, "fixture", as tools report it.

Value

Stringnon-null
Constant: "fixture"

Methods5

static T largest(Collection)Returns the largest shape.

largest

static
public static <T extends Shape & Comparable<? super T>> T largest(
+Geometry (fixture 1.0)
fixture1.0
All types

Geometry

Javaclassin fixture.javasince 1.0null-marked

public final class Geometry
Inheritance
  1. Object
  2. Geometry

Operations on shapes.

Every method is pure: it never modifies its arguments. Thread safety: every method is safe to call concurrently.

  1. First, measure.

  2. Then compare, with compareTo.

Unit factors
UnitFactor
Units.METERS1.0
Units.FEET0.3048
Shape big = Geometry.largest(List.of(Circle.of(1), Rect.square(2)));
+double total = Geometry.totalArea(big, Circle.of(3));

Measure twice, cut once.

Edge cases

Text with an entity — a superscript kept as raw markup, a line
break, a hyperlink, and <angle brackets> as literal text.

Implementation note

Areas are computed in double precision.

See also

Nested types

NameKindDescription
LegacyclassMethods from before null markings; their nullness is unspecified.

Fields2

static int PRECISION

PRECISION

static
public static final int PRECISION

The default number of significant digits: 6.

Value

int
Constant: 6
static String NAME

NAME

static
public static final String NAME

The library's name, "fixture", as tools report it.

Value

Stringnon-null
Constant: "fixture"

Methods5

static T largest(Collection)

largest

static
public static <T extends Shape & Comparable<? super T>> T largest(
     Collection<? extends T> shapes
-)

Returns the largest shape.

Type parameters

<T>
the shape type

Parameters

shapesCollection<? extends T>non-null
the shapes; not empty

Returns

T
the largest of shapes

Throws

NoSuchElementExceptionunchecked
if shapes is empty

Implementation requirements

Compares with Comparable.compareTo(Object), keeping the first of equal shapes.

static double totalArea(Shape...)Sums the shapes' areas.

totalArea

static
@Measured(precision = 6)
-public static double totalArea(Shape... shapes)

Sums the shapes' areas.

Parameters

shapesShape...non-null
the shapes

Returns

double
the total area in square meters; 0 for no shapes
static Shape parse(String)Parses a shape from its text form, such as circle 2.5.Has an API note

parse

static
public static Shape parse(String text) throws IOException, ParseException

Parses a shape from its text form, such as circle 2.5.

Parameters

textStringnon-null
the text form

Returns

Shapenon-null
the shape

Throws

IOException
if the text names a file that cannot be read
IllegalStateExceptionunchecked
if the parser was closed
ParseException
No description.

API note

The text form is not stable across releases; store shapes some other way.

static double sum(List)Sums the areas of a list of shapes.for removal

sum

static
@Deprecated(since = "1.1", forRemoval = true)
-public static double sum(List<Shape> shapes)

Deprecated for removal since 1.1

Use totalArea(Shape...), which takes any number of shapes.

Sums the areas of a list of shapes.

Parameters

shapesList<Shape>non-null
the shapes

Returns

double
the total area
static Shape find(Map, String)Finds a shape by name.

find

staticsince 1.1
public static @Nullable Shape find(
+)

Returns the largest shape.

Type parameters

<T>
the shape type

Parameters

shapesCollection<? extends T>non-null
the shapes; not empty

Returns

T
the largest of shapes

Throws

NoSuchElementExceptionunchecked
if shapes is empty

Implementation requirements

Compares with Comparable.compareTo(Object), keeping the first of equal shapes.

static double totalArea(Shape...)

totalArea

static
@Measured(precision = 6)
+public static double totalArea(Shape... shapes)

Sums the shapes' areas.

Parameters

shapesShape...non-null
the shapes

Returns

double
the total area in square meters; 0 for no shapes
static Shape parse(String)Has an API note

parse

static
public static Shape parse(String text) throws IOException, ParseException

Parses a shape from its text form, such as circle 2.5.

Parameters

textStringnon-null
the text form

Returns

Shapenon-null
the shape

Throws

IOException
if the text names a file that cannot be read
IllegalStateExceptionunchecked
if the parser was closed
ParseException
No description.

API note

The text form is not stable across releases; store shapes some other way.

static double sum(List)for removal

sum

static
@Deprecated(since = "1.1", forRemoval = true)
+public static double sum(List<Shape> shapes)

Deprecated for removal since 1.1

Use totalArea(Shape...), which takes any number of shapes.

Sums the areas of a list of shapes.

Parameters

shapesList<Shape>non-null
the shapes

Returns

double
the total area
static Shape find(Map, String)

find

staticsince 1.1
public static @Nullable Shape find(
     Map<String, ? extends Shape> shapes,
     String name
 )

Finds a shape by name.

Parameters

shapesMap<String, ? extends Shape>non-null
shapes by name
nameStringnon-null
the name to look up

Returns

@Nullable Shapenullable
the shape, or null when there is none

Inherited members

@@ -16,18 +16,18 @@ exports[`render HTML snapshots: fixture/java/Geometry.html 1`] = ` exports[`render HTML snapshots: fixture/java/Circle.html 1`] = ` " -Circle (fixture 1.0)
fixture1.0
All types

Circle

Javarecordin fixture.javasince 1.0null-marked

public record Circle(double radius, @Nullable String label) implements Shape
Inheritance
  1. Object
  2. Record
  3. Circle
Implements

A circle.

Record components

radiusdouble
the radius in meters; not negative
label@Nullable Stringnullable
an optional label

Constructors1

Circle(double, String)Checks the radius.

Circle

public Circle(double radius, @Nullable String label)

Checks the radius.

Parameters

radiusdouble
the radius in meters; not negative
label@Nullable Stringnullable
an optional label

Throws

IllegalArgumentExceptionunchecked
if radius is negative

Methods9

static Circle of(double)Creates an unlabeled circle.

of

static
public static Circle of(double radius)

Creates an unlabeled circle.

Parameters

radiusdouble
the radius in meters

Returns

Circlenon-null
the circle
double area()The shape's area.

area

public double area()

The shape's area. For a circle this is π r².

Returns

double
the area in square meters, never negative

Overrides area().

String name()Returns the shape's name, or null for an anonymous shape.

name

public @Nullable String name()

Returns the shape's name, or null for an anonymous shape.

Description copied from name().

Returns

@Nullable Stringnullable
the shape's name, or null for an anonymous shape

Overrides name().

R accept(Shape.Visitor)Calls the visitor's method for this shape's kind.

accept

public <R> R accept(Shape.Visitor<R> visitor)

Calls the visitor's method for this shape's kind.

Description copied from accept().

Type parameters

<R>
the visitor's result type

Parameters

visitorShape.Visitor<R>non-null
the visitor

Returns

R
what the visitor returned

Overrides accept().

String toString()No description.

toString

public final String toString()

No description.

Returns

Stringnon-null
No description.

Overrides toString().

int hashCode()No description.

hashCode

public final int hashCode()

No description.

Returns

int
No description.

Overrides hashCode().

boolean equals(Object)No description.

equals

public final boolean equals(Object o)

No description.

Parameters

oObjectnon-null
No description.

Returns

boolean
No description.

Overrides equals(java.lang.Object).

double radius()No description.

radius

public double radius()

No description.

Returns

double
No description.
String label()No description.

label

public @Nullable String label()

No description.

Returns

@Nullable Stringnullable
No description.

Inherited members

From interface Shape

compareTo

+Circle (fixture 1.0)
fixture1.0
All types

Circle

Javarecordin fixture.javasince 1.0null-marked

public record Circle(double radius, @Nullable String label) implements Shape
Inheritance
  1. Object
  2. Record
  3. Circle
Implements

A circle.

Record components

radiusdouble
the radius in meters; not negative
label@Nullable Stringnullable
an optional label

Constructors1

Circle(double, String)

Circle

public Circle(double radius, @Nullable String label)

Checks the radius.

Parameters

radiusdouble
the radius in meters; not negative
label@Nullable Stringnullable
an optional label

Throws

IllegalArgumentExceptionunchecked
if radius is negative

Methods9

static Circle of(double)

of

static
public static Circle of(double radius)

Creates an unlabeled circle.

Parameters

radiusdouble
the radius in meters

Returns

Circlenon-null
the circle
double area()

area

public double area()

The shape's area. For a circle this is π r².

Returns

double
the area in square meters, never negative

Overrides area().

String name()

name

public @Nullable String name()

Returns the shape's name, or null for an anonymous shape.

Description copied from name().

Returns

@Nullable Stringnullable
the shape's name, or null for an anonymous shape

Overrides name().

R accept(Shape.Visitor)

accept

public <R> R accept(Shape.Visitor<R> visitor)

Calls the visitor's method for this shape's kind.

Description copied from accept().

Type parameters

<R>
the visitor's result type

Parameters

visitorShape.Visitor<R>non-null
the visitor

Returns

R
what the visitor returned

Overrides accept().

String toString()No description.

toString

public final String toString()

No description.

Returns

Stringnon-null
No description.

Overrides toString().

int hashCode()No description.

hashCode

public final int hashCode()

No description.

Returns

int
No description.

Overrides hashCode().

boolean equals(Object)No description.

equals

public final boolean equals(Object o)

No description.

Parameters

oObjectnon-null
No description.

Returns

boolean
No description.

Overrides equals(java.lang.Object).

double radius()No description.

radius

public double radius()

No description.

Returns

double
No description.
String label()No description.

label

public @Nullable String label()

No description.

Returns

@Nullable Stringnullable
No description.

Inherited members

From interface Shape

compareTo

" `; exports[`render HTML snapshots: fixture/java/index.html 1`] = ` " -fixture.java (fixture 1.0)
fixture1.0
All types

fixture.java

Javapackagesince 1.0null-marked

Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.

Where to start

Start with fixture.java.Shape and the operations in fixture.java.Geometry. Readers live in fixture.java.io.

Interfaces

NameDescription
CanvasSomewhere to draw shapes.
ShapeA closed plane figure.

Classes

NameDescription
AbstractCanvasA canvas that counts what it draws.
BoxA mutable holder for one comparable value.
GeometryOperations on shapes.
PolygonA regular polygon.
RectAn axis-aligned rectangle.

Records

NameDescription
CircleA circle.

Enums

NameDescription
UnitsUnits of length.

Exceptions

NameDescription
GeometryExceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.

Annotations

NameDescription
MeasuredMarks a declaration whose values are lengths, and in which unit.
+fixture.java (fixture 1.0)
fixture1.0
All types

fixture.java

Javapackagesince 1.0null-marked

Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.

Where to start

Start with fixture.java.Shape and the operations in fixture.java.Geometry. Readers live in fixture.java.io.

Interfaces

NameDescription
CanvasSomewhere to draw shapes.
ShapeA closed plane figure.

Classes

NameDescription
AbstractCanvasA canvas that counts what it draws.
BoxA mutable holder for one comparable value.
GeometryOperations on shapes.
PolygonA regular polygon.
RectAn axis-aligned rectangle.

Records

NameDescription
CircleA circle.

Enums

NameDescription
UnitsUnits of length.

Exceptions

NameDescription
GeometryExceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.

Annotations

NameDescription
MeasuredMarks a declaration whose values are lengths, and in which unit.
" `; exports[`render HTML snapshots: index.html 1`] = ` " -fixture 1.0 API
fixture1.0
All types

fixture

version 1.0Java

API reference for fixture.

Packages

NameDescription
fixture.javaShapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.
fixture.java.ioReading shapes from streams.

All types

fixture.java

NameKindDescription
AbstractCanvasabstract classA canvas that counts what it draws.
BoxclassA mutable holder for one comparable value.
CanvasinterfaceSomewhere to draw shapes.
Canvas.LayerinterfaceOne layer of a canvas.
Canvas.Layer.Kindenum classWhat a layer holds.
CirclerecordA circle.
GeometryclassOperations on shapes.
Geometry.LegacyclassMethods from before null markings; their nullness is unspecified.
GeometryExceptionexceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.
Measuredannotation interfaceMarks a declaration whose values are lengths, and in which unit.
PolygonclassA regular polygon.
Polygon.BuilderclassBuilds a polygon one side at a time.
Polygon.EdgeclassOne edge of this polygon: an inner class, bound to its polygon.
RectclassAn axis-aligned rectangle.
Shapesealed interfaceA closed plane figure.
Shape.VisitorinterfaceOperations over each kind of shape.
Unitsenum classUnits of length.

fixture.java.io

NameKindDescription
ShapeReaderclassReads shapes in their text form, one per line.
+fixture 1.0 API
fixture1.0
All types

fixture

version 1.0Java

API reference for fixture.

Packages

NameDescription
fixture.javaShapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.
fixture.java.ioReading shapes from streams.

All types

fixture.java

NameKindDescription
AbstractCanvasabstract classA canvas that counts what it draws.
BoxclassA mutable holder for one comparable value.
CanvasinterfaceSomewhere to draw shapes.
Canvas.LayerinterfaceOne layer of a canvas.
Canvas.Layer.Kindenum classWhat a layer holds.
CirclerecordA circle.
GeometryclassOperations on shapes.
Geometry.LegacyclassMethods from before null markings; their nullness is unspecified.
GeometryExceptionexceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.
Measuredannotation interfaceMarks a declaration whose values are lengths, and in which unit.
PolygonclassA regular polygon.
Polygon.BuilderclassBuilds a polygon one side at a time.
Polygon.EdgeclassOne edge of this polygon: an inner class, bound to its polygon.
RectclassAn axis-aligned rectangle.
Shapesealed interfaceA closed plane figure.
Shape.VisitorinterfaceOperations over each kind of shape.
Unitsenum classUnits of length.

fixture.java.io

NameKindDescription
ShapeReaderclassReads shapes in their text form, one per line.
" `; diff --git a/packages/apidocs/test/astro.test.ts b/packages/apidocs/test/astro.test.ts index 406dcc9..08bb747 100644 --- a/packages/apidocs/test/astro.test.ts +++ b/packages/apidocs/test/astro.test.ts @@ -9,7 +9,7 @@ import { samples } from "../samples"; import { guidesModel, importMarkdown, readSuite } from "../src/import"; import type { Model } from "../src/model"; import { render } from "../src/render"; -import { assertBase, isBaseRelative, linkHeader, mapUrl, notFound, pageUrl, prefersMarkdown, renderPage, renderText, resolvePage, searchEntries, sitePaths, textFiles } from "../src/astro/helpers"; +import { assertBase, isBaseRelative, linkHeader, mapUrl, notFound, notFoundText, pageUrl, prefersMarkdown, renderPage, renderText, resolvePage, searchEntries, sitePaths, textFiles } from "../src/astro/helpers"; const fixture: Model = JSON.parse(readFileSync(new URL("fixtures/fixture-java.api.json", import.meta.url), "utf8")); const suite = readSuite(fileURLToPath(new URL("../samples/guides", import.meta.url))); @@ -20,7 +20,8 @@ const theme = { extends: "elide" as const, baseUrl: "https://example.com/docs/" for (const [name, model] of Object.entries(models)) { describe(`${name}: every page and file`, () => { const out = render(model, theme); - const pages = Object.keys(out).filter(f => f.endsWith(".html")).map(f => f.slice(0, -".html".length)); + // Every page but the not-found page, which an app renders for a missing path and no path resolves to. + const pages = Object.keys(out).filter(f => f.endsWith(".html") && f !== "404.html").map(f => f.slice(0, -".html".length)); test("the pages are the static renderer's pages", () => { const astroPages = sitePaths(model, theme).filter(p => p.endsWith(".md")).map(p => p.slice(0, -".md".length)); @@ -43,7 +44,8 @@ for (const [name, model] of Object.entries(models)) { for (const page of pages) { expect(resolvePage(model, `${page}.md`, theme)).toEqual({ kind: "markdown", page }); const text = renderText(model, `${page}.md`, theme)!; - expect(text.body).toBe(out[`${page}.md`] as string); + // The frontmatter's canonical URL is the page's in each form. + expect(text.body).toBe((out[`${page}.md`] as string).replace(`canonical: "${theme.baseUrl}${page}.html"`, `canonical: "${theme.baseUrl}${pageUrl(page)}"`)); expect(text.contentType).toBe("text/markdown; charset=utf-8"); } }); @@ -141,7 +143,7 @@ describe("renderPage", () => { const astroHead = pageOf(model, page).head; const metadata = (head: string, map: (u: string) => string | undefined) => ({ title: /(.*?)<\/title>/.exec(head)?.[1], - meta: [...head.matchAll(/<meta (?:name|property)="([^"]*)" content="([^"]*)"\/>/g)].map(m => [m[1], m[1] === "og:url" ? map(m[2]!) : m[2]]), + meta: [...head.matchAll(/<meta (?:name|property)="([^"]*)" content="([^"]*)"\/>/g)].map(m => [m[1], m[1] === "og:url" || m[1] === "og:image" ? map(m[2]!) : m[2]]), links: [...head.matchAll(/<link rel="(canonical|alternate|index)"[^>]*? href="([^"]*)"/g)].map(m => [m[1], map(m[2]!)]), jsonLd: JSON.parse(/<script type="application\/ld\+json">(.*?)<\/script>/.exec(head)![1]!, (key, value) => (["url", "item", "contentUrl"].includes(key) ? map(value) : value)), }); @@ -165,6 +167,26 @@ describe("renderPage", () => { expect(parts.moduleVersion).toBe('<span class="module-version"><span class="version">2.1.0</span></span>'); }); + test("the not-found page renders in the shell, and its Markdown names the site's base", () => { + const parts = pageOf(samples.java, "404"); + expect(parts.title).toBe("Not found (geo 2.1.0)"); + expect(parts.head).toContain('<meta name="robots" content="noindex"/>'); + expect(parts.head).not.toContain('rel="canonical"'); + expect(parts.body.join("")).toContain('<a href="/docs/packages">Packages</a>'); + const md = notFoundText(samples.java, "/docs/", theme); + expect(md).toContain("[overview](/docs/index.md)"); + expect(md).toContain("- [Deprecated](/docs/deprecated.md)"); + // The static 404.md's text, which links from the site's address. + expect(md.replaceAll("](/docs/", `](${theme.baseUrl}`)).toBe(render(samples.java, theme)["404.md"] as string); + expect(resolvePage(samples.java, "404", theme)).toEqual({ kind: "missing" }); + }); + + test("the social image is the app's bundled file, as an absolute URL", () => { + const parts = renderPage(samples.java, "index", theme, { base, baseUrl: theme.baseUrl, assetUrl: () => "/_astro/elide.abc123.png" }); + expect(parts.head).toContain('<meta property="og:image" content="https://example.com/_astro/elide.abc123.png"/>'); + expect(parts.head).toContain('<meta name="twitter:card" content="summary_large_image"/>'); + }); + test("an unknown page is an error, not an empty page", () => { expect(() => pageOf(samples.java, "com/example/geo/Nope")).toThrow("no page"); }); diff --git a/packages/apidocs/test/browser.test.ts b/packages/apidocs/test/browser.test.ts index 50c767c..5aa91dc 100644 --- a/packages/apidocs/test/browser.test.ts +++ b/packages/apidocs/test/browser.test.ts @@ -28,7 +28,8 @@ beforeAll(async () => { const model = join(site, "model.json"); const theme = join(site, "theme.json"); writeFileSync(model, JSON.stringify(samples.java)); - writeFileSync(theme, JSON.stringify({ extends: "elide" })); + // With sibling sites, so the suite switcher is in every page the tests open. + writeFileSync(theme, JSON.stringify({ extends: "elide", links: { header: [{ label: "User guide", url: "https://example.com/user/" }, { label: "API reference", url: "index.html", current: true }, { label: "Kotlin API", url: "https://example.com/kotlin/" }] } })); const run = spawnSync(process.execPath, [join(root, "dist/runner.mjs"), "--bundle", join(root, "dist/render.js"), "--assets", join(root, "dist/assets"), "--model", model, "--theme", theme, "--out", out], { encoding: "utf8" }); if (run.status !== 0) throw new Error(run.stderr); server = Bun.serve({ @@ -165,6 +166,28 @@ describe("from file:// with JavaScript on", () => { await page.context().close(); }); + test("copy as Markdown copies the page's text, without the frontmatter its twin opens with", async () => { + const { page } = await open("com/example/geo/Shapes.html", { http: true }); + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + await page.locator("button.formats-main").click(); + await page.waitForSelector("button.formats-main[data-copied]"); + const copied = await page.evaluate(() => navigator.clipboard.readText()); + expect(copied.startsWith("# ")).toBe(true); + expect(copied).toContain("Operations on"); + expect(readFileSync(join(out, "com/example/geo/Shapes.md"), "utf8").startsWith('---\ntitle: "Shapes"')).toBe(true); + await page.context().close(); + }); + + test("a member row shows its summary sentence, drawn from the entry's text, and the members filter matches it", async () => { + const { page } = await open("com/example/geo/Shapes.html"); + const row = page.locator("details.member", { has: page.locator("#parse\\(java\\.lang\\.String\\)") }).locator(".member-brief"); + const brief = await row.getAttribute("data-brief"); + expect(brief?.length).toBeGreaterThan(10); + expect(await row.evaluate(e => getComputedStyle(e, "::before").content)).toBe(JSON.stringify(brief)); + expect(await page.getByRole("group").filter({ has: page.locator("#parse\\(java\\.lang\\.String\\)") }).locator("summary").evaluate(e => e.textContent)).not.toContain(brief!); + await page.context().close(); + }); + test("font preloads appear over HTTP and not on file://", async () => { const preloads = (page: Page) => page.locator('head link[rel="preload"][as="font"]').count(); const local = await open("com/example/geo/Shapes.html"); @@ -204,7 +227,7 @@ describe("layout stability", () => { describe("accessibility", () => { for (const colorScheme of ["light", "dark"] as const) { - for (const path of ["index.html", "com/example/geo/index.html", "com/example/geo/Shapes.html", "com/example/geo/Circle.html"]) { + for (const path of ["index.html", "com/example/geo/index.html", "com/example/geo/Shapes.html", "com/example/geo/Shapes.html#parse(java.lang.String)", "com/example/geo/Circle.html", "guides/concepts.html", "guides/getting-started.html", "packages.html", "types.html", "index-all.html", "deprecated.html", "404.html"]) { test(`${path} in ${colorScheme} has no axe violations`, async () => { const { page } = await open(path, { colorScheme }); await page.addScriptTag({ path: require.resolve("axe-core/axe.min.js") }); diff --git a/packages/apidocs/test/check.ts b/packages/apidocs/test/check.ts index 835826b..092f6cb 100644 --- a/packages/apidocs/test/check.ts +++ b/packages/apidocs/test/check.ts @@ -57,6 +57,8 @@ export function checkSite(out: Output, options: CheckOptions): string[] { if (!options.allowed.some(prefix => url.startsWith(prefix))) errors.push(`${file}: absolute URL ${url}`); continue; } + // 404.html is served at whatever URL was missing: a link within it can only be a fragment. + if (url.startsWith("#") && url.length > 1 && file === "404.html") continue; if (url === "" || url.startsWith("#")) { errors.push(`${file}: link does not name its file: "${url}"`); continue; diff --git a/packages/apidocs/test/color.test.ts b/packages/apidocs/test/color.test.ts new file mode 100644 index 0000000..239aee2 --- /dev/null +++ b/packages/apidocs/test/color.test.ts @@ -0,0 +1,86 @@ +/** + * The colors the stylesheet and the presets write as oklch() are their former sRGB hex colors exactly: each converts + * back to the same 8-bit color, so pages draw the same pixels and every contrast ratio is what it was. + */ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { code, neutral, purple, status, syntax, syntaxLight } from "@elide/tokens"; +import { contrast, oklch, parseHex, parseOklch } from "../src/color"; +import { elide } from "../src/presets/elide"; + +/** apidocs.css's neutral defaults as they were in hex and rgb(), light then dark: the colors converted. */ +const NEUTRAL_LIGHT: Record<string, string> = { + bg: "#fbfcfd", surface: "#ffffff", subtle: "#f2f4f7", fg: "#161a21", muted: "#4f5766", faint: "#5f6775", rule: "#e1e4ea", + "rule-strong": "#c7ccd6", accent: "#0f6e7a", link: "#0c5f6b", focus: "#0f6e7a", "note-api": "#0f6e7a", "note-spec": "#2d55a8", + "note-impl": "#5f6775", deprecated: "#a8321f", nullable: "#8a5300", "non-null": "#2b6b3a", "code-bg": "#f3f5f8", "code-fg": "#1d2430", + "syn-comment": "#5f6775", "syn-keyword": "#7a3196", "syn-string": "#1c6d45", "syn-number": "#9a4a00", "syn-type": "#0c5f6b", + "syn-function": "#2b4db3", "syn-annotation": "#8a5300", "syn-param": "#8c1f4f", +}; +const NEUTRAL_DARK: Record<string, string> = { + bg: "#0f1216", surface: "#151920", subtle: "#1a1f27", fg: "#e6e8ec", muted: "#a3abb8", faint: "#8f98a6", rule: "#262c35", + "rule-strong": "#3a414d", accent: "#5cc6d0", link: "#6fd0d9", focus: "#5cc6d0", "note-api": "#5cc6d0", "note-spec": "#8fb0f0", + "note-impl": "#8f98a6", deprecated: "#f08a78", nullable: "#e3b25c", "non-null": "#7cc98d", "code-bg": "#141920", "code-fg": "#d9dde3", + "syn-comment": "#8a93a1", "syn-keyword": "#d09be6", "syn-string": "#8fd1a6", "syn-number": "#f0b47a", "syn-type": "#6fd0d9", + "syn-function": "#9ab5ff", "syn-annotation": "#e3b25c", "syn-param": "#f09ac0", +}; + +/** The largest difference, in 8-bit steps, between an oklch() string and a hex color. */ +function delta(css: string, hex: string): number { + const a = parseOklch(css).rgb; + const b = parseHex(hex).rgb; + return Math.max(...a.map((v, i) => Math.abs(v - b[i]!) * 255)); +} + +const css = readFileSync(new URL("../src/styles/apidocs.css", import.meta.url), "utf8"); +/** The token values in a block of apidocs.css: the :root defaults, or the explicit dark theme. */ +function tokens(block: string): Record<string, string> { + return Object.fromEntries([...block.matchAll(/--apidocs-([a-z0-9-]+): (oklch\([^)]*\));/g)].map(m => [m[1]!, m[2]!])); +} +const light = tokens(css.slice(css.indexOf(":root {"), css.indexOf("@media (prefers-color-scheme: dark)"))); +const dark = tokens(css.slice(css.indexOf(':root[data-theme="dark"]'), css.indexOf("/* ---- Base ---- */"))); + +describe("the conversion", () => { + test("is within half an 8-bit step on a random sample of sRGB", () => { + let worst = 0; + for (let i = 0; i < 20_000; i++) { + const hex = `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, "0")}`; + worst = Math.max(worst, delta(oklch(hex), hex)); + } + expect(worst).toBeLessThan(0.5); + }); + test("writes a gray's hue as none", () => { + expect(oklch("#ffffff")).toBe("oklch(100% 0 none)"); + expect(oklch("#000000", 0.28)).toBe("oklch(0% 0 none / 0.28)"); + }); +}); + +describe("apidocs.css's neutral defaults", () => { + for (const [name, table, values] of [["light", NEUTRAL_LIGHT, light], ["dark", NEUTRAL_DARK, dark]] as const) { + test(`${name}: every color token is its former hex color, within a tenth of a step`, () => { + for (const [token, hex] of Object.entries(table)) expect([token, delta(values[token]!, hex) < 0.1]).toEqual([token, true]); + }); + test(`${name}: contrast ratios of text on the page are unchanged`, () => { + for (const fg of ["fg", "muted", "faint", "accent", "link", "deprecated", "nullable", "non-null"]) { + const before = contrast(parseHex(table[fg]!).rgb, parseHex(table.bg!).rgb); + const after = contrast(parseOklch(values[fg]!).rgb, parseOklch(values.bg!).rgb); + expect(Math.abs(after - before)).toBeLessThan(0.01); + } + }); + } +}); + +describe("the Elide preset", () => { + const hexes = [neutral, purple, status, syntax, syntaxLight, code].flatMap(scale => Object.values(scale) as string[]); + const byOklch = new Map(hexes.map(hex => [oklch(hex), hex])); + test("every token color is an @elide/tokens color, converted exactly", () => { + for (const mode of ["light", "dark"] as const) { + for (const [token, value] of Object.entries(elide.tokens![mode]!)) { + for (const color of value.match(/oklch\([^)]*\)/g) ?? []) { + const hex = byOklch.get(color) ?? (color === oklch("#ffffff") ? "#ffffff" : undefined); + expect([token, hex !== undefined && delta(color, hex) < 0.1]).toEqual([token, true]); + } + expect([token, /#[0-9a-f]{3,8}\b/i.test(value)]).toEqual([token, false]); + } + } + }); +}); diff --git a/packages/apidocs/test/guides-browser.test.ts b/packages/apidocs/test/guides-browser.test.ts index d22d941..712320f 100644 --- a/packages/apidocs/test/guides-browser.test.ts +++ b/packages/apidocs/test/guides-browser.test.ts @@ -90,6 +90,19 @@ describe("a guides-only site from file://", () => { await page.context().close(); }); + test("the navigator's filter narrows the guides", async () => { + const { page } = await open("guides/getting-started.html"); + const rows = page.locator(".nav-guides .nav-row"); + const visible = async () => (await rows.all()).length - (await page.locator(".nav-guides [data-filtered-out]").count()); + const all = await rows.count(); + await page.locator("#apidocs-nav-filter").fill("pictures"); + expect(await visible()).toBe(1); + expect(await page.locator(".nav-guides .nav-row:visible").allTextContents()).toEqual([expect.stringContaining("Pictures")]); + await page.locator("#apidocs-nav-filter").press("Escape"); + expect(await visible()).toBe(all); + await page.context().close(); + }); + test("previous and next follow reading order across groups", async () => { const { page } = await open("guides/concepts/images.html", { javaScriptEnabled: false }); await page.locator("a.guide-next").click(); diff --git a/packages/apidocs/test/render.test.ts b/packages/apidocs/test/render.test.ts index 45664cf..f729f57 100644 --- a/packages/apidocs/test/render.test.ts +++ b/packages/apidocs/test/render.test.ts @@ -11,7 +11,8 @@ import type { Model, Token } from "../src/model"; import { render } from "../src/render"; import { sanitize } from "../src/sanitize"; import { layoutSignature } from "../src/signature"; -import { sharedPrefix } from "../src/components/chrome"; +import { navIndexes, sharedPrefix, suites } from "../src/components/chrome"; +import { buildSite, isThrowable } from "../src/site"; import { checkSite } from "./check"; import { validate } from "./validate"; @@ -88,7 +89,8 @@ describe("render", () => { expect(site["assets/fonts/jetbrains-mono-latin-wght-normal.woff2"]).toEqual({ asset: "fonts/jetbrains-mono-latin-wght-normal.woff2" }); // Prose and headings use the reader's system fonts: no other font file ships. expect(Object.keys(site).filter(f => f.startsWith("assets/fonts/")).sort()).toEqual(["assets/fonts/jetbrains-mono-latin-wght-italic.woff2", "assets/fonts/jetbrains-mono-latin-wght-normal.woff2"]); - expect(site["assets/theme.css"]).toContain("--apidocs-accent:#6d28d9"); + // @elide/tokens' purple[700], #6d28d9, written as oklch(). + expect(site["assets/theme.css"]).toContain("--apidocs-accent:oklch(49.067% 0.24123 292.581);"); }); test("notes render as distinct callouts, the API note first", () => { const html = out["fixture/java/Geometry.html"] as string; @@ -101,6 +103,89 @@ describe("render", () => { }); }); +describe("agent readiness", () => { + const base = "https://example.com/geo/"; + const elide = render(samples.java, { extends: "elide", baseUrl: base, lastModified: "2026-11-21" }); + const head = (html: string) => html.split("<head>")[1]!.split("</head>")[0]!; + const graph = (html: string) => JSON.parse(/<script type="application\/ld\+json">(.*?)<\/script>/.exec(html)![1]!)["@graph"]; + + test("a theme's social image gives og:image, its size and alt text, and the large card; none without one", () => { + const h = head(elide["com/example/geo/Shapes.html"] as string); + expect(h).toContain(`<meta property="og:image" content="${base}assets/social/elide.png"/>`); + expect(h).toContain('<meta property="og:image:width" content="1200"/>'); + expect(h).toContain('<meta property="og:image:height" content="630"/>'); + expect(h).toContain('<meta property="og:image:alt" content="The Elide logo on a dark background"/>'); + expect(h).toContain('<meta name="twitter:card" content="summary_large_image"/>'); + expect(elide["assets/social/elide.png"]).toEqual({ asset: "social/elide.png" }); + expect(head(render(samples.java)["index.html"] as string)).toContain('<meta property="og:image" content="assets/social/neutral.png"/>'); + const none = head(render(samples.java, { socialImage: null })["index.html"] as string); + expect(none).not.toContain("og:image"); + expect(none).toContain('<meta name="twitter:card" content="summary"/>'); + // A URL that is not http(s), or an asset path that climbs out of assets/, is dropped. + expect(render(samples.java, { socialImage: { url: "javascript:x", width: 1, height: 1, alt: "" } })["index.html"]).not.toContain("og:image"); + expect(Object.keys(render(samples.java, { socialImage: { asset: "../secret.png", width: 1, height: 1, alt: "" } }))).not.toContain("assets/../secret.png"); + }); + test("the overview's JSON-LD lists the guides and packages, every page's has a url", () => { + const parts = graph(elide["index.html"] as string)[0].hasPart as { "@type": string; name: string; url: string }[]; + expect(parts[0]).toEqual({ "@type": "TechArticle", name: "Getting started", url: `${base}guides/getting-started.html` }); + expect(parts.find(p => p.name === "com.example.geo")).toEqual({ "@type": "APIReference", name: "com.example.geo", url: `${base}com/example/geo/index.html` }); + expect(graph(elide["com/example/geo/Shapes.html"] as string)[0].url).toBe(`${base}com/example/geo/Shapes.html`); + // Relative without a base URL, as the breadcrumbs are. + expect(graph(render(samples.java)["com/example/geo/Shapes.html"] as string)[0].url).toBe("Shapes.html"); + }); + test("404.html and 404.md: the page shell with the way back, links from the site's address, kept out of the indexes", () => { + const html = elide["404.html"] as string; + expect(html).toContain(`<head><base href="${base}"/>`); + expect(html).toContain('<meta name="robots" content="noindex"/>'); + expect(html).not.toContain('rel="canonical"'); + expect(html).toContain('<h1>Not found</h1>'); + expect(html).toContain('<a href="deprecated.html">Deprecated</a>'); + expect(elide["404.md"]).toContain(`Start at the [overview](${base}index.md)`); + expect(render(samples.java)["404.md"]).toContain("Start at the [overview](index.md)"); + expect(elide["llms.txt"]).not.toContain("404"); + expect(elide["sitemap.xml"]).not.toContain("404"); + }); + test("sitemap.xml has lastmod from the theme, never from the clock", () => { + expect(elide["sitemap.xml"]).toContain(`<url><loc>${base}index.html</loc><lastmod>2026-11-21</lastmod></url>`); + expect(render(samples.java, { baseUrl: base })["sitemap.xml"]).not.toContain("lastmod"); + expect(render(samples.java, { baseUrl: base, lastModified: "yesterday" })["sitemap.xml"]).not.toContain("lastmod"); + }); + test("llms.txt says when to use the reference: the theme's text, or a sentence from the module's", () => { + expect(elide["llms.txt"]).toContain("## When to use this\n\nUse this API reference when you write, read or review code that uses geo 2.1.0. A small geometry library: the Java-flavored sample for @elide/apidocs."); + expect(render(samples.java, { whenToUse: "Read the guides first." })["llms.txt"]).toContain("## When to use this\n\nRead the guides first."); + }); + test("Markdown twins open with frontmatter; llms-full.txt joins them without it", () => { + expect((elide["com/example/geo/Shapes.md"] as string).split("\n---\n")[0]).toBe( + `---\ntitle: "Shapes"\ndescription: "Operations on shapes."\nkind: "class"\nid: "com.example.geo.Shapes"\nmodule: "geo"\nversion: "2.1.0"\ncanonical: "${base}com/example/geo/Shapes.html"`); + expect(elide["guides/concepts.md"]).toMatch(/^---\ntitle: "Concepts"\n[\s\S]*kind: "guide"\nid: "guide:concepts"/); + expect(elide["packages.md"]).toMatch(/^---\ntitle: "Packages"\ndescription: "Packages: every package with its summary and type counts\."\nkind: "index"/); + const full = elide["llms-full.txt"] as string; + expect(full).not.toMatch(/^(title|kind|canonical): "/m); + expect(full).toContain("<!-- com/example/geo/Shapes.md -->\n# "); + }); +}); + +describe("exceptions", () => { + const type = (id: string, ancestors: string[]) => ({ id, name: id, kind: "class", signature: [], language: "java", ancestors: ancestors.map(a => ({ id: a })) }) as unknown as import("../src/model").Type; + test("a Java exception: java.lang.Throwable among its ancestors", () => { + expect(isThrowable(type("com.example.Oops", ["java.lang.RuntimeException", "java.lang.Exception", "java.lang.Throwable", "java.lang.Object"]))).toBe(true); + expect(isThrowable(type("java.lang.Throwable", ["java.lang.Object"]))).toBe(true); + }); + test("a Kotlin exception: kotlin.Throwable, or the Java class, as Dokka DRIs", () => { + expect(isThrowable(type("org.example/Oops///PointingToDeclaration/", ["kotlin/Exception///PointingToDeclaration/", "kotlin/Throwable///PointingToDeclaration/", "kotlin/Any///PointingToDeclaration/"]))).toBe(true); + expect(isThrowable(type("org.example/Oops///PointingToDeclaration/", ["java.lang/IllegalStateException///PointingToDeclaration/", "java.lang/Throwable///PointingToDeclaration/"]))).toBe(true); + }); + test("a class that merely has Throwable in its name is not one", () => { + expect(isThrowable(type("com.example.ThrowableFactory", ["java.lang.Object"]))).toBe(false); + expect(isThrowable(type("org.example/Wrapper///PointingToDeclaration/", ["org.example/ThrowableHolder///PointingToDeclaration/", "my.Throwable", "kotlin/Any///PointingToDeclaration/"]))).toBe(false); + }); + test("the Kotlin sample's exception gets the exception glyph and group", () => { + const html = render(samples.kotlin)["org/example/kgeo/ShapeParseException.html"] as string; + expect(html).toContain('data-tone="exception"'); + expect(render(samples.kotlin)["org/example/kgeo/index.md"]).toContain("## Exceptions"); + }); +}); + describe("layout", () => { const java = render(samples.java, { extends: "elide" }); const between = (html: string, start: string, end: string) => html.slice(html.indexOf(start), html.indexOf(end, html.indexOf(start))); @@ -139,6 +224,49 @@ describe("layout", () => { expect(html).toContain('<input type="checkbox" id="apidocs-nav-toggle"'); expect(html).toContain('for="apidocs-nav-toggle"'); }); + test("theme links are resolved from the site root on pages at any depth, header and footer alike", () => { + const out = render(samples.java, { links: { header: [{ label: "Guide", url: "guides/concepts.html" }, { label: "Here", url: "./", current: true }], footer: [{ label: "Notes", url: "guides/concepts.html" }, { label: "Root", url: "/docs/" }, { label: "Elsewhere", url: "https://example.com/x" }] } }); + const footer = (page: string) => between(out[page] as string, '<p class="footer-links">', "</p>"); + expect(footer("index.html")).toContain('href="guides/concepts.html"'); + expect(footer("com/example/geo/Shapes.html")).toContain('href="../../../guides/concepts.html"'); + expect(footer("com/example/geo/Shapes.html")).toContain('href="/docs/"'); + expect(footer("com/example/geo/Shapes.html")).toContain('href="https://example.com/x"'); + expect(between(out["com/example/geo/Shapes.html"] as string, '<nav class="suites-row"', "</nav>")).toContain('href="../../../guides/concepts.html"'); + expect(checkSite(out, { allowed: [...allowed(samples.java), "/docs/"] }).filter(e => !e.includes("/docs/"))).toEqual([]); + }); + test("the suite switcher marks the current site, given or inferred, and is left out with nothing to switch to", () => { + const sites = [{ label: "Guide", url: "https://example.com/guide/" }, { label: "API", url: "https://example.com/api/" }]; + expect(suites({ links: { header: sites } }, "index").map(s => s.current)).toEqual([false, false]); + expect(suites({ links: { header: [sites[0]!, { ...sites[1]!, current: true }] } }, "a/B").map(s => [s.current, s.href])).toEqual([[false, "https://example.com/guide/"], [true, "../index.html"]]); + // Inferred from the base URL, or from a link to the site's own root. + expect(suites({ baseUrl: "https://example.com/api/", links: { header: sites } }, "index").map(s => s.current)).toEqual([false, true]); + expect(suites({ links: { header: [sites[0]!, { label: "API", url: "index.html" }] } }, "index").map(s => s.current)).toEqual([false, true]); + // Only this site, or no links: no switcher. + expect(suites({ links: { header: [{ label: "API", url: "./" }] } }, "index")).toEqual([]); + expect(suites({}, "index")).toEqual([]); + expect(java["index.html"]).not.toContain('class="suites"'); + const html = render(samples.java, { extends: "elide", links: { header: [...sites, { label: "Here", url: "./", current: true }] } })["com/example/geo/Shapes.html"] as string; + expect(between(html, '<nav class="suites-row"', "</nav>")).toContain('<a href="../../../index.html" aria-current="true">Here</a>'); + expect(between(html, '<section class="nav-section nav-suites"', "</section>")).toContain(">Guide<"); + }); + test("the navigator lists the indexes: rows under Reference past two, the current one marked; none on a guides-only site", () => { + const site = buildSite(samples.java); + expect(navIndexes(site, "types").map(e => [e.label, e.current])).toEqual([["Overview", false], ["Packages", false], ["All types", true], ["Index", false], ["Deprecated", false]]); + const nav = between(java["com/example/geo/Shapes.html"] as string, '<nav class="sidebar"', "</nav>"); + expect(nav).toContain('<section class="nav-section nav-reference"><h2 class="nav-heading"><span>Reference</span></h2>'); + expect(between(java["types.html"] as string, '<section class="nav-section nav-reference"', "</section>")).toContain('<a class="nav-row" href="types.html" aria-current="page">'); + expect(java["index.html"]).not.toContain('class="topbar-nav"'); + // A guides-only site whose overview is a guide has none: the overview is the first guide row. + const guides = render({ ...samples.java, packages: [], module: { ...samples.java.module, overview: samples.java.module.guides![0]!.id } }); + expect(guides["index.html"]).not.toMatch(/nav-reference|nav-index/); + // One with a generated overview has a one-link row. + const plain = render({ ...samples.java, packages: [], module: { ...samples.java.module, overview: undefined } }); + expect(between(plain["index.html"] as string, '<ul class="nav-index"', "</ul>")).toContain(">Overview<"); + // The filter is there on guides-only sites too, and filters guides and types, never sites, indexes or packages. + expect(plain["index.html"]).toContain("data-nav-filter"); + expect(nav).toContain('<section class="nav-section nav-guides" data-nav-filterable'); + expect(nav).not.toMatch(/nav-packages" data-nav-filterable|nav-reference" data-nav-filterable/); + }); test("font preloads are added at run time off file://, upright faces only", () => { const head = between(java["com/example/geo/Shapes.html"] as string, "<head>", "</head>"); expect(head).not.toContain('<link rel="preload"'); diff --git a/packages/apidocs/test/topbar.test.ts b/packages/apidocs/test/topbar.test.ts new file mode 100644 index 0000000..1c94f05 --- /dev/null +++ b/packages/apidocs/test/topbar.test.ts @@ -0,0 +1,264 @@ +/** + * The top bar at every width from 320 to 1600px (in steps of 20), in both renderers' markup: nothing in it may + * wrap, overflow or be cut off, with zero to five sibling sites in the switcher, with and without a version menu, + * and with a short and a long product name. Static pages are built with dist/runner.mjs; the Astro form is the + * integration's own page parts (renderPage) assembled as ApidocsPage.astro assembles them, with the version menu + * and the search field in their holes. The Astro sample app's suite sweeps its real pages too. + * + * Also: the switcher's menu works with and without the script, and pages with a switcher do not shift as they load. + * Needs `bun run build` first and a Playwright Chromium. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { extname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { type Browser, chromium, type Page } from "playwright"; +import { renderToString } from "preact-render-to-string"; +import { h } from "preact"; +import { samples } from "../samples"; +import { renderPage } from "../src/astro/render"; +import { SearchField } from "../src/components/chrome"; +import type { Theme, ThemeLink } from "../src/theme"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +let browser: Browser; +let dir: string; +let server: ReturnType<typeof Bun.serve>; + +const SITES: ThemeLink[] = [ + { label: "User guide", url: "https://example.com/user/" }, + { label: "Developer guide", url: "https://example.com/developer/" }, + { label: "API reference", url: "index.html", current: true }, + { label: "Kotlin API", url: "https://example.com/kotlin/" }, + { label: "Release notes", url: "https://example.com/notes/" }, +]; +const SUITES: Record<number, ThemeLink[]> = { 0: [], 1: [SITES[0]!], 3: SITES.slice(0, 3), 5: SITES }; +const LONG = "Komodo Kotlin Standard Library Reference"; +const PAGE = "com/example/geo/Shapes"; + +interface Variant { + name: string; + suites: number; + long: boolean; + astro: boolean; + /** The Astro form with a version menu in the top bar's slot (in place of the module's version). */ + versionMenu: boolean; +} + +const variants: Variant[] = []; +for (const astro of [false, true]) { + for (const suites of [0, 1, 3, 5]) { + for (const long of [false, true]) { + for (const versionMenu of astro ? [false, true] : [false]) { + variants.push({ name: `${astro ? "astro" : "static"}-s${suites}${long ? "-long" : ""}${versionMenu ? "-menu" : ""}`, suites, long, astro, versionMenu }); + } + } + } +} + +const theme = (v: { suites: number; long: boolean }): Theme => ({ extends: "elide", ...(v.long ? { productName: LONG } : {}), links: { header: SUITES[v.suites] } }); + +const CHEVRON = '<svg class="icon" viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path d="M4 6.25 8 10.25l4-4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"></path></svg>'; +/** VersionSelect.astro's markup, for two versions. */ +const VERSION_MENU = `<details class="version-menu" data-version-menu><summary class="version-current" aria-label="Version 2.0: other versions" title="Other versions"><span class="version">2.0</span>${CHEVRON}</summary><ul class="version-list"><li><a href="/v/2.0/" aria-current="page"><span class="version">2.0</span><small>latest</small></a></li><li><a href="/v/main/"><span class="version">main</span><small>development</small></a></li></ul></details>`; + +/** An Astro page as ApidocsPage.astro assembles it, served under /<name>/ with the static stylesheets and client. */ +function astroPage(v: Variant): string { + const base = `/${v.name}/`; + const parts = renderPage(samples.java, PAGE, theme(v), { base, baseUrl: `http://127.0.0.1/${v.name}/`, fontUrl: asset => `/assets/${asset}` }); + const search = renderToString(h(SearchField, { apiLabel: parts.api })); + return `<!doctype html>\n<html lang="en" data-root="${base}"><head>${parts.head}<link rel="stylesheet" href="/assets/apidocs.css"><link rel="stylesheet" href="/astro.css"><style>${parts.themeCss}</style></head><body>` + + `${parts.body[0]}${v.versionMenu ? VERSION_MENU : parts.moduleVersion}${parts.body[1]}${search}${parts.body[2]}${parts.body[3]}<script src="/assets/apidocs.js"></script></body></html>`; +} + +beforeAll(async () => { + if (!existsSync(join(root, "dist/render.js"))) throw new Error("dist/ is missing: run `bun run build` first"); + dir = mkdtempSync(join(tmpdir(), "apidocs-topbar-")); + const model = join(dir, "model.json"); + writeFileSync(model, JSON.stringify(samples.java)); + for (const v of variants.filter(v => !v.astro)) { + const themeFile = join(dir, `${v.name}.theme.json`); + writeFileSync(themeFile, JSON.stringify(theme(v))); + const run = spawnSync(process.execPath, [join(root, "dist/runner.mjs"), "--bundle", join(root, "dist/render.js"), "--assets", join(root, "dist/assets"), "--model", model, "--theme", themeFile, "--out", join(dir, v.name)], { encoding: "utf8" }); + if (run.status !== 0) throw new Error(run.stderr); + } + for (const v of variants.filter(v => v.astro)) { + mkdirSync(join(dir, v.name), { recursive: true }); + writeFileSync(join(dir, v.name, "page.html"), astroPage(v)); + } + const types: Record<string, string> = { ".html": "text/html", ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".svg": "image/svg+xml" }; + server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(request) { + const path = decodeURIComponent(new URL(request.url).pathname); + const file = path === "/astro.css" ? join(root, "src/astro/apidocs-astro.css") + : path.startsWith("/assets/") ? join(root, "dist", path) + : resolve(dir, `.${path}`); + if (!file.startsWith(root) && !file.startsWith(dir)) return new Response("Not found", { status: 404 }); + if (!existsSync(file)) return new Response("Not found", { status: 404 }); + return new Response(readFileSync(file), { headers: { "content-type": types[extname(file)] ?? "application/octet-stream" } }); + }, + }); + browser = await chromium.launch(); +}, 120_000); + +afterAll(async () => { + await browser?.close(); + server?.stop(true); + if (dir) rmSync(dir, { recursive: true, force: true }); +}); + +const urlOf = (v: Variant) => `http://127.0.0.1:${server.port}/${v.name}/${v.astro ? "page.html" : `${PAGE}.html`}`; + +/** + * What is wrong with the top bar as laid out now: the bar scrolls; a visible part lies outside it; a visible part + * is cut off (its content wider than its box) other than by an ellipsis; or text in it wraps. + */ +export async function topBarProblems(page: Page): Promise<string[]> { + return page.evaluate(() => { + const bar = document.querySelector<HTMLElement>(".topbar")!; + const box = bar.getBoundingClientRect(); + const problems: string[] = []; + if (bar.scrollWidth > bar.clientWidth) problems.push(`the bar scrolls: ${bar.scrollWidth} > ${bar.clientWidth}`); + const shown = (e: Element) => { + for (let n: Element | null = e; n && n !== bar.parentElement; n = n.parentElement) { + const s = getComputedStyle(n); + if (s.display === "none" || s.visibility === "hidden" || n.classList.contains("visually-hidden")) return false; + } + return true; + }; + for (const e of bar.querySelectorAll<HTMLElement>("*")) { + // The switcher's measuring row paints nothing and takes no pointer events (see SuiteSwitcher); what it holds is checked. + if (e.matches(".suites-fit, .suites-probe") || e.closest(".search-results, .suite-list, .version-list, script") || !shown(e)) continue; + const r = e.getBoundingClientRect(); + if (r.width === 0 && r.height === 0) continue; + const name = `${e.tagName.toLowerCase()}${e.className && typeof e.className === "string" ? `.${e.className.split(" ")[0]}` : ""}`; + // The switcher's row or menu out of view sits far above the page, and is hidden by the script. + if (r.bottom < 0) continue; + if (r.left < box.left - 0.5 || r.right > box.right + 0.5 || r.top < box.top - 0.5 || r.bottom > box.bottom + 0.5) problems.push(`${name} lies outside the bar: ${Math.round(r.left)}..${Math.round(r.right)} x ${Math.round(r.top)}..${Math.round(r.bottom)}`); + const s = getComputedStyle(e); + if (s.overflowX !== "visible" && e.scrollWidth > e.clientWidth + 1 && s.textOverflow !== "ellipsis" && !(e instanceof HTMLInputElement)) problems.push(`${name} is cut off: ${e.scrollWidth} > ${e.clientWidth}`); + if (e.children.length === 0 && e.textContent?.trim() && s.whiteSpace !== "nowrap" && r.height > parseFloat(s.lineHeight || "0") * 1.5 + 1) problems.push(`${name} wraps: ${Math.round(r.height)}px tall`); + } + return problems; + }); +} + +describe("the top bar never wraps, overflows or is cut off", () => { + for (const v of variants) { + test(`${v.name}, 320 to 1600px`, async () => { + const page = await browser.newPage({ viewport: { width: 1600, height: 600 } }); + await page.goto(urlOf(v)); + await page.evaluate(() => document.fonts.ready); + const found: string[] = []; + for (let width = 320; width <= 1600; width += 20) { + await page.setViewportSize({ width, height: 600 }); + await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))); + for (const problem of await topBarProblems(page)) found.push(`${width}px: ${problem}`); + } + expect(found).toEqual([]); + await page.close(); + }, 120_000); + } +}); + +describe("right to left", () => { + test("a page laid out with dir=rtl mirrors: navigator on the right, rail on the left, bar intact", async () => { + const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); + await page.goto(urlOf(variants.find(v => v.name === "static-s3")!)); + await page.evaluate(() => document.documentElement.setAttribute("dir", "rtl")); + await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))); + const box = (selector: string) => page.locator(selector).first().evaluate(e => { const r = e.getBoundingClientRect(); return { left: r.left, right: r.right }; }); + const [nav, content, toc] = [await box(".sidebar"), await box(".content"), await box(".toc")]; + expect(nav.left).toBeGreaterThan(content.left); + expect(toc.right).toBeLessThanOrEqual(content.left + 1); + // The brand starts the bar on the right; the theme switch ends it on the left. + expect((await box(".brand")).left).toBeGreaterThan((await box(".theme-switch")).left); + // Text starts at the right edge of its box: a navigator row's label, a member row's signature. + const row = await page.locator(".sidebar .nav-row").first().evaluate(e => getComputedStyle(e).direction); + expect(row).toBe("rtl"); + expect(await topBarProblems(page)).toEqual([]); + await page.screenshot({ path: join(dir, "rtl.png") }); + await page.close(); + }); +}); + +describe("the suite switcher", () => { + const five = () => variants.find(v => v.name === "static-s5")!; + + test("shows the row where it fits, the menu where it does not, and leaves a phone's bar", async () => { + const page = await browser.newPage({ viewport: { width: 1440, height: 700 } }); + await page.goto(urlOf(five())); + const state = () => page.locator(".suites").getAttribute("data-fit"); + expect(await state()).toBe("row"); + expect(await page.locator(".suites-row").isVisible()).toBe(true); + expect(await page.locator('.suites-row a[aria-current="true"]').textContent()).toBe("API reference"); + await page.setViewportSize({ width: 1000, height: 700 }); + await page.waitForFunction(() => document.querySelector(".suites")?.getAttribute("data-fit") === "menu"); + expect(await page.locator(".suites-row").isVisible()).toBe(false); + expect(await page.locator(".suite-current").textContent()).toBe("API reference"); + await page.setViewportSize({ width: 360, height: 700 }); + await page.waitForFunction(() => document.querySelector(".suites")?.getAttribute("data-fit") === "none"); + expect(await page.locator(".suite-current").isVisible()).toBe(false); + // The drawer lists the sites first. + await page.locator(".nav-button").click(); + expect(await page.locator(".sidebar > :first-child a").allTextContents()).toEqual(SITES.map(s => s.label)); + expect(await page.locator('.sidebar > :first-child a[aria-current="true"]').textContent()).toBe("API reference"); + await page.close(); + }); + + test("the menu opens, and closes on Escape and on a click outside it", async () => { + const page = await browser.newPage({ viewport: { width: 1000, height: 700 } }); + await page.goto(urlOf(five())); + const open = () => page.locator("details.suite-menu").evaluate(d => (d as HTMLDetailsElement).open); + await page.locator(".suite-current").click(); + expect(await open()).toBe(true); + expect(await page.locator(".suite-list a").allTextContents()).toEqual(SITES.map(s => s.label)); + await page.keyboard.press("Escape"); + expect(await open()).toBe(false); + expect(await page.evaluate(() => document.activeElement?.classList.contains("suite-current"))).toBe(true); + await page.locator(".suite-current").click(); + await page.locator("main h1").click(); + expect(await open()).toBe(false); + await page.close(); + }); + + test("without JavaScript, the layout still picks the row or the menu, and the menu opens", async () => { + const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 1440, height: 700 } }); + const page = await context.newPage(); + // With a long product name: without the script there is no search field, so the row fits at 1000px otherwise. + await page.goto(urlOf(variants.find(v => v.name === "static-s5-long")!)); + const inView = (selector: string) => page.locator(selector).evaluate(e => e.getBoundingClientRect().bottom > 0); + expect(await inView(".suites-row")).toBe(true); + expect(await inView(".suite-menu")).toBe(false); + await page.setViewportSize({ width: 1000, height: 700 }); + expect(await inView(".suites-row")).toBe(false); + expect(await inView(".suite-menu")).toBe(true); + expect(await topBarProblems(page)).toEqual([]); + await page.locator(".suite-current").click(); + expect(await page.locator(".suite-list").isVisible()).toBe(true); + await context.close(); + }); + + for (const width of [1440, 1000, 360]) { + test(`a page with five sites does not shift as it loads, at ${width}px`, async () => { + const page = await browser.newPage({ viewport: { width, height: 800 } }); + await page.addInitScript(() => { + (window as unknown as { cls: number }).cls = 0; + new PerformanceObserver(list => { + for (const entry of list.getEntries() as unknown as { value: number; hadRecentInput: boolean }[]) { + if (!entry.hadRecentInput) (window as unknown as { cls: number }).cls += entry.value; + } + }).observe({ type: "layout-shift", buffered: true }); + }); + await page.goto(urlOf(five()), { waitUntil: "load" }); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(500); + expect(await page.evaluate(() => (window as unknown as { cls: number }).cls)).toBe(0); + await page.close(); + }); + } +});