diff --git a/public/images/hero-palm-cutout-still.webp b/public/images/hero-palm-cutout-still.webp new file mode 100644 index 000000000..3602a7519 Binary files /dev/null and b/public/images/hero-palm-cutout-still.webp differ diff --git a/public/images/hero-palm-cutout.webp b/public/images/hero-palm-cutout.webp new file mode 100644 index 000000000..4a5d3197a Binary files /dev/null and b/public/images/hero-palm-cutout.webp differ diff --git a/src/components/home/HeroPalmMedia.tsx b/src/components/home/HeroPalmMedia.tsx index 21c67c41d..659cad19c 100644 --- a/src/components/home/HeroPalmMedia.tsx +++ b/src/components/home/HeroPalmMedia.tsx @@ -1,109 +1,59 @@ import * as React from 'react' -import { PauseIcon, PlayIcon } from '@phosphor-icons/react' +import { preload } from 'react-dom' import { Squircle } from '~/components/Squircle' -export function HeroPalmMedia() { - const videoRef = React.useRef(null) - const [isVideoReady, setIsVideoReady] = React.useState(false) - const [isPlaying, setIsPlaying] = React.useState(false) - - const playVideo = React.useCallback((video: HTMLVideoElement) => { - if (video.networkState === HTMLMediaElement.NETWORK_NO_SOURCE) video.load() - const promise = video.play() - if (promise !== undefined) { - promise - .then(() => setIsVideoReady(true)) - .catch((error: unknown) => { - if (error instanceof DOMException && error.name === 'AbortError') - return - console.error('Unable to play the homepage hero animation', error) - setIsPlaying(false) - setIsVideoReady(false) - }) - } - }, []) - - React.useEffect(() => { - const video = videoRef.current - if (!video) return - const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)') - - const pauseForReducedMotion = () => { - if (reducedMotion.matches) video.pause() - } +const motion = '/images/hero-palm-cutout.webp' +const still = '/images/hero-palm-cutout-still.webp' +const allowMotion = '(prefers-reduced-motion: no-preference)' - pauseForReducedMotion() - setIsPlaying(!video.paused) - setIsVideoReady(video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) - reducedMotion.addEventListener('change', pauseForReducedMotion) - return () => - reducedMotion.removeEventListener('change', pauseForReducedMotion) - }, []) - - const togglePlayback = () => { - const video = videoRef.current - if (!video) return +export function HeroPalmMedia() { + preload(still, { as: 'image', fetchPriority: 'high' }) + preload(motion, { as: 'image', fetchPriority: 'high', media: allowMotion }) - if (video.paused) { - playVideo(video) - } else { - video.pause() - } - } + const [motionFailed, setMotionFailed] = React.useState(false) return ( - <> - - - + + {/* Keep the palm aligned with the original 944 × 416 composition. */} +
+
- - - - - + + {!motionFailed && ( + + )} + { + // A failed request can finish before hydration attaches onError. + if ( + image?.complete && + !image.naturalWidth && + image.currentSrc.endsWith(motion) + ) { + setMotionFailed(true) + } + }} + onError={() => setMotionFailed(true)} + className="block h-auto w-full" + /> + +
+
+
) } diff --git a/src/components/home/HomeApplicationStarter.tsx b/src/components/home/HomeApplicationStarter.tsx index 0b8d13aa1..e10eb9a11 100644 --- a/src/components/home/HomeApplicationStarter.tsx +++ b/src/components/home/HomeApplicationStarter.tsx @@ -1,6 +1,6 @@ import * as React from 'react' import { Hydrate } from '@tanstack/react-start' -import { idle, visible } from '@tanstack/react-start/hydration' +import { visible } from '@tanstack/react-start/hydration' import { ApplicationStarter } from '~/components/ApplicationStarter' import { HomeApplicationStarterFallback } from './HomeSectionFallbacks' @@ -17,8 +17,7 @@ const headlines = [ export function HomeApplicationStarter() { return ( } > diff --git a/src/routes/index.tsx b/src/routes/index.tsx index c97e1666d..77394aaba 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -12,11 +12,14 @@ import { LightningIcon, type Icon, } from '@phosphor-icons/react' +import { Hydrate } from '@tanstack/react-start' +import { visible } from '@tanstack/react-start/hydration' import { HeroPalmMedia } from '~/components/home/HeroPalmMedia' import { HomeApplicationStarter } from '~/components/home/HomeApplicationStarter' import { HomeCommunitySection } from '~/components/home/HomeCommunitySection' import { HomeNewsletterSection } from '~/components/home/HomeNewsletterSection' import { HomeSocialProofSection } from '~/components/home/HomeSocialProofSection' +import { HomeStatsFallback } from '~/components/home/HomeSectionFallbacks' import { HomeStatsSection } from '~/components/home/HomeStatsSection' import { useQuery } from '@tanstack/react-query' import { Button, Eyebrow } from '~/components/ds/ui' @@ -31,15 +34,7 @@ import { seo } from '~/utils/seo' import { getTanStackHomepageJsonLd } from '~/utils/organization-structured-data' export const Route = createFileRoute('/')({ - loader: async ({ context: { queryClient } }) => { - const [, , recentPosts] = await Promise.all([ - queryClient.ensureQueryData(ossStatsQuery()), - queryClient.ensureQueryData(homepageNpmStatsSummaryQuery()), - fetchRecentPosts(), - ]) - - return { recentPosts } - }, + loader: () => fetchRecentPosts(), head: () => ({ meta: seo({ title: 'TanStack | The open-source application stack for the web.', @@ -57,7 +52,7 @@ export const Route = createFileRoute('/')({ }) function Index() { - const { recentPosts } = Route.useLoaderData() + const recentPosts = Route.useLoaderData() const { openLibraries } = useLibrariesOverlay() const startWithPrompt = (e: React.MouseEvent) => { @@ -78,19 +73,14 @@ function Index() {
- {/* Hero — Figma node 802:2027. Full-bleed palm/gradient photo card: - headline bottom-left, description + CTA bottom-right. The photo is + {/* Hero — Figma node 802:2027. Full-bleed palm and sky: + headline bottom-left, description + CTA bottom-right. The sky is always light, so text uses a mode-stable dark token (neutral-500) rather than a theme-flipping semantic. */}
{/* `svh`, not `dvh` — the dynamic viewport grows as iOS collapses the URL bar mid-scroll, visibly stretching the hero. */}
- {/* The parent supplies the 4px frame shared by the hero and stats. - This wrapper clips the image to the inner radius so the - fills it exactly instead of overflowing. Plain (not OptimizedImage): - the Cloudflare transform resolves against the production origin, - so a newly-added asset 404s until deployed. */}

The{' '} @@ -106,7 +96,7 @@ function Index() { applications that work naturally for developers and reliably for agents

- {/* The photo is always light, so scope the CTAs to the DS + {/* The sky is always light, so scope the CTAs to the DS light mode — the Buttons then render as their standard DS light-mode selves (no per-button color overrides). */}
@@ -143,7 +133,12 @@ function Index() {

- + } + > + +
- + + + ))} @@ -495,7 +492,7 @@ function WhyTanStackSection() { */ function PrinciplePanel({ children }: { children: React.ReactNode }) { return ( -
+
{children}
) @@ -706,8 +703,8 @@ function PrincipleProof({ } /** - * Production-Grade proof: the live npm download odometer already prefetched by - * the route loader, plus weekly volume and stars. Real numbers rather than + * Production-Grade proof: the live npm download odometer shared with + * the hero stats, plus weekly volume and stars. Real numbers rather than * adjectives — the point of the principle is scale. */ function AdoptionProof({ accentClassName }: { accentClassName: string }) { diff --git a/src/styles/app.css b/src/styles/app.css index e3f98c2ce..cdef5eb85 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -2751,6 +2751,16 @@ html:not(.dark) .library-landing-graphic [style*='drop-shadow'] { transition: opacity 120ms linear; } +.home-palm-sky { + background: linear-gradient( + #8fd7fe, + #b0dbff 25%, + #d3e0ff 50%, + #e7dffb 75%, + #f5d9f2 + ); +} + @keyframes home-open-source-gradient-shift { 0%, 100% { diff --git a/tests/hero-media.test.ts b/tests/hero-media.test.ts index 8f71345ab..13ba69f19 100644 --- a/tests/hero-media.test.ts +++ b/tests/hero-media.test.ts @@ -8,14 +8,12 @@ import { createElement } from 'react' import { renderToString } from 'react-dom/server' import { chromium } from 'playwright-core' import { build } from 'esbuild' +import sharp from 'sharp' import { HeroPalmMedia } from '../src/components/home/HeroPalmMedia' const repoRoot = path.resolve(import.meta.dirname, '..') -const componentPath = path.join( - repoRoot, - 'src/components/home/HeroPalmMedia.tsx', -) -const videoPath = path.join(repoRoot, 'public/images/hero-palm-motion.mp4') +const motion = '/images/hero-palm-cutout.webp' +const still = '/images/hero-palm-cutout-still.webp' const serverMarkup = renderToString(createElement(HeroPalmMedia)) const chromePath = [ process.env.CHROME_BIN, @@ -26,45 +24,72 @@ const chromePath = [ chromium.executablePath(), ].find((candidate) => candidate && fs.existsSync(candidate)) -test('server render exposes a motion source selected by reduced-motion preference', () => { - const markup = renderToString(createElement(HeroPalmMedia)) - const videoMarkup = markup.match(/]*>/)?.[0] +test('the palm loop stays at 24 fps, matches its still, and fits the media budget', async () => { + const animation = await sharp( + path.join(repoRoot, 'public', motion), + ).metadata() + const poster = await sharp(path.join(repoRoot, 'public', still)).metadata() + // The source has 121 frames at 24 fps. WebP stores whole milliseconds. + const delays = Array.from( + { length: 121 }, + (_, i) => Math.round(((i + 1) * 1000) / 24) - Math.round((i * 1000) / 24), + ) + assert.deepEqual(animation.delay, delays) + const assetSize = (file: string) => + fs.statSync(path.join(repoRoot, 'public', file)).size + // The MP4 and its posters transferred 1.91 MB in the mobile baseline. + assert.ok( + assetSize(motion) + assetSize(still) < 1_900_000, + 'the combined palm assets should stay under 1.90 MB', + ) + assert.equal(animation.loop, 0) + assert.ok(animation.hasAlpha && poster.hasAlpha) + assert.equal(animation.width, poster.width) + assert.equal(animation.height, poster.height) + const firstFrame = await sharp(path.join(repoRoot, 'public', motion)) + .ensureAlpha() + .raw() + .toBuffer() + const stillFrame = await sharp(path.join(repoRoot, 'public', still)) + .ensureAlpha() + .raw() + .toBuffer() + assert.ok( + firstFrame.equals(stillFrame), + 'the still must match the first frame', + ) +}) - assert.ok(videoMarkup) - assert.doesNotMatch(videoMarkup, /\s(?:src|poster)=/) - assert.match(markup, /srcSet="\/images\/hero-palm-gradient-/) - assert.match(markup, /loading="eager"/) - assert.match(markup, /fetchPriority="high"/) - assert.match(markup, /media="\(prefers-reduced-motion: no-preference\)"/) - assert.match(markup, / { + assert.doesNotMatch(serverMarkup, /]+rel="preload"[^>]*>/g) ?? [] + assert.equal(preloads.length, 2) + const poster = preloads.find((tag) => tag.includes(`href="${still}"`)) + const animation = preloads.find((tag) => tag.includes(`href="${motion}"`)) + assert.ok(poster && animation) + assert.doesNotMatch(poster, /media=/) + assert.match(animation, /media="\(prefers-reduced-motion: no-preference\)"/) + assert.match(poster, /fetchPriority="high"/i) + assert.match(animation, /fetchPriority="high"/i) }) test( - 'hero video starts before hydration, honors preference changes, and retains the still image', + 'responsive hero motion preference and image recovery', { skip: chromePath ? false : 'Chrome is not installed', timeout: 60_000 }, - async () => { + async (t) => { const bundle = await build({ stdin: { contents: ` import React from 'react' import { hydrateRoot } from 'react-dom/client' - import { HeroPalmMedia } from ${JSON.stringify(componentPath)} - - function HydrationHarness() { - React.useEffect(() => { - document.documentElement.dataset.heroMediaHydrated = 'true' - }, []) + import { HeroPalmMedia } from './src/components/home/HeroPalmMedia' + function Harness() { + React.useEffect(() => { document.documentElement.dataset.hydrated = 'true' }, []) return React.createElement(HeroPalmMedia) } - - hydrateRoot( - document.getElementById('root'), - React.createElement(HydrationHarness), - ) + hydrateRoot(document.getElementById('root'), React.createElement(Harness)) `, resolveDir: repoRoot, - sourcefile: 'hero-media-browser-test.tsx', loader: 'tsx', }, alias: { '~': path.join(repoRoot, 'src') }, @@ -73,345 +98,77 @@ test( platform: 'browser', write: false, }) - const browser = await chromium.launch({ - executablePath: chromePath, - headless: true, - }) - - const makePage = async ( - reducedMotion: 'reduce' | 'no-preference', - videoResponse: 'hold' | 'fail' = 'hold', - hydrateImmediately = true, - ) => { - const page = await browser.newPage() - let shouldFailVideo = videoResponse === 'fail' - let videoRequests = 0 - let jpegRequests = 0 - const pageErrors: string[] = [] - const consoleErrors: string[] = [] - let resolveVideoRequest = () => {} - const videoRequest = new Promise((resolve) => { - resolveVideoRequest = resolve - }) - let releaseVideoResponse = () => {} - const videoResponseGate = new Promise((resolve) => { - releaseVideoResponse = resolve - }) - - await page.emulateMedia({ reducedMotion }) - page.on('pageerror', (error) => pageErrors.push(error.message)) - page.on('console', (message) => { - if (message.type() === 'error') consoleErrors.push(message.text()) - }) - page.on('request', (request) => { - const pathname = new URL(request.url()).pathname - if (pathname.endsWith('/images/hero-palm-motion.mp4')) { - videoRequests += 1 - resolveVideoRequest() - } - if (pathname.endsWith('.jpg')) jpegRequests += 1 + const browser = await chromium.launch({ executablePath: chromePath }) + t.after(() => browser.close()) + + async function openHero( + width: number, + reduced = false, + failOnce = new Set(), + ) { + const page = await browser.newPage({ + viewport: { width, height: 844 }, + reducedMotion: reduced ? 'reduce' : 'no-preference', }) - await page.route('**/images/hero-palm-motion.mp4', async (route) => { - if (shouldFailVideo) { - await route.abort() - return + const requests: string[] = [] + await page.route('http://hero.test/**', (route) => { + const url = new URL(route.request().url()) + if (url.pathname === '/') { + return route.fulfill({ + contentType: 'text/html', + body: `
${serverMarkup}
`, + }) } - await videoResponseGate - await route.fulfill({ path: videoPath, contentType: 'video/mp4' }) - }) - await page.route('**/images/hero-palm-gradient*', async (route) => { - const filename = path.basename(new URL(route.request().url()).pathname) - await route.fulfill({ - path: path.join(repoRoot, 'public/images', filename), + requests.push(url.pathname) + if (failOnce.delete(url.pathname)) return route.abort() + return route.fulfill({ + path: path.join(repoRoot, 'public', url.pathname), }) }) - await page.setContent( - `
${serverMarkup}
`, - { waitUntil: 'domcontentloaded' }, - ) - const hydrate = () => - page.addScriptTag({ content: bundle.outputFiles[0].text }) - if (hydrateImmediately) await hydrate() - await page.locator('img').evaluate((image) => { - if (!(image instanceof HTMLImageElement)) { - throw new Error('Expected the hero still image') - } - return image.decode() - }) - - return { - page, - get videoRequests() { - return videoRequests - }, - get jpegRequests() { - return jpegRequests - }, - pageErrors, - consoleErrors, - hydrate, - videoRequest, - releaseVideoResponse, - allowVideoRetry: () => { - shouldFailVideo = false - releaseVideoResponse() - }, + await page.goto('http://hero.test/') + const hydrate = async () => { + await page.addScriptTag({ content: bundle.outputFiles[0].text }) + await page.waitForFunction( + () => document.documentElement.dataset.hydrated === 'true', + ) } - } - - try { - const reduced = await makePage('reduce', 'hold', false) - const reducedVideo = reduced.page.locator('video') - assert.equal(reduced.videoRequests, 0) - assert.equal(reduced.jpegRequests, 0) - assert.equal(await reducedVideo.getAttribute('src'), null) - - await reduced.hydrate() - await reduced.page.waitForFunction( - () => document.documentElement.dataset.heroMediaHydrated === 'true', - ) - assert.deepEqual( - { - poster: await reducedVideo.getAttribute('poster'), - source: await reducedVideo.getAttribute('src'), - sourceElements: await reducedVideo.locator('source').count(), - media: await reducedVideo.locator('source').getAttribute('media'), - requests: reduced.videoRequests, - jpegRequests: reduced.jpegRequests, - }, - { - poster: null, - source: null, - sourceElements: 1, - media: '(prefers-reduced-motion: no-preference)', - requests: 0, - jpegRequests: 0, - }, - ) - - await reduced.page.emulateMedia({ reducedMotion: 'no-preference' }) - assert.equal(await reducedVideo.getAttribute('src'), null) - assert.equal(reduced.videoRequests, 0) - - await reduced.page - .getByRole('button', { name: 'Play hero animation' }) - .click() - await reduced.videoRequest - assert.equal(reduced.videoRequests, 1) - assert.equal( - await reduced.page - .locator('img') - .evaluate((image) => getComputedStyle(image).opacity), - '1', - ) - assert.equal( - await reduced.page.locator('img').evaluate((image) => { - if (!(image instanceof HTMLImageElement)) { - throw new Error('Expected the hero still image') - } - return image.complete - }), - true, - ) - reduced.releaseVideoResponse() - await reduced.page.waitForFunction(() => - document.querySelector('img')?.classList.contains('opacity-0'), - ) - await reduced.page.waitForFunction( - () => document.querySelector('video')?.paused === false, - ) - await reduced.page.close() - - const normal = await makePage('no-preference', 'hold', false) - const normalVideo = normal.page.locator('video') - assert.equal( - await normal.page.evaluate( - () => window.matchMedia('(prefers-reduced-motion: reduce)').matches, - ), - false, - ) - assert.equal( - await normalVideo.locator('source').getAttribute('src'), - '/images/hero-palm-motion.mp4', - ) - await normal.videoRequest - assert.equal( - await normal.page.evaluate( - () => document.documentElement.dataset.heroMediaHydrated, - ), - undefined, - ) - assert.equal(normal.videoRequests, 1) - assert.equal(normal.jpegRequests, 0) - assert.equal( - await normal.page - .locator('img') - .evaluate((image) => getComputedStyle(image).opacity), - '1', - ) - normal.releaseVideoResponse() - await normal.page.waitForFunction(() => { - const video = document.querySelector('video') - return video !== null && video.readyState >= 3 - }) - const aspectRatios = await normal.page.evaluate(() => { - const image = document.querySelector('img') - const video = document.querySelector('video') - if (!image || !video) throw new Error('Expected hero image and video') - return { - image: image.naturalWidth / image.naturalHeight, - video: video.videoWidth / video.videoHeight, - } - }) - assert.ok(Math.abs(aspectRatios.image - aspectRatios.video) < 0.005) - await normal.hydrate() - await normal.page.waitForFunction( - () => document.querySelector('video')?.paused === false, - ) - await normal.page - .getByRole('button', { name: 'Pause hero animation' }) - .waitFor() - assert.equal(await normalVideo.getAttribute('poster'), null) - assert.equal( - await normal.page - .locator('img') - .evaluate((image) => getComputedStyle(image).opacity), - '0', - ) - - // Chrome can pause hidden autoplay media before dispatching the preference - // change. Wait for that event so consecutive changes are not coalesced. - await normal.page.evaluate(() => { - window - .matchMedia('(prefers-reduced-motion: reduce)') - .addEventListener('change', (event) => { - document.documentElement.dataset.reducedMotion = String( - event.matches, - ) - }) - }) - await normal.page.emulateMedia({ reducedMotion: 'reduce' }) - await normal.page.waitForFunction( - () => document.documentElement.dataset.reducedMotion === 'true', - ) - await normal.page.waitForFunction( - () => document.querySelector('video')?.paused === true, - ) - await normal.page.emulateMedia({ reducedMotion: 'no-preference' }) - await normal.page.waitForFunction( - () => document.documentElement.dataset.reducedMotion === 'false', - ) - assert.equal( - await normalVideo.evaluate((video) => { - if (!(video instanceof HTMLVideoElement)) { - throw new Error('Expected the hero video') - } - return video.paused - }), - true, - ) - assert.equal(normal.videoRequests, 1) - - await normal.page - .getByRole('button', { name: 'Play hero animation' }) - .press('Enter') - await normal.page.waitForFunction( - () => document.querySelector('video')?.paused === false, - ) - await normal.page - .getByRole('button', { name: 'Pause hero animation' }) - .press('Enter') - await normal.page.waitForFunction( - () => document.querySelector('video')?.paused === true, - ) - assert.equal(normal.videoRequests, 1) - await normalVideo.evaluate((video) => { - if (!(video instanceof HTMLVideoElement)) { - throw new Error('Expected the hero video') - } - const play = video.play.bind(video) - video.play = () => { - video.play = play - return Promise.reject( - new DOMException('Playback blocked', 'NotAllowedError'), + const waitForImage = (source: string) => + page.waitForFunction((part) => { + const img = document.querySelector('picture img') + return ( + img instanceof HTMLImageElement && + img.complete && + img.naturalWidth > 0 && + img.currentSrc.includes(part) ) - } - }) - await normal.page - .getByRole('button', { name: 'Play hero animation' }) - .press('Enter') - await normal.page.waitForFunction( - () => !document.querySelector('img')?.classList.contains('opacity-0'), - ) - assert.deepEqual(normal.pageErrors, []) - assert.ok( - normal.consoleErrors.some((message) => - message.includes('Unable to play the homepage hero animation'), - ), - ) - await normal.page - .getByRole('button', { name: 'Play hero animation' }) - .press('Enter') - await normal.page.waitForFunction(() => { - const video = document.querySelector('video') - return ( - video?.paused === false && - document.querySelector('img')?.classList.contains('opacity-0') - ) - }) - await normal.page.close() + }, source) + return { page, requests, hydrate, waitForImage } + } - const failed = await makePage('no-preference', 'fail') - await failed.videoRequest - await failed.page.waitForFunction( - () => - document.querySelector('video')?.networkState === - HTMLMediaElement.NETWORK_NO_SOURCE, - ) - await failed.page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => resolve()), - ), - ) - assert.equal( - await failed.page - .locator('img') - .evaluate((image) => getComputedStyle(image).opacity), - '1', - ) - assert.equal( - await failed.page.locator('img').evaluate((image) => { - if (!(image instanceof HTMLImageElement)) { - throw new Error('Expected the hero still image') - } - return image.complete - }), - true, - ) - assert.equal(failed.videoRequests, 1) - assert.deepEqual(failed.pageErrors, []) - failed.allowVideoRetry() - await failed.page - .getByRole('button', { name: 'Play hero animation' }) - .click() - await failed.page.waitForFunction(() => { - const video = document.querySelector('video') - return ( - video?.paused === false && - document.querySelector('img')?.classList.contains('opacity-0') - ) - }) - assert.equal(failed.videoRequests, 2) - await failed.page.close() - } finally { - await browser.close() + for (const width of [390, 844, 1024, 1512]) { + const hero = await openHero(width) + await hero.waitForImage(motion) + assert.deepEqual([...hero.requests].sort(), [still, motion].sort()) + assert.equal(await hero.page.locator('picture img').isVisible(), true) + await hero.hydrate() + assert.deepEqual([...hero.requests].sort(), [still, motion].sort()) + await hero.page.close() } + + const reduced = await openHero(390, true) + await reduced.waitForImage(still) + await reduced.hydrate() + assert.deepEqual(reduced.requests, [still]) + await reduced.page.emulateMedia({ reducedMotion: 'no-preference' }) + await reduced.waitForImage(motion) + await reduced.page.emulateMedia({ reducedMotion: 'reduce' }) + await reduced.waitForImage(still) + await reduced.page.close() + + const failed = await openHero(1512, false, new Set([motion])) + await failed.hydrate() + await failed.waitForImage(still) + assert.ok(failed.requests.includes(motion)) + await failed.page.close() }, )