mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 00:03:13 +03:00
perf(site): stop the home stats and page preloads from restyling the page, and fix WebKit's reload jump (#62445)
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
// Loads are returning visits: each run navigates from about:blank with the HTTP cache warm, so they
|
||||
// measure parsing, running and hydrating the page's code, not the network. Interactions start from a
|
||||
// fresh load of the home page, so each run is the first ⌘K, hover or click after a load.
|
||||
import { bench, url, web, type Context, type RunCase } from "@hona/strobe"
|
||||
import { bench, url, web, type Context, type PrepareContext, type RunCase } from "@hona/strobe"
|
||||
|
||||
const desktop = { width: 1440, height: 900 }
|
||||
const phone = { width: 390, height: 844 }
|
||||
@@ -22,6 +22,17 @@ const load = (path: string): RunCase<unknown> => ({
|
||||
reset: (ctx) => ctx.page.goto("about:blank"),
|
||||
})
|
||||
|
||||
// Each target's input: a desktop has a mouse, a phone a touch screen, and the site takes different
|
||||
// paths for each (preloading links as they scroll into view, autoplaying card videos). Headless
|
||||
// Chromium as strobe 0.14 launches it has neither and matches (hover: none), so until strobe gives it
|
||||
// a mouse, point STROBE_BROWSER at a wrapper that runs Chrome with
|
||||
// --blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4.
|
||||
// The phone target turns touch emulation on, and setup refuses a page with the wrong input.
|
||||
const touch = async (ctx: PrepareContext<unknown>) => {
|
||||
const session = await ctx.playwright.context.newCDPSession(ctx.playwright.page)
|
||||
await session.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 })
|
||||
}
|
||||
|
||||
const reload = async (ctx: Context<unknown>) => {
|
||||
await ctx.page.goto(new URL("/", ctx.url).href)
|
||||
await ctx.page.idle()
|
||||
@@ -30,11 +41,14 @@ const reload = async (ctx: Context<unknown>) => {
|
||||
export default bench({
|
||||
targets: {
|
||||
desktop: web({ url: "/", viewport: desktop }),
|
||||
phone: web({ url: "/", viewport: phone, scale: 3 }),
|
||||
phone: web({ url: "/", viewport: phone, scale: 3, prepare: touch }),
|
||||
// The live site, for reference only: `--target production --blocks 5 --head .` (nothing to build).
|
||||
production: url("https://opencode.ai/", { viewport: desktop }),
|
||||
},
|
||||
async setup({ page }) {
|
||||
async setup({ page, target }) {
|
||||
const mouse = await page.eval(() => matchMedia("(hover: hover) and (pointer: fine)").matches)
|
||||
if (mouse !== (target !== "phone"))
|
||||
throw new Error(`the ${target} page ${mouse ? "has" : "lacks"} a mouse; see the input note in site.bench.ts`)
|
||||
await page.idle()
|
||||
},
|
||||
cases: {
|
||||
@@ -44,7 +58,7 @@ export default bench({
|
||||
"load-docs": { ...load("/docs/"), targets: ["desktop", "production"] },
|
||||
"scroll-home": {
|
||||
primary: "main.work",
|
||||
targets: ["desktop", "production"],
|
||||
targets: ["desktop", "phone", "production"],
|
||||
run: ({ page }) => page.scroll("main", { by: 12000, speed: 6000 }),
|
||||
reset: reload,
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Link, Title, Meta } from "@solidjs/meta"
|
||||
import { Router, useCurrentMatches, useLocation } from "@solidjs/router"
|
||||
import { Router, useBeforeLeave, useCurrentMatches, useIsRouting, useLocation } from "@solidjs/router"
|
||||
import { FileRoutes } from "@solidjs/start/router"
|
||||
import { Show, Suspense } from "solid-js"
|
||||
import { createEffect, Show, Suspense } from "solid-js"
|
||||
import { isServer } from "solid-js/web"
|
||||
import { Favicon } from "@opencode/ui/favicon"
|
||||
import { Font } from "@opencode/ui/font"
|
||||
@@ -15,7 +15,7 @@ import { ogImage } from "~/lib/og"
|
||||
import { strip } from "~/lib/language"
|
||||
import { HeadMetaProvider, LiveMeta } from "~/component/head-meta"
|
||||
import { viewportContent } from "~/lib/viewport"
|
||||
import { quietPreloads } from "~/lib/route-preloads"
|
||||
import { quietPreloads, setNavigating } from "~/lib/route-preloads"
|
||||
// Before the router, so its popstate listener comes first.
|
||||
import "~/component/site/popstate"
|
||||
import { monoFontFaces } from "~/component/site/mono-fonts"
|
||||
@@ -50,6 +50,16 @@ function AppMeta() {
|
||||
// The 404 route and its /dev/404 previews (the dev server shows one for bad URLs).
|
||||
const notFound = () => matches().some((match) => match.route.pattern.includes("404"))
|
||||
preloadStrings()
|
||||
// Preloaded pages' stylesheets wait for a navigation (lib/route-preloads.ts).
|
||||
if (!isServer) {
|
||||
const routing = useIsRouting()
|
||||
// A leave that another listener blocked, or that stays on this page, never starts routing.
|
||||
useBeforeLeave(() => {
|
||||
setNavigating(true)
|
||||
queueMicrotask(() => routing() || setNavigating(false))
|
||||
})
|
||||
createEffect(() => setNavigating(routing()))
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Title>opencode</Title>
|
||||
|
||||
@@ -10,7 +10,16 @@ import preloads from "virtual:i18n-preload"
|
||||
// Every language, before any page renders.
|
||||
import "~/i18n/server"
|
||||
|
||||
const criticalCSS = `[data-component="top"]{min-height:80px;display:flex;align-items:center}`
|
||||
const criticalCSS = `[data-component="top"]{min-height:80px;display:flex;align-items:center}html[data-scroll-restore] #app{opacity:0}`
|
||||
|
||||
// A reload, or a return from another site, lands on a history entry the router left a scroll position
|
||||
// for (createScrollRestoration in @solidjs/router keeps them in sessionStorage by the entry's depth).
|
||||
// WebKit paints the top of the page while it's still parsing and restores only once the page has
|
||||
// loaded, so the reader saw the top and then a jump. When there's a position to go back to, the page
|
||||
// stays hidden (its background still paints) until the document has been parsed, and the script after
|
||||
// #app scrolls there before anything paints; the timer shows it anyway if that never runs.
|
||||
const scrollHoldScript = `try{const n=performance.getEntriesByType("navigation")[0],d=history.state&&history.state._depth,y=n&&n.type!=="navigate"&&d!=null&&JSON.parse(sessionStorage.getItem("solid-router:scroll")||"{}")[d];if(y>0){const r=document.documentElement;r.dataset.scrollRestore=y;setTimeout(()=>delete r.dataset.scrollRestore,2000)}}catch{}`
|
||||
const scrollRestoreScript = `{const r=document.documentElement,y=+r.dataset.scrollRestore;if(y){scrollTo(0,y);delete r.dataset.scrollRestore}}`
|
||||
|
||||
// A reload in the Markdown view keeps the page hidden until the view shows (site.tsx), so the view's
|
||||
// code (markdown-pages.ts, loaded on first use) and its strings in the page's language are fetched
|
||||
@@ -51,6 +60,7 @@ export default createHandler(
|
||||
{/* After the charset meta: the art is over 1 KB, and the meta must come in the first 1024 bytes. */}
|
||||
{ssr([`\n${sourceLogo}\n`]) as unknown as Element}
|
||||
<style>{criticalCSS}</style>
|
||||
<script innerHTML={scrollHoldScript} />
|
||||
{/* Development only, before Vite's client loads: the device preview's Freeze (lib/freeze.ts). */}
|
||||
{import.meta.env.DEV && <script innerHTML={freezeScript} />}
|
||||
{assets}
|
||||
@@ -58,6 +68,7 @@ export default createHandler(
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">{children}</div>
|
||||
<script innerHTML={scrollRestoreScript} />
|
||||
{scripts}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -6,6 +6,10 @@ type Route = {
|
||||
}
|
||||
|
||||
const quiet = new WeakSet<object>()
|
||||
// Stylesheets that preloads added between navigations, held off until the next navigation starts.
|
||||
const held = new Set<HTMLLinkElement>()
|
||||
// True until the first page has rendered, and from the start of each navigation until it settles.
|
||||
let navigating = true
|
||||
|
||||
/**
|
||||
* SolidStart reloads the page when a route's code fails to load (reloadOnRouteChunkError), so a page
|
||||
@@ -15,6 +19,11 @@ const quiet = new WeakSet<object>()
|
||||
* the reader followed a link to another page reloaded the page they were leaving instead. Here a
|
||||
* route's preload loads its code without that reload and hands it to the route once it has loaded;
|
||||
* one that fails leaves the route as it was, to load (and recover) when it's opened.
|
||||
*
|
||||
* Loading a route's code also adds its stylesheets (Vite's preload helper does, and never again for
|
||||
* the same file). Added between navigations, they would restyle the page being read with another
|
||||
* page's rules, at once and again whenever it changes, so they're held off (media "not all": fetched
|
||||
* and parsed, never applied) until a navigation starts (setNavigating).
|
||||
*/
|
||||
export function quietPreloads<T extends Route>(routes: T[]) {
|
||||
routes.forEach((route) => {
|
||||
@@ -24,11 +33,33 @@ export function quietPreloads<T extends Route>(routes: T[]) {
|
||||
const preload = component?.preload
|
||||
if (!component || !load || !preload || quiet.has(component)) return
|
||||
quiet.add(component)
|
||||
component.preload = () =>
|
||||
load().then(
|
||||
component.preload = () => {
|
||||
const before = navigating ? undefined : new Set(document.querySelectorAll('link[rel="stylesheet"]'))
|
||||
const loading = load()
|
||||
// The helper adds the stylesheets synchronously, before any of them has loaded or applied.
|
||||
if (before)
|
||||
document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]').forEach((link) => {
|
||||
if (before.has(link)) return
|
||||
link.media = "not all"
|
||||
held.add(link)
|
||||
})
|
||||
return loading.then(
|
||||
() => preload(),
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
})
|
||||
return routes
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a navigation is under way (from the router's beforeLeave until it settles). The page being
|
||||
* opened needs its stylesheets, so a navigation's start applies every held one, before the router
|
||||
* renders the page, and preloads add theirs as before until it settles.
|
||||
*/
|
||||
export function setNavigating(on: boolean) {
|
||||
navigating = on
|
||||
if (!on) return
|
||||
held.forEach((link) => link.removeAttribute("media"))
|
||||
held.clear()
|
||||
}
|
||||
|
||||
@@ -957,6 +957,11 @@
|
||||
height: 1lh;
|
||||
}
|
||||
}
|
||||
|
||||
/* A reel keeps its cells once it has spun (SlotDigit); only a spinning reel shows them. */
|
||||
[data-slot="reel"]:not([data-spinning]) [data-slot="strip"] > span + span {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="odometer"] {
|
||||
|
||||
@@ -896,7 +896,11 @@ function SlotStat(props: { value: string; start?: number; stat: number }) {
|
||||
}
|
||||
|
||||
function SlotDigit(props: { digit: number; start?: number; place: number; stat: number }) {
|
||||
// The reel's cells are added when it first spins and stay; only a spinning reel shows more than the
|
||||
// first (index.css). Removing them as each digit landed, a frame apart, restyled the whole page in
|
||||
// each of those frames (every :has() rule re-checks a removal), right while it scrolled.
|
||||
const [reel, setReel] = createSignal([props.digit])
|
||||
const [spinning, setSpinning] = createSignal(false)
|
||||
let strip: HTMLSpanElement | undefined
|
||||
createEffect(
|
||||
on(
|
||||
@@ -911,6 +915,7 @@ function SlotDigit(props: { digit: number; start?: number; place: number; stat:
|
||||
props.digit,
|
||||
]
|
||||
setReel(digits)
|
||||
setSpinning(true)
|
||||
const line = strip.parentElement?.getBoundingClientRect().height ?? 0
|
||||
const animation = strip.animate(
|
||||
[{ transform: "translateY(0)" }, { transform: `translateY(${-(digits.length - 1) * line}px)` }],
|
||||
@@ -922,7 +927,8 @@ function SlotDigit(props: { digit: number; start?: number; place: number; stat:
|
||||
},
|
||||
)
|
||||
animation.onfinish = () => {
|
||||
setReel([props.digit])
|
||||
setReel((cells) => cells.with(0, props.digit))
|
||||
setSpinning(false)
|
||||
animation.cancel()
|
||||
}
|
||||
onCleanup(() => animation.cancel())
|
||||
@@ -930,7 +936,7 @@ function SlotDigit(props: { digit: number; start?: number; place: number; stat:
|
||||
),
|
||||
)
|
||||
return (
|
||||
<span data-slot="reel" aria-hidden="true" data-spinning={reel().length > 1 ? "" : undefined}>
|
||||
<span data-slot="reel" aria-hidden="true" data-spinning={spinning() ? "" : undefined}>
|
||||
<span data-slot="strip" ref={strip}>
|
||||
<Index each={reel()}>{(digit) => <span>{digit()}</span>}</Index>
|
||||
</span>
|
||||
|
||||
Reference in New Issue
Block a user