From edfaf204ba2d4b3faf535364b2a3281ee659e9c2 Mon Sep 17 00:00:00 2001 From: Sam Gammon Date: Sat, 21 Nov 2026 20:49:23 -0800 Subject: [PATCH 1/6] feat(apidocs): a suite switcher in the top bar; the module's indexes move to the navigator The top bar now holds only what belongs to the whole site: the navigator toggle, the brand, the version (or the Astro version menu), a switcher between sibling documentation sites, search and the theme switch. Between 1101 and 1180px it overflowed by 31 to 78px, and below 1100px the sibling links were hidden, so a phone could not reach the other suites at all. - The theme's header links are the sibling sites. ThemeLink gains `current`; without it, the entry whose URL is the site's own root (or its baseUrl) is current. The switcher is a row of the sites with the current one marked, or, where the bar has no room, one
menu button that names the current site (closed by Escape and an outside click with the script). Where the navigator is a drawer, the drawer lists the sites first and the bar shows the row only when it fits. - No width is written down. Hidden copies of the labels form a wrapping row whose height (one line or more) places the visible row or the menu, so the layout alone decides, with or without JavaScript. A small script at the end of the bar, run before first paint and on resize, sizes the switcher to what it shows, so a menu leaves no dead space, and hides the other form from the keyboard and assistive technology. The order in which the bar gives way is in apidocs.css: the search field narrows (19rem to 10rem, then 5rem in a drawer layout), the switcher gives way, the product name ends in an ellipsis. - Overview, Packages, All types, Index and Deprecated are at the top of the navigator, under the filter: as many as the site has, one line when at most two, else rows under "Reference" (any three need 223 to 238px against a 223px line at the narrowest navigator, measured in Chromium at both presets). - Footer theme links are resolved from the site root, as header links are; a path from the server root ("/x/") is written as given in both. - The navigator's filter is there on guides-only sites and narrows guides; it never filters the sites, the indexes or the packages. - Fixes found on the way: the drawer took its content's height and sat behind the top bar, unscrollable (align-self: start on a fixed box); links in the deprecated index's summaries were not underlined (axe link-in-text-block). - Astro: the persisted top bar and navigator still update per page. The navigator's blocks keep their order around the kept filter field, the kept filter text is applied to the new rows before the scroll position is put back, and a top bar from another site is sized before it paints. The sample app's sites switch between each other. - The dev bar can show none, one, three or five sibling sites. Tests: test/topbar.test.ts sweeps 320 to 1600px in steps of 20 in the static and the Astro markup, with 0, 1, 3 and 5 sites, with and without a version menu, and with a long product name (nothing wraps, overflows or is cut off); the menu with and without JavaScript; no layout shift at 1440, 1000 and 360px. axe now covers every page kind in light and dark. The Astro app's suite sweeps its own pages and checks the current index link and site across navigations. bun test: 306 pass, 4 skip; the Astro app: 32 pass. Signed-off-by: Sam Gammon --- apps/apidocs-astro/astro.config.mjs | 20 +- apps/apidocs-astro/test/browser.test.ts | 94 ++++++- packages/apidocs/README.md | 43 +++- packages/apidocs/scripts/dev.ts | 28 +- packages/apidocs/src/astro/client.ts | 36 ++- packages/apidocs/src/client/behaviors.tsx | 58 ++++- packages/apidocs/src/components/chrome.tsx | 197 ++++++++++++-- packages/apidocs/src/styles/apidocs.css | 115 +++++++-- packages/apidocs/src/theme.ts | 11 + .../test/__snapshots__/import.test.ts.snap | 2 +- .../test/__snapshots__/narrative.test.ts.snap | 2 +- .../test/__snapshots__/render.test.ts.snap | 8 +- packages/apidocs/test/browser.test.ts | 5 +- packages/apidocs/test/guides-browser.test.ts | 13 + packages/apidocs/test/render.test.ts | 46 +++- packages/apidocs/test/topbar.test.ts | 243 ++++++++++++++++++ 16 files changed, 828 insertions(+), 93 deletions(-) create mode 100644 packages/apidocs/test/topbar.test.ts 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..0066fea 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"); diff --git a/packages/apidocs/README.md b/packages/apidocs/README.md index 8ed3159..0415d80 100644 --- a/packages/apidocs/README.md +++ b/packages/apidocs/README.md @@ -163,6 +163,34 @@ 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`. +### 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 `
` 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 @@ -326,7 +354,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 ``, 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 +371,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 +391,8 @@ The dev server renders pages with the production `render()` and the same compone `/site///`. 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 +423,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/scripts/dev.ts b/packages/apidocs/scripts/dev.ts index 3dd0a84..6c93d45 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; const cache = new Map(); -async function site(server: ViteDevServer, model: string, preset: string): Promise { - 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 { + 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"); @@ -117,6 +129,7 @@ function shell(): string { @elide/apidocs dev + @@ -125,10 +138,11 @@ function shell(): string {
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__/narrative.test.ts.snap b/packages/apidocs/test/__snapshots__/narrative.test.ts.snap index 5d4176c..947ef5a 100644 --- a/packages/apidocs/test/__snapshots__/narrative.test.ts.snap +++ b/packages/apidocs/test/__snapshots__/narrative.test.ts.snap @@ -152,7 +152,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..507ebca 100644
--- a/packages/apidocs/test/__snapshots__/render.test.ts.snap
+++ b/packages/apidocs/test/__snapshots__/render.test.ts.snap
@@ -2,7 +2,7 @@
 
 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)));
+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(
     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)
@@ -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)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

" `; 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/browser.test.ts b/packages/apidocs/test/browser.test.ts index 50c767c..ced5ebf 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({ @@ -204,7 +205,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"]) { 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/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..3739cc6 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 } from "../src/site"; import { checkSite } from "./check"; import { validate } from "./validate"; @@ -139,6 +140,49 @@ describe("layout", () => { expect(html).toContain(' { + 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, '"); + 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, '