feat(site): report the site and docs to the funnel (#62407)

This commit is contained in:
Adam
2026-11-06 12:58:15 -06:00
committed by GitHub
Unverified
parent a04dc98d60
commit 151a14a012
31 changed files with 542 additions and 50 deletions
+7
View File
@@ -19,6 +19,13 @@ Read the design-system rules in `DESIGN.md` (also shown at `/dev/components#rule
- A button that opens a menu, popover, dropdown, sheet or dialog sets `aria-expanded="true"` while it is open and is styled from that attribute, not hover: filled and split buttons fill with the link blue (like the product cards' split chevron), neutral buttons keep their pressed grey, and text or nav triggers take the current-item colour with the chevron flipped; Escape closes and returns focus to the trigger.
## Funnel
- Every page and the docs report to the Console's funnel through `src/lib/funnel.ts`: `entry-client.tsx` and `src/docs/client.ts` start it, and it loads the Console's tracker (`/console/funnel/v1.js`) with `src/lib/funnel-config.ts` once the visitor first presses a key or the pointer, or the page is idle. Keep the stub free of imports, and imported only by `entry-client.tsx` on the site, so it stays in the entry chunk and the config and the tracker stay out of every page's first JavaScript.
- The tracker reads the markup: `data-section` names a part of a page (`section.viewed`, and every click's section), `data-funnel` names a control, `data-funnel-copy` (with `data-funnel-method`) marks what a copy button or a selection inside copies, `data-funnel-surface` names a page's surface (the 404 page), and `data-funnel="ignore"` leaves a control out. Give a new page a surface in `surfaceOf` (`test/funnel.test.ts` fails until you do) and its main parts a `data-section`.
- `data-section` names, `data-funnel` slugs and surfaces are analytics keys: rename one only together with the reports that read it.
- Never send what a visitor typed. Code that reports its own events (search, the Markdown shortcut) pushes them onto `window.__ocFunnel` (`Funnel.track` in the docs), with counts and lengths, never text.
## Boundaries
- This service is the website and the V2 docs, deployed as its own Worker with `cf` (`cloudflare.config.ts`, `script/build.ts`). Never add Wrangler or SST here.
+7 -7
View File
@@ -68,21 +68,21 @@ const budgets: Record<string, number> = {
"brand/index.tsx": 107,
"changelog/[tag].tsx": 113,
"changelog/index.tsx": 112,
"desktop.tsx": 126,
"desktop.tsx": 126.3,
"devices.tsx": 51,
"extensions/browse.tsx": 99,
"font/index.tsx": 121,
"ide.tsx": 126,
"ide.tsx": 126.3,
"index.tsx": 118,
"legal/index.tsx": 148,
"legal/privacy-policy/index.tsx": 137,
"legal/terms-of-service/index.tsx": 135,
"mini.tsx": 126,
"mobile.tsx": 126,
"mini.tsx": 126.3,
"mobile.tsx": 126.3,
"press/index.tsx": 112,
"product/index.tsx": 113,
"sdk.tsx": 126,
"terminal.tsx": 126,
"product/index.tsx": 113.3,
"sdk.tsx": 126.3,
"terminal.tsx": 126.3,
"video-editor/index.tsx": 49,
}
type Chunk = { file: string; imports?: string[] }
@@ -20,6 +20,7 @@ export function AgentRulesButton(props: { label: string; copied: string; source:
type="button"
data-component="site-button"
data-slot="agent-rules"
data-funnel-copy="agent-rules"
data-variant="neutral"
data-design="agentButtonCopied"
data-design-copy="brand.agentButton"
@@ -21,7 +21,8 @@ export function NotFoundPage(props: { title: string; status: number; only3D?: bo
const [phone, setPhone] = createSignal(false)
onMount(() => setPhone(isPhone()))
return (
<main data-page="not-found">
// Names its surface for the funnel, whatever the address (lib/funnel.ts).
<main data-page="not-found" data-funnel-surface="www-404">
<Title>{props.title}</Title>
<Meta name="robots" content="noindex" />
{/* A dead link pasted into a chat still unfurls, so the 404 has its own card (script/og.ts). */}
@@ -63,6 +63,7 @@ export function CopyButton(props: { text: string; slot?: "code-copy" | "copy" })
type="button"
data-slot={props.slot ?? "code-copy"}
data-state={state()}
data-funnel-copy="snippet"
aria-label={i18n.t("site.code.copy")}
onClick={copy}
>
@@ -30,6 +30,7 @@ export function Companions(props: { product: PageSlug }) {
return (
<section
data-component="companions"
data-section="companions"
data-design="companionStyle"
data-style={siteSettings.companionStyle}
aria-label={i18n.t("site.companions")}
@@ -32,12 +32,14 @@ function useCopy() {
/**
* One copyable command as a list row: the method, the command, and a neutral Copy button. Clicking
* the command copies too; the button alone says so (and is the keyboard's way in).
* the command copies too; the button alone says so (and is the keyboard's way in). `copies` names
* what it installs for the funnel's `ui.copied` (lib/funnel.ts), and the item's id the method.
*/
function CopyRow(props: { item: Command; method: string; state: ReturnType<typeof useCopy> }) {
function CopyRow(props: { item: Command; method: string; copies: string; state: ReturnType<typeof useCopy> }) {
const i18n = useI18n()
return (
<li data-slot="copy-row">
// data-funnel makes the row a control for the tracker, as a click on its command copies too.
<li data-slot="copy-row" data-funnel-copy={props.copies} data-funnel-method={props.item.id} data-funnel="copy">
<span data-slot="method">{props.method}</span>
<span
data-slot="name"
@@ -109,7 +111,7 @@ export function DownloadSections(props: {
onMount(() => alignActions(root))
const Section = (section: { id: string; title: string; children: JSX.Element }) => (
<section data-component="block" data-columns={props.columns ? "" : undefined}>
<section data-component="block" data-section={section.id} data-columns={props.columns ? "" : undefined}>
{props.heading(section.id, section.title)}
<div data-slot="body">{section.children}</div>
</section>
@@ -129,7 +131,7 @@ export function DownloadSections(props: {
<Section id="download-terminal" title={content().terminal.title}>
<ul data-component="download-list">
<For each={content().terminal.installs}>
{(item) => <CopyRow item={item} method={item.id} state={state} />}
{(item) => <CopyRow item={item} method={item.id} copies="terminal" state={state} />}
</For>
</ul>
</Section>
@@ -213,7 +215,7 @@ function DesktopList(props: { os: OS; build?: DownloadPlatform; state: ReturnTyp
</li>
)}
</For>
<CopyRow item={content().desktop.install} method="brew" state={props.state} />
<CopyRow item={content().desktop.install} method="brew" copies="desktop" state={props.state} />
</ul>
)
}
@@ -328,7 +330,7 @@ export function ProductDownload(props: { slug: PageSlug }) {
})
return (
<section data-component="block" data-slot="product-download">
<section data-component="block" data-slot="product-download" data-section="download">
<SectionHeading id="download" title={i18n.t("download.action.download")} label />
<div data-slot="body" ref={root}>
<Show when={details().lead}>{(lead) => <p data-slot="lead">{lead()}</p>}</Show>
@@ -347,7 +349,9 @@ export function ProductDownload(props: { slug: PageSlug }) {
<Show when={details().commandsLead}>{(lead) => <p data-slot="lead">{lead()}</p>}</Show>
<Show when={details().commands.length > 0}>
<ul data-component="download-list">
<For each={details().commands}>{(item) => <CopyRow item={item} method={item.id} state={state} />}</For>
<For each={details().commands}>
{(item) => <CopyRow item={item} method={item.id} copies={props.slug} state={state} />}
</For>
</ul>
</Show>
<Show when={details().more}>
@@ -369,14 +373,19 @@ export function ExtensionDownload(props: { lead: string; command?: string }) {
let root!: HTMLDivElement
onMount(() => alignActions(root))
return (
<section data-component="block" data-slot="product-download">
<section data-component="block" data-slot="product-download" data-section="download">
<SectionHeading id="download" title={i18n.t("download.action.install")} label />
<div data-slot="body" ref={root}>
<p data-slot="lead">{props.lead}</p>
<Show when={props.command}>
{(command) => (
<ul data-component="download-list">
<CopyRow item={{ id: "install", command: command() }} method={command().split(" ")[0]} state={state} />
<CopyRow
item={{ id: "install", command: command() }}
method={command().split(" ")[0]}
copies="extension"
state={state}
/>
</ul>
)}
</Show>
@@ -111,7 +111,7 @@ export function ExtensionPage(props: { slug: ExtensionSlug }) {
{/* Plain black until there is real footage of the extension. */}
<div data-component="product-hero" data-product={props.slug} data-empty />
<section data-component="product-intro">
<section data-component="product-intro" data-section="intro">
<div data-slot="copy">
<h1>{extension().name}</h1>
<p>{extension().intro}</p>
@@ -125,7 +125,11 @@ export function ExtensionPage(props: { slug: ExtensionSlug }) {
</section>
</div>
<ul data-component="product-features" data-columns={siteSettings.productFeatureColumns.charAt(0)}>
<ul
data-component="product-features"
data-section="features"
data-columns={siteSettings.productFeatureColumns.charAt(0)}
>
<For each={extension().features}>
{(feature) => (
<li>
@@ -507,6 +507,7 @@ function CopyMarkdown(props: { path: string }) {
data-variant="neutral"
data-slot="copy-markdown"
data-state={state()}
data-funnel-copy="page-markdown"
onPointerEnter={() => void load().catch(() => undefined)}
onFocus={() => void load().catch(() => undefined)}
onClick={() => void copy()}
@@ -171,6 +171,7 @@ export function LogoWall(props: {
return (
<section
data-component="logo-wall"
data-section="logos"
data-design="logoWall logoAnimation logoStagger logoLayout logoDividers logoLabel spacer spacerLength spacerCount spacerStartDash spacerStartGap spacerCurve ditherHeight ditherOrientation ditherDirection ditherLength ditherPixel ditherPattern ditherDensity ditherOpacity ditherCurve ditherLine"
data-kind={props.kind}
data-layout={label()}
@@ -52,7 +52,7 @@ export function MarkdownView(props: { source: string; file: string; href?: strin
</Show>
</nav>
<div data-slot="actions">
<button type="button" data-slot="copy" onClick={copy}>
<button type="button" data-slot="copy" data-funnel-copy="page-markdown" onClick={copy}>
<span aria-live="polite">{copied() ? "Copied" : "Copy Markdown"}</span>
</button>
</div>
@@ -67,6 +67,7 @@ export function OpenSourceFork() {
</h3>
<div
data-slot="terminal"
data-funnel-copy="fork"
ref={terminal}
data-entrance
data-mounted={wash.mounted() ? "" : undefined}
@@ -95,7 +95,7 @@ function Command(props: { command: string }) {
let timer: ReturnType<typeof setTimeout> | undefined
onCleanup(() => clearTimeout(timer))
return (
<div data-slot="command">
<div data-slot="command" data-funnel-copy="pair">
<code>{props.command}</code>
<button
type="button"
@@ -305,7 +305,11 @@ export function ProductPage(props: { slug: PageSlug }) {
</Show>
</div>
<section data-component="product-intro" data-install={exposedInstall() ? "exposed" : undefined}>
<section
data-component="product-intro"
data-section="intro"
data-install={exposedInstall() ? "exposed" : undefined}
>
<div data-slot="copy">
<h1>{product().name}</h1>
<p data-design-copy={`product.${props.slug}.intro`}>
@@ -336,6 +340,7 @@ export function ProductPage(props: { slug: PageSlug }) {
<Show when={showcase().length > 0}>
<section
data-component="showcase"
data-section="showcase"
data-design="featureClipStyle featureClipCount"
data-count={siteSettings.featureClipCount}
data-media={productDetails[props.slug].showcaseMedia === false ? "none" : undefined}
@@ -364,7 +369,11 @@ export function ProductPage(props: { slug: PageSlug }) {
</Show>
<Show when={detail().features.length > 0}>
<ul data-component="product-features" data-columns={siteSettings.productFeatureColumns.charAt(0)}>
<ul
data-component="product-features"
data-section="features"
data-columns={siteSettings.productFeatureColumns.charAt(0)}
>
<For each={detail().features}>
{(feature) => (
<li>
@@ -380,7 +389,7 @@ export function ProductPage(props: { slug: PageSlug }) {
<Show when={areas()}>
{(filter) => (
<section data-component="block" data-slot="product-changelog">
<section data-component="block" data-slot="product-changelog" data-section="changelog">
<h2 data-slot="label">{i18n.t("nav.changelog")}</h2>
{/* Its own boundary, so the page (and the card growing into its hero) does not wait for
GitHub's releases, which can take over a second. */}
+17 -1
View File
@@ -289,6 +289,7 @@ export function ProductCarousel(props: { exclude?: ProductSlug; header?: JSX.Ele
return (
<section
data-component="products"
data-section="products"
data-layout="carousel"
data-design="buttonHover cardTone cardInfo phoneCardContent cardVideo cardHover cardHoverEntry productBadges mobileCover mobileOrbShade cardLoopSpeed cardVideoCut cardTransition cardGrowDuration cardShrinkDuration cardEasing extensionsCard"
data-tone={siteSettings.cardTone}
@@ -482,6 +483,7 @@ export function ProductGrid() {
return (
<section
data-component="products"
data-section="products"
data-layout="grid"
data-design="buttonHover productButton cardTone cardInfo cardVideo cardHover cardHoverEntry productBadges mobileCover mobileOrbShade cardLoopSpeed cardVideoCut cardTransition cardGrowDuration cardShrinkDuration cardEasing"
data-tone={siteSettings.cardTone}
@@ -1339,6 +1341,8 @@ export function ProductAction(props: { slug: PageSlug; split?: boolean; both?: b
type="button"
data-slot="install"
data-copied={copied() === item.id ? "" : undefined}
data-funnel-copy="terminal"
data-funnel-method={item.id}
onClick={() => copy(item)}
>
<span data-slot="method">{item.id}</span>
@@ -1401,6 +1405,8 @@ export function ProductAction(props: { slug: PageSlug; split?: boolean; both?: b
type="button"
data-slot="row"
data-copied={copied() === item.id ? "" : undefined}
data-funnel-copy="terminal"
data-funnel-method={item.id}
onClick={() => copy(item)}
>
<span data-slot="method">{item.id}</span>
@@ -1507,6 +1513,7 @@ export function InstallTabs() {
aria-controls={`${id}-panel`}
aria-selected={selected() === index() ? "true" : "false"}
tabIndex={selected() === index() ? 0 : -1}
data-funnel={`install-tab:${item.id}`}
onClick={() => select(index())}
onKeyDown={(event) => keyDown(event, index())}
>
@@ -1515,7 +1522,16 @@ export function InstallTabs() {
)}
</For>
</div>
<div data-slot="code" id={`${id}-panel`} role="tabpanel" aria-labelledby={`${id}-tab-${selected()}`}>
<div
data-slot="code"
id={`${id}-panel`}
role="tabpanel"
aria-labelledby={`${id}-tab-${selected()}`}
data-funnel-copy="terminal"
data-funnel-method={installs[selected()].id}
// A control for the tracker, as a click on the command copies too.
data-funnel="copy"
>
<code data-copy-command {...copyOnClick(copy)}>
{installs[selected()].command}
</code>
@@ -3,6 +3,8 @@ import { useLocation } from "@solidjs/router"
import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show } from "solid-js"
import { useI18n } from "~/context/i18n"
import { useLanguage } from "~/context/language"
import type { FunnelEvent } from "~/lib/funnel"
import { strip } from "~/lib/language"
import { devicePreviewOpenEvent, inDevicePreview } from "~/lib/platform"
import { siteSettings, type SiteSettings } from "./settings"
import { onCloseMenus } from "./menu-open"
@@ -11,6 +13,7 @@ import {
searchOpenEvent,
setSearchAnnouncement,
setSearchShown,
type SearchVia,
type SiteSearchProps,
} from "./search"
import type { SearchAction, SearchGroup, SearchItem, SearchResult } from "./search-index"
@@ -44,7 +47,7 @@ function englishOnly(item: { id: string; group: string; href?: string; action?:
)
}
export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean }) {
export function SearchPalette(props: SiteSearchProps & { openOnMount?: SearchVia }) {
const i18n = useI18n()
const language = useLanguage()
const location = useLocation()
@@ -61,6 +64,8 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
let list: HTMLDivElement | undefined
let opener: HTMLElement | undefined
let closeTimer: ReturnType<typeof setTimeout> | undefined
// Whether a result was chosen since the search opened, so closing it then isn't a dismissal.
let chosen = false
// Spotlight and minimal are one list; the others follow Settings › Search results.
const grouped = () =>
@@ -163,8 +168,13 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
.catch(() => undefined)
}
const show = () => {
// How many results showed for how many characters; never what was typed.
const searched = () => ({ results: rows().length, query_len: query().trim().length })
const show = (via: SearchVia) => {
if (open() && !closing()) return
report({ name: "search.opened", action: "opened", target: via, properties: { kind: "site" } })
chosen = false
clearTimeout(closeTimer)
setClosing(false)
opener = document.activeElement instanceof HTMLElement ? document.activeElement : undefined
@@ -178,6 +188,7 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
const close = (restore = true) => {
if (!open() || closing()) return
if (!chosen) report({ name: "search.closed", action: "dismissed", target: "", properties: searched() })
const instant = siteSettings.searchMotion === "none" || matchMedia("(prefers-reduced-motion: reduce)").matches
const finish = () => {
setOpen(false)
@@ -212,6 +223,13 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
return
}
const item = row.result.item
chosen = true
report({
name: "search.selected",
action: "selected",
target: resultTarget(item),
properties: { rank: rows().indexOf(row) + 1, ...searched() },
})
remember(item, query().trim())
if (item.action && item.action !== "brand-assets") return act(item.action)
if (!item.href) return
@@ -348,8 +366,9 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
if (!isSearchShortcut(event)) return
event.preventDefault()
if (event.key !== "/" && open() && !closing()) return close()
show()
show(event.key === "/" ? "slash" : "shortcut")
}
const showFromButton = () => show("button")
// Focus stays in the dialog, except for Design mode's controls and the Settings panel, which
// tune it live (Settings › Search › Preview opens it under the panel).
const trap = (event: FocusEvent) => {
@@ -365,8 +384,8 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
}
document.addEventListener("keydown", shortcut)
document.addEventListener("focusin", trap)
document.addEventListener(searchOpenEvent, show)
if (props.openOnMount) show()
document.addEventListener(searchOpenEvent, showFromButton)
if (props.openOnMount) show(props.openOnMount)
// Mounted ahead of the first open (⌘ or Ctrl pressed): build the index in the next idle period,
// so the first ⌘K shows results at once.
const idle = window.requestIdleCallback ?? ((run: () => void) => setTimeout(run, 500))
@@ -376,7 +395,7 @@ export function SearchPalette(props: SiteSearchProps & { openOnMount: boolean })
clearTimeout(closeTimer)
document.removeEventListener("keydown", shortcut)
document.removeEventListener("focusin", trap)
document.removeEventListener(searchOpenEvent, show)
document.removeEventListener(searchOpenEvent, showFromButton)
})
})
@@ -633,6 +652,19 @@ function find(target: SearchItem["target"]): HTMLElement | undefined {
)
}
/** A chosen result for the funnel: the page it opens, without its language (`link:/desktop`), or the action it runs. */
function resultTarget(item: SearchItem) {
if (item.action && item.action !== "brand-assets") return `action:${item.action}`
const url = new URL(item.href ?? "/", window.location.origin)
const target = url.origin === window.location.origin ? `link:${strip(url.pathname)}` : `outbound:${url.hostname}`
return target.replace(/[^A-Za-z0-9/_.:+-]+/g, "-").slice(0, 96)
}
/** Reports a search event to the funnel (lib/funnel.ts), through its queue. */
function report(event: FunnelEvent) {
window.__ocFunnel?.push({ event, at: performance.now() })
}
function trim(path: string) {
return path.length > 1 ? path.replace(/\/$/, "") : path
}
+12 -8
View File
@@ -34,6 +34,9 @@ export const setSearchShown = setShown
const [announcement, setAnnouncement] = createSignal("")
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
@@ -53,15 +56,15 @@ export function prefetchSearch() {
export function SiteSearch(props: SiteSearchProps) {
const i18n = useI18n()
const [Palette, setPalette] = createSignal<Component<SiteSearchProps & { openOnMount: boolean }>>()
const [Palette, setPalette] = createSignal<Component<SiteSearchProps & { openOnMount?: SearchVia }>>()
const [mounted, setMounted] = createSignal(false)
const [mac, setMac] = createSignal(true)
let openOnMount = false
let openOnMount: SearchVia | undefined
// Until the dialog has loaded; once mounted it handles the shortcut and the open event itself.
const open = () => {
const open = (via: SearchVia) => {
if (Palette()) return
openOnMount = true
openOnMount = via
void prefetchSearch().then((module) => setPalette(() => module.SearchPalette))
}
@@ -75,13 +78,14 @@ export function SiteSearch(props: SiteSearchProps) {
return void prefetchSearch().then((module) => !Palette() && setPalette(() => module.SearchPalette))
if (!isSearchShortcut(event)) return
event.preventDefault()
open()
open(event.key === "/" ? "slash" : "shortcut")
}
const openFromButton = () => open("button")
document.addEventListener("keydown", shortcut)
document.addEventListener(searchOpenEvent, open)
document.addEventListener(searchOpenEvent, openFromButton)
onCleanup(() => {
document.removeEventListener("keydown", shortcut)
document.removeEventListener(searchOpenEvent, open)
document.removeEventListener(searchOpenEvent, openFromButton)
})
})
@@ -101,7 +105,7 @@ export function SiteSearch(props: SiteSearchProps) {
aria-expanded={shown() ? "true" : "false"}
onPointerEnter={() => void prefetchSearch()}
onFocus={() => void prefetchSearch()}
onClick={() => (Palette() ? document.dispatchEvent(new Event(searchOpenEvent)) : open())}
onClick={() => (Palette() ? document.dispatchEvent(new Event(searchOpenEvent)) : open("button"))}
>
{mac() ? "⌘K" : "Ctrl K"}
</button>
+12
View File
@@ -715,6 +715,16 @@ export function Site(props: {
lastKey = { key, time: event.timeStamp }
if (key !== "d" || !quick) return
lastKey = { key: "", time: 0 }
// The funnel's queue (lib/funnel.ts), as the switch reports its own clicks.
window.__ocFunnel?.push({
event: {
name: "ui.clicked",
action: "clicked",
target: `markdown-view:${markdown() ? "off" : "on"}`,
properties: { via: "shortcut" },
},
at: performance.now(),
})
toggleMarkdown()
}
// The pre-paint script hid the page while it waited for the Markdown view, whose code it started
@@ -1084,6 +1094,7 @@ export function Site(props: {
type="button"
aria-label={markdown() ? i18n.t("site.view.person") : i18n.t("site.view.markdown")}
aria-pressed={markdown() ? "true" : "false"}
data-funnel={markdown() ? "markdown-view:off" : "markdown-view:on"}
onPointerEnter={prefetchMarkdown}
onFocus={prefetchMarkdown}
onClick={(event) => toggleMarkdown(!!event.currentTarget.closest('[data-component="site-footer"]'))}
@@ -1101,6 +1112,7 @@ export function Site(props: {
href={href()}
aria-label={markdown() ? i18n.t("site.view.person") : i18n.t("site.view.markdown")}
data-active={markdown() ? "" : undefined}
data-funnel={markdown() ? "markdown-view:off" : "markdown-view:on"}
onPointerEnter={prefetchMarkdown}
onFocus={prefetchMarkdown}
onClick={(event) => {
+1
View File
@@ -15,6 +15,7 @@
- Pages are plain HTML. They never hydrate and never load the site's styles, fonts or scripts; the site's never load the docs'. A page links `styles/global.css` and the one browser script, `client.ts`.
- 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 (search, copy buttons, tabs, the status link) are delegated listeners in `client.ts`, keyed on `data-*` attributes the components render. Don't add Solid state or effects to docs components; they only run on the server.
- `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 script is 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), so the markup and `global.css` stay unchanged.
+43 -6
View File
@@ -1,6 +1,13 @@
// The docs pages' only script: search, copy buttons, tabs and the status link. Pages are plain HTML
// (no hydration); everything here is delegated from the document, so it needs no per-element setup.
// The theme toggle is in the layout's head script, so it works before this loads.
// The docs pages' only script: search, copy buttons, tabs, the status link and the funnel. Pages are
// plain HTML (no hydration); everything here is delegated from the document, so it needs no
// per-element setup. The theme toggle is in the layout's head script, so it works before this loads.
import { Funnel } from "../lib/funnel"
import { downloadOf, surfaceOf, targetOf } from "../lib/funnel-config"
// The page reports to the Console's funnel like the site's (lib/funnel.ts). The docs are English, at the host's root
// like the site; their config is built in, as a chunk would bring Vite's preload helper with it.
Funnel.start(async () => ({ surfaceOf, targetOf, localeOf: () => "en", base: "", downloadOf }))
type PagefindResult = { url: string; excerpt: string; meta: { title: string } }
type Pagefind = { search(query: string): Promise<{ results: { data(): Promise<PagefindResult> }[] }> }
@@ -11,16 +18,46 @@ const load = new Function("url", "return import(url)") as (url: string) => Promi
const dialog = document.querySelector<HTMLDialogElement>("[data-search-dialog]")
const input = document.querySelector<HTMLInputElement>("[data-search-input]")
const results = document.querySelector<HTMLElement>("[data-search-results]")
// Whether a result was chosen since the search opened, so closing it then isn't a dismissal.
let chosen = false
function openSearch() {
function openSearch(via: "shortcut" | "button") {
if (dialog && !dialog.open)
Funnel.track({ name: "search.opened", action: "opened", target: via, properties: { kind: "docs" } })
chosen = false
dialog?.showModal()
input?.focus()
}
// How many results showed for how many characters; never what was typed.
const searched = () => ({
results: results?.querySelectorAll("a").length ?? 0,
query_len: input?.value.trim().length ?? 0,
})
dialog?.addEventListener("close", () => {
if (!chosen) Funnel.track({ name: "search.closed", action: "dismissed", target: "", properties: searched() })
})
// A chosen result, captured on the window so it's reported before the tracker's own report of the click sends what's
// waiting as the result's page loads.
window.addEventListener(
"click",
(event) => {
const result = event.target instanceof Element && event.target.closest<HTMLAnchorElement>("[data-search-results] a")
if (!result) return
chosen = true
const target = `link:${new URL(result.href).pathname}`.replace(/[^A-Za-z0-9/_.:+-]+/g, "-").slice(0, 96)
const rank = [...(results?.querySelectorAll("a") ?? [])].indexOf(result) + 1
Funnel.track({ name: "search.selected", action: "selected", target, properties: { rank, ...searched() } })
},
true,
)
document.addEventListener("keydown", (event) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault()
openSearch()
openSearch("shortcut")
}
})
@@ -54,7 +91,7 @@ input?.addEventListener("input", async () => {
document.addEventListener("click", async (event) => {
if (!(event.target instanceof Element)) return
if (event.target.closest("[data-search-open]")) return openSearch()
if (event.target.closest("[data-search-open]")) return openSearch("button")
const code = event.target.closest<HTMLButtonElement>("[data-copy-code]")
if (code) {
@@ -1,7 +1,7 @@
// The copy button works through client.ts.
export function CodeBlock(props: { code: string }) {
return (
<div class="docs-code-block">
<div class="docs-code-block" data-funnel-copy="snippet">
<pre>
<code>{props.code}</code>
</pre>
@@ -16,6 +16,7 @@ export function CodeTabs(props: { id: string; label: string; tabs: { label: stri
aria-selected={index() === 0 ? "true" : "false"}
tabindex={index() === 0 ? 0 : -1}
data-code-tab
data-funnel={`code-tab:${tab.label}`}
>
{tab.label}
</button>
@@ -23,6 +23,7 @@ export function PlanTabs(props: { id: string; label: string; syncKey: string; ch
aria-selected={index() === 0 ? "true" : "false"}
tabindex={index() === 0 ? 0 : -1}
data-plan-tab={plan.id}
data-funnel={`plan-tab:${plan.id}`}
>
{plan.label}
</button>
@@ -95,7 +95,13 @@ export function DocsLayout(props: {
>
<h1>
{props.title}
<button type="button" aria-label="Copy page as Markdown" data-copy-markdown data-pagefind-ignore>
<button
type="button"
aria-label="Copy page as Markdown"
data-copy-markdown
data-funnel-copy="page-markdown"
data-pagefind-ignore
>
<svg
width="16"
height="16"
+3
View File
@@ -51,6 +51,9 @@ function astroCode(lang: string): ShikiTransformer {
const join = (value: unknown) => (Array.isArray(value) ? value.join(" ") : value)
node.properties.class = String(join(node.properties.class) ?? "").replace(/shiki/g, "astro-code")
node.properties.dataLanguage = lang
// A copy of text selected in it is the funnel's `ui.copied` `snippet` (lib/funnel.ts).
node.properties.dataFunnelCopy = "snippet"
node.properties.dataFunnelMethod = lang
node.properties.style = `${join(node.properties.style) ?? ""}; overflow-x: auto;`
},
line(node) {
+4
View File
@@ -1,6 +1,10 @@
// @refresh reload
import { mount, StartClient } from "@solidjs/start/client"
import { loadSlice } from "~/i18n/content"
import { Funnel } from "~/lib/funnel"
// Every page, the not-found page too, reports to the Console's funnel from its markup (lib/funnel.ts).
Funnel.start(() => import("~/lib/funnel-config").then((module) => module.funnelConfig()))
// The strings every page shows arrive before hydration (the server preloads them, i18n/preload.ts),
// so the first client render matches the server's. Each page route loads its own before it runs.
+97
View File
@@ -0,0 +1,97 @@
// What the funnel tracker (lib/funnel.ts) needs to know about the site and the docs, loaded with it. Surfaces and
// targets are analytics keys: rename one only together with the reports that read it.
import { fromPathname, LOCALES, strip, tag } from "./language"
// Pages named by their first segment, as `www-<segment>`.
const pages = new Set([
"product",
"desktop",
"terminal",
"mobile",
"sdk",
"ide",
"mini",
"extensions",
"changelog",
"brand",
"press",
"font",
"legal",
])
// Development tools, which report nothing.
const tools = new Set(["dev", "devices", "video-editor"])
// Stores and marketplaces, by host, and what a link to one downloads.
const stores: Record<string, string> = {
"apps.apple.com": "mobile",
"testflight.apple.com": "mobile",
"play.google.com": "mobile",
"marketplace.visualstudio.com": "ide",
"open-vsx.org": "ide",
"plugins.jetbrains.com": "ide",
}
/** The config `start` of `/console/funnel/v1.js` takes for this site's and the docs' pages. */
export function funnelConfig() {
const stamp = Object.values(
import.meta.glob<{ default: { commit?: string; build?: string } }>("./build-stamp.json", { eager: true }),
)[0]?.default
return {
surfaceOf,
targetOf,
normalizePath: strip,
localeOf,
// The site is at the host's root, so every page on the host is `link:`; the Console's are calls to action.
base: "",
downloadOf,
build: stamp?.build ?? stamp?.commit ?? "dev",
}
}
/** A page's surface by its path without the locale (`www-home`, `www-docs`), or undefined for a development tool. */
export function surfaceOf(path: string) {
const parts = path.split("/")
if (path === "/") return "www-home"
if (parts[1] === "docs") return "www-docs"
if (tools.has(parts[1])) return undefined
return pages.has(parts[1]) ? `www-${parts[1]}` : "www-other"
}
/** What a view targets: the docs' section, the extension, the release or the legal document; `""` for the rest. */
export function targetOf(path: string) {
const parts = path.split("/").filter((part) => part !== "")
const part = parts[0] === "docs" || pages.has(parts[0]) ? parts[1] : undefined
return (part ?? "").replace(/[^A-Za-z0-9_.:+-]+/g, "-").slice(0, 96)
}
/** The page's language: its address's prefix, else the one it's shown in (`<html lang>`), else English. */
export function localeOf(path: string) {
return fromPathname(path) ?? LOCALES.find((locale) => tag(locale) === document.documentElement.lang) ?? "en"
}
/**
* A download link's target and details: the update API's desktop and CLI builds (`desktop`, `cli`) with their file,
* channel and whether they're for the visitor's system, and the app stores and editor marketplaces (`mobile`, `ide`).
*/
export function downloadOf(link: URL) {
const build = /^\/update\/api\/([a-z0-9-]+)\/(desktop|cli)\/opencode\/([A-Za-z0-9_.-]+)$/.exec(link.pathname)
// Always production's: there is one release service (lib/download.ts).
if (build && link.hostname === "opencode.ai")
return {
target: build[2],
properties: { file: build[3], channel: build[1], os_match: systemOf(build[3]) === systemOf(visitorSystem()) },
}
const store = stores[link.hostname]
if (store) return { target: store, properties: { file: link.hostname } }
}
const systemOf = (text: string) => {
const value = text.toLowerCase()
if (/iphone|ipad|android/.test(value)) return "mobile"
if (/mac|darwin/.test(value)) return "macos"
if (/win/.test(value)) return "windows"
if (/linux|x11|cros/.test(value)) return "linux"
return "other"
}
const visitorSystem = () =>
(navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform || navigator.userAgent
+67
View File
@@ -0,0 +1,67 @@
// Reports the site's and the docs' pages to the Console's funnel (opencode-console docs/features/funnel.md). The
// tracker the Console serves at /console/funnel/v1.js reads views, sections, clicks, copies, downloads, page speed and
// chunk errors from the page's markup (`data-section`, `data-funnel`, `data-funnel-copy`, `data-funnel-surface`).
// This module is the only part in a page's first JavaScript: it loads the tracker, with the page's config, on the first
// pointer or key press or once the page is idle, and keeps the events a page reports itself until then. Nothing a
// visitor types is ever sent.
export * as Funnel from "./funnel"
type Value = string | number | boolean | null
/** An event the page reports itself, such as a search; the tracker adds the view's surface and path. */
export type FunnelEvent = {
name: string
action: string
target?: string
properties?: Record<string, Value | readonly string[]>
}
type Queued = { event: FunnelEvent; at: number }
declare global {
interface Window {
/**
* Where a page reports its own events, each at its time on the page's clock: a list until the tracker loads, then
* the tracker's queue. Only a page that started the funnel has it, so the site's other modules push here directly
* rather than importing this one, which would split it out of the entry chunk.
*/
__ocFunnel?: Array<Queued> | { push: (item: Queued) => unknown }
}
}
// Through Function, as Vite would wrap a plain import() in its preload helper: a kilobyte the docs don't otherwise load.
const load = new Function("url", "return import(url)") as (
url: string,
) => Promise<{ start: (config: object) => unknown }>
/** Reports `event` on the current view, now; it waits for the tracker when that hasn't loaded yet. */
export function track(event: FunnelEvent) {
window.__ocFunnel?.push({ event, at: performance.now() })
}
let started = false
/**
* Loads the tracker and starts it with the config `config` loads, once per page load, on the first pointer or key
* press or when the page is next idle (within a second). A page in a frame (the device preview) reports nothing.
* Failures, such as a host without the Console, leave the page as it is.
*/
export function start(config: () => Promise<object>) {
if (started || typeof window === "undefined" || window.top !== window) return
started = true
window.__ocFunnel ??= []
let waiting = true
const inputs = ["pointerdown", "keydown"]
const begin = () => {
if (!waiting) return
waiting = false
inputs.forEach((type) => removeEventListener(type, begin, true))
// The tracker's URL is a public contract of the Console's: a breaking change ships as v2.js.
Promise.all([config(), load("/console/funnel/v1.js")])
.then(([options, module]) => module.start(options))
.catch(() => undefined)
}
inputs.forEach((type) => addEventListener(type, begin, { capture: true, passive: true }))
if ("requestIdleCallback" in window) return void requestIdleCallback(begin, { timeout: 1000 })
setTimeout(begin, 1000)
}
+1
View File
@@ -230,6 +230,7 @@ export default function Home() {
<Announcement />
<section
data-component="hero"
data-section="hero"
data-design="hero heroTitleSize heroText heroInstall homeAnnouncement"
data-variant={heroVariant()}
data-title-size={siteSettings.heroTitleSize}
+3 -2
View File
@@ -52,6 +52,7 @@ export default function Product() {
and the cards below land where the home page's do (hero-title.css). */}
<section
data-component="hero"
data-section="hero"
data-design="hero heroTitleSize"
data-variant={siteSettings.hero}
data-title-size={siteSettings.heroTitleSize}
@@ -69,7 +70,7 @@ export default function Product() {
{/* Hidden while extensionPages is empty. */}
<Show when={extensionPages.length > 0}>
<section data-component="block" data-slot="products-extensions">
<section data-component="block" data-slot="products-extensions" data-section="extensions">
<SectionHeading id="extensions" title={i18n.t("site.extensions")} label />
<div data-slot="body">
{/* Each extension's page, with its install steps; a blank tile until one has an icon. */}
@@ -86,7 +87,7 @@ export default function Product() {
</Show>
{/* /product#download lands here, the first of the download page's sections on this page. */}
<section data-component="block" data-slot="products-integrations">
<section data-component="block" data-slot="products-integrations" data-section="integrations">
<SectionHeading id="download" title={download().integrations.title} label />
<div data-slot="body">
<ProductList
+173
View File
@@ -0,0 +1,173 @@
import { describe, expect, test } from "bun:test"
import { fileURLToPath } from "node:url"
import type { Element, Root } from "hast"
// SolidStart's own file router, as in sitemap.test.ts: every page route the app serves.
import { DEFAULT_EXTENSIONS } from "../node_modules/@solidjs/start/dist/config/constants.js"
import { SolidStartServerFileRouter } from "../node_modules/@solidjs/start/dist/config/fs-router.js"
import { docsHref, docsSections } from "~/docs/lib/navigation"
import rehypeShiki from "~/docs/rehype-shiki"
import { downloadOf, surfaceOf, targetOf } from "~/lib/funnel-config"
import { LOCALES, route, strip } from "~/lib/language"
const router = new SolidStartServerFileRouter({
dir: fileURLToPath(new URL("../src/routes", import.meta.url)),
extensions: DEFAULT_EXTENSIONS,
})
const manifest: { path: string; page?: boolean }[] = await router.getRoutes()
const routes = manifest.filter((item) => item.page).map((item) => item.path)
// A sample address for each route, its parameters filled in.
const sample = (path: string) =>
path
.replace("*404", "no-such-page")
.replace(":tag", "v1.14.40")
.replace(/(.)\/$/, "$1")
// The surface each page route reports as. A new page fails here until it's given one, so a report never
// lumps it in with "www-other" by accident.
const surfaces: Record<string, string | undefined> = {
"/": "www-home",
"/brand": "www-brand",
"/changelog": "www-changelog",
"/changelog/v1.14.40": "www-changelog",
"/desktop": "www-desktop",
"/devices": undefined,
"/extensions/browse": "www-extensions",
"/font": "www-font",
"/ide": "www-ide",
"/legal": "www-legal",
"/legal/privacy-policy": "www-legal",
"/legal/terms-of-service": "www-legal",
"/mini": "www-mini",
"/mobile": "www-mobile",
"/no-such-page": "www-other",
"/press": "www-press",
"/product": "www-product",
"/sdk": "www-sdk",
"/terminal": "www-terminal",
"/video-editor": undefined,
}
describe("funnel config", () => {
test("names every page route's surface", () => {
expect(Object.fromEntries(routes.map(sample).map((path) => [path, surfaceOf(path)]))).toEqual(surfaces)
})
test("reports a page the same in every language, by its path without the locale", () => {
for (const locale of LOCALES)
for (const path of routes.map(sample)) expect(surfaceOf(strip(route(locale, path)))).toBe(surfaces[path])
expect(strip("/ja/desktop")).toBe("/desktop")
expect(targetOf(strip("/zh/extensions/browse"))).toBe("browse")
})
test("reports every docs page as www-docs, targeting its section", () => {
const slugs = docsSections.flatMap((section) =>
section.groups.flatMap((group) => group.items.map((item) => item.slug)),
)
expect(slugs.length).toBeGreaterThan(20)
for (const slug of slugs) {
const path = docsHref(slug)
expect(surfaceOf(strip(path))).toBe("www-docs")
expect(targetOf(path)).toBe(slug === "index" ? "" : slug.split("/")[0])
}
expect([surfaceOf("/docs/"), targetOf("/docs/cli/keybinds/")]).toEqual(["www-docs", "cli"])
})
test("leaves the development tools out", () => {
for (const path of ["/dev", "/dev/components", "/dev/404", "/devices", "/video-editor"])
expect(surfaceOf(strip(`/ja${path}`))).toBeUndefined()
})
test("targets a release, an extension or a legal document, as a slug the API accepts", () => {
expect(targetOf("/changelog/v1.14.40")).toBe("v1.14.40")
expect(targetOf("/changelog")).toBe("")
expect(targetOf("/legal/privacy-policy")).toBe("privacy-policy")
expect(targetOf("/")).toBe("")
expect(targetOf("/product")).toBe("")
expect(targetOf("/no-such-page")).toBe("")
expect(targetOf("/changelog/v1%20<b>")).toBe("v1-20-b-")
})
test("names downloads by what they are", () => {
expect(
downloadOf(new URL("https://opencode.ai/update/api/latest/desktop/opencode/opencode-desktop-mac-arm64.dmg")),
).toEqual({
target: "desktop",
properties: { file: "opencode-desktop-mac-arm64.dmg", channel: "latest", os_match: expect.any(Boolean) },
})
expect(downloadOf(new URL("https://opencode.ai/update/api/beta/cli/opencode/opencode-linux-x64.tar.gz"))).toEqual({
target: "cli",
properties: { file: "opencode-linux-x64.tar.gz", channel: "beta", os_match: expect.any(Boolean) },
})
expect(downloadOf(new URL("https://testflight.apple.com/join/M9eFEE1q"))).toEqual({
target: "mobile",
properties: { file: "testflight.apple.com" },
})
expect(downloadOf(new URL("https://marketplace.visualstudio.com/items?itemName=sst-dev.opencode"))?.target).toBe(
"ide",
)
expect(downloadOf(new URL("https://open-vsx.org/extension/sst-dev/opencode"))?.target).toBe("ide")
expect(downloadOf(new URL("https://github.com/anomalyco/opencode/releases"))).toBeUndefined()
expect(downloadOf(new URL("https://example.com/update/api/latest/desktop/opencode/x.dmg"))).toBeUndefined()
})
})
describe("funnel markup", () => {
test("docs code blocks are copy regions, named by their language", async () => {
const code: Element = {
type: "element",
tagName: "code",
properties: { className: ["language-bash"] },
children: [{ type: "text", value: "npm i -g opencode" }],
}
const tree: Root = {
type: "root",
children: [{ type: "element", tagName: "pre", properties: {}, children: [code] }],
}
await rehypeShiki()(tree)
const pre = tree.children[0] as Element
expect(pre.tagName).toBe("pre")
expect(pre.properties).toMatchObject({ dataFunnelCopy: "snippet", dataFunnelMethod: "bash" })
})
// The components only render on the server, through Vite's Solid compiler, so their markup is read from source.
const source = (path: string) => Bun.file(new URL(`../src/${path}`, import.meta.url)).text()
test("install rows, copy buttons and tabs carry their funnel names", async () => {
const marks: Record<string, RegExp[]> = {
"component/site/download-sections.tsx": [
/<li data-slot="copy-row" data-funnel-copy=\{props\.copies\} data-funnel-method=\{props\.item\.id\} data-funnel="copy">/,
/copies="terminal"/,
/copies="desktop"/,
/copies=\{props\.slug\}/,
],
"component/site/products.tsx": [
/data-funnel-copy="terminal"\s+data-funnel-method=\{item\.id\}\s+onClick=\{\(\) => copy\(item\)\}/,
/data-funnel=\{`install-tab:\$\{item\.id\}`\}/,
/data-funnel-copy="terminal"\s+data-funnel-method=\{installs\[selected\(\)\]\.id\}/,
],
"component/site/code-frame.tsx": [/data-funnel-copy="snippet"/],
"component/site/markdown-view.tsx": [/data-funnel-copy="page-markdown"/],
"component/site/legal.tsx": [/data-funnel-copy="page-markdown"/],
"component/site/site.tsx": [/data-funnel=\{markdown\(\) \? "markdown-view:off" : "markdown-view:on"\}/],
"component/site/arcade3d/not-found-page.tsx": [/data-funnel-surface="www-404"/],
"docs/components/CodeBlock.tsx": [/class="docs-code-block" data-funnel-copy="snippet"/],
"docs/components/CodeTabs.tsx": [/data-funnel=\{`code-tab:\$\{tab\.label\}`\}/],
"docs/components/PlanTabs.tsx": [/data-funnel=\{`plan-tab:\$\{plan\.id\}`\}/],
"docs/layouts/DocsLayout.tsx": [/data-copy-markdown\s+data-funnel-copy="page-markdown"/],
}
for (const [path, patterns] of Object.entries(marks)) {
const text = await source(path)
for (const pattern of patterns) expect({ path, found: pattern.test(text) }).toEqual({ path, found: true })
}
})
test("the site's and the docs' first JavaScript start the tracker through the stub", async () => {
const start = 'Funnel.start(() => import("~/lib/funnel-config").then((module) => module.funnelConfig()))'
expect(await source("entry-client.tsx")).toContain(start)
expect(await source("docs/client.ts")).toContain(
'Funnel.start(async () => ({ surfaceOf, targetOf, localeOf: () => "en", base: "", downloadOf }))',
)
// The stub imports nothing, so the config and the tracker stay out of every page's first JavaScript.
expect(await source("lib/funnel.ts")).not.toMatch(/^import /m)
})
})