refactor(site): share the docs' and static pages' shell code (#63161)

This commit is contained in:
Adam
2026-11-10 11:04:33 -06:00
committed by GitHub
Unverified
parent 9118c948c5
commit 7aa3be190c
16 changed files with 252 additions and 296 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ Read the design-system rules in `DESIGN.md` (also shown at `/dev/components#rule
- Production hydrates no page. The pages in `staticPaths` (`src/static/routes.ts`: home, the product pages, legal, Brand, Press, the changelog, Browse and the font page) render as plain HTML from the same components, without hydration (`src/static/render.tsx`), and so does the not-found page, for every address no route answers. They load one small script, `src/client/entry.ts`, which reads the markup the components render and loads each island in `src/client/islands/` only when the page has it. The app's browser build only provides the stylesheets.
- Between the home page, /product and the product pages, a card grows into its product's hero and back with a cross-document view transition (`card-morph.ts`); every other page change is a plain page load.
- Behaviour both renderings need lives in framework-free modules in `src/component/site/` that the component and the script both call, such as `contents-spy.ts`, `changelog-motion.ts`, `tooltips.ts`, `site-frame.ts`, `theme-switch.ts` and `sheet-motion.ts`. Put new behaviour there. Where a component renders its state from signals and the script keeps its own copy, each names the other in a comment: change both.
- Behaviour both renderings need lives in framework-free modules in `src/component/site/` that the component and the script both call, such as `contents-spy.ts`, `changelog-motion.ts`, `tooltips.ts`, `site-frame.ts`, `theme-switch.ts` and `sheet-motion.ts`. Put new behaviour there. The docs' script (`src/docs/client.ts`) shares the theme switch, copy feedback and heading links (`copy-feedback.ts`), Contents and the search shortcut (`search-key.ts`) with `entry.ts` the same way; the docs' own menus (the section lockup and the section menu) stay in it. Where a component renders its state from signals and the script keeps its own copy, each names the other in a comment: change both.
- `vite dev` renders these pages hydrated, because Design mode and Settings need the app, so a change that only works hydrated looks right there. Check them in a production build served by `perf/serve.ts`: `bun run build`, then `bun perf/serve.ts --port 4300`, and open the page on that port.
- A new page route needs its path in `staticPaths`, or production answers it with the not-found page (`test/static-routes.test.ts` lists the ones that may be missing: the development tools).
-73
View File
@@ -1,73 +0,0 @@
import { activeSection, keepInRail, markStuck } from "~/component/site/contents-spy"
import { holdOpenMenu } from "~/component/site/menu-hold"
import { $, $$, on, target } from "./dom"
// "Contents" (on-this-page.tsx): the aside's list and the phone Contents bar mark the section being
// read (contents-spy.ts), the rail keeps it in view and the phone bar draws its lines once pinned. The
// bar opens as a dropdown that a choice, a tap outside or Escape closes, as ContentsMenu does.
const lists = '[data-component="on-this-page"], [data-component="contents-menu"]'
let links: HTMLAnchorElement[] = []
let frame = 0
let active: string | undefined
export function startContents() {
refreshContents()
if (!links.length) return
addEventListener("scroll", schedule, { passive: true })
addEventListener("resize", schedule, { passive: true })
addEventListener("hashchange", schedule)
on("click", (event) => {
const link = target(event).closest<HTMLAnchorElement>(`:is(${lists}) a`)
if (!link) return
mark(decodeURIComponent(link.hash.slice(1)))
const menu = link.closest("details")
if (menu) menu.open = false
})
document.addEventListener(
"toggle",
(event) => (event.target as Element).matches?.('[data-component="contents-menu"]') && holdOpenMenu(),
true,
)
on("pointerdown", (event) => {
const menu = $<HTMLDetailsElement>('[data-component="contents-menu"][open]')
if (menu && !menu.contains(target(event))) menu.open = false
})
on("keydown", (event) => {
const menu = $<HTMLDetailsElement>('[data-component="contents-menu"][open]')
if (event.key !== "Escape" || !menu) return
menu.open = false
$("summary", menu)?.focus()
})
}
/** Reads the lists again, after an island swapped their items (the legal pages' History). */
export function refreshContents() {
links = $$<HTMLAnchorElement>(`:is(${lists}) a`)
active = undefined
track()
}
function schedule() {
if (frame) return
frame = requestAnimationFrame(() => {
frame = 0
track()
})
}
function track() {
markStuck($('[data-component="contents-menu"]'))
mark(activeSection([...new Set(links.map((link) => decodeURIComponent(link.hash.slice(1))))]))
}
function mark(id: string | undefined) {
if (id === active) return
active = id
links.forEach((link) =>
decodeURIComponent(link.hash.slice(1)) === id
? link.setAttribute("aria-current", "location")
: link.removeAttribute("aria-current"),
)
keepInRail($('[data-component="on-this-page"] [aria-current]'))
}
+10 -50
View File
@@ -1,42 +1,18 @@
import { copyWithFeedback } from "~/component/site/copy-feedback"
import { checkPath, copyPath } from "~/component/site/icon-paths"
import { on, t, target, wait } from "./dom"
// Copy with feedback in place (DESIGN.md), for the static pages and their islands. The docs keep a
// smaller one (src/docs/client.ts copied), as their buttons show their state from data-state alone.
import { t } from "./dom"
/**
* Copies, then marks `button` with data-state "copied" (or "failed") for 1.5s, draws its copy icon as
* a check meanwhile, and says so in `live` if there is one. A later copy from the same button owns the
* mark; the button's own state comes back after.
* Copies with feedback in place (copy-feedback.ts), saying "Copied" in `live` if there is one, with
* the button's copy icon drawn as a check meanwhile.
*/
export async function copied(
button: HTMLElement,
write: () => Promise<unknown>,
live?: Element | null,
message = t("site.action.copied"),
) {
const run = String(Number(button.dataset.run ?? 0) + 1)
button.dataset.run = run
// The state the button rests in (CopyMarkdown's "idle"), or none.
const idle = (button.dataset.idle ??= button.dataset.state ?? "")
const state = await Promise.resolve()
.then(write)
.then(
() => "copied",
() => "failed",
)
export function copied(button: HTMLElement, write: () => Promise<unknown>, live?: Element | null) {
const icon = button.querySelector<SVGPathElement>(`path[d="${copyPath}"], path[d="${checkPath}"]`)
button.dataset.state = state
if (state === "copied") icon?.setAttribute("d", checkPath)
if (state === "copied") icon?.setAttribute("stroke-linecap", "square")
if (live) live.textContent = state === "copied" ? message : ""
await wait(1500)
if (button.dataset.run !== run) return
if (idle) button.dataset.state = idle
if (!idle) delete button.dataset.state
icon?.setAttribute("d", copyPath)
icon?.removeAttribute("stroke-linecap")
if (live) live.textContent = ""
return copyWithFeedback(button, write, t("site.action.copied"), "", live ?? null, (check) => {
icon?.setAttribute("d", check ? checkPath : copyPath)
if (check) icon?.setAttribute("stroke-linecap", "square")
if (!check) icon?.removeAttribute("stroke-linecap")
})
}
/** Copies the text a URL serves, keeping the click's user activation while it loads (Safari needs it). */
@@ -49,19 +25,3 @@ export function copyUrl(url: string) {
}),
])
}
/** Heading links (on-this-page.tsx HeadingLink): copy the section's address and put it in the address bar. */
export function startCopy() {
on("click", (event) => {
const heading = target(event).closest<HTMLElement>("[data-heading-id]")
if (!heading) return
const id = heading.dataset.headingId!
history.replaceState(history.state, "", `#${id}`)
void copied(
heading,
() => navigator.clipboard.writeText(`${location.origin}${location.pathname}#${id}`),
heading.nextElementSibling?.matches('[data-slot="heading-copied"]') ? heading.nextElementSibling : undefined,
t("changelog.share.copied"),
)
})
}
+7 -10
View File
@@ -7,13 +7,14 @@
import { Funnel } from "~/lib/funnel"
import { installConsoleStub } from "~/lib/console-stub"
import type { SearchVia } from "~/component/site/search"
import { isSearchShortcut } from "~/component/site/search-key"
import { markdownShortcut } from "~/component/site/markdown-key"
import { revealHandedOff } from "~/component/site/search-reveal"
import { startTooltips } from "~/component/site/tooltips"
import { copyHeadingLinks } from "~/component/site/copy-feedback"
import { startContents } from "~/component/site/contents-spy"
import { inlineKey } from "~/lib/direction"
import { $, $$, on, site, target } from "./dom"
import { startContents } from "./contents"
import { startCopy } from "./copy"
import { $, $$, on, site, t, target } from "./dom"
import { startFaq } from "./faq"
import { startFrame } from "./footer"
import { startIslands } from "./islands"
@@ -29,7 +30,7 @@ startIslands()
function startShell() {
startTheme()
startMenus()
startCopy()
copyHeadingLinks(t("changelog.share.copied"))
startFaq()
startContents()
startFrame()
@@ -56,13 +57,9 @@ function startShell() {
on("keydown", (event) => {
if (searching) return
if (event.key === "Meta" || event.key === "Control") return void loadSearch()
if (event.defaultPrevented || event.altKey || event.repeat || target(event).closest("[contenteditable]")) return
const command = (event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "k"
const slash =
event.key === "/" && !event.metaKey && !event.ctrlKey && !target(event).closest("input, textarea, select")
if (!command && !slash) return
if (!isSearchShortcut(event)) return
event.preventDefault()
pending.via = slash ? "slash" : "shortcut"
pending.via = event.key === "/" ? "slash" : "shortcut"
void loadSearch()
})
+1 -1
View File
@@ -2,7 +2,7 @@ import { inHistory, pinnedScroll, revealTab } from "~/component/site/legal-tabs"
import { checkPath, copyPath } from "~/component/site/icon-paths"
import { copySelection } from "~/lib/clipboard"
import { strip } from "~/lib/language"
import { refreshContents } from "../contents"
import { refreshContents } from "~/component/site/contents-spy"
import { $, $$, on, target } from "../dom"
/**
+2 -1
View File
@@ -42,7 +42,8 @@ export function startMenus() {
onCloseMenus(closeNav)
on("opencode-nav-menu-open" as keyof DocumentEventMap, () => runMenuClosers(closeNav))
// One highlighted row per menu: keyboard focus follows the pointer into another row (as Site does).
// One highlighted row per menu: keyboard focus follows the pointer into another row (as Site and the
// docs' lockup do, src/docs/client.ts).
on("pointerover", (event) => {
if (event.pointerType !== "mouse") return
const row = target(event).closest<HTMLElement>(
+11 -19
View File
@@ -1,5 +1,5 @@
import { showTheme, themes, type Theme } from "~/component/site/theme-switch"
import { on, site, t, target } from "./dom"
import { startThemeSwitch, type Theme } from "~/component/site/theme-switch"
import { site, t } from "./dom"
// The footer's theme switch: system, light, dark (theme-switch.ts), in step with the browser bar
// colour and form controls.
@@ -8,19 +8,20 @@ const dark = matchMedia("(prefers-color-scheme: dark)")
/** The browser bar colour in a scheme: the "Like letters?" bar's blue while it fills the bottom. */
let barColor: string | undefined
let show: ReturnType<typeof startThemeSwitch> | undefined
export function startTheme() {
show((site.dataset.theme as Theme | undefined) ?? "system")
on("click", (event) => {
if (!target(event).closest('[data-component="theme-toggle"] [data-slot="cycle"]')) return
setTheme(themes[(themes.indexOf(site.dataset.theme as Theme) + 1) % 3])
})
show = startThemeSwitch(
site,
(current, next) => t("site.theme.cycle", { theme: t(`site.theme.${current}`), next: t(`site.theme.${next}`) }),
() => barColor,
)
}
/** Shows and saves a theme (the switch, and search's "Toggle theme"). */
/** Shows and saves a theme (search's "Toggle theme"). */
export function setTheme(theme: Theme) {
localStorage.setItem("opencode-theme", theme)
show(theme)
show?.(theme)
}
/** Whether the page shows the dark theme. */
@@ -29,14 +30,5 @@ export const isDark = () => site.dataset.theme === "dark" || (site.dataset.theme
/** Sets (or clears) the colour the browser bar takes over the theme's. */
export function setBarColor(color: string | undefined) {
barColor = color
show(site.dataset.theme as Theme)
}
function show(theme: Theme) {
showTheme(
site,
theme,
(current, next) => t("site.theme.cycle", { theme: t(`site.theme.${current}`), next: t(`site.theme.${next}`) }),
barColor,
)
show?.()
}
@@ -1,5 +1,82 @@
import { holdOpenMenu } from "./menu-hold"
// "Contents" as the reader scrolls (on-this-page.tsx), with no Solid, so the hydrated pages, the
// static pages (src/client/contents.ts) and the docs (src/docs/client.ts) mark the same section.
// static pages (src/client/entry.ts) and the docs (src/docs/client.ts) mark the same section.
const lists = '[data-component="on-this-page"], [data-component="contents-menu"]'
let links: HTMLAnchorElement[] = []
let frame = 0
let active: string | undefined
let marked: ((id: string | undefined) => void) | undefined
/**
* Runs "Contents" on a page that never hydrates: the aside's list and the phone Contents bar mark the
* section being read, the rail keeps it in view and the phone bar draws its lines once pinned. The
* bar opens as a dropdown that a choice, a tap outside or Escape closes, as ContentsMenu does.
* `onMark` hears each section marked.
*/
export function startContents(onMark?: (id: string | undefined) => void) {
marked = onMark
refreshContents()
if (!links.length) return
addEventListener("scroll", schedule, { passive: true })
addEventListener("resize", schedule, { passive: true })
addEventListener("hashchange", schedule)
document.addEventListener("click", (event) => {
const link = (event.target as Element).closest?.<HTMLAnchorElement>(`:is(${lists}) a`)
if (!link) return
mark(decodeURIComponent(link.hash.slice(1)))
const menu = link.closest("details")
if (menu) menu.open = false
})
document.addEventListener(
"toggle",
(event) => (event.target as Element).matches?.('[data-component="contents-menu"]') && holdOpenMenu(),
true,
)
document.addEventListener("pointerdown", (event) => {
const menu = document.querySelector<HTMLDetailsElement>('[data-component="contents-menu"][open]')
if (menu && !menu.contains(event.target as Node)) menu.open = false
})
document.addEventListener("keydown", (event) => {
const menu = document.querySelector<HTMLDetailsElement>('[data-component="contents-menu"][open]')
if (event.key !== "Escape" || !menu) return
menu.open = false
menu.querySelector("summary")?.focus()
})
}
/** Reads the lists again, after an island swapped their items (the legal pages' History). */
export function refreshContents() {
links = [...document.querySelectorAll<HTMLAnchorElement>(`:is(${lists}) a`)]
active = undefined
track()
}
function schedule() {
if (frame) return
frame = requestAnimationFrame(() => {
frame = 0
track()
})
}
function track() {
markStuck(document.querySelector('[data-component="contents-menu"]'))
mark(activeSection([...new Set(links.map((link) => decodeURIComponent(link.hash.slice(1))))]))
}
function mark(id: string | undefined) {
if (id === active) return
active = id
links.forEach((link) =>
decodeURIComponent(link.hash.slice(1)) === id
? link.setAttribute("aria-current", "location")
: link.removeAttribute("aria-current"),
)
keepInRail(document.querySelector('[data-component="on-this-page"] [aria-current]'))
marked?.(id)
}
/**
* The section being read: the last whose heading has passed a third of the way down the window. At
@@ -0,0 +1,58 @@
// Copy with feedback in place (DESIGN.md), with no Solid, for the pages that never hydrate: the static
// pages and their islands (src/client/copy.ts) and the docs (src/docs/client.ts). The components
// render the same from signals (CopyButton in code-frame.tsx, HeadingLink in on-this-page.tsx).
/**
* Copies, then marks `button` with data-state "copied" (or "failed") for 1.5s, and says `copied` (or
* `failed`) in `live` (by default the live region right after the button) if there is one. `draw`
* hears when "copied" starts and ends (the static pages' buttons draw their copy icon as a check
* meanwhile; the docs' have no icon). A later copy from the same button owns the mark; the state the
* button rests in comes back after.
*/
export async function copyWithFeedback(
button: HTMLElement,
write: () => Promise<unknown>,
copied: string,
failed = "",
live = button.nextElementSibling?.matches("[aria-live]") ? button.nextElementSibling : null,
draw?: (copied: boolean) => void,
) {
const run = String(Number(button.dataset.run ?? 0) + 1)
button.dataset.run = run
// The state the button rests in (CopyButton's "idle"), or none.
const idle = (button.dataset.idle ??= button.dataset.state ?? "")
const state = await Promise.resolve()
.then(write)
.then(
() => "copied",
() => "failed",
)
button.dataset.state = state
if (state === "copied") draw?.(true)
if (live) live.textContent = state === "copied" ? copied : failed
await new Promise((done) => setTimeout(done, 1500))
if (button.dataset.run !== run) return
if (idle) button.dataset.state = idle
if (!idle) delete button.dataset.state
draw?.(false)
if (live) live.textContent = ""
}
/**
* Heading links (HeadingLink): a click copies the section's address and puts it in the address bar,
* and the live region after the link says `copied` (or `failed`).
*/
export function copyHeadingLinks(copied: string, failed?: string) {
document.addEventListener("click", (event) => {
const heading = (event.target as Element).closest?.<HTMLElement>("[data-heading-id]")
if (!heading) return
const id = heading.dataset.headingId
history.replaceState(history.state, "", `#${id}`)
void copyWithFeedback(
heading,
() => navigator.clipboard.writeText(`${location.origin}${location.pathname}#${id}`),
copied,
failed,
)
})
}
@@ -97,7 +97,7 @@ export function OnThisPage(props: { items: ContentsItem[] }) {
* "Contents" folded up for phones, where the aside's list is hidden: put it above the first section of
* any page that passes OnThisPage to <Site aside>. Hidden from 60rem up and in print. On phones it
* sticks under the top bar (and any sticky bar the page adds above it). The static pages drive the same
* markup from src/client/contents.ts, and the docs from src/docs/client.ts.
* markup with startContents (contents-spy.ts), and so do the docs (src/docs/client.ts).
*/
export function ContentsMenu(props: { items: ContentsItem[] }) {
const i18n = useI18n()
@@ -188,8 +188,8 @@ export function SectionHeading(props: { level?: 2 | 3; id: string; title: string
/**
* The inside of a heading: a button with the title that copies the section's address and puts it in
* the address bar, then says "Link copied" for a moment (also to screen readers). `children` replaces
* the plain title for headings with markup of their own. Pages that never hydrate (the docs) do the
* same from a delegated listener keyed on `data-heading-id` (src/docs/client.ts, src/client/copy.ts).
* the plain title for headings with markup of their own. Pages that never hydrate (the static pages
* and the docs) do the same from a delegated listener keyed on `data-heading-id` (copy-feedback.ts).
*/
export function HeadingLink(props: { id: string; title: string; children?: JSX.Element }) {
const i18n = useI18n()
@@ -0,0 +1,11 @@
// The search shortcut, with no Solid, so the hydrated pages (search.tsx, search-palette.tsx), the static
// pages (src/client/entry.ts) and the docs (src/docs/client.ts) open search on the same keys.
/** ⌘K or Ctrl+K anywhere, or "/" outside text fields. */
export function isSearchShortcut(event: KeyboardEvent) {
if (event.defaultPrevented || event.altKey || event.repeat) return false
const target = event.target as HTMLElement
if (target.closest?.("[contenteditable]")) return false
if ((event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "k") return true
return event.key === "/" && !event.metaKey && !event.ctrlKey && !target.closest?.("input, textarea, select")
}
@@ -8,15 +8,9 @@ import { strip } from "~/lib/language"
import { devicePreviewOpenEvent, inDevicePreview } from "~/lib/platform"
import { siteSettings, type SiteSettings } from "./settings"
import { onCloseMenus } from "./menu-open"
import { isSearchShortcut } from "./search-key"
import { handOff, reveal, trim } from "./search-reveal"
import {
isSearchShortcut,
searchOpenEvent,
setSearchAnnouncement,
setSearchShown,
type SearchVia,
type SiteSearchProps,
} from "./search"
import { searchOpenEvent, setSearchAnnouncement, setSearchShown, type SearchVia, type SiteSearchProps } from "./search"
import type { SearchAction, SearchGroup, SearchItem, SearchResult } from "./search-index"
/**
+1 -9
View File
@@ -3,6 +3,7 @@ import { createSignal, onCleanup, onMount, Show, type Component } from "solid-js
import { Dynamic } from "solid-js/web"
import { useI18n } from "~/context/i18n"
import { detectPlatform, isApple } from "~/lib/platform"
import { isSearchShortcut } from "./search-key"
import { revealHandedOff } from "./search-reveal"
import { siteSettings } from "./settings"
@@ -39,15 +40,6 @@ export const setSearchAnnouncement = setAnnouncement
/** How the search was opened, for the funnel's `search.opened`. */
export type SearchVia = "shortcut" | "slash" | "button"
/** ⌘K or Ctrl+K anywhere, or "/" outside text fields. */
export function isSearchShortcut(event: KeyboardEvent) {
if (event.defaultPrevented || event.altKey || event.repeat) return false
const target = event.target as HTMLElement
if (target.closest?.("[contenteditable]")) return false
if ((event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "k") return true
return event.key === "/" && !event.metaKey && !event.ctrlKey && !target.closest?.("input, textarea, select")
}
let palette: Promise<typeof import("./search-palette")> | undefined
/** Starts loading the dialog and the index, for a trigger's hover or focus. */
export function prefetchSearch() {
@@ -6,11 +6,33 @@
export const themes = ["system", "light", "dark"] as const
export type Theme = (typeof themes)[number]
/**
* Runs the switch: shows the theme the page starts in, and a click on the switch shows and saves the
* next one. `label` names the switch for the theme it shows and the one it goes to; `bar`, while it
* gives a colour, replaces the browser bar's. Returns `show`, which shows a theme (by default the
* current one) without saving it.
*/
export function startThemeSwitch(
site: HTMLElement,
label: (theme: Theme, next: Theme) => string,
bar?: () => string | undefined,
) {
const show = (theme = (site.dataset.theme as Theme | undefined) ?? "system") => showTheme(site, theme, label, bar?.())
show()
document.addEventListener("click", (event) => {
if (!(event.target as Element).closest?.('[data-component="theme-toggle"] [data-slot="cycle"]')) return
const next = themes[(themes.indexOf(site.dataset.theme as Theme) + 1) % 3]
localStorage.setItem("opencode-theme", next)
show(next)
})
return show
}
/**
* Shows `theme` on the site root and the switch (its label, from `label`, and its icon), and colours
* the browser bar and form controls for it. `bar` replaces the bar's colour while it is set.
*/
export function showTheme(site: HTMLElement, theme: Theme, label: (theme: Theme, next: Theme) => string, bar?: string) {
function showTheme(site: HTMLElement, theme: Theme, label: (theme: Theme, next: Theme) => string, bar?: string) {
site.dataset.theme = theme
const next = themes[(themes.indexOf(theme) + 1) % 3]
document.querySelectorAll('[data-component="theme-toggle"] [data-slot="cycle"]').forEach((cycle) => {
+1 -1
View File
@@ -17,7 +17,7 @@
- Pages are plain HTML in the site's docs layout (`layouts/DocsLayout.tsx`: the root attributes production renders, the logo and section lockup, the section nav, the article, search and Contents, and the site's footer). They render the site's own components on the server (`component/site/`: `DocsLockup`, `CodeFrame`, `FileTree`, `HeadingLink`, `OnThisPage`, `ContentsMenu`, the phone menu, the footer's parts) with the English strings, and never hydrate. Use those components instead of copying their markup; a component the docs need to drive from `client.ts` renders its state as attributes (`hidden`, `aria-expanded`, `data-state`, `data-code`).
- A page links its stylesheet, `styles/docs.css` (the site's stylesheets, `docs-variants.css` and the docs' own base rules, built with the site's production CSS plugins), and the one browser script, `client.ts`. They never load the site's built files, and the site's pages never load the docs'.
- Everything a page loads lives under `/docs` (the stylesheet, script and fonts are built to `/docs/_build`, images are in `public/docs/assets`), so the docs never depend on the site's files and never collide with them (the site's own build files are at `/_build`). The build fails otherwise.
- Interactive pieces (the theme switch, copy buttons, heading links, tabs, the lockup's menus, the phone menus, the Contents rail, search, the status bars) are delegated listeners in `client.ts`, keyed on the attributes the components render. The Contents rail, the section nav's scrolling and the theme switch call the site's framework-free modules (`component/site/contents-spy.ts`, `site-frame.ts`, `theme-switch.ts`), so they behave as on the site's pages. Don't add Solid state or effects to docs components; they only run on the server. `script/build.ts` fails when `client.ts` is over 8 kB gzipped or `docs.css` over 30 kB. The logo and product menus (`@opencode/nav-menus`) load on first use (`component/site/nav-intent.ts`).
- Interactive pieces (the theme switch, copy buttons, heading links, tabs, the lockup's menus, the phone menus, the Contents rail, search, the status bars) are delegated listeners in `client.ts`, keyed on the attributes the components render. What the site's pages do too comes from the site's framework-free modules, so it behaves as on the site's pages: the theme switch (`component/site/theme-switch.ts`), copy feedback and heading links (`copy-feedback.ts`), the Contents rail and its phone bar (`contents-spy.ts`), the section nav's scrolling (`site-frame.ts`) and the search shortcut (`search-key.ts`). Put shell behaviour both need there, not in `client.ts`. The lockup's and section menus are the docs' own. Don't add Solid state or effects to docs components; they only run on the server. `script/build.ts` fails when `client.ts` is over 8 kB gzipped or `docs.css` over 30 kB. The logo and product menus (`@opencode/nav-menus`) load on first use (`component/site/nav-intent.ts`).
- `client.ts` also reports the page to the Console's funnel, as the site's pages do (the site's `AGENTS.md`, "Funnel"). Its config (`lib/funnel-config.ts`) is built in, since a chunk would bring Vite's preload helper into every page. Code blocks are `data-funnel-copy` regions and tabs carry `data-funnel`; search reports counts, never the query.
- The theme is the site's (`opencode-theme`, the site's pre-paint script), inline in `layouts/DocsLayout.tsx` so pages never flash. Navigation is ordinary page loads, made instant by Speculation Rules and cross-document view transitions.
- `vite.ts` compiles MDX the way Astro's MDX integration did (GitHub-flavoured Markdown, smart punctuation, Shiki with the github-light and github-dark themes, GitHub-style heading ids). `rehype-shiki.ts` puts each fenced block in the site's `CodeFrame` (a terminal for shell, `FileTree` for a `├──` tree, the file's icon for a `title="file"`), and `rehype-headings.ts` wraps h2 and h3 in `HeadingLink`.
+43 -118
View File
@@ -4,12 +4,14 @@
// menus, the phone menus, the Contents rail, search, the status bars and the funnel.
import { Funnel } from "../lib/funnel"
import { downloadOf, surfaceOf, targetOf } from "../lib/funnel-config"
import { activeSection, keepInRail, markStuck } from "../component/site/contents-spy"
import { startContents } from "../component/site/contents-spy"
import { copyHeadingLinks, copyWithFeedback } from "../component/site/copy-feedback"
import { fanMotion } from "../component/site/fan-motion"
import { holdOpenMenu } from "../component/site/menu-hold"
import { navMenusOnIntent } from "../component/site/nav-intent"
import { isSearchShortcut } from "../component/site/search-key"
import { sectionNavScroll } from "../component/site/site-frame"
import { showTheme, themes, type Theme } from "../component/site/theme-switch"
import { startThemeSwitch } from "../component/site/theme-switch"
// The page reports to the Console's funnel like the site's (lib/funnel.ts), in its language (English but on the V1
// docs' other languages), at the host's root like the site; their config is built in, as a chunk would bring Vite's
@@ -37,68 +39,28 @@ const inline = (key: string) =>
const wait = (ms: number) => new Promise((done) => setTimeout(done, ms))
// The theme switch (component/site/theme-switch.ts), saved as the site saves it, so the docs and the
// site share one choice.
const show = (theme: Theme) =>
showTheme(site, theme, (current, next) => fill(strings.cycle, { theme: strings[current], next: strings[next] }))
show((site.dataset.theme as Theme) ?? "system")
// Copy with feedback in place (DESIGN.md): the button's data-state shows "Copied" or "Failed" for
// 1.5s, and the live region after it says so. The static pages' copied() (src/client/copy.ts) also
// draws the copy icon as a check and keeps a resting state, which the docs' buttons don't have.
async function copied(
button: HTMLElement,
write: () => Promise<unknown>,
message: string,
failure = strings.copyFailed,
) {
const live = button.nextElementSibling?.matches("[aria-live]") ? button.nextElementSibling : undefined
const run = String(Number(button.dataset.run ?? 0) + 1)
button.dataset.run = run
const state = await Promise.resolve()
.then(write)
.then(
() => "copied",
() => "failed",
)
button.dataset.state = state
if (live) live.textContent = state === "copied" ? message : failure
await wait(1500)
// A later copy owns the label now.
if (button.dataset.run !== run) return
button.dataset.state = "idle"
if (live) live.textContent = ""
}
// site share one choice, and heading links (copy-feedback.ts), as on the site's pages.
startThemeSwitch(site, (current, next) => fill(strings.cycle, { theme: strings[current], next: strings[next] }))
copyHeadingLinks(strings.linkCopied, strings.copyFailed)
const clipboard = (text: string) => navigator.clipboard.writeText(text)
on("click", (event) => {
const target = event.target as Element
const cycle = target.closest("[data-slot=cycle]")
if (cycle) {
const theme = themes[(themes.indexOf(site.dataset.theme as Theme) + 1) % 3]
localStorage.setItem("opencode-theme", theme)
return show(theme)
}
const copy = target.closest<HTMLElement>("[data-code]")
if (copy) return copied(copy, () => clipboard(copy.dataset.code ?? ""), strings.copied, strings.codeFailed)
const heading = target.closest<HTMLElement>("[data-heading-id]")
if (heading) {
const id = heading.dataset.headingId
history.replaceState(history.state, "", `#${id}`)
return copied(heading, () => clipboard(`${location.origin}${location.pathname}#${id}`), strings.linkCopied)
}
// Copy with feedback in place (copy-feedback.ts): the live region after the button says how it went.
if (copy) return copyWithFeedback(copy, () => clipboard(copy.dataset.code ?? ""), strings.copied, strings.codeFailed)
const markdown = target.closest<HTMLElement>("[data-copy-markdown]")
if (markdown)
return copied(
return copyWithFeedback(
markdown,
() =>
fetch(location.pathname, { headers: { Accept: "text/markdown" } }).then((response) =>
response.ok ? response.text().then(clipboard) : Promise.reject(),
),
strings.markdownCopied,
strings.copyFailed,
)
const tab = target.closest<HTMLElement>("[data-code-tab], [data-plan-tab]")
@@ -144,20 +106,14 @@ function toggleSection(open?: boolean) {
holdOpenMenu()
}
// The Contents bar's list holds the page still while it's open (component/site/menu-hold.ts).
document.addEventListener(
"toggle",
(event) => (event.target as Element).matches("[data-component=contents-menu]") && holdOpenMenu(),
true,
)
phone.addEventListener("change", () => {
toggleSection(false)
closeLockup()
})
// The logo menu and the product menu (on DOCS), shared with the site and the other OpenCode sites (packages/nav-menus),
// loaded on first use (nav-intent.ts). Opening one closes the lockup's own menus.
// loaded on first use (nav-intent.ts). Opening one closes the lockup's own menus, as the static pages' script closes
// the site's (src/client/menus.ts).
const navMenus = navMenusOnIntent({ link: (path) => path })
on("opencode-nav-menu-open" as keyof DocumentEventMap, () => closeLockup())
@@ -305,7 +261,8 @@ on("keydown", (event) => {
})
// The flyout opens while the pointer rests on "Docs" and closes 300ms after it leaves, so the pointer
// can cut across to it. Keyboard focus follows the pointer between rows, so only one row looks active.
// can cut across to it. Keyboard focus follows the pointer between rows, so only one row looks active, as in the
// static pages' menus (src/client/menus.ts).
on("pointerover", (event) => {
if (event.pointerType !== "mouse" || !lockup) return
const target = event.target as Element
@@ -324,8 +281,6 @@ on("pointerover", (event) => {
on("pointerdown", (event) => {
const target = event.target as Element
if (lockup && !lockup.contains(target)) closeLockup()
const contents = $<HTMLDetailsElement>("[data-component=contents-menu][open]")
if (contents && !contents.contains(target)) contents.open = false
const section = $("[data-component=section-nav][data-open]")
if (section && !section.contains(target)) toggleSection(false)
})
@@ -350,31 +305,21 @@ on("change", (event) => {
if (select) location.assign(select.value)
})
// Escape closes what's open (menus return focus to their button); "0" goes to the site's home page,
// as on the site; "/", ⌘K and Ctrl+K open search.
// Escape closes the section menu (the Contents menu closes itself, contents-spy.ts) and gives focus
// back to its button; "/", ⌘K and Ctrl+K open search (search-key.ts); "0" goes to the site's home
// page, as on the site's pages (src/client/entry.ts, which also has the nav's number keys).
on("keydown", (event) => {
const typing = (event.target as Element).closest?.("input, textarea, select, [contenteditable]")
if (event.key === "Escape") {
const contents = $<HTMLDetailsElement>("[data-component=contents-menu][open]")
if (contents) {
contents.open = false
$("summary", contents)?.focus()
}
if ($("[data-component=section-nav][data-open]")) {
toggleSection(false)
$("[data-slot=section-toggle]")?.focus()
}
if (event.key === "Escape" && $("[data-component=section-nav][data-open]")) {
toggleSection(false)
$("[data-slot=section-toggle]")?.focus()
}
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
if (isSearchShortcut(event)) {
event.preventDefault()
return openSearch("shortcut")
}
if (event.metaKey || event.ctrlKey || event.altKey || event.repeat || typing) return
if (event.key === "/") {
event.preventDefault()
openSearch("shortcut")
}
if (event.key === "0") location.assign("/")
const typing = (event.target as Element).closest?.("input, textarea, select, [contenteditable]")
if (event.key === "0" && !event.metaKey && !event.ctrlKey && !event.altKey && !event.repeat && !typing)
location.assign("/")
})
// The section nav scrolls under the logo and lockup, as on the site's pages (component/site/site-frame.ts).
@@ -383,13 +328,13 @@ sectionNavScroll(nav)
// The sidebar leaves with the article at the page's end, but the logo and lockup stay fixed
// (site.css): while it is on its way out its items pass under them, and data-under fades them there,
// as Site does on the site's own pages. The scroll spy below sets it, in the same frame.
// as Site does on the site's own pages.
const sidebar = nav.parentElement!
const under = () => sidebar.toggleAttribute("data-under", sidebar.getBoundingClientRect().top < -0.5)
addEventListener("scroll", under, { passive: true })
addEventListener("resize", under, { passive: true })
under()
// The Contents rail and its phone bar mark the section being read, the rail keeps it in view and the
// phone bar draws its lines once pinned, as on the site's pages (component/site/contents-spy.ts).
const links = $$<HTMLAnchorElement>(":is([data-component=on-this-page], [data-component=contents-menu]) a")
const ids = [...new Set(links.map((link) => decodeURIComponent(link.hash.slice(1))))]
// The phone Contents bar names the section being read. A new name replaces
// the old within the label's own line: the old leaves upward (4px, fading out, 150ms) as the new comes
// up from 4px below (fading in, 200ms), both on the strong ease-out, transform and opacity only. A swap
@@ -433,47 +378,27 @@ function nameSection(title: string, animate: boolean) {
)
}
let spied = ""
function spy() {
sidebar.toggleAttribute("data-under", sidebar.getBoundingClientRect().top < -0.5)
const id = activeSection(ids)
markStuck($("[data-component=contents-menu]"))
if (id === spied) return
const named = links.find(
(link) => link.closest("[data-docs-contents]") && decodeURIComponent(link.hash.slice(1)) === id,
)
if (named) nameSection(named.textContent ?? "", spied !== "")
spied = id ?? ""
links.forEach((link) =>
decodeURIComponent(link.hash.slice(1)) === id
? link.setAttribute("aria-current", "location")
: link.removeAttribute("aria-current"),
)
keepInRail($("[data-component=on-this-page] [aria-current]"))
}
let frame = 0
const schedule = () => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(spy)
}
addEventListener("scroll", schedule, { passive: true })
addEventListener("resize", schedule, { passive: true })
on("click", (event) => {
const link = (event.target as Element).closest("[data-component=contents-menu] a")
const menu = link?.closest("details")
if (menu) menu.open = false
})
// An address naming an endpoint or schema of the API reference opens its card.
// An address naming an endpoint or schema of the API reference opens its card, before Contents reads
// the page.
function reveal() {
const target = location.hash && document.getElementById(decodeURIComponent(location.hash.slice(1)))
const card = target && target.closest("details")
if (card) card.open = true
schedule()
}
addEventListener("hashchange", reveal)
reveal()
// The Contents rail, and its phone bar (a dropdown) named after the section marked, as on the site's
// pages (contents-spy.ts).
let named = false
startContents((id) => {
const link = $$<HTMLAnchorElement>("[data-docs-contents] a").find(
(item) => decodeURIComponent(item.hash.slice(1)) === id,
)
if (link) nameSection(link.textContent ?? "", named)
named = true
})
// Search: the site's palette over Pagefind's full-text index of the docs, loaded from its built file on
// first use or as soon as a search looks likely. Through `Function`, because Vite would wrap a plain
// import() in its preload helper, a second script on every page for a file it can't preload. The funnel