fix(site): stop idle polling and scroll layout thrashing (#62966)

This commit is contained in:
Adam
2026-11-09 16:30:13 -06:00
committed by GitHub
Unverified
parent 6ee519e071
commit 0a812d4d70
18 changed files with 267 additions and 170 deletions
+19 -19
View File
@@ -64,25 +64,25 @@ console.log(
// Each page's budget in kB, gzipped: what it was when last measured, plus a kB of room. Lower a
// budget when a page gets lighter; a page without one fails until it has one.
const budgets: Record<string, number> = {
"[...404].tsx": 104,
"brand/index.tsx": 107,
"changelog/[tag].tsx": 113,
"changelog/index.tsx": 112,
"desktop.tsx": 127.6,
"devices.tsx": 51,
"product/browse.tsx": 106,
"font/index.tsx": 121,
"ide.tsx": 127.6,
"index.tsx": 118,
"legal/index.tsx": 151.4,
"legal/privacy-policy/index.tsx": 140.9,
"legal/terms-of-service/index.tsx": 136.3,
"mini.tsx": 127.6,
"mobile.tsx": 127.6,
"press/index.tsx": 112,
"product/index.tsx": 114.7,
"sdk.tsx": 127.6,
"terminal.tsx": 127.6,
"[...404].tsx": 103.1,
"brand/index.tsx": 106.9,
"changelog/[tag].tsx": 100.1,
"changelog/index.tsx": 99.3,
"desktop.tsx": 126.9,
"devices.tsx": 50.6,
"product/browse.tsx": 105.7,
"font/index.tsx": 120.2,
"ide.tsx": 126.9,
"index.tsx": 117.2,
"legal/index.tsx": 150.7,
"legal/privacy-policy/index.tsx": 140.3,
"legal/terms-of-service/index.tsx": 135.6,
"mini.tsx": 126.9,
"mobile.tsx": 126.9,
"press/index.tsx": 111.6,
"product/index.tsx": 114.3,
"sdk.tsx": 126.9,
"terminal.tsx": 126.9,
"video-editor/index.tsx": 49,
}
type Chunk = { file: string; imports?: string[] }
+5 -5
View File
@@ -13,11 +13,11 @@ import { transformSync, types, type NodePath, type PluginObj } from "@babel/core
import type { Plugin } from "vite"
import defaults from "../src/component/site/settings-defaults.json"
// Settings that production pages change at runtime, so they stay live: ⇧A and ⇧N turn the home
// announcement on and off on any page (site-banner.tsx). Production reads and writes them in a store
// of their own (liveModule), so the Settings store and everything it needs leave the bundle. The
// build fails if production code writes any other setting (see generateBundle below).
const live = new Set(["homeAnnouncement"])
// Settings that production pages change at runtime, so they stay live (none today; ⇧A and ⇧N, which
// turn the announcement on and off, are development only). Production reads and writes them in a
// store of their own (liveModule), so the Settings store and everything it needs leave the bundle.
// The build fails if production code writes any other setting (see generateBundle below).
const live = new Set<string>()
const liveModule = "virtual:fold-settings-live"
// Design mode's reordering and renaming, which save only while Design mode is on.
@@ -18,7 +18,8 @@ import {
type Letter,
} from "~/lib/font-content"
import { GlyphShape, Word } from "./glyph"
import { Plate, useSeen, useVisible } from "./plate"
import { useVisible } from "~/component/site/visible"
import { Plate, useSeen } from "./plate"
const topBigram = Object.entries(bigrams).sort((a, b) => b[1] - a[1])[0]
const zeroBigrams = Object.values(bigrams).filter((count) => count === 0).length
@@ -13,7 +13,8 @@ import {
type Letter,
} from "~/lib/font-content"
import { GlyphShape } from "./glyph"
import { ease, Plate, prefersReducedMotion, span, useClock, useSeen, useVisible } from "./plate"
import { useVisible } from "~/component/site/visible"
import { ease, Plate, prefersReducedMotion, span, useClock, useSeen } from "./plate"
const HOLD = 1800
const FADE = 400
+2 -1
View File
@@ -3,7 +3,8 @@ import { arrangements, fontContent, glyphs, isLetter, subAnagrams, words } from
import { CoverTitle } from "./cover-title"
import { downloadFont } from "./download"
import { layout, Word } from "./glyph"
import { Plate, prefersReducedMotion, useClock, useVisible } from "./plate"
import { useVisible } from "~/component/site/visible"
import { Plate, prefersReducedMotion, useClock } from "./plate"
const pad = (value: number, length: number) => String(value).padStart(length, "0")
@@ -1,5 +1,6 @@
import { createMemo, createSignal, For, onCleanup, onMount } from "solid-js"
import { createEffect, createMemo, createSignal, For, onCleanup, onMount } from "solid-js"
import { buildOrder, cellToFont, cells, fontContent, glyphNames, letters, type Letter } from "~/lib/font-content"
import { useVisible } from "~/component/site/visible"
import { GlyphShape } from "./glyph"
import { clamp, ease, Plate, prefersReducedMotion } from "./plate"
@@ -136,12 +137,12 @@ export function Exploded() {
const [manual, setManual] = createSignal<number>()
const explode = () => manual() ?? scroll()
onMount(() => {
// Reduced motion: a still, half-exploded view, so the rule is still visible.
if (prefersReducedMotion()) {
setManual(0.5)
return
}
const visible = useVisible(() => section)
// Reduced motion: a still, half-exploded view, so the rule is still visible.
onMount(() => prefersReducedMotion() && setManual(0.5))
// Only while the plate is near the screen: it arrives at the lift for where the page is.
createEffect(() => {
if (!visible() || prefersReducedMotion()) return
let frame = 0
let target = 1
const progress = () => {
@@ -53,19 +53,6 @@ export function Plate(props: {
)
}
/** True while `element` is near the viewport, so animations can pause offscreen. */
export function useVisible(element: () => Element | undefined, margin = "200px 0px") {
const [visible, setVisible] = createSignal(false)
onMount(() => {
const target = element()
if (!target) return
const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting), { rootMargin: margin })
observer.observe(target)
onCleanup(() => observer.disconnect())
})
return visible
}
/** Turns true once, the first time `element` scrolls into view: for entrance animations. */
export function useSeen(element: () => Element | undefined) {
const [seen, setSeen] = createSignal(false)
@@ -20,6 +20,7 @@ import { CarouselArrows } from "./carousel-arrows"
import { Chevron, ExternalArrow, NewTab } from "./icons"
import { Inline, ReleaseItem } from "./release"
import { prefersReducedMotion } from "./media"
import { useVisible } from "./visible"
import {
changelogCarousels,
changelogFilters,
@@ -236,29 +237,36 @@ export function ChangelogTimeline(props: {
const language = useLanguage()
let list!: HTMLOListElement
onMount(() => {
const visible = useVisible(() => list)
// Only while the timeline is near the screen.
createEffect(() => {
if (!visible()) return
const frame = { id: 0 }
const update = () => {
frame.id = 0
const line = window.innerHeight * 0.4
const items = [...list.querySelectorAll<HTMLElement>(":scope > li")]
// Every read before any write, so the writes never force a layout mid-loop.
// The sticky top line (each entry's scroll-margin-top is the same --content-top). The active
// entry is the one whose date is stuck there, or would be with sticky off: the last entry
// whose top has reached it, else the first.
const stickyTop = items[0] ? parseFloat(getComputedStyle(items[0]).scrollMarginTop) : 0
const rects = items.map((item) => ({
item: item.getBoundingClientRect(),
marker: item.querySelector('[data-slot="marker"]')!.getBoundingClientRect(),
}))
const active = Math.max(
0,
items.findLastIndex((item) => item.getBoundingClientRect().top <= stickyTop + 0.5),
rects.findLastIndex((rect) => rect.item.top <= stickyTop + 0.5),
)
// Both marker styles are kept current, so switching the setting needs no scroll. --fill is
// how far the progress line runs down this entry's rail, from its marker's centre.
items.forEach((item, index) => {
const marker = item.querySelector('[data-slot="marker"]')!.getBoundingClientRect()
const center = marker.top + marker.height / 2
const rect = rects[index]
const center = rect.marker.top + rect.marker.height / 2
item.toggleAttribute("data-active", index === active)
item.toggleAttribute("data-reached", center <= line)
const fill = Math.max(0, Math.min(line - center, item.getBoundingClientRect().bottom - center))
item.style.setProperty("--fill", `${fill}px`)
item.style.setProperty("--fill", `${Math.max(0, Math.min(line - center, rect.item.bottom - center))}px`)
// Once this marker is passed, the line above it (up to the page top, clipped) is covered too.
item.style.setProperty("--fill-up", center <= line ? "100000px" : "0px")
})
@@ -269,6 +277,14 @@ export function ChangelogTimeline(props: {
update()
window.addEventListener("scroll", schedule, { passive: true })
window.addEventListener("resize", schedule)
onCleanup(() => {
cancelAnimationFrame(frame.id)
window.removeEventListener("scroll", schedule)
window.removeEventListener("resize", schedule)
})
})
onMount(() => {
// A phone's stuck date row is held back by its title's height, so the two leave together.
const titles = new ResizeObserver((entries) =>
entries.forEach((entry) =>
@@ -278,12 +294,7 @@ export function ChangelogTimeline(props: {
list
.querySelectorAll(':scope > li > [data-component="changelog-entry"] > [data-slot="title"]')
.forEach((title) => titles.observe(title))
onCleanup(() => {
cancelAnimationFrame(frame.id)
titles.disconnect()
window.removeEventListener("scroll", schedule)
window.removeEventListener("resize", schedule)
})
onCleanup(() => titles.disconnect())
})
return (
@@ -2,6 +2,7 @@ import "./logo-wall.css"
import { createEffect, createMemo, createSignal, createUniqueId, For, on, onCleanup, onMount, Show } from "solid-js"
import { inView, revealMotion, washRootMargin, washStartTime, washThreshold } from "./reveal"
import type { logoAnimations, logoLayouts, SiteSettings } from "./settings"
import { useVisible } from "./visible"
type Logo = { name: string; logo: string; metrics: { aspect: number; density: number; centerY: number } }
@@ -67,7 +68,6 @@ export function LogoWall(props: {
// The next logo to try, in list order.
let next = slots().length
let tick = 0
let visible = false
// The entrance: the first time the row scrolls into view the logos arrive one at a time from the
// left (top left first where they wrap), in the reveal style. Armed on the client only and never
// with reduced motion; until the wash starts the logos are hidden, and no swap runs before it ends.
@@ -115,11 +115,10 @@ export function LogoWall(props: {
() => props.items.reduce((sum, item) => sum + logoWidth(item.metrics), 0) / Math.max(1, props.items.length),
)
// Swaps run only while the row is on screen and the tab is showing.
const visible = useVisible(() => row, "0px")
onMount(() => {
const observer = new IntersectionObserver((entries) => {
visible = entries.some((entry) => entry.isIntersecting)
})
if (row) observer.observe(row)
setMounted(true)
let first = true
const entrance = new IntersectionObserver(
@@ -151,15 +150,14 @@ export function LogoWall(props: {
if (row?.parentElement) resize.observe(row.parentElement)
measure()
onCleanup(() => {
observer.disconnect()
entrance.disconnect()
resize.disconnect()
})
})
createEffect(() => {
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
const timer = setInterval(() => visible && !document.hidden && entranceDone() && swap(), props.interval * 1000)
if (!visible() || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
const timer = setInterval(() => entranceDone() && swap(), props.interval * 1000)
onCleanup(() => clearInterval(timer))
})
@@ -3,6 +3,7 @@ import "./on-this-page.css"
import { createEffect, createSignal, For, onCleanup, onMount, Show, type JSX } from "solid-js"
import { Chevron } from "./icons"
import { holdOpenMenu } from "./menu-hold"
import { useVisible } from "./visible"
type ContentsItem = {
id: string
@@ -19,37 +20,52 @@ type ContentsItem = {
* last section in view.
*/
function useActiveSection(items: () => ContentsItem[]) {
const [active, setActive] = createSignal<string>()
onMount(() => {
const track = () => {
const list = items()
const headings = list.flatMap((item) => {
const heading = document.getElementById(item.id)
return heading ? [{ id: item.id, top: heading.getBoundingClientRect().top }] : []
})
const passed = headings.filter((heading) => heading.top <= window.innerHeight / 3)
const bottom = window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2
const visible = headings.filter((heading) => heading.top >= 0 && heading.top < window.innerHeight)
const target = visible.find((heading) => `#${heading.id}` === decodeURIComponent(location.hash))
setActive(
bottom && (target ?? visible.at(-1)) ? (target ?? visible.at(-1))!.id : (passed.at(-1)?.id ?? list[0]?.id),
)
}
spy.items = items
track()
window.addEventListener("scroll", track, { passive: true })
window.addEventListener("resize", track, { passive: true })
window.addEventListener("hashchange", track)
if (spy.users++ === 0) {
window.addEventListener("scroll", schedule, { passive: true })
window.addEventListener("resize", schedule, { passive: true })
window.addEventListener("hashchange", schedule)
}
onCleanup(() => {
window.removeEventListener("scroll", track)
window.removeEventListener("resize", track)
window.removeEventListener("hashchange", track)
if (--spy.users) return
cancelAnimationFrame(spy.frame)
spy.frame = 0
window.removeEventListener("scroll", schedule)
window.removeEventListener("resize", schedule)
window.removeEventListener("hashchange", schedule)
})
})
return [active, setActive] as const
}
// The aside's list and the phone menu show the page's same sections, so one spy, once a frame,
// serves both.
const [active, setActive] = createSignal<string>()
const spy = { users: 0, frame: 0, items: (): ContentsItem[] => [] }
function schedule() {
if (spy.frame) return
spy.frame = requestAnimationFrame(() => {
spy.frame = 0
track()
})
}
function track() {
const list = spy.items()
const headings = list.flatMap((item) => {
const heading = document.getElementById(item.id)
return heading ? [{ id: item.id, top: heading.getBoundingClientRect().top }] : []
})
const passed = headings.filter((heading) => heading.top <= window.innerHeight / 3)
const bottom = window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2
const visible = headings.filter((heading) => heading.top >= 0 && heading.top < window.innerHeight)
const target = visible.find((heading) => `#${heading.id}` === decodeURIComponent(location.hash))
setActive(bottom && (target ?? visible.at(-1)) ? (target ?? visible.at(-1))!.id : (passed.at(-1)?.id ?? list[0]?.id))
}
/**
* "Contents" for long pages, in the right-hand aside: pass it to <Site aside={...}>. The docs, Brand,
* Press and legal pages all use it, so the list looks and behaves the same everywhere. The docs layout
@@ -121,9 +137,21 @@ export function ContentsMenu(props: { items: ContentsItem[] }) {
menu.open = false
menu.querySelector("summary")?.focus()
}
// Pinned (its top at its sticky offset, once the page has scrolled), the bar shows its lines
// (data-stuck, on-this-page.css). Measured on scroll, so it works where CSS scroll-state queries
// don't (WebKit).
document.addEventListener("pointerdown", outside)
document.addEventListener("keydown", escape)
onCleanup(() => {
document.removeEventListener("pointerdown", outside)
document.removeEventListener("keydown", escape)
document.documentElement.removeAttribute("data-menu-hold")
})
})
// Pinned (its top at its sticky offset, once the page has scrolled), the bar shows its lines
// (data-stuck, on-this-page.css). Measured on scroll, so it works where CSS scroll-state queries
// don't (WebKit), and only while the bar is near the screen: from 60rem up it is hidden.
const shown = useVisible(() => menu)
createEffect(() => {
if (!shown()) return
let frame = 0
const stuck = () => {
cancelAnimationFrame(frame)
@@ -133,18 +161,13 @@ export function ContentsMenu(props: { items: ContentsItem[] }) {
menu.toggleAttribute("data-stuck", window.scrollY > 0 && menu.getBoundingClientRect().top <= top + 0.5)
})
}
document.addEventListener("pointerdown", outside)
document.addEventListener("keydown", escape)
window.addEventListener("scroll", stuck, { passive: true })
window.addEventListener("resize", stuck)
stuck()
onCleanup(() => {
cancelAnimationFrame(frame)
document.removeEventListener("pointerdown", outside)
document.removeEventListener("keydown", escape)
window.removeEventListener("scroll", stuck)
window.removeEventListener("resize", stuck)
document.documentElement.removeAttribute("data-menu-hold")
})
})
@@ -998,10 +998,15 @@ export function ProductAction(props: { slug: PageSlug; split?: boolean; both?: b
setOS(detectOS())
setSheet(prefersSheet())
if (props.slug === "desktop") void detectDesktopDownload().then(setBuild)
onCleanup(() => clearTimeout(timer))
})
// While the menu is open, Escape or a click outside it closes it.
createEffect(() => {
if (!open()) return
const close = (event: Event) => {
if (event instanceof KeyboardEvent && event.key !== "Escape") return
if (event instanceof MouseEvent && menu?.contains(event.target as Node)) return
if (event instanceof KeyboardEvent && open() && menu?.contains(document.activeElement)) trigger?.focus()
if (event instanceof KeyboardEvent && menu?.contains(document.activeElement)) trigger?.focus()
setOpen(false)
}
document.addEventListener("keydown", close)
@@ -1009,7 +1014,6 @@ export function ProductAction(props: { slug: PageSlug; split?: boolean; both?: b
onCleanup(() => {
document.removeEventListener("keydown", close)
document.removeEventListener("click", close)
clearTimeout(timer)
})
})
@@ -1,4 +1,7 @@
import { createSignal } from "solid-js"
import { announcementCopy, announcements } from "./announcement"
import { designCopy } from "./design-copy"
import { siteSettings } from "./settings"
// The banner's message as it was dismissed with ×, kept apart from the Announcement setting so a
// new message shows again. Read after hydration; bannerDismissScript applies it before first paint.
@@ -17,3 +20,30 @@ const shown = import.meta.env.DEV
* the message the banner will show was dismissed.
*/
export const bannerDismissScript = `(()=>{try{const r=document.currentScript.parentElement;if(!r.hasAttribute("data-banner"))return;const d=localStorage.getItem(${JSON.stringify(dismissKey)});if(!d)return;const m=${shown};if(d===m)r.removeAttribute("data-banner")}catch{}})()`
// The banner's state, which the page reads too (site.tsx) without loading the banner itself.
export const [dismissed, setDismissed] = createSignal<string>()
export const message = () => designCopy("home.announcement", announcementCopy(announcements[0]))
/** On when the announcement is on in the "banner" style (the other styles are home only) and its message wasn't dismissed. */
export const bannerVisible = () =>
siteSettings.homeAnnouncement === "on" && siteSettings.announcementStyle === "banner" && dismissed() !== message()
// Whether the banner still covers the top of the screen (it scrolls away with the page), and its blue
// as painted, which follows the theme and the blue settings.
export const [onTop, setOnTop] = createSignal(true)
export const [blue, setBlue] = createSignal<string>()
/**
* The banner's blue while it is open and covers the top of the screen, else undefined: the browser
* bar colour (theme-color) then matches it, so the status bar area and the banner read as one surface.
*/
export const bannerTopColor = () => (bannerVisible() && onTop() ? blue() : undefined)
/**
* Runs while the page is parsed, right after the banner: when it is open, gives the theme-color tags
* its blue before first paint. The stylesheets come before it in the document, so it reads the blue
* as painted; it skips the tags if they have not applied yet.
*/
export const bannerThemeColorScript = `(()=>{const a=document.currentScript.parentElement;if(!a.hasAttribute("data-banner"))return;const l=a.querySelector('[data-component="announcement-banner"] a');const c=l&&getComputedStyle(l).backgroundColor;if(!c||c==="transparent"||/, 0\\)$/.test(c))return;document.querySelectorAll('meta[name="theme-color"]').forEach((m)=>{m.content=c})})()`
@@ -2,48 +2,22 @@ import { useArea } from "~/i18n/content"
import { announcementsSource } from "~/i18n/content/areas/announcements"
import { useI18n } from "~/context/i18n"
import "./site-banner.css"
import { createSignal, onCleanup, onMount, Show } from "solid-js"
import { onCleanup, onMount, Show } from "solid-js"
import { useLanguage } from "~/context/language"
import { announcementCopy, announcements } from "./announcement"
import { designCopy } from "./design-copy"
import { dismissKey } from "./site-banner-script"
import { bannerVisible, dismissed, dismissKey, message, setBlue, setDismissed, setOnTop } from "./site-banner-script"
import { ChevronRight, CloseIcon } from "./icons"
import { setSiteSetting, siteSettings } from "./settings"
const [dismissed, setDismissed] = createSignal<string>()
const message = () => designCopy("home.announcement", announcementCopy(announcements[0]))
/** On when the announcement is on in the "banner" style (the other styles are home only) and its message wasn't dismissed. */
export const bannerVisible = () =>
siteSettings.homeAnnouncement === "on" && siteSettings.announcementStyle === "banner" && dismissed() !== message()
// Whether the banner still covers the top of the screen (it scrolls away with the page), and its blue
// as painted, which follows the theme and the blue settings.
const [onTop, setOnTop] = createSignal(true)
const [blue, setBlue] = createSignal<string>()
/**
* The banner's blue while it is open and covers the top of the screen, else undefined: the browser
* bar colour (theme-color) then matches it, so the status bar area and the banner read as one surface.
*/
export const bannerTopColor = () => (bannerVisible() && onTop() ? blue() : undefined)
/**
* Runs while the page is parsed, right after the banner: when it is open, gives the theme-color tags
* its blue before first paint. The stylesheets come before it in the document, so it reads the blue
* as painted; it skips the tags if they have not applied yet.
*/
export const bannerThemeColorScript = `(()=>{const a=document.currentScript.parentElement;if(!a.hasAttribute("data-banner"))return;const l=a.querySelector('[data-component="announcement-banner"] a');const c=l&&getComputedStyle(l).backgroundColor;if(!c||c==="transparent"||/, 0\\)$/.test(c))return;document.querySelectorAll('meta[name="theme-color"]').forEach((m)=>{m.content=c})})()`
/**
* The announcement's "banner" style: a full-width blue bar above the whole page, the footer letters
* bar's twin, the whole bar the link, with × to dismiss it. Every page renders it first in its banner
* host (Site's root, the product nav demos); the host's data-banner, set before first paint for a
* saved value, opens it and pushes the page down. While it is on screen the host's fixed elements sit
* below it through --banner-offset, and --banner-scroll follows the page's scroll so they rise as it
* scrolls away. ⇧A or ⇧N turns the announcement on and off from any page (bringing back a dismissed
* banner first), except while typing.
* scrolls away. On the development server, ⇧A or ⇧N turns the announcement on and off from any page
* (bringing back a dismissed banner first), except while typing. Production renders the banner only
* when the default settings turn it on (site.tsx).
*/
export function SiteBanner() {
const language = useLanguage()
@@ -87,27 +61,29 @@ export function SiteBanner() {
const scheme = window.matchMedia("(prefers-color-scheme: dark)")
scheme.addEventListener("change", paint)
paint()
const key = (event: KeyboardEvent) => {
if (!["KeyA", "KeyN"].includes(event.code) || !event.shiftKey || event.metaKey || event.ctrlKey || event.altKey)
return
if ((event.target as HTMLElement).closest("input, textarea, select, [contenteditable]")) return
event.preventDefault()
if (siteSettings.homeAnnouncement === "on" && dismissed() === message()) {
localStorage.removeItem(dismissKey)
return setDismissed(undefined)
}
setSiteSetting("homeAnnouncement", siteSettings.homeAnnouncement === "on" ? "off" : "on")
}
scroll()
window.addEventListener("scroll", scroll, { passive: true })
document.addEventListener("keydown", key)
onCleanup(() => {
window.removeEventListener("scroll", scroll)
document.removeEventListener("keydown", key)
colors.disconnect()
scheme.removeEventListener("change", paint)
host?.style.removeProperty("--banner-scroll")
})
if (import.meta.env.DEV) {
const key = (event: KeyboardEvent) => {
if (!["KeyA", "KeyN"].includes(event.code) || !event.shiftKey || event.metaKey || event.ctrlKey || event.altKey)
return
if ((event.target as HTMLElement).closest("input, textarea, select, [contenteditable]")) return
event.preventDefault()
if (siteSettings.homeAnnouncement === "on" && dismissed() === message()) {
localStorage.removeItem(dismissKey)
return setDismissed(undefined)
}
setSiteSetting("homeAnnouncement", siteSettings.homeAnnouncement === "on" ? "off" : "on")
}
document.addEventListener("keydown", key)
onCleanup(() => document.removeEventListener("keydown", key))
}
})
return (
+24 -12
View File
@@ -62,8 +62,7 @@ import { NavVersions } from "./nav-versions"
import { closeAllMenus, closeMenusOnLinks, onCloseMenus, takeMenuNavigation } from "./menu-open"
import { watchSurfaces } from "./surface"
import { designCopy, designMode } from "./design-copy"
import { bannerThemeColorScript, bannerTopColor, bannerVisible, SiteBanner } from "./site-banner"
import { bannerDismissScript } from "./site-banner-script"
import { bannerDismissScript, bannerThemeColorScript, bannerTopColor, bannerVisible } from "./site-banner-script"
import { Tooltips } from "./tooltip"
import { SiteSearch } from "./search"
import { preloadVisibleLinks } from "./preload-visible"
@@ -105,6 +104,12 @@ export {
const SettingsPanel = import.meta.env.DEV ? lazy(() => import("./settings-panel")) : undefined
const DesignMode = import.meta.env.DEV ? lazy(() => import("./design-mode")) : undefined
const DevicePreview = import.meta.env.DEV ? lazy(() => import("./device-preview")) : undefined
// The announcement's "banner" style, where it can open: production renders the default settings, so
// while they keep it off the banner, its scripts and its CSS leave the build.
const SiteBanner =
import.meta.env.DEV || (siteSettings.homeAnnouncement === "on" && siteSettings.announcementStyle === "banner")
? lazy(() => import("./site-banner").then((module) => ({ default: module.SiteBanner })))
: undefined
// A nav item as the nav renders it: a known one (links.ts) or a custom link (nav-order.tsx).
type NavItemView = { id: string; label: string; href: string; arrow: boolean; external: boolean; company: boolean }
@@ -626,12 +631,15 @@ export function Site(props: {
})
onMount(() => {
// Hydration keeps the server's attributes (theme "system"), so the toggle would show the wrong
// option. Flip the signal away and back so every theme binding re-applies the saved value; the
// second set waits a microtask, or the batched updates cancel out and nothing re-renders.
// Hydration keeps the server's attributes (theme "system"), so for a saved light or dark theme
// the toggle would show the wrong option. Flip the signal away and back so every theme binding
// re-applies the saved value; the second set waits a microtask, or the batched updates cancel out
// and nothing re-renders.
const saved = theme()
setTheme(saved === "system" ? "light" : "system")
queueMicrotask(() => setTheme(saved))
if (saved !== "system") {
setTheme("system")
queueMicrotask(() => setTheme(saved))
}
loadSiteSettings()
// The settings store now drives the same rules, so the pre-paint copy can go.
document.getElementById("site-settings-preload")?.remove()
@@ -1321,15 +1329,15 @@ export function Site(props: {
theme first. The theme script also sets the theme-color and color-scheme tags. */}
{import.meta.env.DEV && <script innerHTML={preloadSettings} />}
{/* After the settings: closes the banner again before first paint if its message was dismissed. */}
<script innerHTML={bannerDismissScript} />
{SiteBanner && <script innerHTML={bannerDismissScript} />}
<script innerHTML={themeScript(import.meta.env.DEV)} />
{/* Card stills and product hero posters fade in as soon as their image loads, long before the
page's code has loaded: load events reach a capturing listener on the document (added once,
though the script runs again when a client navigation renders it). One already decoded when
it first paints (preloaded, or cached) is marked data-instant and shows at once instead: a
check each frame, before paint, while the page loads. */}
check in the frame after the page gains elements, before paint, while the page loads. */}
<script
innerHTML={`if(!document.posterLoads){document.posterLoads=1;document.addEventListener("load",(e)=>{const t=e.target;if(t instanceof HTMLImageElement&&t.hasAttribute("data-poster"))t.setAttribute("data-loaded","")},true);const scan=()=>{document.querySelectorAll("img[data-poster]:not([data-seen])").forEach((i)=>{i.setAttribute("data-seen","");if(i.complete&&i.naturalWidth){i.setAttribute("data-instant","");i.setAttribute("data-loaded","")}});if(document.readyState!=="complete")requestAnimationFrame(scan)};requestAnimationFrame(scan)}`}
innerHTML={`if(!document.posterLoads){document.posterLoads=1;document.addEventListener("load",(e)=>{const t=e.target;if(t instanceof HTMLImageElement&&t.hasAttribute("data-poster"))t.setAttribute("data-loaded","")},true);let f=0;const scan=()=>{f=0;document.querySelectorAll("img[data-poster]:not([data-seen])").forEach((i)=>{i.setAttribute("data-seen","");if(i.complete&&i.naturalWidth){i.setAttribute("data-instant","");i.setAttribute("data-loaded","")}})};const o=new MutationObserver(()=>{f||(f=requestAnimationFrame(scan))});o.observe(document,{childList:true,subtree:true});addEventListener("load",()=>o.disconnect(),{once:true})}`}
/>
<script type="speculationrules" innerHTML={speculationRules} />
<Show when={props.markdown?.href}>{(href) => <Link rel="alternate" type="text/markdown" href={href()} />}</Show>
@@ -1346,8 +1354,12 @@ export function Site(props: {
{i18n.t("site.skipToContent")}
</a>
{/* The announcement's "banner" style, above everything on every page (site-banner.tsx). */}
<SiteBanner />
<script innerHTML={bannerThemeColorScript} />
{SiteBanner && (
<>
<SiteBanner />
<script innerHTML={bannerThemeColorScript} />
</>
)}
{/* Hide the page before first paint when the Markdown view will replace it on mount. */}
<script
innerHTML={`(()=>{try{if(sessionStorage.getItem("${markdownKey}")==="1")document.currentScript.parentElement.dataset.markdownBoot=""}catch{}})()`}
+33 -6
View File
@@ -5,7 +5,8 @@
* Behind it means the first element under the mark that says what it is: `data-surface` on it or an
* ancestor (for media and canvases), else its own background colour (an SVG shape's fill) when
* mostly opaque. Nothing
* decisive (the page itself) leaves the attribute off, so the page theme decides.
* decisive (the page itself) leaves the attribute off, so the page theme decides. It checks again
* when something could have changed behind a mark, and never while nothing does.
*/
export function watchSurfaces(marks: () => HTMLElement[]) {
const check = () =>
@@ -23,10 +24,10 @@ export function watchSurfaces(marks: () => HTMLElement[]) {
const dark = votes.filter((vote) => vote === "dark").length
const light = votes.filter((vote) => vote === "light").length
const surface = dark === light ? votes[0] : dark > light ? "dark" : "light"
if (surface) mark.dataset.onSurface = surface
if (surface && mark.dataset.onSurface !== surface) mark.dataset.onSurface = surface
if (!surface) delete mark.dataset.onSurface
})
const frame = { id: 0 }
const frame = { id: 0, timer: 0, again: false }
const schedule = () => {
if (frame.id) return
frame.id = requestAnimationFrame(() => {
@@ -34,16 +35,42 @@ export function watchSurfaces(marks: () => HTMLElement[]) {
check()
})
}
// The page changes under a still mark too: the theme, a page swapped in, the film starting, a
// plate animating. Animations change it every frame, so at most one check per 400ms, and one
// after the last change.
const changed = () => {
if (frame.timer) {
frame.again = true
return
}
schedule()
frame.timer = window.setTimeout(() => {
frame.timer = 0
if (!frame.again) return
frame.again = false
changed()
}, 400)
}
const mutations = new MutationObserver(
(records) => records.some((record) => record.attributeName !== "data-on-surface") && changed(),
)
const scheme = window.matchMedia("(prefers-color-scheme: dark)")
check()
window.addEventListener("scroll", schedule, { passive: true })
window.addEventListener("resize", schedule)
// Pinned stages and the film change under a still mark too.
const timer = setInterval(schedule, 400)
scheme.addEventListener("change", schedule)
document.addEventListener("transitionend", changed, true)
document.addEventListener("animationend", changed, true)
mutations.observe(document.documentElement, { subtree: true, childList: true, attributes: true })
return () => {
cancelAnimationFrame(frame.id)
clearInterval(timer)
clearTimeout(frame.timer)
mutations.disconnect()
window.removeEventListener("scroll", schedule)
window.removeEventListener("resize", schedule)
scheme.removeEventListener("change", schedule)
document.removeEventListener("transitionend", changed, true)
document.removeEventListener("animationend", changed, true)
}
}
@@ -0,0 +1,24 @@
import { createSignal, onCleanup, onMount } from "solid-js"
/**
* True while `element` is near the viewport and the tab is showing, so loops, timers and scroll
* work can stop off screen and in background tabs.
*/
export function useVisible(element: () => Element | undefined, margin = "200px 0px") {
const [near, setNear] = createSignal(false)
const [shown, setShown] = createSignal(true)
onMount(() => {
const target = element()
if (!target) return
const observer = new IntersectionObserver(([entry]) => setNear(entry.isIntersecting), { rootMargin: margin })
observer.observe(target)
const sync = () => setShown(!document.hidden)
sync()
document.addEventListener("visibilitychange", sync)
onCleanup(() => {
observer.disconnect()
document.removeEventListener("visibilitychange", sync)
})
})
return () => near() && shown()
}
+7 -7
View File
@@ -78,10 +78,14 @@ export default function Brand() {
// While the page scrolls, rows passing under a resting pointer would light up one after another
// (a flicker). The content ignores the pointer until scrolling has stopped for 150ms.
const state: { idle?: ReturnType<typeof setTimeout> } = {}
// Written once per scroll, not per event: it restyles the whole page.
const scrolling = () => {
document.documentElement.dataset.scrolling = ""
if (state.idle === undefined) document.documentElement.dataset.scrolling = ""
clearTimeout(state.idle)
state.idle = setTimeout(() => delete document.documentElement.dataset.scrolling, 150)
state.idle = setTimeout(() => {
state.idle = undefined
delete document.documentElement.dataset.scrolling
}, 150)
}
window.addEventListener("scroll", scrolling, { passive: true })
onCleanup(() => {
@@ -701,11 +705,7 @@ export default function Brand() {
{content().hero.all.text}
<DownloadIcon />
</a>
<AgentRulesButton
label={content().hero.copy.text}
copied={content().hero.copy.copied}
source={rules}
/>
<AgentRulesButton label={content().hero.copy.text} copied={content().hero.copy.copied} source={rules} />
</div>
</section>
+2 -1
View File
@@ -506,7 +506,8 @@ export default function Home() {
* Settings › Announcement: a "New" bar level with the logo, over the hero's three card columns
* (in the page's flow on phones). It always renders; the site root's data-home-announcement (set
* before first paint for a saved value) opens it, and changes animate its height and opacity.
* ⇧A (or the older ⇧N) toggles it, like ⇧S and ⇧D for Settings and Design mode, except while typing.
* On the development server ⇧A (or the older ⇧N) toggles it, like ⇧S and ⇧D for Settings and Design
* mode, except while typing.
*/
function Announcement() {
const language = useLanguage()