Skip to content

Commit 7aa3be1

Browse files
authored
refactor(site): share the docs' and static pages' shell code (#63161)
1 parent 9118c94 commit 7aa3be1

16 files changed

Lines changed: 252 additions & 296 deletions

File tree

‎services/site/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Read the design-system rules in `DESIGN.md` (also shown at `/dev/components#rule
2323

2424
- 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.
2525
- 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.
26-
- 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.
26+
- 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.
2727
- `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.
2828
- 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).
2929

‎services/site/src/client/contents.ts‎

Lines changed: 0 additions & 73 deletions
This file was deleted.

‎services/site/src/client/copy.ts‎

Lines changed: 10 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,18 @@
1+
import { copyWithFeedback } from "~/component/site/copy-feedback"
12
import { checkPath, copyPath } from "~/component/site/icon-paths"
2-
import { on, t, target, wait } from "./dom"
3-
4-
// Copy with feedback in place (DESIGN.md), for the static pages and their islands. The docs keep a
5-
// smaller one (src/docs/client.ts copied), as their buttons show their state from data-state alone.
3+
import { t } from "./dom"
64

75
/**
8-
* Copies, then marks `button` with data-state "copied" (or "failed") for 1.5s, draws its copy icon as
9-
* a check meanwhile, and says so in `live` if there is one. A later copy from the same button owns the
10-
* mark; the button's own state comes back after.
6+
* Copies with feedback in place (copy-feedback.ts), saying "Copied" in `live` if there is one, with
7+
* the button's copy icon drawn as a check meanwhile.
118
*/
12-
export async function copied(
13-
button: HTMLElement,
14-
write: () => Promise<unknown>,
15-
live?: Element | null,
16-
message = t("site.action.copied"),
17-
) {
18-
const run = String(Number(button.dataset.run ?? 0) + 1)
19-
button.dataset.run = run
20-
// The state the button rests in (CopyMarkdown's "idle"), or none.
21-
const idle = (button.dataset.idle ??= button.dataset.state ?? "")
22-
const state = await Promise.resolve()
23-
.then(write)
24-
.then(
25-
() => "copied",
26-
() => "failed",
27-
)
9+
export function copied(button: HTMLElement, write: () => Promise<unknown>, live?: Element | null) {
2810
const icon = button.querySelector<SVGPathElement>(`path[d="${copyPath}"], path[d="${checkPath}"]`)
29-
button.dataset.state = state
30-
if (state === "copied") icon?.setAttribute("d", checkPath)
31-
if (state === "copied") icon?.setAttribute("stroke-linecap", "square")
32-
if (live) live.textContent = state === "copied" ? message : ""
33-
await wait(1500)
34-
if (button.dataset.run !== run) return
35-
if (idle) button.dataset.state = idle
36-
if (!idle) delete button.dataset.state
37-
icon?.setAttribute("d", copyPath)
38-
icon?.removeAttribute("stroke-linecap")
39-
if (live) live.textContent = ""
11+
return copyWithFeedback(button, write, t("site.action.copied"), "", live ?? null, (check) => {
12+
icon?.setAttribute("d", check ? checkPath : copyPath)
13+
if (check) icon?.setAttribute("stroke-linecap", "square")
14+
if (!check) icon?.removeAttribute("stroke-linecap")
15+
})
4016
}
4117

4218
/** 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) {
4925
}),
5026
])
5127
}
52-
53-
/** Heading links (on-this-page.tsx HeadingLink): copy the section's address and put it in the address bar. */
54-
export function startCopy() {
55-
on("click", (event) => {
56-
const heading = target(event).closest<HTMLElement>("[data-heading-id]")
57-
if (!heading) return
58-
const id = heading.dataset.headingId!
59-
history.replaceState(history.state, "", `#${id}`)
60-
void copied(
61-
heading,
62-
() => navigator.clipboard.writeText(`${location.origin}${location.pathname}#${id}`),
63-
heading.nextElementSibling?.matches('[data-slot="heading-copied"]') ? heading.nextElementSibling : undefined,
64-
t("changelog.share.copied"),
65-
)
66-
})
67-
}

‎services/site/src/client/entry.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,14 @@
77
import { Funnel } from "~/lib/funnel"
88
import { installConsoleStub } from "~/lib/console-stub"
99
import type { SearchVia } from "~/component/site/search"
10+
import { isSearchShortcut } from "~/component/site/search-key"
1011
import { markdownShortcut } from "~/component/site/markdown-key"
1112
import { revealHandedOff } from "~/component/site/search-reveal"
1213
import { startTooltips } from "~/component/site/tooltips"
14+
import { copyHeadingLinks } from "~/component/site/copy-feedback"
15+
import { startContents } from "~/component/site/contents-spy"
1316
import { inlineKey } from "~/lib/direction"
14-
import { $, $$, on, site, target } from "./dom"
15-
import { startContents } from "./contents"
16-
import { startCopy } from "./copy"
17+
import { $, $$, on, site, t, target } from "./dom"
1718
import { startFaq } from "./faq"
1819
import { startFrame } from "./footer"
1920
import { startIslands } from "./islands"
@@ -29,7 +30,7 @@ startIslands()
2930
function startShell() {
3031
startTheme()
3132
startMenus()
32-
startCopy()
33+
copyHeadingLinks(t("changelog.share.copied"))
3334
startFaq()
3435
startContents()
3536
startFrame()
@@ -56,13 +57,9 @@ function startShell() {
5657
on("keydown", (event) => {
5758
if (searching) return
5859
if (event.key === "Meta" || event.key === "Control") return void loadSearch()
59-
if (event.defaultPrevented || event.altKey || event.repeat || target(event).closest("[contenteditable]")) return
60-
const command = (event.metaKey || event.ctrlKey) && !event.shiftKey && event.key.toLowerCase() === "k"
61-
const slash =
62-
event.key === "/" && !event.metaKey && !event.ctrlKey && !target(event).closest("input, textarea, select")
63-
if (!command && !slash) return
60+
if (!isSearchShortcut(event)) return
6461
event.preventDefault()
65-
pending.via = slash ? "slash" : "shortcut"
62+
pending.via = event.key === "/" ? "slash" : "shortcut"
6663
void loadSearch()
6764
})
6865

‎services/site/src/client/islands/legal.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { inHistory, pinnedScroll, revealTab } from "~/component/site/legal-tabs"
22
import { checkPath, copyPath } from "~/component/site/icon-paths"
33
import { copySelection } from "~/lib/clipboard"
44
import { strip } from "~/lib/language"
5-
import { refreshContents } from "../contents"
5+
import { refreshContents } from "~/component/site/contents-spy"
66
import { $, $$, on, target } from "../dom"
77

88
/**

‎services/site/src/client/menus.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ export function startMenus() {
4242
onCloseMenus(closeNav)
4343
on("opencode-nav-menu-open" as keyof DocumentEventMap, () => runMenuClosers(closeNav))
4444

45-
// One highlighted row per menu: keyboard focus follows the pointer into another row (as Site does).
45+
// One highlighted row per menu: keyboard focus follows the pointer into another row (as Site and the
46+
// docs' lockup do, src/docs/client.ts).
4647
on("pointerover", (event) => {
4748
if (event.pointerType !== "mouse") return
4849
const row = target(event).closest<HTMLElement>(

‎services/site/src/client/theme.ts‎

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { showTheme, themes, type Theme } from "~/component/site/theme-switch"
2-
import { on, site, t, target } from "./dom"
1+
import { startThemeSwitch, type Theme } from "~/component/site/theme-switch"
2+
import { site, t } from "./dom"
33

44
// The footer's theme switch: system, light, dark (theme-switch.ts), in step with the browser bar
55
// colour and form controls.
@@ -8,19 +8,20 @@ const dark = matchMedia("(prefers-color-scheme: dark)")
88

99
/** The browser bar colour in a scheme: the "Like letters?" bar's blue while it fills the bottom. */
1010
let barColor: string | undefined
11+
let show: ReturnType<typeof startThemeSwitch> | undefined
1112

1213
export function startTheme() {
13-
show((site.dataset.theme as Theme | undefined) ?? "system")
14-
on("click", (event) => {
15-
if (!target(event).closest('[data-component="theme-toggle"] [data-slot="cycle"]')) return
16-
setTheme(themes[(themes.indexOf(site.dataset.theme as Theme) + 1) % 3])
17-
})
14+
show = startThemeSwitch(
15+
site,
16+
(current, next) => t("site.theme.cycle", { theme: t(`site.theme.${current}`), next: t(`site.theme.${next}`) }),
17+
() => barColor,
18+
)
1819
}
1920

20-
/** Shows and saves a theme (the switch, and search's "Toggle theme"). */
21+
/** Shows and saves a theme (search's "Toggle theme"). */
2122
export function setTheme(theme: Theme) {
2223
localStorage.setItem("opencode-theme", theme)
23-
show(theme)
24+
show?.(theme)
2425
}
2526

2627
/** Whether the page shows the dark theme. */
@@ -29,14 +30,5 @@ export const isDark = () => site.dataset.theme === "dark" || (site.dataset.theme
2930
/** Sets (or clears) the colour the browser bar takes over the theme's. */
3031
export function setBarColor(color: string | undefined) {
3132
barColor = color
32-
show(site.dataset.theme as Theme)
33-
}
34-
35-
function show(theme: Theme) {
36-
showTheme(
37-
site,
38-
theme,
39-
(current, next) => t("site.theme.cycle", { theme: t(`site.theme.${current}`), next: t(`site.theme.${next}`) }),
40-
barColor,
41-
)
33+
show?.()
4234
}

‎services/site/src/component/site/contents-spy.ts‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,82 @@
1+
import { holdOpenMenu } from "./menu-hold"
2+
13
// "Contents" as the reader scrolls (on-this-page.tsx), with no Solid, so the hydrated pages, the
2-
// static pages (src/client/contents.ts) and the docs (src/docs/client.ts) mark the same section.
4+
// static pages (src/client/entry.ts) and the docs (src/docs/client.ts) mark the same section.
5+
6+
const lists = '[data-component="on-this-page"], [data-component="contents-menu"]'
7+
let links: HTMLAnchorElement[] = []
8+
let frame = 0
9+
let active: string | undefined
10+
let marked: ((id: string | undefined) => void) | undefined
11+
12+
/**
13+
* Runs "Contents" on a page that never hydrates: the aside's list and the phone Contents bar mark the
14+
* section being read, the rail keeps it in view and the phone bar draws its lines once pinned. The
15+
* bar opens as a dropdown that a choice, a tap outside or Escape closes, as ContentsMenu does.
16+
* `onMark` hears each section marked.
17+
*/
18+
export function startContents(onMark?: (id: string | undefined) => void) {
19+
marked = onMark
20+
refreshContents()
21+
if (!links.length) return
22+
addEventListener("scroll", schedule, { passive: true })
23+
addEventListener("resize", schedule, { passive: true })
24+
addEventListener("hashchange", schedule)
25+
document.addEventListener("click", (event) => {
26+
const link = (event.target as Element).closest?.<HTMLAnchorElement>(`:is(${lists}) a`)
27+
if (!link) return
28+
mark(decodeURIComponent(link.hash.slice(1)))
29+
const menu = link.closest("details")
30+
if (menu) menu.open = false
31+
})
32+
document.addEventListener(
33+
"toggle",
34+
(event) => (event.target as Element).matches?.('[data-component="contents-menu"]') && holdOpenMenu(),
35+
true,
36+
)
37+
document.addEventListener("pointerdown", (event) => {
38+
const menu = document.querySelector<HTMLDetailsElement>('[data-component="contents-menu"][open]')
39+
if (menu && !menu.contains(event.target as Node)) menu.open = false
40+
})
41+
document.addEventListener("keydown", (event) => {
42+
const menu = document.querySelector<HTMLDetailsElement>('[data-component="contents-menu"][open]')
43+
if (event.key !== "Escape" || !menu) return
44+
menu.open = false
45+
menu.querySelector("summary")?.focus()
46+
})
47+
}
48+
49+
/** Reads the lists again, after an island swapped their items (the legal pages' History). */
50+
export function refreshContents() {
51+
links = [...document.querySelectorAll<HTMLAnchorElement>(`:is(${lists}) a`)]
52+
active = undefined
53+
track()
54+
}
55+
56+
function schedule() {
57+
if (frame) return
58+
frame = requestAnimationFrame(() => {
59+
frame = 0
60+
track()
61+
})
62+
}
63+
64+
function track() {
65+
markStuck(document.querySelector('[data-component="contents-menu"]'))
66+
mark(activeSection([...new Set(links.map((link) => decodeURIComponent(link.hash.slice(1))))]))
67+
}
68+
69+
function mark(id: string | undefined) {
70+
if (id === active) return
71+
active = id
72+
links.forEach((link) =>
73+
decodeURIComponent(link.hash.slice(1)) === id
74+
? link.setAttribute("aria-current", "location")
75+
: link.removeAttribute("aria-current"),
76+
)
77+
keepInRail(document.querySelector('[data-component="on-this-page"] [aria-current]'))
78+
marked?.(id)
79+
}
380

481
/**
582
* The section being read: the last whose heading has passed a third of the way down the window. At

0 commit comments

Comments
 (0)