Skip to content

A Claude Code skill that reverse-engineers any animation frame by frame, then proves the copy moves the same.

Add the Vercel, Next.js and Turborepo examples

NiazMorshed2007322626e278af
diff --git a/README.md b/README.md
index 4ea266e..77e073a 100644
--- a/README.md
+++ b/README.md
@@ -63,10 +63,16 @@ By default it matches the motion and leaves the look to you. Ask for more or les
## Examples
-Three cards from the stripe.com homepage, the integrations visual from workos.com/atlas, the feature cards from clerk.com, the demo under the liveblocks.io/comments hero, the cube in the resend.com hero and React Bits Pro's Fading Stars, each cloned by its own agent running this skill, most in 30 to 80 minutes. The [site](site/) shows each one next to a recording of the original, except the Clerk cards, which run live in the page.
+Six animations from vercel.com, nextjs.org and turborepo.com, three cards from the stripe.com homepage, the integrations visual from workos.com/atlas, the feature cards from clerk.com, the demo under the liveblocks.io/comments hero, the cube in the resend.com hero and React Bits Pro's Fading Stars, each cloned by its own agent running this skill, most in 30 to 90 minutes. The [site](site/) runs the ones you can hover or drag live in the page, and shows the others next to a recording of the original.
| Clone | Built with | Measured against the original |
|---|---|---|
+| **Vercel Toolbar** (vercel.com/products/previews): a toolbar among seven tags; hover a button and its tag takes its colour while the others blur | HTML, SVG, CSS | 417 of 417 frames identical; every change on the same frame |
+| **Drop to deploy** (vercel.com): the hero triangle, lit by the pointer; drag a file over the page and it turns into a prism | WebGL2, Web Workers | 785 of 803 frames byte-identical, the rest within 1 level |
+| **Fluid ocean** (vercel.com/fluid): 262,144 dots rolling like a sea behind the hero | WebGPU, Web Workers | 0 px differ over 12 s, light and dark |
+| **Inspect every run** (vercel.com/workflow): a dashboard playing one run of a workflow | HTML, SVG | all six bars 0 px off; every step on time (0 ms) |
+| **Speedometer** (turborepo.com): a needle that revs into the red under the pointer, and a counter rolling up | SVG, springs | 0 px differ while hovering, light and dark |
+| **Feature cards** (nextjs.org): image frames lit by the pointer, streaks streaming into a page, a component tree | canvas, SVG | every animated value identical on every frame |
| **Agentic commerce**: a chat over a 10,000-point particle ring | three.js, CSS | chat timing within 43 ms, layout within 0.05 px |
| **Card issuing**: a Visa card that tilts toward the pointer | three.js, Web Workers | 0.03 % of pixels differ at rest; tilt within 0.4 px |
| **Stablecoins and crypto**: a dotted globe with flying payments | three.js, Web Workers | globe pose exact; arcs and labels within stripe.com's own spread |
@@ -114,4 +120,4 @@ Only `skills/reanimate/` is installed by the skills CLI; `site/` is the website
## License
-[MIT](LICENSE). The examples recreate parts of stripe.com, workos.com, clerk.com, liveblocks.io, resend.com and pro.reactbits.dev as a study of the technique; it is not affiliated with or endorsed by Stripe, WorkOS, Clerk, Liveblocks, Resend or React Bits. All trademarks belong to their owners.
+[MIT](LICENSE). The examples recreate parts of vercel.com, nextjs.org, turborepo.com, stripe.com, workos.com, clerk.com, liveblocks.io, resend.com and pro.reactbits.dev as a study of the technique; it is not affiliated with or endorsed by Vercel, Stripe, WorkOS, Clerk, Liveblocks, Resend or React Bits. All trademarks belong to their owners.
diff --git a/site/README.md b/site/README.md
index c5c55d0..10e5bf0 100644
--- a/site/README.md
+++ b/site/README.md
@@ -20,13 +20,14 @@ bun run lint
1. Put the clone, as a standalone page, in `public/examples/<name>/` (see `stripe-bento/`).
2. Put its media in `public/media/<slug>/`: `poster.webp` (the clone at rest, for the thumbnails) and, for a recorded example, `compare.mp4` (the original and the clone, recorded the same way and side by side in one file).
-3. Add an entry to `src/examples.ts`. The home page shows it at the end, under Examples; what it does and its numbers sit behind a "details" tooltip. `show.kind` picks the picture: `"video"` plays `compare.mp4`; `"live"` runs the clone itself in the page, in an iframe (the clerk.com cards do this; `clerk-bento/?card=<slug>&embed` frames one card for it).
+3. Add an entry to `src/examples.ts`. The home page shows it at the end, under Examples; what it does and its numbers sit behind a "details" tooltip. `show.kind` picks the picture: `"video"` plays `compare.mp4` (`stacked` when the two takes are one above the other); `"live"` runs the clone itself in the page, in an iframe, for the ones you can hover or drag (the clerk.com cards and most of the Vercel ones; `clerk-bento/?card=<slug>&embed` frames one card for it). A live one needs only `poster.webp`; `background` colours its frame and `try` says what to do with it.
-To record the media, add a row to `CLIPS` in `scripts/record-media.ts`: the original's URL, the clone's path and the elements to film, plus `pin` when the animation picks things at random, so both sides pick the same, and `sync` when each page runs a loop that starts on its own clock rather than on the scroll or hover, so the two takes are lined up by their frames. With the site running on `bun run preview`:
+To record the media, add a row to `CLIPS` in `scripts/record-media.ts`: the original's URL, the clone's path and the elements to film, plus `pin` when the animation picks things at random, so both sides pick the same, and `sync` when each page runs a loop that starts on its own clock rather than on the scroll or hover, so the two takes are lined up by their frames. A hover clip can take its own pointer `path` and length `ms`; `still` keeps a speck repainting while it films a page that rests between moves, so frames still come at 60 fps; `trigger: "drop"` drags a file over the element (vercel.com's hero). With the site running on `bun run preview`:
```sh
bun run media # every clip
bun run media --only <slug> # one clip
+bun run media --keep <dir> # also keep the takes, lined up, for video/ (masters.json)
```
It films the original and the clone in the same browser with the same scroll, pointer path and timing, at 2x and 60 fps, and writes `compare.mp4` and `poster.webp` into `public/media/<slug>/`. Both recordings go into one file so they can never drift apart on the page. It also writes the README animations in `../.github/assets/`. It needs Playwright's Chromium (`bunx playwright install chromium`), and `ffmpeg`, `cwebp` and `webpmux` on your PATH (`brew install ffmpeg webp`). The 2x zoom and GPU flags it uses are tested on macOS.
@@ -54,7 +55,7 @@ Then either:
| `src/app/page.tsx` | The whole page: copy, sections, tables. |
| `src/examples.ts` | The examples, in the order they appear. |
| `src/components/` | `CompareVideo` (plays a `compare.mp4` while it's on screen), `LiveCard` (a clone in an iframe, scaled down on narrow screens), `Nav`, `Sidenote`, `CopyCommand`. |
-| `public/examples/` | The clones as standalone pages. `stripe-bento/?card=agentic-commerce\|issuing\|crypto` shows one card; `workos-atlas/` is the workos.com integrations visual; `clerk-bento/` is clerk.com's grid of feature cards (`?card=<slug>` for one); `liveblocks-comments/` is the demo under the liveblocks.io/comments hero; `resend-cube/` is the resend.com hero cube; `reactbits-fading-stars/` is React Bits Pro's Fading Stars. |
+| `public/examples/` | The clones as standalone pages. `stripe-bento/?card=agentic-commerce\|issuing\|crypto` shows one card; `workos-atlas/` is the workos.com integrations visual; `clerk-bento/` is clerk.com's grid of feature cards (`?card=<slug>` for one); `liveblocks-comments/` is the demo under the liveblocks.io/comments hero; `resend-cube/` is the resend.com hero cube; `reactbits-fading-stars/` is React Bits Pro's Fading Stars. `vercel-previews/` is the toolbar on vercel.com/products/previews; `vercel-hero/` is the vercel.com hero triangle; `vercel-fluid/` is the vercel.com/fluid ocean; `vercel-workflow/` is the dashboard on vercel.com/workflow; `turborepo-gauge/` is the turborepo.com speedometer; `nextjs-features/` is nextjs.org's three illustrated cards (`?card=optimizations\|streaming\|rsc`). The live ones take `?embed`. |
| `public/media/` | Comparisons and posters, one folder per example. `stripe-bento/` is the entrance at the top of the page. |
| `scripts/record-media.ts` | Records the examples' media and the README animations. |
| `marketing/launch.md` | Launch post drafts. |
@@ -62,4 +63,4 @@ Then either:
## About the examples
-The live examples recreate parts of stripe.com, workos.com and clerk.com as a study of the technique. The Stripe cards use Inter instead of Stripe's licensed Söhne, but port Stripe's shaders and use Stripe's images; the WorkOS visual uses WorkOS's robot images, app icons and screen shaders; the Clerk cards use Geist and Geist Mono instead of Clerk's licensed fonts, and port Clerk's inline SVG, light-streak canvas and dot-field shader. The Liveblocks demo uses Inter instead of the licensed Suisse Int'l, and reuses liveblocks.io's avatars, drawings and icons. The Resend cube draws resend.com's own Spline scene (geometry, textures and shaders) with three.js, over resend.com's hero images. Fading Stars ports the shaders and simulation that pro.reactbits.dev runs for its live preview. Not affiliated with or endorsed by Stripe, WorkOS, Clerk, Liveblocks, Resend or React Bits.
+The live examples recreate parts of vercel.com, nextjs.org, turborepo.com, stripe.com, workos.com, clerk.com, liveblocks.io, resend.com and pro.reactbits.dev as a study of the technique. The Stripe cards use Inter instead of Stripe's licensed Söhne, but port Stripe's shaders and use Stripe's images; the WorkOS visual uses WorkOS's robot images, app icons and screen shaders; the Clerk cards use Geist and Geist Mono instead of Clerk's licensed fonts, and port Clerk's inline SVG, light-streak canvas and dot-field shader. The Liveblocks demo uses Inter instead of the licensed Suisse Int'l, and reuses liveblocks.io's avatars, drawings and icons. The Resend cube draws resend.com's own Spline scene (geometry, textures and shaders) with three.js, over resend.com's hero images. Fading Stars ports the shaders and simulation that pro.reactbits.dev runs for its live preview. The Vercel, Next.js and Turborepo copies use the Geist builds those sites serve (OFL). The vercel.com hero and Fluid ocean port vercel.com's own renderers, its 13 GLSL shaders and 10 WGSL modules unchanged; the toolbar, workflow dashboard and Turborepo gauge reuse their sites' inline SVG and run their animation code ported from the page, the toolbar with vercel.com's avatar images; the Next.js cards port nextjs.org's canvas and SVG drawing code with its dot data. Not affiliated with or endorsed by Vercel, Stripe, WorkOS, Clerk, Liveblocks, Resend or React Bits.
diff --git a/site/public/examples/nextjs-features/assets/fonts/Geist-Variable.woff2 b/site/public/examples/nextjs-features/assets/fonts/Geist-Variable.woff2
new file mode 100644
index 0000000..1864b37
Binary files /dev/null and b/site/public/examples/nextjs-features/assets/fonts/Geist-Variable.woff2 differ
diff --git a/site/public/examples/nextjs-features/assets/fonts/GeistMono-Variable-latin.woff2 b/site/public/examples/nextjs-features/assets/fonts/GeistMono-Variable-latin.woff2
new file mode 100644
index 0000000..cf24126
Binary files /dev/null and b/site/public/examples/nextjs-features/assets/fonts/GeistMono-Variable-latin.woff2 differ
diff --git a/site/public/examples/nextjs-features/assets/fonts/LICENSE-geist.txt b/site/public/examples/nextjs-features/assets/fonts/LICENSE-geist.txt
new file mode 100644
index 0000000..8d003fe
--- /dev/null
+++ b/site/public/examples/nextjs-features/assets/fonts/LICENSE-geist.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2023 Vercel, in collaboration with basement.studio
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/public/examples/nextjs-features/index.html b/site/public/examples/nextjs-features/index.html
new file mode 100644
index 0000000..291171a
--- /dev/null
+++ b/site/public/examples/nextjs-features/index.html
@@ -0,0 +1,157 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>nextjs.org feature cards, rebuilt with reanimate</title>
+ <meta name="robots" content="noindex">
+ <!--
+ The three illustrated cards at the top of nextjs.org's "Everything you need to build great products on the
+ web" grid. Built-in Optimizations: image frames drawn on a canvas whose dots light up in bands of blue round
+ the pointer. Dynamic HTML Streaming: once the card is well in view, four streaks of blue run along the grid
+ into a wireframe page, each on its own loop (2 s each while hovered), the image placeholder turns into an
+ avatar every 5 s and the content blocks change layout every 8 s. React Server Components: dashes flow down
+ the tree and blue arcs glide round three nodes, faster while hovered, paused off screen. The SVG markup is
+ nextjs.org's; src/ ports its drawing code, its frame loop ("phase") and the part of Motion it uses. Plain
+ HTML + ES modules, no dependencies.
+ -->
+ <link rel="preload" href="./assets/fonts/Geist-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="preload" href="./assets/fonts/GeistMono-Variable-latin.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="stylesheet" href="./src/features.css">
+ <script>
+ // ?card=<slug> shows a single card (optimizations, streaming, rsc); with &embed, closely framed for an iframe
+ const params = new URLSearchParams(location.search);
+ const card = params.get("card");
+ if (card) document.documentElement.dataset.card = card;
+ if (card && params.has("embed")) document.documentElement.dataset.embed = "";
+ // without &embed on a screen narrower than the card (a phone), the card is scaled down to fit
+ if (card && !params.has("embed")) {
+ const root = document.documentElement;
+ const fit = () => {
+ const z = Math.min(1, (innerWidth - 32) / 448);
+ root.style.setProperty("--fit", z);
+ root.toggleAttribute("data-fit", z < 1);
+ };
+ fit();
+ addEventListener("resize", fit);
+ }
+ </script>
+ <script type="module" src="./src/features.js"></script>
+</head>
+<body>
+ <main class="nf-page">
+ <ul class="nf-grid grid grid-cols-12 gap-x-6 gap-y-12 @md:gap-y-24 list-none">
+<li class="nf-card col-span-full flex flex-col gap-8 @lg:col-span-4" data-card="optimizations"><a class="nf-link group flex flex-col gap-6" href="https://nextjs.org/docs/app/getting-started/images"><div aria-hidden="true" class="nf-box aspect-5/4 overflow-hidden rounded-xs border border-solid border-gray-300"><div class="nf-center grid size-full place-items-center p-4"><div class="nf-canvas-wrap aspect-[322/246] w-full max-w-[320px]"><canvas aria-hidden="true" class="block size-full" height="246" width="322"></canvas></div></div></div><div class="nf-text flex flex-col gap-3" data-agent-content="feature"><span class="nf-title flex items-center gap-3 text-pretty text-copy-16 text-gray-900" data-agent-description=""><strong class="font-medium text-gray-1000">Built-in Optimizations</strong><span aria-hidden="true" class="nf-arrow inline-block -translate-x-1 font-medium text-gray-1000 transition-transform group-hover:translate-x-0">→</span></span><span class="nf-desc max-w-94 text-pretty text-copy-16 text-gray-900 transition-colors group-hover:text-gray-1000" data-agent-description="">Automatic Image, Font, and Script Optimizations for improved UX and Core Web Vitals.</span></div></a></li>
+<li class="nf-card col-span-full flex flex-col gap-8 @lg:col-span-4" data-card="streaming"><a class="nf-link group flex flex-col gap-6" href="https://nextjs.org/docs/app/getting-started/fetching-data#streaming"><div aria-hidden="true" class="nf-box aspect-5/4 overflow-hidden rounded-xs border border-solid border-gray-300"><div class="nf-stream relative size-full"><svg class="absolute top-1/2 w-full -translate-y-1/2" fill="none" viewBox="0 0 424 362">
+<path d="M31 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M63.9092 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M96.8184 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M129.728 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M162.637 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M195.546 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M228.454 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M261.363 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M294.272 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M327.182 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M360.091 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M393 10.5V351.5" stroke="var(--color-gray-200)"></path>
+<path d="M424 0.5L3.8912e-05 0.499981" stroke="var(--color-gray-200)"></path>
+<path d="M424 33.3181L3.8912e-05 33.3181" stroke="var(--color-gray-200)"></path>
+<path d="M424 66.1365L3.8912e-05 66.1365" stroke="var(--color-gray-200)"></path>
+<path d="M424 98.9546L3.8912e-05 98.9546" stroke="var(--color-gray-200)"></path>
+<path d="M424 131.773L3.8912e-05 131.773" stroke="var(--color-gray-200)"></path>
+<path d="M424 164.591L3.8912e-05 164.591" stroke="var(--color-gray-200)"></path>
+<path d="M424 197.409L3.8912e-05 197.409" stroke="var(--color-gray-200)"></path>
+<path d="M424 230.227L3.8912e-05 230.227" stroke="var(--color-gray-200)"></path>
+<path d="M424 263.045L3.8912e-05 263.045" stroke="var(--color-gray-200)"></path>
+<path d="M424 295.864L3.8912e-05 295.864" stroke="var(--color-gray-200)"></path>
+<path d="M424 328.682L3.8912e-05 328.682" stroke="var(--color-gray-200)"></path>
+<path d="M424 361.5L3.8912e-05 361.5" stroke="var(--color-gray-200)"></path>
+<g clip-path="url(#clip0_streaming)">
+<rect x="64" y="65.5" width="296" height="231" rx="12" fill="var(--color-background-200)"></rect>
+<circle cx="78.0256" cy="79.3" r="2.8" fill="var(--color-gray-500)"></circle>
+<circle cx="86.426" cy="79.3001" r="2.8" fill="var(--color-gray-500)"></circle>
+<circle cx="94.8254" cy="79.3001" r="2.8" fill="var(--color-gray-500)"></circle>
+<path d="M135.916 122.284C135.916 121.18 136.811 120.284 137.916 120.284H163.158C164.263 120.284 165.158 121.18 165.158 122.284V122.653C165.158 123.758 164.263 124.653 163.158 124.653H137.916C136.811 124.653 135.916 123.758 135.916 122.653V122.284Z" fill="var(--color-gray-200)"></path>
+<rect x="135.916" y="108.15" width="29.2423" height="8.29858" rx="4.14929" fill="var(--color-gray-200)"></rect>
+<path d="M177.106 122.284C177.106 121.18 178.002 120.284 179.106 120.284H340.877C341.982 120.284 342.877 121.18 342.877 122.284V122.653C342.877 123.758 341.982 124.653 340.877 124.653H179.106C178.002 124.653 177.106 123.758 177.106 122.653V122.284Z" fill="var(--color-gray-200)"></path>
+<path d="M62.501 90.3481L360 90.3482" stroke="var(--color-gray-200)"></path>
+<g>
+<rect fill="var(--color-gray-200)" height="41.8457" rx="2" width="41.8457" x="75.0781" y="108.15"></rect>
+<path d="M96.0015 122.556L103.019 134.71H88.984Z" fill="var(--color-gray-700)"></path>
+<rect fill="var(--color-gray-200)" height="4.3689" rx="2" width="41.8457" x="75.0781" style="transform:translateY(158.476px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" height="4.3689" rx="2" width="27.3217" x="75.0781" style="transform:translateY(164.497px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" height="4.3689" rx="2" width="41.8457" x="75.0781" style="transform:translateY(170.517px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" height="4.3689" rx="2" width="41.8457" x="75.0781" style="transform:translateY(176.538px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" height="4.3689" rx="2" width="29.4039" x="75.0781" style="transform:translateY(182.559px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" rx="2" width="99.4837" x="135.916" height="50.7081" style="transform:translateY(130.489px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" rx="2" width="99.4837" x="242.399" height="50.7081" style="transform:translateY(130.489px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" rx="2" width="99.4837" x="135.916" height="50.7081" style="transform:translateY(188.198px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" rx="2" width="99.4837" x="242.399" height="108.416" style="transform:translateY(188.198px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+<rect fill="var(--color-gray-200)" rx="2" width="99.4837" x="135.916" height="50.7081" style="transform:translateY(245.906px);transform-origin:50% 50%;transform-box:fill-box"></rect>
+</g>
+</g>
+<rect x="64" y="65.5" width="296" height="231" rx="12" stroke="var(--color-gray-500)"></rect>
+<path d="M0 33.5H30C30.5523 33.5 31 33.9477 31 34.5V98C31 98.5523 31.4477 99 32 99H63C63.5523 99 64 98.5523 64 98V78C64 70.8203 69.8203 65 77 65H310" stroke="url(#nf-stream-0)" stroke-linecap="round" stroke-width="2" style="mask-image: linear-gradient(to right, white 50%, transparent);"></path>
+<path d="M393 0.5V131C393 131.552 392.552 132 392 132H361C360.448 132 360 132.448 360 133V284C360 291.18 354.18 297 347 297H254.5" stroke="url(#nf-stream-1)" stroke-linecap="round" stroke-width="2" style="mask-image: linear-gradient(to left, white 50%, transparent);"></path>
+<path d="M0 328.5H30C30.5523 328.5 31 328.052 31 327.5V264C31 263.448 31.4499 263 32.0022 263C43.9398 263 51.0602 263 62.9978 263C63.5501 263 64 263.448 64 264V284C64 291.18 69.8203 297 77 297H262" stroke="url(#nf-stream-2)" stroke-linecap="round" stroke-width="2" style="mask-image: linear-gradient(to right, white 60%, transparent);"></path>
+<path d="M424 197.5L394 197.5C393.448 197.5 393 197.948 393 198.5L393 229.5C393 230.052 392.552 230.5 392 230.5L361 230.5C360.448 230.5 360 230.948 360 231.5L360 284C360 291.18 354.18 297 347 297L172.5 297" stroke="url(#nf-stream-3)" stroke-linecap="round" stroke-width="2" style="mask-image: linear-gradient(to left, white 60%, transparent);"></path>
+<defs>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-stream-0" x1="0" x2="-52" y1="33" y2="-18">
+<stop stop-color="var(--color-blue-700)" stop-opacity="0"></stop>
+<stop stop-color="var(--color-blue-700)"></stop>
+<stop offset="1" stop-color="var(--color-blue-600)" stop-opacity="0"></stop>
+</linearGradient>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-stream-1" x1="254.5" x2="254.5" y1="0" y2="-57">
+<stop stop-color="var(--color-blue-700)" stop-opacity="0"></stop>
+<stop stop-color="var(--color-blue-700)"></stop>
+<stop offset="1" stop-color="var(--color-blue-600)" stop-opacity="0"></stop>
+</linearGradient>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-stream-2" x1="-40" x2="-140" y1="360" y2="480">
+<stop stop-color="var(--color-blue-700)" stop-opacity="0"></stop>
+<stop stop-color="var(--color-blue-700)"></stop>
+<stop offset="1" stop-color="var(--color-blue-600)" stop-opacity="0"></stop>
+</linearGradient>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-stream-3" x1="423" x2="467" y1="197.5" y2="197.5">
+<stop stop-color="var(--color-blue-700)" stop-opacity="0"></stop>
+<stop stop-color="var(--color-blue-700)"></stop>
+<stop offset="1" stop-color="var(--color-blue-600)" stop-opacity="0"></stop>
+</linearGradient>
+<clipPath id="clip0_streaming">
+<rect x="64" y="65.5" width="296" height="231" rx="12" fill="var(--color-background-100)"></rect>
+</clipPath>
+</defs>
+</svg></div></div><div class="nf-text flex flex-col gap-3" data-agent-content="feature"><span class="nf-title flex items-center gap-3 text-pretty text-copy-16 text-gray-900" data-agent-description=""><strong class="font-medium text-gray-1000">Dynamic HTML Streaming</strong><span aria-hidden="true" class="nf-arrow inline-block -translate-x-1 font-medium text-gray-1000 transition-transform group-hover:translate-x-0">→</span></span><span class="nf-desc max-w-94 text-pretty text-copy-16 text-gray-900 transition-colors group-hover:text-gray-1000" data-agent-description="">Instantly stream UI from the server, integrated with the App Router and React Suspense.</span></div></a></li>
+<li class="nf-card col-span-full flex flex-col gap-8 @lg:col-span-4" data-card="rsc"><a class="nf-link group flex flex-col gap-6" href="https://nextjs.org/docs/app/getting-started/server-and-client-components"><div aria-hidden="true" class="nf-box aspect-5/4 overflow-hidden rounded-xs border border-solid border-gray-300"><div class="nf-center grid size-full place-items-center p-4"><svg class="nf-rsc-svg w-full max-w-67" fill="none" viewBox="0 0 269 222" xmlns="http://www.w3.org/2000/svg">
+<path d="M134.054 29.7175L222.847 167.84" stroke="var(--color-gray-700)" stroke-dasharray="4 3"></path>
+<path d="M90.3994 98.6835L38.7445 179.036" stroke="var(--color-gray-700)" stroke-dasharray="4 3"></path>
+<path d="M134.734 29.7175L84.0173 108.611" stroke="var(--color-blue-900)" stroke-dasharray="4 3"></path>
+<path d="M80.5459 110.517L134.054 193.752" stroke="var(--color-blue-900)" stroke-dasharray="4 3"></path>
+<circle cx="134.239" cy="28.8441" fill="var(--color-gray-100)" r="28.3441" stroke="var(--color-gray-500)" transform="rotate(-90 134.239 28.8441)"></circle>
+<circle cx="186.736" cy="106.809" fill="var(--color-gray-100)" r="28.3441" stroke="var(--color-gray-500)"></circle>
+<circle cx="239.257" cy="192.189" fill="var(--color-gray-100)" r="28.3441" stroke="var(--color-gray-500)"></circle>
+<circle cx="81.7415" cy="106.809" fill="var(--color-gray-100)" r="28.3441" stroke="var(--color-gray-500)"></circle>
+<circle cx="28.8441" cy="192.189" fill="var(--color-gray-100)" r="28.3441" stroke="var(--color-gray-500)"></circle>
+<circle cx="133.864" cy="192.189" fill="var(--color-gray-100)" r="28.3441" stroke="var(--color-gray-500)"></circle>
+<circle cx="134.239" cy="28.8441" fill="none" r="27.8441" stroke="url(#nf-rsc-0)" stroke-width="1.75" style="opacity: 0.55;"></circle>
+<circle cx="81.7415" cy="106.809" fill="none" r="27.8441" stroke="url(#nf-rsc-1)" stroke-width="1.75" style="opacity: 0.55;"></circle>
+<circle cx="133.864" cy="192.189" fill="none" r="27.8441" stroke="url(#nf-rsc-2)" stroke-width="1.75" style="opacity: 0.55;"></circle>
+<defs>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-rsc-0">
+<stop stop-color="var(--color-blue-500)" stop-opacity="0"></stop>
+<stop offset="1" stop-color="var(--color-blue-900)"></stop>
+</linearGradient>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-rsc-1">
+<stop stop-color="var(--color-blue-500)" stop-opacity="0"></stop>
+<stop offset="1" stop-color="var(--color-blue-900)"></stop>
+</linearGradient>
+<linearGradient gradientUnits="userSpaceOnUse" id="nf-rsc-2">
+<stop stop-color="var(--color-blue-500)" stop-opacity="0"></stop>
+<stop offset="1" stop-color="var(--color-blue-900)"></stop>
+</linearGradient>
+</defs>
+</svg></div></div><div class="nf-text flex flex-col gap-3" data-agent-content="feature"><span class="nf-title flex items-center gap-3 text-pretty text-copy-16 text-gray-900" data-agent-description=""><strong class="font-medium text-gray-1000">React Server Components</strong><span aria-hidden="true" class="nf-arrow inline-block -translate-x-1 font-medium text-gray-1000 transition-transform group-hover:translate-x-0">→</span></span><span class="nf-desc max-w-94 text-pretty text-copy-16 text-gray-900 transition-colors group-hover:text-gray-1000" data-agent-description="">Add components without sending additional client-side JavaScript. Built on the latest React features.</span></div></a></li>
+ </ul>
+ </main>
+</body>
+</html>
diff --git a/site/public/examples/nextjs-features/src/features.css b/site/public/examples/nextjs-features/src/features.css
new file mode 100644
index 0000000..6ea3140
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/features.css
@@ -0,0 +1,115 @@
+/* nextjs.org "Everything you need to build great products on the web": the three illustrated cards of the
+ feature grid, at the reference viewport (1440x900, the @lg breakpoint). Values are nextjs.org's resolved
+ Tailwind tokens (light theme). The markup keeps nextjs.org's class names next to the nf-* ones used here,
+ so selectors written for nextjs.org find the same elements. */
+
+/* Geist and Geist Mono (SIL OFL 1.1, assets/fonts/LICENSE-geist.txt), the very files nextjs.org serves:
+ its Geist build is about 1 % narrower than Geist 1.3.1, which would move every line of text. */
+@font-face {
+ font-family: GeistSans;
+ src: url(../assets/fonts/Geist-Variable.woff2) format("woff2");
+ font-weight: 100 900;
+ font-display: swap;
+}
+@font-face {
+ font-family: "Geist Mono";
+ src: url(../assets/fonts/GeistMono-Variable-latin.woff2) format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+ unicode-range: U+0-FF, U+131, U+152-153, U+2BB-2BC, U+2C6, U+2DA, U+2DC, U+304, U+308, U+329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+
+:root {
+ --font-sans: GeistSans, ui-sans-serif, system-ui, sans-serif;
+ --font-mono: 'Geist Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Liberation Mono, DejaVu Sans Mono, Courier New, monospace, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
+ /* nextjs.org light theme */
+ --color-gray-100: hsla(0, 0%, 95%, 1);
+ --color-gray-200: hsla(0, 0%, 92%, 1);
+ --color-gray-300: hsla(0, 0%, 90%, 1);
+ --color-gray-400: hsla(0, 0%, 92%, 1);
+ --color-gray-500: hsla(0, 0%, 79%, 1);
+ --color-gray-700: hsla(0, 0%, 56%, 1);
+ --color-gray-900: hsla(0, 0%, 30%, 1);
+ --color-gray-1000: hsla(0, 0%, 9%, 1);
+ --color-blue-300: hsla(210, 100%, 94%, 1);
+ --color-blue-400: hsla(209, 100%, 90%, 1);
+ --color-blue-500: hsla(209, 100%, 80%, 1);
+ --color-blue-600: hsla(208, 100%, 66%, 1);
+ --color-blue-700: hsla(212, 100%, 48%, 1);
+ --color-blue-900: hsla(211, 100%, 42%, 1);
+ --color-blue-1000: hsla(211, 100%, 15%, 1);
+ --color-background-100: hsla(0, 0%, 100%, 1);
+ --color-background-200: hsla(0, 0%, 98%, 1);
+}
+
+*, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid var(--color-gray-200); }
+html {
+ line-height: 1.5;
+ -webkit-text-size-adjust: 100%;
+ font-family: var(--font-sans);
+ background: var(--color-background-200);
+ color: var(--color-gray-1000);
+}
+body {
+ min-height: 100vh;
+ font-size: 16px;
+ line-height: 26.4px;
+ font-feature-settings: "calt" 0, "rlig", "ss11";
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ background: var(--color-background-200);
+}
+a { color: inherit; text-decoration: inherit; }
+ul { list-style: none; }
+svg, canvas { display: block; vertical-align: middle; }
+strong { font-weight: inherit; }
+
+/* page: the grid's top row, where nextjs.org puts it horizontally (24px from the sides of a 1440px column) */
+.nf-page { max-width: 1440px; margin: 0 auto; padding: 96px 24px; }
+.nf-grid { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); column-gap: 24px; row-gap: 48px; }
+.nf-card { grid-column: span 4 / span 4; display: flex; flex-direction: column; gap: 32px; }
+.nf-link { display: flex; flex-direction: column; gap: 24px; }
+
+/* the illustration box: aspect 5/4, 1px gray-300 border, 2px radius */
+.nf-box { aspect-ratio: 5 / 4; overflow: hidden; border: 1px solid var(--color-gray-300); border-radius: 2px; }
+.nf-center { display: grid; width: 100%; height: 100%; place-items: center; padding: 16px; }
+.nf-canvas-wrap { aspect-ratio: 322 / 246; width: 100%; max-width: 320px; }
+.nf-canvas-wrap canvas { width: 100%; height: 100%; }
+.nf-stream { position: relative; width: 100%; height: 100%; }
+.nf-stream > svg { position: absolute; top: 50%; width: 100%; translate: 0 -50%; }
+.nf-rsc-svg { width: 100%; max-width: 268px; }
+
+/* title, arrow and description */
+.nf-text { display: flex; flex-direction: column; gap: 12px; }
+.nf-title { display: flex; align-items: center; gap: 12px; text-wrap: pretty; font-size: 16px; line-height: 24px; color: var(--color-gray-900); }
+.nf-title strong { font-weight: 550; color: var(--color-gray-1000); }
+.nf-arrow {
+ display: inline-block; font-weight: 500; color: var(--color-gray-1000); translate: -4px 0;
+ transition-property: transform, translate, scale, rotate;
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-duration: 150ms;
+}
+.nf-desc {
+ max-width: 376px; text-wrap: pretty; font-size: 16px; line-height: 24px; color: var(--color-gray-900);
+ transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke;
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-duration: 150ms;
+}
+@media (hover: hover) {
+ .nf-link:hover .nf-arrow { translate: 0 0; }
+ .nf-link:hover .nf-desc { color: var(--color-gray-1000); }
+}
+
+/* ?card=<slug>: one card on its own */
+html[data-card] .nf-card { display: none; }
+html[data-card="optimizations"] .nf-card[data-card="optimizations"],
+html[data-card="streaming"] .nf-card[data-card="streaming"],
+html[data-card="rsc"] .nf-card[data-card="rsc"] { display: flex; grid-column: 1 / -1; }
+html[data-card] .nf-grid { display: block; }
+html[data-card] .nf-page { width: calc(448px + 48px); max-width: none; padding: 48px 24px; }
+/* narrower than the card (a phone): scaled to fit, 16px from the sides (index.html sets --fit) */
+html[data-fit] .nf-page { zoom: var(--fit); }
+/* ?card=<slug>&embed: the card 24px from every edge, no scrolling (the reanimate site shows it in an iframe) */
+html[data-embed] { overflow: hidden; }
+html[data-embed] .nf-page { padding: 24px; }
diff --git a/site/public/examples/nextjs-features/src/features.js b/site/public/examples/nextjs-features/src/features.js
new file mode 100644
index 0000000..92094ec
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/features.js
@@ -0,0 +1,18 @@
+// Mounts the three illustrations. Like nextjs.org, where they start after hydration, they are set up once
+// the document has loaded, so a page that pushes them below the fold first sees them start on scroll.
+import { mountOptimizations } from "./optimizations.js";
+import { mountStreaming } from "./streaming.js";
+import { mountRsc } from "./rsc.js";
+
+function mount() {
+ const card = (slug) => document.querySelector(`.nf-card[data-card="${slug}"]`);
+ const opt = card("optimizations")?.querySelector(".nf-canvas-wrap");
+ const stream = card("streaming")?.querySelector(".nf-stream");
+ const rsc = card("rsc")?.querySelector(".nf-center");
+ if (opt) mountOptimizations(opt);
+ if (stream) mountStreaming(stream);
+ if (rsc) mountRsc(rsc);
+}
+
+if (document.readyState === "loading") addEventListener("DOMContentLoaded", mount, { once: true });
+else mount();
diff --git a/site/public/examples/nextjs-features/src/motion.js b/site/public/examples/nextjs-features/src/motion.js
new file mode 100644
index 0000000..ba9fc80
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/motion.js
@@ -0,0 +1,111 @@
+// The part of Motion (framer-motion) the streaming card uses, ported from the build nextjs.org ships:
+// keyframe tweens with per-segment easing, delay, repeat and repeatDelay, on one requestAnimationFrame batch.
+// As in Motion, an animation asked for between frames starts on the next frame (its start time is that
+// frame's timestamp), the time is rounded to whole milliseconds, the value holds the first keyframe during
+// the delay and the last keyframe during repeatDelay.
+
+// Motion's cubic bezier: x solved by bisection, 12 steps at most, to 1e-7
+const bez = (t, a1, a2) => (((1 - 3 * a2 + 3 * a1) * t + (3 * a2 - 6 * a1)) * t + 3 * a1) * t;
+export function cubicBezier(x1, y1, x2, y2) {
+ if (x1 === y1 && x2 === y2) return (p) => p;
+ const solve = (x) => {
+ let lo = 0;
+ let hi = 1;
+ let mid;
+ let err;
+ let i = 0;
+ do {
+ mid = lo + (hi - lo) / 2;
+ err = bez(mid, x1, x2) - x;
+ if (err > 0) hi = mid;
+ else lo = mid;
+ } while (Math.abs(err) > 1e-7 && ++i < 12);
+ return mid;
+ };
+ return (p) => (p === 0 || p === 1 ? p : bez(solve(p), y1, y2));
+}
+export const easeIn = cubicBezier(0.42, 0, 1, 1);
+export const easeOut = cubicBezier(0, 0, 0.58, 1);
+
+const clamp = (lo, hi, v) => Math.min(Math.max(v, lo), hi);
+const mix = (from, to, p) => from + (to - from) * p;
+// numbers inside a string (an SVG path), mixed one by one; Motion rounds them to 5 decimals
+const NUM = /-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi;
+const sanitize = (v) => Math.round(v * 1e5) / 1e5;
+function mixString(from, to) {
+ const a = from.match(NUM).map(Number);
+ const b = to.match(NUM).map(Number);
+ const parts = to.split(NUM);
+ return (p) => {
+ let out = parts[0];
+ for (let i = 0; i < b.length; i++) out += sanitize(mix(a[i], b[i], p)) + parts[i + 1];
+ return out;
+ };
+}
+
+// ---------- the frame batch ----------
+const running = new Set();
+const starting = new Set();
+let rafId = null;
+function batch() {
+ rafId = null;
+ const now = performance.now();
+ for (const a of starting) {
+ a.startTime = now;
+ running.add(a);
+ }
+ starting.clear();
+ for (const a of running) a.tick(now);
+ if (running.size || starting.size) rafId = requestAnimationFrame(batch);
+}
+function wake() {
+ if (rafId === null) rafId = requestAnimationFrame(batch);
+}
+
+// keyframes: numbers or path strings; ease: one easing for every segment; times evenly spaced
+export function animate({ keyframes, duration, delay = 0, ease = easeOut, repeat = 0, repeatDelay = 0, onUpdate }) {
+ const ms = duration * 1000;
+ const delayMs = delay * 1000;
+ const repeatDelayMs = repeatDelay * 1000;
+ const segments = keyframes.length - 1;
+ const mixers = [];
+ for (let i = 0; i < segments; i++) {
+ const a = keyframes[i];
+ const b = keyframes[i + 1];
+ mixers.push(typeof a === "string" ? mixString(a, b) : (p) => mix(a, b, p));
+ }
+ const at = (t) => {
+ const x = clamp(0, 1, t / ms) * segments;
+ const i = Math.min(segments - 1, Math.floor(x));
+ return mixers[i](ease(clamp(0, 1, x - i)));
+ };
+ const resolved = ms + repeatDelayMs;
+ const total = repeat === Infinity ? Infinity : resolved * (repeat + 1) - repeatDelayMs;
+ const anim = {
+ startTime: null,
+ value: keyframes[0],
+ tick(now) {
+ const time = Math.round(now - anim.startTime) - delayMs;
+ const inDelay = time < 0;
+ let t = Math.max(time, 0);
+ if (repeat) {
+ const progress = Math.min(t, total) / resolved;
+ let iterationProgress = progress % 1;
+ if (!iterationProgress && progress >= 1) iterationProgress = 1;
+ t = clamp(0, 1, iterationProgress) * resolved;
+ }
+ const done = !inDelay && time >= total;
+ // a finished tween lands on its last keyframe exactly (a path string as written, not re-rounded)
+ anim.value = inDelay ? keyframes[0] : done ? keyframes[segments] : at(t);
+ onUpdate(anim.value);
+ if (done) anim.stop();
+ },
+ stop() {
+ running.delete(anim);
+ starting.delete(anim);
+ },
+ };
+ starting.add(anim);
+ wake();
+ return anim;
+}
diff --git a/site/public/examples/nextjs-features/src/optimizations.js b/site/public/examples/nextjs-features/src/optimizations.js
new file mode 100644
index 0000000..f660f58
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/optimizations.js
@@ -0,0 +1,197 @@
+// "Built-in Optimizations": three image frames (ORIGINAL, 1440PX, 375PX) drawn on a 2D canvas, each with a
+// dotted mountain. Over the canvas the dots within 40 px of the pointer light up in six bands of blue; a
+// press sends a ring out to 112 px that fades over 500 ms. Ported from nextjs.org's FeatureVisualOptimizations:
+// the same dot data, drawing calls and colours, in its 322x246 coordinate space.
+import { createLoop, createPointer, prefersReducedMotion, watchPixelRatio, watchReducedMotion } from "./phase.js";
+
+const TAU = 2 * Math.PI;
+const W = 322;
+const H = 246;
+
+// rows of [y, x0, x1, x2, x3 …]: a dot every 3.92 px from x0 to x1, x2 to x3 …
+function dots(rows) {
+ const out = [];
+ for (const [y, ...xs] of rows)
+ for (let i = 0; i < xs.length; i += 2) {
+ const from = xs[i];
+ const to = xs[i + 1];
+ if (from !== undefined && to !== undefined) for (let x = from; x <= to + 0.01; x += 3.92) out.push(x, y);
+ }
+ return Float32Array.from(out);
+}
+
+const FRAMES = [
+ {
+ x: 88.5625, y: 0.5, width: 232, height: 161,
+ label: "ORIGINAL", labelX: 302, labelY: 19.5, textAlign: "right", restingColorIndex: 0,
+ dots: dots([
+ [55.626, 151.643, 151.643], [59.546, 147.723, 155.562], [63.466, 143.803, 159.484], [67.386, 139.883, 163.403],
+ [71.306, 135.962, 167.323], [75.226, 132.043, 171.243], [79.146, 128.123, 175.163], [83.066, 124.204, 179.084],
+ [86.986, 120.284, 183.004], [90.906, 116.363, 186.923, 230.043, 233.962], [94.826, 112.443, 190.842, 226.123, 237.883],
+ [98.746, 108.523, 194.762, 222.204, 241.803, 269.243, 273.163], [102.666, 104.603, 198.683, 218.284, 245.723, 265.323, 277.084],
+ [106.586, 100.683, 202.603, 214.363, 249.643, 261.403, 281.004], [110.506, 96.762, 284.923], [114.426, 96.762, 288.842],
+ [118.346, 96.762, 292.762], [122.266, 96.762, 296.683], [126.186, 96.762, 300.603], [130.106, 96.762, 304.523],
+ [134.026, 96.762, 308.443], [137.946, 96.762, 312.363], [141.866, 96.762, 312.363], [145.786, 96.762, 312.363],
+ [149.706, 96.762, 312.363], [153.626, 96.762, 312.363],
+ ]),
+ },
+ {
+ x: 46.5225, y: 86.366, width: 172, height: 107,
+ label: "1440PX", labelX: 164, labelY: 103.5, textAlign: "start", restingColorIndex: 1,
+ dots: dots([
+ [115.712, 93.26, 93.26], [119.632, 89.34, 97.179], [123.552, 85.421, 101.101], [127.472, 81.501, 105.02],
+ [131.392, 77.58, 108.94], [135.312, 73.66, 112.86], [139.232, 69.74, 116.78, 152.06, 152.06],
+ [143.152, 65.821, 120.701, 148.14, 155.98], [147.072, 61.901, 124.621, 144.22, 159.901, 179.501, 183.421],
+ [150.992, 57.98, 128.541, 140.3, 163.821, 175.58, 187.34], [154.912, 54.06, 191.26], [158.832, 54.06, 195.179],
+ [162.752, 54.06, 199.101], [166.672, 54.06, 203.02], [170.592, 54.06, 206.94], [174.512, 54.06, 210.86],
+ [178.432, 54.06, 210.86], [182.352, 54.06, 210.86], [186.272, 54.06, 210.86],
+ ]),
+ },
+ {
+ x: 0.5, y: 174.5, width: 109, height: 71,
+ label: "375PX", labelX: 65, labelY: 190, textAlign: "start", restingColorIndex: 1,
+ dots: dots([
+ [197.554, 29.52, 29.52], [201.473, 25.6, 33.441], [205.394, 21.68, 37.361], [209.313, 17.76, 41.28],
+ [213.234, 13.84, 45.2, 64.8, 68.719], [217.154, 9.92, 49.12, 60.88, 72.641, 84.4, 88.32], [221.074, 6, 92.241],
+ [224.994, 6, 96.161], [228.914, 6, 100.081], [232.834, 6, 104], [236.754, 6, 104], [240.674, 6, 104],
+ ]),
+ },
+];
+
+function drawFrame(ctx, f, c, px, py, radius, fade) {
+ ctx.fillStyle = c.background;
+ ctx.strokeStyle = c.border;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.roundRect(f.x, f.y, f.width, f.height, 1.5);
+ ctx.fill();
+ ctx.stroke();
+ ctx.fillStyle = c.label;
+ ctx.font = c.monoFont;
+ ctx.textAlign = f.textAlign;
+ ctx.fillText(f.label, f.labelX, f.labelY);
+ ctx.save();
+ ctx.beginPath();
+ ctx.roundRect(f.x, f.y, f.width, f.height, 1.5);
+ ctx.clip();
+ ctx.fillStyle = c.resting[f.restingColorIndex];
+ const d = f.dots;
+ ctx.beginPath();
+ for (let i = 0; i < d.length; i += 2) {
+ ctx.moveTo(d[i] + 1.4, d[i + 1]);
+ ctx.arc(d[i], d[i + 1], 1.4, 0, TAU);
+ }
+ ctx.fill();
+ if (radius > 0) {
+ ctx.globalAlpha = 1 - fade;
+ for (let i = 0; i < d.length; i += 2) {
+ const x = d[i];
+ const y = d[i + 1];
+ const dist = Math.hypot(x - px, y - py);
+ if (dist >= radius) continue;
+ ctx.fillStyle = c.gradient[Math.min(c.gradient.length - 1, Math.floor((dist / radius) * c.gradient.length))];
+ ctx.beginPath();
+ ctx.arc(x, y, 1.4, 0, TAU);
+ ctx.fill();
+ }
+ ctx.globalAlpha = 1;
+ }
+ ctx.restore();
+}
+
+export function mountOptimizations(wrap) {
+ const canvas = wrap.querySelector("canvas");
+ const ctx = canvas.getContext("2d");
+ let size = null; // the wrapper's content box
+ let dpr = 1;
+ let draw = null;
+ const ripple = { active: false, x: 0, y: 0 };
+ let rippleLoop = null;
+ let reduced = false;
+ watchReducedMotion((m) => (reduced = m));
+
+ const colour = (name) => {
+ canvas.style.color = `var(${name})`;
+ return getComputedStyle(canvas).color;
+ };
+ function setup() {
+ if (!size) return;
+ const c = Math.min(dpr, 2);
+ canvas.width = Math.round(size.width * c);
+ canvas.height = Math.round(size.height * c);
+ ctx.setTransform((size.width / W) * c, 0, 0, (size.height / H) * c, 0, 0);
+ const root = getComputedStyle(document.documentElement);
+ const colours = {
+ background: colour("--color-background-200"),
+ border: colour("--color-gray-500"),
+ gradient: ["--color-blue-1000", "--color-blue-700", "--color-blue-600", "--color-blue-500", "--color-blue-400", "--color-blue-300"].map(colour),
+ label: colour("--color-blue-900"),
+ monoFont: `8px ${root.getPropertyValue("--font-mono").trim()}`,
+ resting: [colour("--color-gray-300"), colour("--color-gray-400")],
+ };
+ canvas.style.removeProperty("color");
+ draw = (px, py, radius, fade) => {
+ ctx.clearRect(0, 0, W, H);
+ for (const f of FRAMES) drawFrame(ctx, f, colours, px, py, radius, fade);
+ };
+ draw(0, 0, 0, 0);
+ return colours.monoFont;
+ }
+
+ // nextjs.org draws once its fonts are in; wait for Geist Mono so the labels never start in a fallback
+ let ready = false;
+ const fontReady = document.fonts.load(`8px ${getComputedStyle(document.documentElement).getPropertyValue("--font-mono").trim()}`, "ORIGINAL1440PX375PX");
+ fontReady.finally(() => {
+ ready = true;
+ setup();
+ });
+ new ResizeObserver((entries) => {
+ for (const e of entries) {
+ if (e.target !== wrap) continue;
+ const box = e.contentBoxSize[0];
+ if (!box || (size && box.inlineSize === size.width && box.blockSize === size.height)) continue;
+ size = { width: box.inlineSize, height: box.blockSize };
+ if (ready) setup();
+ }
+ }).observe(wrap);
+ dpr = watchPixelRatio((r) => {
+ dpr = r;
+ if (ready) setup();
+ });
+
+ const pointer = createPointer({
+ target: wrap,
+ onPointer: (p) => {
+ if (!draw || !size || ripple.active) return;
+ if (!p.active) return void draw(0, 0, 0, 0);
+ draw((p.x / size.width) * W, (p.y / size.height) * H, 40, 0);
+ },
+ });
+
+ wrap.addEventListener("pointerdown", (e) => {
+ if (e.button !== 0 || reduced || prefersReducedMotion()) return;
+ const p = pointer.state;
+ if (!p.active || !size) return;
+ ripple.x = (p.x / size.width) * W;
+ ripple.y = (p.y / size.height) * H;
+ ripple.active = true;
+ if (rippleLoop) return;
+ // nextjs.org runs the ring on a second loop observing the same element with the same options as the
+ // pointer tracker, so (like there) that loop only starts once the canvas leaves the screen and returns
+ rippleLoop = createLoop({
+ target: wrap,
+ onTick: (t) => {
+ if (!draw || !ripple.active) return;
+ const k = Math.min(1, t.elapsed / 500);
+ const eased = 1 - Math.pow(1 - k, 4);
+ draw(ripple.x, ripple.y, 40 + 72 * eased, eased);
+ if (k === 1) {
+ ripple.active = false;
+ draw(0, 0, 0, 0);
+ rippleLoop.stop();
+ rippleLoop = null;
+ }
+ },
+ });
+ });
+}
diff --git a/site/public/examples/nextjs-features/src/phase.js b/site/public/examples/nextjs-features/src/phase.js
new file mode 100644
index 0000000..b9184ea
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/phase.js
@@ -0,0 +1,448 @@
+// The small "phase" library nextjs.org runs its feature illustrations on (module 75486 of its bundle), ported
+// without React: one shared requestAnimationFrame clock, one IntersectionObserver per option set, a ticker
+// loop that runs only while its element is on screen (and the tab visible, and motion allowed), and a pointer
+// tracker that reports the pointer position once per frame. The behaviour is kept as it is, quirks included:
+// a second loop on an element that is already observed with the same options never hears from the observer.
+
+// ---------- shared frame clock ----------
+const clock = (globalThis[Symbol.for("phase.clock@2")] ??= { rafId: null, frame: 0, time: 0, ticks: new Map(), input: new Map() });
+let failed = false;
+let failure;
+
+function idle() {
+ if (clock.ticks.size === 0 && clock.input.size === 0 && clock.rafId !== null) {
+ cancelAnimationFrame(clock.rafId);
+ clock.rafId = null;
+ }
+}
+function runInput(registered, fn) {
+ if (registered >= clock.frame) return;
+ clock.input.set(fn, -1);
+ let again = false;
+ try {
+ again = fn(clock.time) === true;
+ } catch (e) {
+ if (!failed) failure = e;
+ failed = true;
+ }
+ const state = clock.input.get(fn);
+ if (state !== undefined && (again || state !== -1)) {
+ clock.input.set(fn, clock.frame);
+ request();
+ } else clock.input.delete(fn);
+}
+function runTick(registered, fn) {
+ if (registered < clock.frame) fn(clock.time);
+}
+function frame(time) {
+ clock.time = time;
+ clock.frame++;
+ failed = false;
+ clock.rafId = clock.ticks.size === 0 ? null : requestAnimationFrame(frame);
+ clock.input.forEach(runInput);
+ const threw = failed;
+ const error = failure;
+ failed = false;
+ failure = undefined;
+ clock.ticks.forEach(runTick);
+ idle();
+ if (threw) throw error;
+}
+function request() {
+ if (clock.rafId === null) clock.rafId = requestAnimationFrame(frame);
+}
+function addTick(fn) {
+ clock.ticks.set(fn, clock.frame);
+ request();
+}
+function removeTick(fn) {
+ clock.ticks.delete(fn);
+ idle();
+}
+function scheduleInput(fn) {
+ const state = clock.input.get(fn);
+ if (state === -1) {
+ clock.input.set(fn, -2);
+ request();
+ return;
+ }
+ if (state === undefined) {
+ clock.input.set(fn, clock.frame);
+ request();
+ }
+}
+function cancelInput(fn) {
+ clock.input.delete(fn);
+ idle();
+}
+
+// ---------- media queries ----------
+const REDUCED = "(prefers-reduced-motion: reduce)";
+const queries = new Map();
+function watchQuery(query, listener) {
+ let q = queries.get(query);
+ if (!q) {
+ const mql = matchMedia(query);
+ const listeners = new Set();
+ q = { mql, listeners, handler: (e) => { for (const l of listeners) l(e.matches); } };
+ mql.addEventListener("change", q.handler);
+ queries.set(query, q);
+ }
+ q.listeners.add(listener);
+ let done = false;
+ return () => {
+ if (done) return;
+ done = true;
+ const r = queries.get(query);
+ if (!r) return;
+ r.listeners.delete(listener);
+ if (r.listeners.size === 0) {
+ r.mql.removeEventListener("change", r.handler);
+ queries.delete(query);
+ }
+ };
+}
+function queryMatches(query) {
+ const q = queries.get(query);
+ return q ? q.mql.matches : matchMedia(query).matches;
+}
+export const prefersReducedMotion = () => queryMatches(REDUCED);
+export function watchReducedMotion(listener) {
+ listener(queryMatches(REDUCED));
+ return watchQuery(REDUCED, listener);
+}
+
+// devicePixelRatio, and a callback when it changes (zoom, moving the window to another screen)
+export function watchPixelRatio(listener) {
+ let ratio = window.devicePixelRatio || 1;
+ let mql;
+ const arm = () => {
+ mql = matchMedia(`(resolution: ${ratio}dppx)`);
+ mql.addEventListener("change", changed);
+ };
+ function changed() {
+ const r = window.devicePixelRatio || 1;
+ if (r === ratio) return;
+ ratio = r;
+ mql.removeEventListener("change", changed);
+ arm();
+ listener(r);
+ }
+ arm();
+ return ratio;
+}
+
+// ---------- shared intersection observers ----------
+const observers = new Map();
+const rootIds = new WeakMap();
+let nextRootId = 1;
+function observe({ element, onIntersect, root, rootMargin, threshold }) {
+ const options = { root, rootMargin, threshold };
+ let rootKey = "null";
+ if (root) {
+ let id = rootIds.get(root);
+ if (id === undefined) rootIds.set(root, (id = nextRootId++));
+ rootKey = String(id);
+ }
+ const key = `${rootKey}|${rootMargin ?? "0px"}|${Array.isArray(threshold) ? threshold.join(",") : String(threshold ?? 0)}`;
+ let entry = observers.get(key);
+ if (!entry) {
+ const callbacks = new Map();
+ entry = {
+ callbacks,
+ observer: new IntersectionObserver((records) => {
+ for (const r of records) {
+ const set = callbacks.get(r.target);
+ if (set) for (const cb of set) cb(r);
+ }
+ }, options),
+ };
+ observers.set(key, entry);
+ }
+ let set = entry.callbacks.get(element);
+ if (!set) entry.callbacks.set(element, (set = new Set()));
+ set.add(onIntersect);
+ entry.observer.observe(element); // a no-op when the element is already observed: no first callback then
+ let done = false;
+ return () => {
+ if (done) return;
+ done = true;
+ const e = observers.get(key);
+ if (!e) return;
+ const s = e.callbacks.get(element);
+ if (s) {
+ s.delete(onIntersect);
+ if (s.size === 0) {
+ e.observer.unobserve(element);
+ e.callbacks.delete(element);
+ }
+ }
+ if (e.callbacks.size === 0) {
+ e.observer.disconnect();
+ observers.delete(key);
+ }
+ };
+}
+
+// ---------- sight: visible = intersecting and the document not hidden ----------
+function createSight({ target, intersectionOptions, onPhaseChange }) {
+ let phase = "unknown";
+ let stopped = false;
+ let docVisible = !document.hidden;
+ let intersecting = false;
+ function update() {
+ if (stopped) return;
+ const next = docVisible && intersecting ? "visible" : "hidden";
+ if (next !== phase) {
+ phase = next;
+ onPhaseChange?.(phase);
+ }
+ }
+ const onVisibility = () => { docVisible = !document.hidden; update(); };
+ const onPageShow = (e) => { if (e.persisted) { docVisible = true; update(); } };
+ document.addEventListener("visibilitychange", onVisibility);
+ window.addEventListener("pageshow", onPageShow);
+ const unobserve = observe({ element: target, onIntersect: (r) => { intersecting = r.isIntersecting; update(); }, ...intersectionOptions });
+ return {
+ stop() {
+ if (stopped) return;
+ stopped = true;
+ document.removeEventListener("visibilitychange", onVisibility);
+ window.removeEventListener("pageshow", onPageShow);
+ unobserve();
+ },
+ };
+}
+
+// ---------- ticker: delta per frame (first frame 16.67 ms, capped at interval + 40 ms), elapsed, frame ----------
+function createTicker({ fps, onTick }) {
+ const toInterval = (f) => (f === undefined ? 0 : 1000 / f);
+ let interval = toInterval(fps);
+ let cap = interval + 40;
+ let state = "idle";
+ let last = -1;
+ let elapsed = 0;
+ let frames = 0;
+ let next = 0;
+ const info = { time: 0, delta: 0, elapsed: 0, frame: 0 };
+ function tick(now) {
+ if (now < next) return;
+ const first = last < 0;
+ const delta = first ? interval || 16.67 : now - last;
+ last = now;
+ if (interval > 0) {
+ if (first) next = now + interval;
+ else {
+ const due = next + interval;
+ const late = now - due;
+ next = late < interval ? due : due + Math.floor(late / interval) * interval;
+ }
+ }
+ info.time = now;
+ info.delta = delta > cap ? cap : delta;
+ elapsed += info.delta;
+ info.elapsed = elapsed;
+ info.frame = ++frames;
+ onTick(info);
+ }
+ return {
+ start() {
+ if (state === "running") return;
+ if (state === "paused") return this.resume();
+ state = "running";
+ last = -1;
+ next = 0;
+ elapsed = 0;
+ frames = 0;
+ info.time = info.delta = info.elapsed = info.frame = 0;
+ addTick(tick);
+ },
+ pause() {
+ if (state !== "running") return;
+ state = "paused";
+ removeTick(tick);
+ },
+ resume() {
+ if (state !== "paused") return;
+ last = -1;
+ next = 0;
+ state = "running";
+ addTick(tick);
+ },
+ stop() {
+ if (state === "stopped") return;
+ state = "stopped";
+ removeTick(tick);
+ },
+ setFps(f) {
+ interval = toInterval(f);
+ cap = interval + 40;
+ next = last < 0 ? 0 : last + interval;
+ },
+ get phase() { return state; },
+ };
+}
+
+// ---------- loop: a ticker that runs while its target is visible and motion is allowed ----------
+// Under load (3 frames in a row over 1.5x the frame time) or without focus it drops to 30 fps.
+export function createLoop({ target, onTick, intersectionOptions }) {
+ let phase = "idle";
+ let started = false;
+ let quality = "full";
+ let slowFrames = 0;
+ let frameMs = 1000 / 60;
+ let unfocused = false;
+ let ticker = null;
+ // lifecycle
+ let visible = false;
+ let reduced = false;
+ let lifecycle = "idle";
+ let lifecycleReason = null;
+ function setQuality(q) {
+ const changed = quality !== q;
+ quality = q;
+ if (changed && phase !== "stopped") applyFps();
+ }
+ function checkQuality() {
+ setQuality(unfocused || slowFrames >= 3 ? "degraded" : "full");
+ }
+ function applyFps() {
+ const fps = quality === "degraded" ? 30 : undefined;
+ frameMs = 1000 / (fps ?? 60);
+ ticker?.setFps(fps);
+ return fps;
+ }
+ function tick(info) {
+ if (info.delta <= 1.5 * frameMs) slowFrames = 0;
+ else if (++slowFrames >= 3) checkQuality();
+ onTick(info);
+ }
+ function sync() {
+ if (phase === "stopped" || !started) return;
+ if (lifecycle === "paused") {
+ if (ticker && phase === "running") ticker.pause();
+ phase = "paused";
+ return;
+ }
+ if (ticker) {
+ if (phase === "paused") {
+ ticker.resume();
+ phase = "running";
+ }
+ } else {
+ ticker = createTicker({ fps: applyFps(), onTick: tick });
+ ticker.start();
+ phase = "running";
+ }
+ }
+ function lifecycleUpdate() {
+ if (lifecycle === "stopped" || !started) return;
+ lifecycleReason = reduced ? "reduced-motion" : visible ? null : "sight";
+ lifecycle = lifecycleReason ? "paused" : "active";
+ sync();
+ }
+ const sight = createSight({ target, intersectionOptions, onPhaseChange: (p) => { visible = p === "visible"; lifecycleUpdate(); } });
+ const unwatch = watchQuery(REDUCED, (m) => { reduced = m; lifecycleUpdate(); });
+ reduced = queryMatches(REDUCED);
+ const onFocus = () => { unfocused = !document.hasFocus(); checkQuality(); };
+ window.addEventListener("focus", onFocus);
+ window.addEventListener("blur", onFocus);
+ started = true;
+ lifecycleUpdate();
+ return {
+ stop() {
+ if (phase === "stopped") return;
+ phase = "stopped";
+ lifecycle = "stopped";
+ ticker?.stop();
+ sight.stop();
+ unwatch();
+ window.removeEventListener("focus", onFocus);
+ window.removeEventListener("blur", onFocus);
+ },
+ get phase() { return phase; },
+ };
+}
+
+// ---------- pointer: position relative to the target, reported once per frame while over it ----------
+// Listens only while the target is on screen. onPointer gets { x, y, active }.
+export function createPointer({ target, onPointer, intersectionOptions }) {
+ const state = { x: 0, y: 0, active: false };
+ let tracking = false;
+ let stopped = false;
+ let clientX = 0;
+ let clientY = 0;
+ let pending = false;
+ function report() {
+ if (!pending || stopped) return;
+ pending = false;
+ const r = target.getBoundingClientRect();
+ state.x = clientX - r.left;
+ state.y = clientY - r.top;
+ onPointer(state);
+ }
+ function cancel() {
+ cancelInput(report);
+ pending = false;
+ }
+ function move(e) {
+ if (stopped || !tracking) return;
+ clientX = e.clientX;
+ clientY = e.clientY;
+ pending = true;
+ scheduleInput(report);
+ }
+ function enter() {
+ if (stopped) return;
+ state.active = true;
+ tracking = true;
+ }
+ function leave() {
+ if (stopped) return;
+ cancel();
+ state.active = false;
+ tracking = false;
+ onPointer(state);
+ }
+ let listening = false;
+ const listen = (on) => {
+ if (on === listening) return;
+ listening = on;
+ const fn = on ? "addEventListener" : "removeEventListener";
+ target[fn]("pointermove", move);
+ target[fn]("pointerenter", enter);
+ target[fn]("pointerleave", leave);
+ };
+ let intersecting = false;
+ let docVisible = !document.hidden;
+ function update() {
+ if (stopped) return;
+ if (docVisible && intersecting) listen(true);
+ else {
+ listen(false);
+ if (state.active) {
+ cancel();
+ state.active = false;
+ tracking = false;
+ }
+ }
+ }
+ const onVisibility = () => { docVisible = !document.hidden; update(); };
+ const onPageShow = (e) => { if (e.persisted) { docVisible = true; update(); } };
+ document.addEventListener("visibilitychange", onVisibility);
+ window.addEventListener("pageshow", onPageShow);
+ const unobserve = observe({ element: target, onIntersect: (r) => { intersecting = r.isIntersecting; update(); }, ...intersectionOptions });
+ return {
+ state,
+ stop() {
+ if (stopped) return;
+ stopped = true;
+ document.removeEventListener("visibilitychange", onVisibility);
+ window.removeEventListener("pageshow", onPageShow);
+ unobserve();
+ listen(false);
+ cancel();
+ state.active = false;
+ },
+ };
+}
diff --git a/site/public/examples/nextjs-features/src/rsc.js b/site/public/examples/nextjs-features/src/rsc.js
new file mode 100644
index 0000000..67ee707
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/rsc.js
@@ -0,0 +1,65 @@
+// "React Server Components": a tree of six nodes. The dashes on the two blue edges flow down the tree, and a
+// blue arc glides round three of the nodes while it pulses. Hovering the card speeds both up and thickens the
+// arcs, easing in and out over about a second. Ported from nextjs.org's FeatureVisualRsc: the same per-frame
+// update on the same loop, which pauses while the card is off screen.
+import { createLoop } from "./phase.js";
+
+const DASH_SPEED = 7 / 2.4; // dash pattern units per second (one 4+3 pattern every 2.4 s)
+const SPIN = (2 * Math.PI) / 5.5; // radians per second (one turn every 5.5 s)
+const NODES = [
+ { cx: 134.239, cy: 28.8441, r: 27.8441, startAngle: 0.85 * Math.PI },
+ { cx: 81.7415, cy: 106.809, r: 27.8441, startAngle: 0.15 },
+ { cx: 133.864, cy: 192.189, r: 27.8441, startAngle: -(0.7 * Math.PI) },
+];
+
+export function mountRsc(root) {
+ const svg = root.querySelector("svg");
+ const link = root.closest("a") ?? root;
+ const edges = [...svg.querySelectorAll('path[stroke="var(--color-blue-900)"]')];
+ const arcs = [...svg.querySelectorAll('circle[stroke^="url("]')];
+ const grads = [...svg.querySelectorAll("defs linearGradient")];
+
+ // at rest, as React renders it: the gradient from 0.28 r to r along the start angle
+ NODES.forEach((n, i) => {
+ const cos = Math.cos(n.startAngle);
+ const sin = Math.sin(n.startAngle);
+ grads[i].setAttribute("x1", n.cx + cos * n.r * 0.28);
+ grads[i].setAttribute("x2", n.cx + cos * n.r);
+ grads[i].setAttribute("y1", n.cy + sin * n.r * 0.28);
+ grads[i].setAttribute("y2", n.cy + sin * n.r);
+ });
+
+ let hovered = false;
+ let hover = 0;
+ let dash = 0;
+ let angle = 0;
+ createLoop({
+ target: link,
+ intersectionOptions: { threshold: 0, rootMargin: "0px" },
+ onTick: (t) => {
+ const dt = 0.001 * t.delta;
+ const h = hover + (+hovered - hover) * Math.min(1, 3.5 * dt);
+ hover = h;
+ dash += dt * DASH_SPEED * (1 + 2 * h);
+ angle += dt * SPIN * (1 + 0.55 * h);
+ const offset = -(dash % 7);
+ for (const e of edges) e.setAttribute("stroke-dashoffset", String(offset));
+ const opacity = 0.38 + 0.22 * h + (0.35 + 0.3 * h) * (0.5 + 0.5 * Math.sin(angle));
+ const inner = 0.28 - 0.13 * h;
+ const width = 1.75 + 0.75 * h;
+ NODES.forEach((n, i) => {
+ arcs[i].style.opacity = String(opacity);
+ arcs[i].setAttribute("stroke-width", String(width));
+ const a = n.startAngle + angle;
+ const cos = Math.cos(a);
+ const sin = Math.sin(a);
+ grads[i].setAttribute("x1", String(n.cx + cos * n.r * inner));
+ grads[i].setAttribute("y1", String(n.cy + sin * n.r * inner));
+ grads[i].setAttribute("x2", String(n.cx + cos * n.r));
+ grads[i].setAttribute("y2", String(n.cy + sin * n.r));
+ });
+ },
+ });
+ link.addEventListener("mouseenter", () => (hovered = true));
+ link.addEventListener("mouseleave", () => (hovered = false));
+}
diff --git a/site/public/examples/nextjs-features/src/streaming.js b/site/public/examples/nextjs-features/src/streaming.js
new file mode 100644
index 0000000..438978c
--- /dev/null
+++ b/site/public/examples/nextjs-features/src/streaming.js
@@ -0,0 +1,131 @@
+// "Dynamic HTML Streaming": a wireframe page on a grid. Once the card is well inside the viewport, four
+// streaks of blue run along the grid lines into the page frame, each on its own loop, and every 5 s the image
+// placeholder turns into an avatar (and back) while every 8 s the content blocks change layout. Hovering the
+// illustration restarts the streaks on a faster 2 s loop. Ported from nextjs.org's FeatureVisualStreaming
+// (React + Motion there); the timings, keyframes and easings are its own.
+import { animate, cubicBezier, easeIn, easeOut } from "./motion.js";
+
+// the four streaks: the path they run along, when they first start, and the pause between runs
+const PULSES = [
+ { delay: 2, repeatDelay: 2.5, initial: { x1: 0, x2: -52, y1: 33, y2: -18 }, animate: { x1: [0, 497], x2: [-52, 340], y1: [33, 33], y2: [-18, 97] } },
+ { delay: 4, repeatDelay: 6, initial: { x1: 254.5, x2: 254.5, y1: 0, y2: -57 }, animate: { x1: [254.5, 20], x2: [254.5, 84], y1: [0, 227], y2: [-57, 113] } },
+ { delay: 3, repeatDelay: 4, initial: { x1: -40, x2: -140, y1: 360, y2: 480 }, animate: { x1: [-40, 398], x2: [-140, 221], y1: [360, 484], y2: [480, 351] } },
+ { delay: 0.5, repeatDelay: 2, initial: { x1: 423, x2: 467, y1: 197.5, y2: 197.5 }, animate: { x1: [423, 229], x2: [467, 264], y1: [197.5, 524], y2: [197.5, 257, 435] } },
+];
+const LOOP = { duration: 4, delay: 1.5, repeat: Infinity }; // Motion's ease for the gradient is easeOut, the stroke easeIn
+const HOVER = { delay: 0, repeatDelay: 0, duration: 2 };
+
+// the image placeholder: a 41.85 px square with a triangle, or a 23.35 px circle (the avatar)
+const IMAGE = { size: 41.8457, rx: 2 };
+const AVATAR = { size: 23.3515625, rx: 11.67578125 };
+function triangle(size) {
+ const k = size / IMAGE.size;
+ const cx = 75.0781 + IMAGE.size / 2;
+ const cy = 108.15 + IMAGE.size / 2;
+ const ox = 75.0781 + size / 2;
+ const oy = 108.15 + size / 2;
+ const at = (x, y) => ({ x: ox + k * (x - cx), y: oy + k * (y - cy) });
+ const a = at(96.0015, 122.556);
+ const b = at(103.019, 134.71);
+ const c = at(88.984, 134.71);
+ return `M${a.x} ${a.y}L${b.x} ${b.y}H${c.x}Z`;
+}
+const LINES_Y = [158.476, 164.497, 170.517, 176.538, 182.559]; // sidebar text lines, under the image
+const LINES_Y_AVATAR = [139.5015, 145.5215, 151.5415, 157.5615, 163.5815]; // moved up under the avatar
+const BLOCKS = [
+ { y: 130.489, height: 50.7081 }, { y: 130.489, height: 50.7081 }, { y: 188.198, height: 50.7081 },
+ { y: 188.198, height: 108.416 }, { y: 245.906, height: 50.7081 },
+];
+const BLOCKS_ALT = [
+ { y: 130.489, height: 35.708 }, { y: 130.489, height: 70.708 }, { y: 173.199, height: 65.708 },
+ { y: 208.199, height: 88.416 }, { y: 245.909, height: 50.708 },
+];
+const SWAP = { duration: 1, ease: cubicBezier(0.76, 0, 0.24, 1) };
+
+// a value animated like a Motion value: a new target starts from wherever the last animation got to
+function motionValue(initial, render) {
+ const v = { current: initial, anim: null };
+ render(initial);
+ v.to = (target) => {
+ if (v.anim) v.anim.stop();
+ if (target === v.current) return;
+ v.anim = animate({ keyframes: [v.current, target], ...SWAP, onUpdate: (x) => { v.current = x; render(x); } });
+ };
+ return v;
+}
+
+export function mountStreaming(root) {
+ const svg = root.querySelector("svg");
+ const group = svg.querySelector("g[clip-path] > g");
+ const [image, ...rects] = group.querySelectorAll("rect");
+ const lines = rects.slice(0, 5);
+ const blocks = rects.slice(5);
+ const paths = [...svg.querySelectorAll('path[stroke^="url("]')];
+ const grads = [...svg.querySelectorAll("defs linearGradient")];
+
+ // the wireframe
+ const imageSize = motionValue(IMAGE.size, (s) => { image.setAttribute("width", s); image.setAttribute("height", s); });
+ const imageRx = motionValue(IMAGE.rx, (r) => image.setAttribute("rx", r));
+ const tri = motionValue(triangle(IMAGE.size), (d) => group.querySelector("path").setAttribute("d", d));
+ const translate = (el) => (y) => (el.style.transform = `translateY(${y}px)`);
+ const lineY = lines.map((el, i) => motionValue(LINES_Y[i], translate(el)));
+ const blockY = blocks.map((el, i) => motionValue(BLOCKS[i].y, translate(el)));
+ const blockH = blocks.map((el, i) => motionValue(BLOCKS[i].height, (h) => el.setAttribute("height", h)));
+
+ let avatar = false;
+ let altBlocks = false;
+ function swapImage() {
+ avatar = !avatar;
+ const to = avatar ? AVATAR : IMAGE;
+ imageSize.to(to.size);
+ imageRx.to(to.rx);
+ tri.to(triangle(to.size));
+ lineY.forEach((v, i) => v.to((avatar ? LINES_Y_AVATAR : LINES_Y)[i]));
+ }
+ function swapBlocks() {
+ altBlocks = !altBlocks;
+ const to = altBlocks ? BLOCKS_ALT : BLOCKS;
+ blockY.forEach((v, i) => v.to(to[i].y));
+ blockH.forEach((v, i) => v.to(to[i].height));
+ }
+
+ // the streaks: React remounts them whenever "in view" or "hovered" changes, so they restart from scratch
+ let inView = false;
+ let hover = false;
+ let running = [];
+ function mountPulses() {
+ for (const a of running) a.stop();
+ running = [];
+ PULSES.forEach((p, i) => {
+ const path = paths[i];
+ const grad = grads[i];
+ path.setAttribute("stroke-width", 2);
+ for (const k of ["x1", "x2", "y1", "y2"]) grad.setAttribute(k, p.initial[k]);
+ if (!inView) return;
+ const timing = { ...LOOP, delay: LOOP.delay + p.delay, repeatDelay: p.repeatDelay, ...(hover ? HOVER : null) };
+ for (const k of ["x1", "x2", "y1", "y2"])
+ running.push(animate({ keyframes: p.animate[k], ...timing, ease: easeOut, onUpdate: (v) => grad.setAttribute(k, v) }));
+ running.push(animate({ keyframes: [2, 1], ...timing, ease: easeIn, onUpdate: (v) => path.setAttribute("stroke-width", v) }));
+ });
+ }
+ mountPulses();
+
+ // Motion's useInView(ref, { margin: "-30%", once: true })
+ const io = new IntersectionObserver(
+ (entries) => {
+ for (const e of entries) {
+ if (!e.isIntersecting || inView) continue;
+ io.disconnect();
+ inView = true;
+ setInterval(swapImage, 5000);
+ setInterval(swapBlocks, 8000);
+ mountPulses();
+ }
+ },
+ { rootMargin: "-30%", threshold: 0 },
+ );
+ io.observe(root);
+
+ root.addEventListener("mouseenter", () => { hover = true; mountPulses(); });
+ root.addEventListener("mouseleave", () => { hover = false; mountPulses(); });
+}
diff --git a/site/public/examples/turborepo-gauge/assets/fonts/Geist-Variable.woff2 b/site/public/examples/turborepo-gauge/assets/fonts/Geist-Variable.woff2
new file mode 100644
index 0000000..5c5999d
Binary files /dev/null and b/site/public/examples/turborepo-gauge/assets/fonts/Geist-Variable.woff2 differ
diff --git a/site/public/examples/turborepo-gauge/assets/fonts/GeistMono-Variable.woff2 b/site/public/examples/turborepo-gauge/assets/fonts/GeistMono-Variable.woff2
new file mode 100644
index 0000000..efaf95d
Binary files /dev/null and b/site/public/examples/turborepo-gauge/assets/fonts/GeistMono-Variable.woff2 differ
diff --git a/site/public/examples/turborepo-gauge/assets/fonts/LICENSE-geist.txt b/site/public/examples/turborepo-gauge/assets/fonts/LICENSE-geist.txt
new file mode 100644
index 0000000..8d003fe
--- /dev/null
+++ b/site/public/examples/turborepo-gauge/assets/fonts/LICENSE-geist.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2023 Vercel, in collaboration with basement.studio
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/public/examples/turborepo-gauge/index.html b/site/public/examples/turborepo-gauge/index.html
new file mode 100644
index 0000000..5f512e0
--- /dev/null
+++ b/site/public/examples/turborepo-gauge/index.html
@@ -0,0 +1,69 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>turborepo.com hero gauge and counter, rebuilt with reanimate</title>
+ <meta name="robots" content="noindex">
+ <!--
+ The hero of turborepo.com: a speedometer whose needle revs toward the red end while the pointer is on it
+ and drops back when it leaves, and below it the stats row, whose "compute hours saved" number rolls up
+ from the server-rendered figure to the live one once the page has loaded, then ticks up every 10 s.
+ The gauge is turborepo.com's own SVG; src/hero.js ports the page's spring (stiffness 520, damping 22)
+ and its 1.2 s easeOutCubic counter tween, frame for frame. The live figure is replaced by the one read
+ from turborepo.com on 30 Oct 2026 and grows at the rate measured then. Plain HTML + ES modules.
+ ?embed: the gauge and the counter alone, for an iframe (the reanimate site shows it this way).
+ -->
+ <script>if (new URLSearchParams(location.search).has("embed")) document.documentElement.dataset.embed = "";</script>
+ <link rel="preload" href="./assets/fonts/Geist-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="preload" href="./assets/fonts/GeistMono-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="stylesheet" href="./src/hero.css">
+ <script type="module" src="./src/hero.js"></script>
+</head>
+<body>
+ <main class="tr-page">
+ <div class="tr-container">
+ <section class="tr-hero">
+ <div class="tr-hero__copy">
+ <h1 class="tr-title">Your codebase, faster</h1>
+ <p class="tr-lede">Turborepo is the build system for coding agents. Developers, CI, and agents never do the same work twice.</p>
+ <div class="tr-install">
+ <div class="tr-toggle">
+ <button aria-pressed="true" class="tr-toggle__button" data-active="" data-command="npm i turbo" type="button">For humans</button>
+ <div aria-hidden="true" class="tr-toggle__divider"></div>
+ <button aria-pressed="false" class="tr-toggle__button" data-command="npx skills add vercel/turborepo" type="button">For agents</button>
+ </div>
+ <div class="group material-small tr-command">
+ <span class="tr-command__prompt">$</span>
+ <span class="tr-command__text"><span aria-hidden="true" class="tr-command__sizer">npm i turbo</span><span class="tr-command__value">npm i turbo</span></span>
+ <button aria-label="Copy command" class="tr-command__copy" type="button"><span class="tr-command__icon"><svg data-slot="geist-icon" height="16" style="color:currentColor" viewBox="0 0 16 16" width="16" class="block"><path clip-rule="evenodd" d="M8.25 2c.14 0 .25.11.25.25V3H10v-.75C10 1.28 9.22.5 8.25.5h-5.5C1.78.5 1 1.28 1 2.25v7.5c0 .97.78 1.75 1.75 1.75H4.5V10H2.75a.25.25 0 0 1-.25-.25v-7.5c0-.14.11-.25.25-.25zm5 4c.14 0 .25.11.25.25v7.5q-.02.23-.25.25h-5.5a.25.25 0 0 1-.25-.25v-7.5c0-.14.11-.25.25-.25zm0 9.5c.97 0 1.75-.78 1.75-1.75v-7.5c0-.97-.78-1.75-1.75-1.75h-5.5C6.78 4.5 6 5.28 6 6.25v7.5c0 .97.78 1.75 1.75 1.75z" fill="currentColor" fill-rule="evenodd"></path></svg></span></button>
+ </div>
+ </div>
+ </div>
+ <div class="tr-hero__visual">
+ <!-- turborepo.com's wrapper classes are kept so the same selectors find the gauge on both pages -->
+ <div class="relative w-full max-w-[500px] aspect-[24/17] tr-gauge"><svg aria-hidden="true" class="absolute inset-0 size-full overflow-visible" viewBox="0 0 480 340"><defs><linearGradient id="remote-cache-gauge-gradient" gradientUnits="userSpaceOnUse" x1="46.4" x2="433.6" y1="310.5" y2="310.5"><stop offset="0" stop-color="#0196FF"></stop><stop offset="1" stop-color="#FF1E56"></stop></linearGradient><linearGradient id="remote-cache-gauge-inner-gradient" gradientUnits="userSpaceOnUse" x1="46.4" x2="433.6" y1="310.5" y2="310.5"><stop offset="0" stop-color="var(--remote-cache-inner-start)"></stop><stop offset="1" stop-color="var(--remote-cache-inner-end)"></stop></linearGradient><linearGradient id="remote-cache-gauge-pointer-gradient" gradientUnits="userSpaceOnUse" x1="236.58" x2="243.42" y1="230.6" y2="249.4"><stop offset="0" stop-color="var(--ds-gray-700)"></stop><stop offset="0.42" stop-color="var(--ds-gray-1000)"></stop><stop offset="1" stop-color="var(--ds-gray-800)"></stop></linearGradient><radialGradient id="remote-cache-gauge-dot-gradient" gradientUnits="userSpaceOnUse" cx="234" cy="233" fx="234" fy="233" r="27"><stop offset="0" stop-color="var(--ds-gray-700)"></stop><stop offset="0.48" stop-color="var(--ds-gray-1000)"></stop><stop offset="1" stop-color="var(--ds-gray-700)"></stop></radialGradient><radialGradient id="remote-cache-gauge-pin-gradient" cx="35%" cy="30%"><stop offset="0" stop-color="var(--ds-gray-100)"></stop><stop offset="1" stop-color="var(--ds-gray-400)"></stop></radialGradient><radialGradient id="remote-cache-gauge-fade" cx="240" cy="240" gradientUnits="userSpaceOnUse" r="197"><stop offset="75%" stop-color="white" stop-opacity="0"></stop><stop offset="81%" stop-color="white" stop-opacity="0.03"></stop><stop offset="87%" stop-color="white" stop-opacity="0.12"></stop><stop offset="92%" stop-color="white" stop-opacity="0.32"></stop><stop offset="95%" stop-color="white" stop-opacity="0.64"></stop><stop offset="100%" stop-color="white" stop-opacity="1"></stop></radialGradient><mask id="remote-cache-gauge-fade-mask" mask-type="alpha"><rect fill="url(#remote-cache-gauge-fade)" height="340" width="480"></rect></mask><mask id="remote-cache-gauge-segment-mask" mask-type="luminance"><path d="M46.4 310.5a206 206 0 1 1 387.2 0" fill="none" stroke="white" stroke-linecap="butt" stroke-width="120"></path><g stroke="black" stroke-width="2.77"><line x1="102.78" x2="-24.65" y1="212.26" y2="186.5"></line><line x1="137.37" x2="42.08" y1="144.78" y2="56.35"></line><line x1="202.08" x2="166.87" y1="105.23" y2="-19.91"></line><line x1="277.92" x2="313.13" y1="105.23" y2="-19.91"></line><line x1="342.63" x2="437.92" y1="144.78" y2="56.35"></line><line x1="377.22" x2="504.65" y1="212.26" y2="186.5"></line></g></mask><mask id="remote-cache-gauge-inner-indicator-mask" mask-type="alpha"><path d="M54.9 307.4a197 197 0 1 1 370.2 0" fill="none" pathLength="100" stroke="white" stroke-dasharray="80.95 19.05" stroke-linecap="butt" stroke-width="394"></path></mask><mask id="remote-cache-gauge-inner-remainder-mask" mask-type="alpha"><path d="M54.9 307.4a197 197 0 1 1 370.2 0" fill="none" pathLength="100" stroke="white" stroke-dasharray="0 80.95 19.05 0" stroke-linecap="butt" stroke-width="394"></path></mask><linearGradient id="remote-cache-gauge-end-fade" gradientUnits="userSpaceOnUse" x1="0" x2="0" y1="310.5" y2="270"><stop offset="0" stop-color="white" stop-opacity="0"></stop><stop offset="100%" stop-color="white"></stop></linearGradient><mask id="remote-cache-gauge-end-fade-mask" mask-type="alpha"><rect fill="url(#remote-cache-gauge-end-fade)" height="340" width="480"></rect></mask><filter id="remote-cache-gauge-glow" height="160%" width="160%" x="-30%" y="-30%"><feGaussianBlur stdDeviation="2.5"></feGaussianBlur></filter><filter id="remote-cache-gauge-pointer-shadow-blur" height="140%" width="140%" x="-20%" y="-20%"><feGaussianBlur stdDeviation="1.2"></feGaussianBlur></filter></defs><g mask="url(#remote-cache-gauge-end-fade-mask)"><path class="opacity-25 dark:mix-blend-screen dark:opacity-40" d="M46.4 310.5a206 206 0 1 1 387.2 0" fill="none" filter="url(#remote-cache-gauge-glow)" pathLength="100" stroke="url(#remote-cache-gauge-gradient)" stroke-dasharray="80.95 19.05" stroke-linecap="butt" stroke-width="21"></path></g><g mask="url(#remote-cache-gauge-segment-mask)"><g mask="url(#remote-cache-gauge-end-fade-mask)"><path d="M46.4 310.5a206 206 0 1 1 387.2 0" fill="none" stroke="var(--ds-gray-alpha-300)" stroke-linecap="butt" stroke-width="18"></path><g mask="url(#remote-cache-gauge-inner-indicator-mask)"><path class="opacity-30 dark:opacity-25" d="M54.9 307.4a197 197 0 1 1 370.2 0L240 240Z" fill="url(#remote-cache-gauge-inner-gradient)" mask="url(#remote-cache-gauge-fade-mask)"></path></g><g mask="url(#remote-cache-gauge-inner-remainder-mask)"><path class="opacity-30 dark:opacity-20" d="M54.9 307.4a197 197 0 1 1 370.2 0L240 240Z" fill="var(--ds-gray-alpha-500)" mask="url(#remote-cache-gauge-fade-mask)"></path></g><path d="M46.4 310.5a206 206 0 1 1 387.2 0" fill="none" pathLength="100" stroke="url(#remote-cache-gauge-gradient)" stroke-dasharray="80.95 19.05" stroke-linecap="butt" stroke-width="18"></path></g></g><g class="mix-blend-multiply dark:mix-blend-normal" stroke="var(--remote-cache-tick-color)" stroke-width="1"><line x1="58.85" x2="51.14" y1="290.27" y2="292.41"></line><line x1="55.47" x2="47.61" y1="275.94" y2="277.47"></line><line x1="53.22" x2="45.27" y1="261.38" y2="262.29"></line><line x1="52.12" x2="44.12" y1="246.69" y2="246.98"></line><line x1="52.17" x2="44.18" y1="231.97" y2="231.62"></line><line x1="53.38" x2="45.44" y1="217.29" y2="216.32"></line><line x1="59.21" x2="51.52" y1="188.44" y2="186.24"></line><line x1="63.8" x2="56.3" y1="174.44" y2="171.65"></line><line x1="69.47" x2="62.22" y1="160.85" y2="157.48"></line><line x1="76.19" x2="69.22" y1="147.75" y2="143.82"></line><line x1="83.92" x2="77.27" y1="135.21" y2="130.75"></line><line x1="92.6" x2="86.33" y1="123.31" y2="118.34"></line><line x1="112.62" x2="107.2" y1="101.73" y2="95.85"></line><line x1="123.83" x2="118.89" y1="92.18" y2="85.89"></line><line x1="135.76" x2="131.33" y1="83.54" y2="76.89"></line><line x1="148.33" x2="144.43" y1="75.86" y2="68.88"></line><line x1="161.46" x2="158.12" y1="69.19" y2="61.92"></line><line x1="175.07" x2="172.31" y1="63.57" y2="56.06"></line><line x1="203.41" x2="201.85" y1="55.6" y2="47.75"></line><line x1="217.95" x2="217.01" y1="53.3" y2="45.35"></line><line x1="232.64" x2="232.32" y1="52.14" y2="44.15"></line><line x1="247.36" x2="247.68" y1="52.14" y2="44.15"></line><line x1="262.05" x2="262.99" y1="53.3" y2="45.35"></line><line x1="276.59" x2="278.15" y1="55.6" y2="47.75"></line><line x1="304.93" x2="307.69" y1="63.57" y2="56.06"></line><line x1="318.54" x2="321.88" y1="69.19" y2="61.92"></line><line x1="331.67" x2="335.57" y1="75.86" y2="68.88"></line><line x1="344.24" x2="348.67" y1="83.54" y2="76.89"></line><line x1="356.17" x2="361.11" y1="92.18" y2="85.89"></line><line x1="367.38" x2="372.8" y1="101.73" y2="95.85"></line><line x1="387.4" x2="393.67" y1="123.31" y2="118.34"></line><line x1="396.08" x2="402.73" y1="135.21" y2="130.75"></line><line x1="403.81" x2="410.78" y1="147.75" y2="143.82"></line><line x1="410.53" x2="417.78" y1="160.85" y2="157.48"></line><line x1="416.2" x2="423.7" y1="174.44" y2="171.65"></line><line x1="420.79" x2="428.48" y1="188.44" y2="186.24"></line><line x1="426.62" x2="434.56" y1="217.29" y2="216.32"></line><line x1="427.83" x2="435.82" y1="231.97" y2="231.62"></line><line x1="427.88" x2="435.88" y1="246.69" y2="246.98"></line><line x1="426.78" x2="434.73" y1="261.38" y2="262.29"></line><line x1="424.53" x2="432.39" y1="275.94" y2="277.47"></line><line x1="421.15" x2="428.86" y1="290.27" y2="292.41"></line><line x1="416.66" x2="424.18" y1="304.3" y2="307.04"></line></g><g transform="translate(1 2)"><g transform="rotate(178.09 240 240)"><path d="M236.58 230.6 103.74 289.59 243.42 249.4Z" fill="black" fill-opacity="0.22" filter="url(#remote-cache-gauge-pointer-shadow-blur)"></path></g></g><g transform="rotate(178.09 240 240)"><path d="M236.58 230.6 103.74 289.59 243.42 249.4Z" fill="url(#remote-cache-gauge-pointer-gradient)"></path><path d="M236.58 230.6 103.74 289.59" fill="none" stroke="white" stroke-opacity="0.16" stroke-width="0.75"></path></g><g><circle cx="240" cy="240" fill="var(--ds-gray-alpha-500)" r="20"></circle><circle cx="240" cy="240" fill="url(#remote-cache-gauge-dot-gradient)" r="18"></circle><ellipse cx="235" cy="233.5" fill="white" fill-opacity="0.16" rx="7" ry="3" transform="rotate(-25 235 233.5)"></ellipse><circle cx="240" cy="240" fill="url(#remote-cache-gauge-pin-gradient)" r="7" stroke="var(--ds-gray-alpha-500)" stroke-width="1"></circle></g></svg></div>
+ </div>
+ </section>
+ <dl class="tr-stats">
+ <div class="min-w-0 tr-stat">
+ <dt class="tr-stat__value tr-stat__value--gradient"><span class="inline-block tabular-nums min-w-0 text-[inherit] leading-[inherit] font-[inherit] tracking-[inherit]">12,434,353</span></dt>
+ <dd class="tr-stat__label">Compute hours saved<span class="tr-wide-only"> with Remote Caching</span></dd>
+ </div>
+ <div class="min-w-0 tr-stat tr-stat--end">
+ <dt class="tr-stat__value">42.5M</dt>
+ <dd class="tr-stat__label">Weekly downloads</dd>
+ </div>
+ <div class="min-w-0 tr-stat tr-stat--end">
+ <dt class="tr-stat__value">31.3K</dt>
+ <dd class="tr-stat__label">GitHub stars</dd>
+ </div>
+ <div class="min-w-0 tr-stat tr-stat--end">
+ <dt class="tr-stat__value">2</dt>
+ <dd class="tr-stat__label">Open issues</dd>
+ </div>
+ </dl>
+ </div>
+ </main>
+</body>
+</html>
diff --git a/site/public/examples/turborepo-gauge/src/hero.css b/site/public/examples/turborepo-gauge/src/hero.css
new file mode 100644
index 0000000..8c9739d
--- /dev/null
+++ b/site/public/examples/turborepo-gauge/src/hero.css
@@ -0,0 +1,181 @@
+/* turborepo.com hero and stats row. Sizes, colours and type come from the computed styles of the original at
+ 1440x900 (its Geist design-system tokens, which it writes in lab()), in its light and dark themes.
+ The fonts are the Geist and Geist Mono files turborepo.com serves (SIL OFL 1.1, assets/fonts/LICENSE-geist.txt);
+ other Geist builds set these words up to 1.6px narrower. */
+
+@font-face {
+ font-family: "GeistSans";
+ src: url("../assets/fonts/Geist-Variable.woff2") format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+}
+@font-face {
+ font-family: "GeistMono";
+ src: url("../assets/fonts/GeistMono-Variable.woff2") format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+}
+
+:root {
+ --ds-background-100: lab(100% 0 0);
+ --ds-background-200: lab(98.144% 0 0);
+ --ds-gray-100: lab(95.476% 0 0);
+ --ds-gray-400: lab(92.692% 0 0);
+ --ds-gray-500: lab(80.976% 0 0);
+ --ds-gray-700: lab(59.4% 0 0);
+ --ds-gray-800: lab(52.44% 0 0);
+ --ds-gray-900: lab(32.72% 0 0);
+ --ds-gray-1000: lab(7.78201% 0 0);
+ --ds-gray-alpha-100: lab(0% 0 0 / .05);
+ --ds-gray-alpha-200: lab(0% 0 0 / .081);
+ --ds-gray-alpha-300: lab(0% 0 0 / .1);
+ --ds-gray-alpha-500: lab(0% 0 0 / .21);
+ --ds-shadow-border-small: 0 0 0 1px #00000014, 0px 2px 2px #0000000a, 0 0 0 1px var(--ds-background-200);
+ --sans: "GeistSans", ui-sans-serif, system-ui, sans-serif;
+ --mono: "GeistMono", ui-monospace, SFMono-Regular, Menlo, monospace;
+}
+
+*, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; }
+html { -webkit-text-size-adjust: 100%; }
+body {
+ min-height: 100vh;
+ background: var(--ds-background-200);
+ color: lab(2.75381% 0 0);
+ font: 400 16px/24px var(--sans);
+ font-feature-settings: "calt" 0, "rlig", "ss05";
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+button { font: inherit; color: inherit; background: transparent; cursor: pointer; }
+
+/* the site header is 64px tall; the hero starts below it */
+.tr-page { padding: 64px 0 128px; background: var(--ds-background-200); }
+.tr-container { width: 100%; max-width: 1448px; margin: 0 auto; padding: 0 24px; }
+
+/* ---------- hero ---------- */
+.tr-hero { position: relative; display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); align-items: center; padding: 160px 0; }
+.tr-hero__copy { position: relative; z-index: 1; grid-column: span 7 / span 7; display: flex; flex-direction: column; justify-content: center; padding-right: 64px; }
+.tr-hero__visual { position: relative; order: 9999; grid-column: span 5 / span 5; display: flex; align-items: center; justify-content: center; width: 100%; min-height: 320px; margin: 0 auto; }
+
+.tr-title { max-width: 700px; font-size: 64px; line-height: 64px; font-weight: 450; letter-spacing: -0.06em; }
+.tr-lede { margin-top: 24px; font-size: 18px; line-height: 28px; color: var(--ds-gray-900); text-wrap: balance; }
+
+.tr-install { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; width: 100%; margin-top: 16px; }
+.tr-toggle { display: flex; align-items: center; }
+.tr-toggle__button {
+ display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-radius: 4px; white-space: nowrap; touch-action: manipulation;
+ font-size: 13px; line-height: 16px; font-weight: 500; color: var(--ds-gray-900);
+ outline: 2px solid transparent; outline-offset: 2px;
+}
+.tr-toggle__button:hover, .tr-toggle__button[data-active] { color: var(--ds-gray-1000); }
+.tr-toggle__divider { width: 1px; height: 12px; background: var(--ds-gray-400); }
+
+.tr-command {
+ position: relative; display: flex; align-items: center; gap: 4px; max-width: calc(100vw - 48px);
+ padding: 8px 12px 8px 20px; border-radius: 9999px;
+ background: var(--ds-background-100); box-shadow: var(--ds-shadow-border-small);
+ transition: color 150ms cubic-bezier(.4, 0, .2, 1), background-color 150ms cubic-bezier(.4, 0, .2, 1);
+}
+.tr-command__prompt { display: block; padding-right: 4px; color: var(--ds-gray-500); font-family: var(--mono); font-size: 16px; line-height: 20px; }
+.tr-command__text { position: relative; display: block; min-width: 0; overflow: hidden; color: var(--ds-gray-1000); font-family: var(--mono); font-size: 14px; line-height: 20px; }
+.tr-command__sizer { position: absolute; visibility: hidden; pointer-events: none; white-space: nowrap; }
+.tr-command__value { display: block; min-width: 0; padding: 8px 0; white-space: nowrap; overflow-x: hidden; }
+.tr-command__copy {
+ position: relative; display: flex; flex-shrink: 0; align-items: center; justify-content: center; width: 32px; height: 32px;
+ border-radius: 9999px; color: var(--ds-gray-1000); translate: 2px 0; touch-action: manipulation;
+ outline: 2px solid transparent; outline-offset: 2px;
+ transition: color 150ms cubic-bezier(.4, 0, .2, 1), background-color 150ms cubic-bezier(.4, 0, .2, 1);
+}
+.tr-command:hover .tr-command__copy { background: var(--ds-gray-alpha-100); }
+.tr-command .tr-command__copy:hover { background: var(--ds-gray-alpha-200); }
+.tr-command__icon { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; }
+.tr-command__icon svg { display: block; }
+
+/* ---------- the gauge (turborepo.com's SVG, with the utility classes it carries) ---------- */
+.tr-gauge {
+ position: relative; width: 100%; max-width: 500px; aspect-ratio: 24 / 17;
+ --remote-cache-inner-start: #0196FF;
+ --remote-cache-inner-end: #FF1E56;
+ --remote-cache-tick-color: var(--ds-gray-alpha-500);
+}
+.tr-gauge > svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
+.tr-gauge .opacity-25 { opacity: .25; }
+.tr-gauge .opacity-30 { opacity: .3; }
+.tr-gauge .mix-blend-multiply { mix-blend-mode: multiply; }
+
+/* ---------- stats ---------- */
+.tr-stats { display: grid; grid-template-columns: 1.6fr repeat(3, minmax(0, 1fr)); gap: 40px 48px; padding: 48px 0; }
+.tr-stat { min-width: 0; }
+.tr-stat--end { justify-self: end; }
+.tr-stat__value { font-size: 64px; line-height: 64px; font-weight: 450; letter-spacing: -0.02em; color: var(--ds-gray-1000); }
+.tr-stat__value--gradient {
+ display: inline-block; padding-right: 4px; color: transparent;
+ background-image: linear-gradient(to right in oklab, #FF1E56, #0196FF);
+ -webkit-background-clip: text; background-clip: text;
+}
+.tr-stat__value .tabular-nums { display: inline-block; min-width: 0; font-variant-numeric: tabular-nums; }
+.tr-stat__label { font-size: 16px; line-height: 24px; color: var(--ds-gray-1000); white-space: nowrap; }
+
+/* the dark theme, which turborepo.com follows from the system setting; the gauge's SVG carries its own dark: classes */
+@media (prefers-color-scheme: dark) {
+ :root {
+ --ds-background-100: lab(0% 0 0);
+ --ds-background-200: lab(.0177803% 0 0);
+ --ds-gray-100: lab(9.288% 0 0);
+ --ds-gray-400: lab(18.916% 0 0);
+ --ds-gray-500: lab(29.24% 0 0);
+ --ds-gray-900: lab(65.896% 0 0);
+ --ds-gray-1000: lab(93.736% 0 0);
+ --ds-gray-alpha-100: lab(100% 0 0 / .07);
+ --ds-gray-alpha-200: lab(100% 0 0 / .09);
+ --ds-gray-alpha-300: lab(100% 0 0 / .13);
+ --ds-gray-alpha-500: lab(100% 0 0 / .24);
+ --ds-gray-alpha-600: lab(100% 0 0 / .51);
+ --ds-shadow-border-small: 0 0 0 1px #ffffff25, 0px 1px 2px #00000029, 0 0 0 1px var(--ds-background-200);
+ }
+ body { color: lab(98.26% 0 0); }
+ .tr-gauge {
+ --remote-cache-inner-start: #52C7FF;
+ --remote-cache-inner-end: #FF5C9A;
+ --remote-cache-tick-color: var(--ds-gray-alpha-600);
+ }
+ .tr-gauge .dark\:opacity-40 { opacity: .4; }
+ .tr-gauge .dark\:opacity-25 { opacity: .25; }
+ .tr-gauge .dark\:opacity-20 { opacity: .2; }
+ .tr-gauge .dark\:mix-blend-screen { mix-blend-mode: screen; }
+ .tr-gauge .dark\:mix-blend-normal { mix-blend-mode: normal; }
+}
+
+/* turborepo.com's breakpoints, so the page still reads on a phone */
+@media (max-width: 1279.98px) {
+ .tr-title { font-size: 48px; line-height: 56px; letter-spacing: -2.88px; }
+}
+@media (max-width: 1023.98px) {
+ .tr-hero { grid-template-columns: minmax(0, 1fr); gap: 48px; padding: 0; }
+ .tr-hero__copy { grid-column: auto; padding-right: 0; }
+ .tr-hero__visual { grid-column: auto; order: -9999; min-height: 224px; padding-top: 40px; }
+ .tr-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 40px 32px; padding: 40px 0; }
+ .tr-stat--end { justify-self: auto; }
+ .tr-stat__value { font-size: 40px; line-height: 48px; }
+ .tr-wide-only { display: none; }
+}
+@media (max-width: 639.98px) {
+ .tr-container { padding: 0 16px; }
+ .tr-title { font-size: 40px; line-height: 48px; letter-spacing: -2.4px; }
+ .tr-stats { column-gap: 12px; }
+ .tr-stat__value { font-size: 32px; line-height: 40px; }
+ .tr-stat__label { white-space: normal; }
+}
+
+/* ?embed: the gauge and the counter, centred, at their desktop size */
+html[data-embed] { overflow: hidden; }
+html[data-embed] .tr-page { padding: 28px 0 0; }
+html[data-embed] .tr-hero { display: block; padding: 0; }
+html[data-embed] .tr-hero__copy,
+html[data-embed] .tr-stat--end { display: none; }
+html[data-embed] .tr-hero__visual { min-height: 0; padding: 0; }
+html[data-embed] .tr-stats { display: block; padding: 20px 0 0; text-align: center; }
+html[data-embed] .tr-stat__value { font-size: 56px; line-height: 64px; }
+html[data-embed] .tr-wide-only { display: inline; }
diff --git a/site/public/examples/turborepo-gauge/src/hero.js b/site/public/examples/turborepo-gauge/src/hero.js
new file mode 100644
index 0000000..8ca8295
--- /dev/null
+++ b/site/public/examples/turborepo-gauge/src/hero.js
@@ -0,0 +1,158 @@
+// turborepo.com's hero gauge and compute-hours counter, ported from the page's own components
+// (RemoteCacheGauge and RemoteCacheCounterClient) without React.
+//
+// On turborepo.com every animated value goes through React state: a frame computes it, and React writes it
+// to the DOM in a scheduler task after that frame, so it is painted one frame later. `commit` does the same
+// with a MessageChannel, so the copy paints each value in the same frame as the original. `after(n, run)`
+// waits n such tasks, as many as React takes between an event and the effect that starts the animation.
+
+const commit = (() => {
+ const channel = new MessageChannel();
+ const queue = [];
+ channel.port1.onmessage = () => { for (const run of queue.splice(0)) run(); };
+ return (run) => { if (queue.push(run) === 1) channel.port2.postMessage(0); };
+})();
+const after = (n, run) => (n ? commit(() => after(n - 1, run)) : run());
+
+const reduced = matchMedia("(prefers-reduced-motion: reduce)");
+const round2 = (x) => Math.round(100 * x) / 100;
+
+// ---------- the gauge ----------
+// The value is 0..100 along the arc. At rest the needle sits at 80.952; while the pointer is on the gauge it
+// revs to 98. A spring (stiffness 520, damping 22, mass 1) moves it there, stepped once per frame with
+// semi-implicit Euler: the first step after a change is 1/60 s, later ones the frame time, capped at 1/30 s.
+// It overshoots past 100 on the way up, where the drawing clamps, and stops once within 0.01 of the target.
+const REST = 80.952;
+const REVVED = 98;
+
+const svg = document.querySelector('svg[viewBox="0 0 480 340"]');
+const gauge = svg.parentElement;
+const dashed = [
+ svg.querySelector('path[filter="url(#remote-cache-gauge-glow)"]'), // the glow under the arc
+ svg.querySelector('#remote-cache-gauge-inner-indicator-mask path'), // the tinted inside, up to the needle
+ svg.querySelector('path[stroke="url(#remote-cache-gauge-gradient)"]:not([filter])'), // the arc
+];
+const remainder = svg.querySelector("#remote-cache-gauge-inner-remainder-mask path"); // the grey inside, past it
+const needles = svg.querySelectorAll('g[transform^="rotate"]'); // the needle and its shadow
+
+let shown = "";
+function draw(value) {
+ const u = round2(Math.min(100, Math.max(0, value)));
+ const c = round2(100 - u);
+ const key = `${u} ${c}`;
+ if (key === shown) return;
+ shown = key;
+ for (const path of dashed) path.setAttribute("stroke-dasharray", key);
+ remainder.setAttribute("stroke-dasharray", `0 ${u} ${c} 0`);
+ for (const g of needles) g.setAttribute("transform", `rotate(${round2(2.2 * u)} 240 240)`);
+}
+
+const needle = { target: REST, x: REST, v: 0, raf: 0, last: 0 };
+function step(now) {
+ const n = needle;
+ const dt = n.last ? Math.min((now - n.last) / 1000, 1 / 30) : 1 / 60;
+ const a = 520 * (n.target - n.x) - 22 * n.v;
+ n.v += a * dt;
+ n.x += n.v * dt;
+ n.last = now;
+ if (Math.abs(n.target - n.x) < 0.01 && Math.abs(n.v) < 0.01) {
+ n.x = n.target;
+ n.v = 0;
+ } else {
+ n.raf = requestAnimationFrame(step);
+ }
+ const x = n.x;
+ commit(() => draw(x));
+}
+function rev(on) {
+ const target = on ? REVVED : REST;
+ if (target === needle.target) return;
+ needle.target = target;
+ cancelAnimationFrame(needle.raf);
+ if (reduced.matches) {
+ needle.x = target;
+ needle.v = 0;
+ draw(target);
+ return;
+ }
+ needle.last = 0;
+ needle.raf = requestAnimationFrame(step);
+}
+
+// Pointer in and out on a desktop; on a phone (as on turborepo.com, up to 767px wide) a tap toggles it.
+// Embedded, the frame is narrow on any screen, so it goes by whether the device can hover.
+const narrow = matchMedia("embed" in document.documentElement.dataset ? "(hover: none)" : "(max-width: 767px)");
+let revved = false;
+// render, effect (sets the target), render, effect (starts the spring)
+const set = (on) => { revved = on; after(4, () => rev(on)); };
+gauge.addEventListener("mouseenter", () => { if (!narrow.matches) set(true); });
+gauge.addEventListener("mouseleave", () => { if (!narrow.matches) set(false); });
+gauge.addEventListener("click", () => { if (narrow.matches) set(!revved); });
+
+// ---------- the counter ----------
+// The page renders 12,434,353 hours on the server. Once it hydrates it fetches /api/remote-cache-minutes-saved
+// and every 10 s after that, and tweens the number from wherever it is to total / 60 over 1.2 s with
+// easeOutCubic. The copy has no server: it uses the total turborepo.com returned on 30 Oct 2026 at
+// 15:41 UTC (22,579,753 hours), adds the 15.9 hours it grew by per 10 s then, and waits as long as the
+// original's hydration (90 ms after the first frame) and fetch (330 ms) took.
+const SERVER_RENDERED = 0xbdbbb1; // 12,434,353
+const TOTAL_MINUTES = 1354785180;
+const GROWTH_PER_POLL = 15.9; // hours
+const POLL_MS = 10000;
+const HYDRATE_MS = 90;
+const FETCH_MS = 330;
+const DURATION = 1200;
+const easeOutCubic = (t) => (t - 1) ** 3 + 1;
+const format = Intl.NumberFormat(undefined, { maximumFractionDigits: 0 });
+
+const number = document.querySelector("main dl dt span");
+const count = { value: SERVER_RENDERED, raf: 0 };
+function tweenTo(target) {
+ cancelAnimationFrame(count.raf);
+ const from = count.value;
+ if (from === target) return;
+ if (reduced.matches) {
+ count.value = target;
+ number.textContent = format.format(target);
+ return;
+ }
+ let start = null;
+ const frame = (now) => {
+ if (start === null) start = now;
+ const t = Math.min(1, Math.max(0, (now - start) / DURATION));
+ const value = from + (target - from) * easeOutCubic(t);
+ count.value = value;
+ commit(() => { number.textContent = format.format(value); });
+ if (t < 1) count.raf = requestAnimationFrame(frame);
+ };
+ count.raf = requestAnimationFrame(frame);
+}
+
+requestAnimationFrame(() => {
+ setTimeout(() => {
+ let polls = 0;
+ const poll = () => {
+ const hours = TOTAL_MINUTES / 60 + polls++ * GROWTH_PER_POLL;
+ setTimeout(() => after(2, () => tweenTo(hours)), FETCH_MS); // render, effect (starts the tween)
+ };
+ poll();
+ setInterval(poll, POLL_MS);
+ }, HYDRATE_MS);
+});
+
+// ---------- the install command ----------
+const buttons = document.querySelectorAll(".tr-toggle__button");
+const command = document.querySelectorAll(".tr-command__sizer, .tr-command__value");
+for (const button of buttons) {
+ button.addEventListener("click", () => {
+ for (const b of buttons) {
+ const on = b === button;
+ b.setAttribute("aria-pressed", String(on));
+ b.toggleAttribute("data-active", on);
+ }
+ for (const el of command) el.textContent = button.dataset.command;
+ });
+}
+document.querySelector(".tr-command__copy").addEventListener("click", () => {
+ navigator.clipboard?.writeText(command[0].textContent).catch(() => {});
+});
diff --git a/site/public/examples/vercel-fluid/assets/fallback-dark.webp b/site/public/examples/vercel-fluid/assets/fallback-dark.webp
new file mode 100644
index 0000000..9a3bdc3
Binary files /dev/null and b/site/public/examples/vercel-fluid/assets/fallback-dark.webp differ
diff --git a/site/public/examples/vercel-fluid/assets/fallback-light.webp b/site/public/examples/vercel-fluid/assets/fallback-light.webp
new file mode 100644
index 0000000..e3d70b5
Binary files /dev/null and b/site/public/examples/vercel-fluid/assets/fallback-light.webp differ
diff --git a/site/public/examples/vercel-fluid/assets/fonts/GeistSans-Variable.woff2 b/site/public/examples/vercel-fluid/assets/fonts/GeistSans-Variable.woff2
new file mode 100644
index 0000000..1864b37
Binary files /dev/null and b/site/public/examples/vercel-fluid/assets/fonts/GeistSans-Variable.woff2 differ
diff --git a/site/public/examples/vercel-fluid/assets/fonts/LICENSE-geist.txt b/site/public/examples/vercel-fluid/assets/fonts/LICENSE-geist.txt
new file mode 100644
index 0000000..8d003fe
--- /dev/null
+++ b/site/public/examples/vercel-fluid/assets/fonts/LICENSE-geist.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2023 Vercel, in collaboration with basement.studio
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/public/examples/vercel-fluid/index.html b/site/public/examples/vercel-fluid/index.html
new file mode 100644
index 0000000..081eab9
--- /dev/null
+++ b/site/public/examples/vercel-fluid/index.html
@@ -0,0 +1,53 @@
+<!doctype html>
+<!--
+ vercel.com/fluid hero ocean, rebuilt with reanimate.
+ A field of tiny dots, snapped to a 4.4 px grid, rolls like a slow sea across the hero. On
+ vercel.com it is an FFT ocean simulated and drawn with WebGPU in a worker; here it is the same
+ worker, ported: the site's own WGSL, constants and seeded noise, so it draws the same frames.
+ It fades in over 700 ms once the first frame is ready. Without WebGPU, or with reduced motion,
+ a still of the same ocean fades in instead (see src/main.js).
+-->
+<html lang="en" class="light-theme">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>vercel.com/fluid hero ocean, rebuilt with reanimate</title>
+ <meta name="robots" content="noindex">
+ <script>
+ // vercel.com follows the system theme with a class on <html>; the ocean reads it from there
+ (() => {
+ const dark = matchMedia("(prefers-color-scheme: dark)");
+ const apply = () => document.documentElement.classList.replace(dark.matches ? "light-theme" : "dark-theme", dark.matches ? "dark-theme" : "light-theme");
+ apply();
+ dark.addEventListener("change", apply);
+ })();
+ </script>
+ <link rel="preload" href="./assets/fonts/GeistSans-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="stylesheet" href="./src/fluid.css">
+ <script type="module" src="./src/main.js"></script>
+</head>
+<body>
+ <main>
+ <div class="relative isolate">
+ <!-- src/main.js mounts the ocean canvas (or its still) in here -->
+ <div aria-hidden="true" data-ocean-hero="true" class="pointer-events-none absolute inset-0 -z-10 overflow-hidden select-none"></div>
+ <div class="hero__container">
+ <div class="relative isolate">
+ <div class="grid-cols-12">
+ <div class="hero__main">
+ <h1 class="hero__title">The power of servers, in serverless form</h1>
+ <div class="hero__actions">
+ <a class="hero__button" href="https://vercel.com/docs/fluid-compute"><span>Enable Fluid</span></a>
+ <a class="hero__button hero__button--secondary" href="https://vercel.com/contact/sales"><span>Request demo</span></a>
+ </div>
+ </div>
+ <div class="hero__side">
+ <div class="text-copy-20">Fluid compute combines the efficiency of servers and the flexibility of serverless, enabling real-time, dynamic workloads like APIs, streaming, and AI.</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </main>
+</body>
+</html>
diff --git a/site/public/examples/vercel-fluid/src/fluid.css b/site/public/examples/vercel-fluid/src/fluid.css
new file mode 100644
index 0000000..f3946fa
--- /dev/null
+++ b/site/public/examples/vercel-fluid/src/fluid.css
@@ -0,0 +1,207 @@
+/* vercel.com/fluid's hero at the sizes and colours it computes to (Geist design tokens), light and
+ dark. The few utility classes the ocean layer uses keep vercel.com's names. */
+
+@font-face {
+ font-family: "GeistSans";
+ src: url(../assets/fonts/GeistSans-Variable.woff2) format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: swap;
+}
+/* vercel.com's metric-matched stand-in: the hero is the same height before and after the font loads,
+ so the ocean is measured right the first time */
+@font-face {
+ font-family: "GeistSans Fallback";
+ src: local("Arial");
+ ascent-override: 94.56%;
+ descent-override: 27.76%;
+ line-gap-override: 0%;
+ size-adjust: 106.28%;
+}
+
+:root {
+ /* Geist tokens as vercel.com defines them (hsla, so the text edges round the same way) */
+ --background: hsla(0, 0%, 98%, 1);
+ --gray-1000: hsla(0, 0%, 9%, 1);
+ --gray-900: hsla(0, 0%, 30%, 1);
+ --button-bg: hsla(0, 0%, 9%, 1);
+ --button-fg: hsla(0, 0%, 100%, 1);
+ --button2-bg: hsla(0, 0%, 100%, 1);
+ --button2-fg: hsla(0, 0%, 9%, 1);
+ --button2-ring: hsla(0, 0%, 92%, 1);
+ color-scheme: light;
+}
+.dark-theme {
+ --background: hsla(0, 0%, 0%, 1);
+ --gray-1000: hsla(0, 0%, 93%, 1);
+ --gray-900: hsla(0, 0%, 63%, 1);
+ --button-bg: hsla(0, 0%, 93%, 1);
+ --button-fg: hsla(0, 0%, 4%, 1);
+ --button2-bg: hsla(0, 0%, 4%, 1);
+ --button2-fg: hsla(0, 0%, 93%, 1);
+ --button2-ring: hsla(0, 0%, 18%, 1);
+ color-scheme: dark;
+}
+
+*,
+*::before,
+*::after {
+ box-sizing: border-box;
+}
+html {
+ background: var(--background);
+}
+body {
+ margin: 0;
+ background: var(--background);
+ color: var(--gray-1000);
+ font-family: GeistSans, "GeistSans Fallback", sans-serif;
+ font-size: 16px;
+ line-height: 24px;
+ font-feature-settings: "calt" 0, "rlig", "ss11";
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+/* ---------- the ocean layer (class names as on vercel.com) ---------- */
+
+.relative { position: relative; }
+.absolute { position: absolute; }
+.isolate { isolation: isolate; }
+.inset-0 { inset: 0; }
+.z-0 { z-index: 0; }
+.z-10 { z-index: 10; }
+.-z-10 { z-index: -10; }
+.h-full { height: 100%; }
+.w-full { width: 100%; }
+.overflow-hidden { overflow: hidden; }
+.pointer-events-none { pointer-events: none; }
+.select-none { user-select: none; -webkit-user-select: none; }
+.opacity-0 { opacity: 0; }
+.opacity-100 { opacity: 1; }
+.transition-opacity {
+ transition-property: opacity;
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-duration: 150ms;
+}
+.duration-700 { transition-duration: 700ms; }
+canvas.absolute { display: block; }
+
+.ocean-fallback { display: block; height: 100%; }
+.ocean-fallback--dark { display: none; }
+.dark-theme .ocean-fallback--light { display: none; }
+.dark-theme .ocean-fallback--dark { display: block; }
+.ocean-fallback__img {
+ display: block;
+ height: 100%;
+ width: auto;
+ max-width: none;
+ margin: 0 auto;
+ object-fit: contain;
+ opacity: 0;
+ transition: opacity 700ms cubic-bezier(0.4, 0, 0.2, 1);
+ mask-image: linear-gradient(to right, transparent 0%, black 6%, black 94%, transparent 100%);
+ -webkit-mask-image: linear-gradient(to right, transparent 0%, black 6%, black 94%, transparent 100%);
+}
+.ocean-fallback__img.is-ready { opacity: 1; }
+@media (prefers-reduced-motion: reduce) {
+ .ocean-fallback__img { transition: none; }
+}
+
+/* ---------- the hero copy ---------- */
+
+.hero__container {
+ container-type: inline-size;
+ max-width: 1448px;
+ margin: 0 auto;
+ padding: 0 24px;
+ overflow: visible;
+}
+.grid-cols-12 {
+ display: grid;
+ grid-template-columns: repeat(12, minmax(0, 1fr));
+ align-items: end;
+ column-gap: 24px;
+ row-gap: 24px;
+ padding: 112px 0 48px;
+}
+.hero__main {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column;
+ gap: 32px;
+}
+.hero__side {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column-reverse;
+ gap: 32px;
+}
+@container (min-width: 64rem) {
+ .grid-cols-12 { padding: 168px 0 72px; }
+ .hero__main { grid-column: 1 / 7; }
+ .hero__side { grid-column: 8 / 13; }
+}
+
+.hero__title {
+ margin: 0;
+ max-width: 14ch;
+ font-size: 40px;
+ line-height: 48px;
+ font-weight: 450;
+ letter-spacing: -0.06em;
+ text-wrap: balance;
+ color: var(--gray-1000);
+}
+@container (min-width: 28rem) {
+ .grid-cols-12 { row-gap: 40px; }
+ .hero__title { font-size: 64px; line-height: 64px; }
+}
+
+.hero__actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 16px;
+}
+.hero__button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ max-width: 100%;
+ height: 40px;
+ padding: 0 12px;
+ border-radius: 9999px;
+ font-size: 16px;
+ line-height: 24px;
+ font-weight: 500;
+ text-decoration: none;
+ transform: translateZ(0); /* vercel.com's translate-z-0: its own layer, which sets how the label is rasterised */
+ background: var(--button-bg);
+ color: var(--button-fg);
+ transition: background 150ms ease-in-out, color 150ms ease-in-out;
+}
+.hero__button span {
+ display: inline-block;
+ padding: 0 6px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.hero__button--secondary {
+ background: var(--button2-bg);
+ color: var(--button2-fg);
+ box-shadow: 0 0 0 1px var(--button2-ring);
+}
+
+.text-copy-20 {
+ max-width: 46ch;
+ font-size: 18px;
+ line-height: 28px;
+ font-weight: 400;
+ text-wrap: balance;
+ color: var(--gray-900);
+}
+@container (min-width: 28rem) {
+ .text-copy-20 { font-size: 20px; line-height: 36px; }
+}
diff --git a/site/public/examples/vercel-fluid/src/main.js b/site/public/examples/vercel-fluid/src/main.js
new file mode 100644
index 0000000..e8e249e
--- /dev/null
+++ b/site/public/examples/vercel-fluid/src/main.js
@@ -0,0 +1,255 @@
+// The hero's ocean, as vercel.com/fluid mounts it. With WebGPU, src/ocean.worker.js renders on an
+// OffscreenCanvas and posts each frame as an ImageBitmap, which is copied onto the visible 2D canvas;
+// the canvas fades in over 700 ms when the first frame arrives. Without WebGPU, with reduced motion,
+// with ?fluidRenderer=static, or when the worker fails, a still of the same ocean fades in instead.
+//
+// The worker starts on load, wherever the hero is, and pauses only once the hero has been on screen
+// and then leaves it (or the tab is hidden): on vercel.com the first "paused" is posted before the
+// worker exists and is lost, and this keeps that.
+
+import { capDpr } from "./settings.js";
+
+const hero = document.querySelector("[data-ocean-hero]");
+const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
+const FALLBACK = {
+ light: new URL("../assets/fallback-light.webp", import.meta.url).href,
+ dark: new URL("../assets/fallback-dark.webp", import.meta.url).href,
+};
+
+/** "dark" or "light", from the theme class on <html> (see index.html), as on vercel.com. */
+function theme() {
+ const c = document.documentElement.classList;
+ return c.contains("dark-theme") || c.contains("dark") ? "dark" : "light";
+}
+
+const el = (tag, className, attrs = {}) => {
+ const e = document.createElement(tag);
+ if (className) e.className = className;
+ for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
+ return e;
+};
+
+function setHero({ mode, state, error }) {
+ hero.dataset.fluidShaderMode = mode;
+ hero.dataset.fluidShaderState = state;
+ if (error) hero.dataset.fluidShaderError = error;
+ else delete hero.dataset.fluidShaderError;
+}
+
+let mounted; // { stop() } of the live renderer or the fallback
+
+function choose() {
+ mounted?.stop();
+ mounted = undefined;
+ if (reducedMotion.matches) return showFallback("main");
+ if (new URLSearchParams(location.search).get("fluidRenderer") === "static") return showFallback();
+ if (navigator.gpu) return startLive();
+ showFallback("main");
+}
+
+// ---------- the static fallback ----------
+
+function showFallback(error) {
+ setHero({ mode: "static", state: "fallback", error });
+ const root = el("div", "absolute inset-0 z-0 overflow-hidden opacity-100", { "data-ocean-static-fallback": "true", "data-ocean-static-fallback-ready": "false" });
+ for (const which of ["light", "dark"]) {
+ const picture = el("picture", `ocean-fallback ocean-fallback--${which}`);
+ const img = el("img", "ocean-fallback__img", { alt: "", width: "1512", height: "436", "aria-hidden": "true", decoding: "async", draggable: "false", src: FALLBACK[which] });
+ const ready = () => {
+ img.classList.add("is-ready");
+ if (which === theme()) root.dataset.oceanStaticFallbackReady = "true";
+ };
+ img.addEventListener("load", () => (img.decode ? img.decode().then(ready, ready) : ready()), { once: true });
+ picture.append(img);
+ root.append(picture);
+ }
+ hero.append(root);
+ mounted = { stop: () => root.remove() };
+}
+
+// ---------- the live renderer ----------
+
+function startLive() {
+ setHero({ mode: "webgpu", state: "starting" });
+ const layer = el("div", "absolute inset-0 z-10", { "data-fluid-shader-renderer": "webgpu", "data-fluid-shader-state": "starting" });
+ const canvas = el("canvas", "absolute inset-0 h-full w-full opacity-0 transition-opacity duration-700");
+ layer.append(canvas);
+ hero.append(layer);
+ Object.assign(canvas.dataset, { fluidShaderReady: "false", fluidShaderRenderer: "webgpu", fluidShaderState: "starting", fluidShaderFramesReceived: "0", fluidShaderFramesDrawn: "0" });
+ canvas.style.opacity = "0";
+
+ const abort = new AbortController();
+ const { signal } = abort;
+ let worker = null;
+ let stopped = false;
+ const send = (message) => worker?.postMessage(message);
+
+ const fail = (reason, stage) => {
+ if (stopped) return;
+ console.warn("[fluid-ocean]", stage, reason);
+ stop();
+ mounted = undefined;
+ showFallback(stage);
+ };
+
+ const ctx = canvas.getContext("2d", { alpha: true });
+ const problem =
+ typeof Worker === "undefined" ? "Worker is unavailable."
+ : typeof OffscreenCanvas === "undefined" ? "OffscreenCanvas is unavailable."
+ : !ctx ? "2D canvas rendering is unavailable."
+ : !navigator.gpu ? "WebGPU is unavailable."
+ : reducedMotion.matches ? "Reduced motion is enabled."
+ : undefined;
+ if (problem) {
+ layer.remove();
+ showFallback("main");
+ return;
+ }
+
+ // Lifecycle: active while on screen (100 px margin) and the tab is visible. The first state is
+ // "paused" and is "sent" before the worker exists, so it never reaches it.
+ let phase = "idle";
+ let intersecting = false;
+ const setPhase = () => {
+ const next = !document.hidden && intersecting ? "active" : "paused";
+ if (next === phase) return;
+ phase = next;
+ send({ type: "lifecycle", lifecycle: next });
+ };
+ setPhase();
+ const io = new IntersectionObserver((entries) => {
+ for (const e of entries) intersecting = e.isIntersecting;
+ setPhase();
+ }, { rootMargin: "100px" });
+ io.observe(layer);
+ document.addEventListener("visibilitychange", setPhase, { signal });
+
+ // Sizes: the backing store is the CSS box × the pixel ratio (capped at 2).
+ const measure = () => {
+ const r = layer.getBoundingClientRect();
+ const dpr = capDpr(window.devicePixelRatio || 1);
+ const cssWidth = Math.max(1, Math.floor(r.width || layer.clientWidth));
+ const cssHeight = Math.max(1, Math.floor(r.height || layer.clientHeight));
+ return { cssWidth, cssHeight, pixelWidth: Math.max(1, Math.floor(cssWidth * dpr)), pixelHeight: Math.max(1, Math.floor(cssHeight * dpr)), dpr };
+ };
+ let size = measure();
+ let drawW = size.pixelWidth;
+ let drawH = size.pixelHeight;
+
+ worker = new Worker(new URL("./ocean.worker.js", import.meta.url), { type: "module" });
+ worker.onerror = (e) => fail(e.message || "Fluid ocean worker failed.", "render");
+ worker.onmessageerror = () => fail("Fluid ocean worker posted an unserializable message.", "render");
+ worker.onmessage = ({ data: m }) => {
+ if (stopped) return;
+ switch (m.type) {
+ case "ready":
+ return;
+ case "firstFrame": {
+ canvas.style.opacity = "1";
+ canvas.dataset.fluidShaderState = "ready";
+ layer.dataset.fluidShaderState = "ready";
+ setHero({ mode: "webgpu", state: "ready" });
+ let done = false;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ canvas.removeEventListener("transitionend", onEnd);
+ if (canvas.isConnected) canvas.dataset.fluidShaderReady = "true";
+ };
+ const onEnd = (e) => e.propertyName === "opacity" && finish();
+ canvas.addEventListener("transitionend", onEnd);
+ const timer = setTimeout(finish, 1300);
+ return;
+ }
+ case "frame": {
+ const bitmap = m.bitmap;
+ canvas.dataset.fluidShaderFramesReceived = String(+canvas.dataset.fluidShaderFramesReceived + 1);
+ canvas.dataset.fluidShaderLastBitmapWidth = String(bitmap.width);
+ canvas.dataset.fluidShaderLastBitmapHeight = String(bitmap.height);
+ try {
+ if (!ctx || drawW < 1 || drawH < 1) return;
+ if (canvas.width !== drawW) canvas.width = drawW;
+ if (canvas.height !== drawH) canvas.height = drawH;
+ // cover: a frame rendered for the previous size is scaled until the next one arrives
+ const k = Math.max(drawW / bitmap.width, drawH / bitmap.height);
+ const w = bitmap.width * k;
+ const h = bitmap.height * k;
+ ctx.globalCompositeOperation = "copy";
+ ctx.drawImage(bitmap, (drawW - w) * 0.5, (drawH - h) * 0.5, w, h);
+ canvas.dataset.fluidShaderFramesDrawn = String(+canvas.dataset.fluidShaderFramesDrawn + 1);
+ } finally {
+ bitmap.close();
+ }
+ return;
+ }
+ case "unsupported":
+ return fail(m.reason, "capabilities");
+ case "error":
+ return fail(`${m.stage}: ${m.reason}`, m.stage);
+ case "disposed":
+ worker?.terminate();
+ worker = null;
+ return;
+ }
+ };
+ send({ type: "init", dimensions: size, theme: theme(), isMobile: matchMedia("(max-width: 1023.98px)").matches });
+
+ // Resizes and pixel-ratio changes reach the worker 150 ms after they settle; the visible canvas
+ // follows at once (the last frame is stretched to cover it meanwhile).
+ let resizeTimer;
+ const pushSize = () => {
+ resizeTimer = undefined;
+ const next = measure();
+ drawW = next.pixelWidth;
+ drawH = next.pixelHeight;
+ if (next.cssWidth !== size.cssWidth || next.cssHeight !== size.cssHeight || next.pixelWidth !== size.pixelWidth || next.pixelHeight !== size.pixelHeight || next.dpr !== size.dpr) {
+ size = next;
+ send({ type: "resize", dimensions: next });
+ }
+ };
+ const resizeSoon = () => {
+ clearTimeout(resizeTimer);
+ resizeTimer = setTimeout(pushSize, 150);
+ };
+ const ro = new ResizeObserver(() => {
+ const next = measure();
+ drawW = next.pixelWidth;
+ drawH = next.pixelHeight;
+ resizeSoon();
+ });
+ ro.observe(layer);
+ let dprQuery;
+ const watchDpr = () => {
+ dprQuery = matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`);
+ dprQuery.addEventListener("change", () => (resizeSoon(), watchDpr()), { once: true, signal });
+ };
+ watchDpr();
+ send({ type: "resize", dimensions: size }); // vercel.com sends one right after init
+
+ const themeObserver = new MutationObserver(() => send({ type: "theme", theme: theme() }));
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
+
+ function stop() {
+ if (stopped) return;
+ stopped = true;
+ abort.abort();
+ io.disconnect();
+ ro.disconnect();
+ themeObserver.disconnect();
+ clearTimeout(resizeTimer);
+ send({ type: "dispose" });
+ worker?.terminate();
+ worker = null;
+ layer.remove();
+ }
+ mounted = { stop };
+}
+
+// vercel.com mounts the ocean after hydration, when the preloaded font is in and the hero has its
+// final height; waiting for the font here gives the first frame the same size.
+const fontReady = Promise.race([document.fonts.load('450 64px "GeistSans"'), new Promise((r) => setTimeout(r, 3000))]).catch(() => {});
+fontReady.then(() => {
+ reducedMotion.addEventListener("change", choose);
+ choose();
+});
diff --git a/site/public/examples/vercel-fluid/src/ocean.worker.js b/site/public/examples/vercel-fluid/src/ocean.worker.js
new file mode 100644
index 0000000..3f76255
--- /dev/null
+++ b/site/public/examples/vercel-fluid/src/ocean.worker.js
@@ -0,0 +1,616 @@
+// The ocean renderer, a port of vercel.com/fluid's ocean worker. It runs off the main thread on an
+// OffscreenCanvas with WebGPU and posts every frame to the page as an ImageBitmap.
+//
+// Each frame: a Tessendorf ocean (a Phillips spectrum from seeded Gaussian noise, advanced in time,
+// then a 2D inverse FFT as 2 × log2(N) render passes) gives a displacement and a normal/foam texture.
+// An N × N grid of dots is displaced by them, projected by a fixed camera, snapped to a square pixel
+// grid and drawn as tiny round sprites. Light theme: black dots with alpha; dark theme: white dots
+// added up, with a bloom. The WGSL is the site's own (shaders.js); the passes, uniform layouts, sizes
+// and the frame loop follow its worker line for line.
+
+import * as WGSL from "./shaders.js";
+import { CAMERA, COLORS, G, LIGHT_DEFAULT, NOISE_SEED, OCEAN_SIZE, PARTICLE_EXTENT, TIME_FACTOR, resolveSettings } from "./settings.js";
+
+const TEX = GPUTextureUsage;
+const SCENE_FORMAT = "rgba16float";
+const SIM_FORMAT = "rgba32float";
+const BLUR_KERNELS = [6, 10, 14, 18, 22];
+// light theme: premultiplied "over"; dark theme: additive
+const BLEND_LIGHT = { color: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" }, alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" } };
+const BLEND_DARK = { color: { srcFactor: "src-alpha", dstFactor: "one", operation: "add" }, alpha: { srcFactor: "one", dstFactor: "one", operation: "add" } };
+
+// ---------- uniforms (byte layouts as on the site) ----------
+
+const floats = (bytes) => new Float32Array(bytes / 4);
+const initialSpectrumUniforms = (s) => {
+ const u = floats(32);
+ u.set([s.particles.resolution, OCEAN_SIZE, s.ocean.windSpeed, s.ocean.windAngle, s.ocean.amplitude, 0, 0, 0]);
+ return u;
+};
+const spectrumUniforms = (s, simTime) => Float32Array.of(s.particles.resolution, OCEAN_SIZE, simTime * TIME_FACTOR, s.ocean.choppiness);
+const ifftUniforms = (n, subtransformSize, horizontal) => Float32Array.of(n, subtransformSize, +!!horizontal, 0);
+const normalFoamUniforms = (s) => {
+ const u = floats(32);
+ u.set([s.particles.resolution, PARTICLE_EXTENT, s.ocean.displacementScale, s.ocean.choppiness, s.ocean.foamThreshold, 0, 0, 0]);
+ return u;
+};
+function blurUniforms(direction, invSize, radius) {
+ const u = floats(112);
+ u.set([direction[0], direction[1], invSize[0], invSize[1]], 0);
+ const coefficients = new Float32Array(24);
+ const sigma = radius / 3;
+ for (let i = 0; i < radius; i += 1) coefficients[i] = (0.39894 * Math.exp((-0.5 * i * i) / (sigma * sigma))) / sigma;
+ u.set(coefficients, 4);
+ return u;
+}
+
+// ---------- matrices (column-major, as the site builds them) ----------
+
+function multiply(a, b) {
+ const r = new Float32Array(16);
+ for (let i = 0; i < 4; i++)
+ for (let n = 0; n < 4; n++) r[4 * i + n] = a[n] * b[4 * i] + a[4 + n] * b[4 * i + 1] + a[8 + n] * b[4 * i + 2] + a[12 + n] * b[4 * i + 3];
+ return r;
+}
+function normalize(v) {
+ const l = Math.hypot(v[0], v[1], v[2]);
+ return l === 0 ? [0, 0, 0] : [v[0] / l, v[1] / l, v[2] / l];
+}
+const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+
+function cameraMatrices(width, height, camera) {
+ const aspect = width / Math.max(1, height);
+ const lift = camera.eyeY - CAMERA.eye[1];
+ const eye = [CAMERA.eye[0], camera.eyeY, CAMERA.eye[2]];
+ const target = [CAMERA.target[0], CAMERA.target[1] + lift, CAMERA.target[2]];
+ const z = normalize([eye[0] - target[0], eye[1] - target[1], eye[2] - target[2]]);
+ const x = normalize(cross(CAMERA.up, z));
+ const y = cross(z, x);
+ const lookAt = new Float32Array([x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, eye), -dot(y, eye), -dot(z, eye), 1]);
+ let view = lookAt;
+ if (camera.pitchDegrees !== 0) {
+ const p = (camera.pitchDegrees * Math.PI) / 180;
+ const c = Math.cos(p);
+ const s = Math.sin(p);
+ view = multiply(new Float32Array([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]), lookAt);
+ }
+ const f = 1 / Math.tan((CAMERA.fovDegrees * Math.PI) / 180 / 2);
+ const projection = new Float32Array(16);
+ projection[0] = f / aspect;
+ projection[5] = f;
+ projection[10] = CAMERA.far / (CAMERA.near - CAMERA.far);
+ projection[11] = -1;
+ projection[14] = (CAMERA.far * CAMERA.near) / (CAMERA.near - CAMERA.far);
+ return { view, projection };
+}
+
+// ---------- the noise: mulberry32 + Box-Muller, seeded, N × N × 4 floats ----------
+
+function gaussianNoise(n, seed = NOISE_SEED) {
+ const out = new Float32Array(n * n * 4);
+ let state = seed >>> 0;
+ const random = () => {
+ let e = (state = (state + 0x6d2b79f5) >>> 0);
+ e = Math.imul(e ^ (e >>> 15), 1 | e);
+ return (((e ^= e + Math.imul(e ^ (e >>> 7), 61 | e)) ^ (e >>> 14)) >>> 0) / 0x100000000;
+ };
+ for (let i = 0; i < out.length; i += 2) {
+ const u = Math.max(random(), 5e-324);
+ const v = random();
+ const r = Math.sqrt(-2 * Math.log(u));
+ const a = 2 * Math.PI * v;
+ out[i] = r * Math.cos(a);
+ if (i + 1 < out.length) out[i + 1] = r * Math.sin(a);
+ }
+ return out;
+}
+
+// ---------- GPU resources ----------
+
+function uniformBuffer(device, data, label) {
+ const buffer = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, label });
+ device.queue.writeBuffer(buffer, 0, data);
+ return buffer;
+}
+const emptyUniform = (device, size, label) => device.createBuffer({ size, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, label });
+const write = (device, buffer, data) => device.queue.writeBuffer(buffer, 0, data);
+const simTexture = (device, n, label) =>
+ device.createTexture({ size: [n, n], format: SIM_FORMAT, usage: TEX.RENDER_ATTACHMENT | TEX.TEXTURE_BINDING | TEX.COPY_SRC | TEX.COPY_DST, label });
+const sceneTexture = (device, width, height, label) =>
+ device.createTexture({ size: [width, height], format: SCENE_FORMAT, usage: TEX.RENDER_ATTACHMENT | TEX.TEXTURE_BINDING | TEX.COPY_SRC, label });
+
+function fullscreenPipeline(device, label, module, format, fragmentExtra = {}) {
+ return device.createRenderPipeline({
+ label,
+ layout: "auto",
+ vertex: { module, entryPoint: "vs_main" },
+ fragment: { module, entryPoint: "fs_main", targets: [{ format }], ...fragmentExtra },
+ primitive: { topology: "triangle-list" },
+ });
+}
+
+function fullscreenPass(encoder, label, view, pipeline, bindGroup) {
+ const pass = encoder.beginRenderPass({ label, colorAttachments: [{ view, loadOp: "clear", storeOp: "store", clearValue: [0, 0, 0, 0] }] });
+ pass.setPipeline(pipeline);
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(3);
+ pass.end();
+}
+
+function createSimulation(device, noise, settings) {
+ const n = settings.particles.resolution;
+ const initialSpectrum = simTexture(device, n, "fluid-full-h0");
+ const spectrum = simTexture(device, n, "fluid-full-spectrum");
+ const ping = simTexture(device, n, "fluid-full-ifft-ping");
+ const pong = simTexture(device, n, "fluid-full-ifft-pong");
+ const normalFoam = simTexture(device, n, "fluid-full-normal-foam");
+ const layout = device.createBindGroupLayout({
+ label: "fluid-full-sim-layout",
+ entries: [
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
+ { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: "unfilterable-float" } },
+ ],
+ });
+ const pipelineLayout = device.createPipelineLayout({ label: "fluid-full-sim-pipeline-layout", bindGroupLayouts: [layout] });
+ const pipeline = (label, module, constants) =>
+ device.createRenderPipeline({
+ label,
+ layout: pipelineLayout,
+ vertex: { module, entryPoint: "vs_main", constants },
+ fragment: { module, entryPoint: "fs_main", constants, targets: [{ format: SIM_FORMAT }] },
+ primitive: { topology: "triangle-list" },
+ });
+ const bind = (label, buffer, texture) =>
+ device.createBindGroup({ label, layout, entries: [{ binding: 0, resource: { buffer } }, { binding: 1, resource: texture.createView() }] });
+
+ const shader = (code) => device.createShaderModule({ code });
+ const ifft = shader(WGSL.IFFT_STAGE); // one module, two pipelines (IFFT_HORIZONTAL overridden)
+ const initialPipeline = pipeline("fluid-full-initial-spectrum", shader(WGSL.INITIAL_SPECTRUM));
+ const spectrumPipeline = pipeline("fluid-full-spectrum", shader(WGSL.SPECTRUM));
+ const horizontalPipeline = pipeline("fluid-full-ifft-horizontal", ifft, { IFFT_HORIZONTAL: 1 });
+ const verticalPipeline = pipeline("fluid-full-ifft-vertical", ifft, { IFFT_HORIZONTAL: 0 });
+ const normalPipeline = pipeline("fluid-full-normal-foam", shader(WGSL.NORMAL_FOAM));
+ const initialUniform = uniformBuffer(device, initialSpectrumUniforms(settings), "fluid-full-initial-spectrum-uniform");
+ const spectrumUniform = uniformBuffer(device, spectrumUniforms(settings, 0), "fluid-full-spectrum-uniform");
+ const normalUniform = uniformBuffer(device, normalFoamUniforms(settings), "fluid-full-normal-foam-uniform");
+ const initialBindGroup = bind("fluid-full-initial-spectrum-bind-group", initialUniform, noise);
+ const spectrumBindGroup = bind("fluid-full-spectrum-bind-group", spectrumUniform, initialSpectrum);
+
+ const stages = Math.log2(n);
+ if (!Number.isInteger(stages)) throw new Error(`resolution must be a power of two, got ${n}`);
+ const ifftSteps = [];
+ const buffers = [];
+ let input = spectrum;
+ let output = ping;
+ let spare = pong;
+ for (const horizontal of [true, false]) {
+ for (let t = 0; t < stages; t += 1) {
+ const name = `fluid-full-ifft-${horizontal ? "horizontal" : "vertical"}-${t}`;
+ const buffer = uniformBuffer(device, ifftUniforms(n, 2 ** (t + 1), horizontal), `${name}-uniform`);
+ buffers.push(buffer);
+ ifftSteps.push({ label: name, output, pipeline: horizontal ? horizontalPipeline : verticalPipeline, bindGroup: bind(`${name}-bind-group`, buffer, input) });
+ input = output;
+ [output, spare] = [spare, output];
+ }
+ }
+ const displacement = input;
+ const normalBindGroup = bind("fluid-full-normal-foam-bind-group", normalUniform, displacement);
+
+ return {
+ displacement,
+ normalFoam,
+ encode(encoder, settings, simTime, needsInitialSpectrum) {
+ write(device, spectrumUniform, spectrumUniforms(settings, simTime));
+ write(device, normalUniform, normalFoamUniforms(settings));
+ if (needsInitialSpectrum) {
+ write(device, initialUniform, initialSpectrumUniforms(settings));
+ fullscreenPass(encoder, "fluid-full-initial-spectrum-pass", initialSpectrum.createView(), initialPipeline, initialBindGroup);
+ }
+ fullscreenPass(encoder, "fluid-full-spectrum-pass", spectrum.createView(), spectrumPipeline, spectrumBindGroup);
+ for (const s of ifftSteps) fullscreenPass(encoder, s.label, s.output.createView(), s.pipeline, s.bindGroup);
+ fullscreenPass(encoder, "fluid-full-normal-foam-pass", normalFoam.createView(), normalPipeline, normalBindGroup);
+ },
+ destroy() {
+ for (const b of [initialUniform, spectrumUniform, normalUniform, ...buffers]) b.destroy();
+ for (const t of [initialSpectrum, spectrum, ping, pong, normalFoam]) t.destroy();
+ },
+ };
+}
+
+function createParticles(device, sim, resolution) {
+ const layout = device.createBindGroupLayout({
+ label: "fluid-particles-bind-group-layout",
+ entries: [
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
+ { binding: 1, visibility: GPUShaderStage.VERTEX, texture: { sampleType: "unfilterable-float" } },
+ { binding: 2, visibility: GPUShaderStage.VERTEX, texture: { sampleType: "unfilterable-float" } },
+ ],
+ });
+ const pipelineLayout = device.createPipelineLayout({ label: "fluid-particles-pipeline-layout", bindGroupLayouts: [layout] });
+ const pipeline = (label, code, blend) => {
+ const shader = device.createShaderModule({ code });
+ return device.createRenderPipeline({
+ label,
+ layout: pipelineLayout,
+ vertex: { module: shader, entryPoint: "vs_main" },
+ fragment: { module: shader, entryPoint: "fs_main", targets: [{ format: SCENE_FORMAT, blend }] },
+ primitive: { topology: "triangle-strip" },
+ });
+ };
+ const dark = pipeline("fluid-particles-pass-dark", WGSL.PARTICLES_DARK, BLEND_DARK);
+ const light = pipeline("fluid-particles-pass-light", WGSL.PARTICLES_LIGHT, BLEND_LIGHT);
+ const uniform = emptyUniform(device, 256, "fluid-particles-uniform");
+ const bindGroup = device.createBindGroup({
+ label: "fluid-particles-bind-group",
+ layout,
+ entries: [
+ { binding: 0, resource: { buffer: uniform } },
+ { binding: 1, resource: sim.displacement.createView() },
+ { binding: 2, resource: sim.normalFoam.createView() },
+ ],
+ });
+ const instances = resolution * resolution;
+ return {
+ encode(encoder, target, o) {
+ const u = floats(256);
+ const s = o.settings;
+ u.set(o.view, 0);
+ u.set(o.projection, 16);
+ u.set([o.width, o.height, o.pixelRatio, s.particles.resolution], 32);
+ u.set([PARTICLE_EXTENT, OCEAN_SIZE, G, 0], 36);
+ u.set([s.particles.fadeNear, s.particles.fadeFar, s.particles.fadePower, s.particles.snap], 40);
+ u.set([...COLORS.ocean, 0], 44);
+ u.set([...COLORS.neon, 0], 48);
+ u.set([...COLORS.foam, 0], 52);
+ u.set([s.ocean.displacementScale, s.particles.pointSize, o.light === undefined ? LIGHT_DEFAULT : +!!o.light, 0], 56);
+ write(device, uniform, u);
+ const pass = encoder.beginRenderPass({ label: "fluid-particles-pass", colorAttachments: [{ view: target.createView(), loadOp: "clear", storeOp: "store", clearValue: [0, 0, 0, 0] }] });
+ pass.setPipeline(o.light ? light : dark);
+ pass.setBindGroup(0, bindGroup, []);
+ pass.draw(4, instances);
+ pass.end();
+ },
+ destroy() {
+ uniform.destroy();
+ },
+ };
+}
+
+function createBloom(device, width, height) {
+ const sizes = [];
+ let w = Math.max(1, Math.round(width / 2));
+ let h = Math.max(1, Math.round(height / 2));
+ for (let i = 0; i < 5; i += 1) {
+ sizes.push({ width: w, height: h });
+ w = Math.max(1, Math.round(w / 2));
+ h = Math.max(1, Math.round(h / 2));
+ }
+ const tex = (size, label) => sceneTexture(device, size.width, size.height, label);
+ const bright = tex(sizes[0], "fluid-bloom-bright");
+ const horizontal = sizes.map((s, i) => tex(s, `fluid-bloom-h${i}`));
+ const vertical = sizes.map((s, i) => tex(s, `fluid-bloom-v${i}`));
+ const composite = tex(sizes[0], "fluid-bloom-composite");
+ const sampler = device.createSampler({ minFilter: "linear", magFilter: "linear" });
+ const brightPipeline = fullscreenPipeline(device, "fluid-bloom-bright", device.createShaderModule({ code: WGSL.BLOOM_BRIGHT }), SCENE_FORMAT);
+ const blurModule = device.createShaderModule({ code: WGSL.BLOOM_BLUR });
+ const blurPipelines = BLUR_KERNELS.map((k) => fullscreenPipeline(device, `fluid-bloom-blur-${k}`, blurModule, SCENE_FORMAT, { constants: { KERNEL_RADIUS: k } }));
+ const compositePipeline = fullscreenPipeline(device, "fluid-bloom-composite", device.createShaderModule({ code: WGSL.BLOOM_COMPOSITE }), SCENE_FORMAT);
+ const brightUniform = emptyUniform(device, 16, "fluid-bloom-bright-uniform");
+ const hUniforms = BLUR_KERNELS.map((_, i) => emptyUniform(device, 112, `fluid-bloom-blur-h-uniform-${i}`));
+ const vUniforms = BLUR_KERNELS.map((_, i) => emptyUniform(device, 112, `fluid-bloom-blur-v-uniform-${i}`));
+ const compositeUniform = emptyUniform(device, 48, "fluid-bloom-composite-uniform");
+ const group = (pipeline, entries) => device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: entries.map((resource, binding) => ({ binding, resource })) });
+
+ return {
+ composite,
+ encode(encoder, scene, settings) {
+ write(device, brightUniform, Float32Array.of(settings.glow.bloomThreshold, 0.01, 0, 0));
+ fullscreenPass(encoder, "fluid-bloom-bright-pass", bright.createView(), brightPipeline, group(brightPipeline, [{ buffer: brightUniform }, scene.createView(), sampler]));
+ let input = bright;
+ for (let i = 0; i < 5; i += 1) {
+ const size = sizes[i];
+ const pipeline = blurPipelines[i];
+ write(device, hUniforms[i], blurUniforms([1, 0], [1 / size.width, 1 / size.height], BLUR_KERNELS[i]));
+ fullscreenPass(encoder, `fluid-bloom-blur-h${i}`, horizontal[i].createView(), pipeline, group(pipeline, [{ buffer: hUniforms[i] }, input.createView(), sampler]));
+ write(device, vUniforms[i], blurUniforms([0, 1], [1 / size.width, 1 / size.height], BLUR_KERNELS[i]));
+ fullscreenPass(encoder, `fluid-bloom-blur-v${i}`, vertical[i].createView(), pipeline, group(pipeline, [{ buffer: vUniforms[i] }, horizontal[i].createView(), sampler]));
+ input = vertical[i];
+ }
+ const c = floats(48);
+ c.set([settings.glow.bloomStrength, settings.glow.bloomRadius, 0, 0], 0);
+ c.set([1, 0.8, 0.6, 0.4, 0.2], 4);
+ write(device, compositeUniform, c);
+ fullscreenPass(encoder, "fluid-bloom-composite-pass", composite.createView(), compositePipeline, group(compositePipeline, [{ buffer: compositeUniform }, ...vertical.map((t) => t.createView()), sampler]));
+ },
+ destroy() {
+ for (const t of [bright, ...horizontal, ...vertical, composite]) t.destroy();
+ for (const b of [brightUniform, ...hUniforms, ...vUniforms, compositeUniform]) b.destroy();
+ },
+ };
+}
+
+function createPresent(device, format) {
+ const sampler = device.createSampler({ minFilter: "linear", magFilter: "linear" });
+ const pipeline = fullscreenPipeline(device, "fluid-present", device.createShaderModule({ code: WGSL.PRESENT }), format);
+ return {
+ encode(encoder, view, scene, bloom) {
+ const bindGroup = device.createBindGroup({
+ layout: pipeline.getBindGroupLayout(0),
+ entries: [
+ { binding: 0, resource: scene.createView() },
+ { binding: 1, resource: bloom.createView() },
+ { binding: 2, resource: sampler },
+ ],
+ });
+ fullscreenPass(encoder, "fluid-present-pass", view, pipeline, bindGroup);
+ },
+ };
+}
+
+function createRenderer(device, format, width, height, settings) {
+ const n = settings.particles.resolution;
+ const noise = simTexture(device, n, "fluid-noise");
+ device.queue.writeTexture({ texture: noise }, gaussianNoise(n), { bytesPerRow: 4 * n * 4, rowsPerImage: n }, { width: n, height: n, depthOrArrayLayers: 1 });
+ const scene = sceneTexture(device, width, height, "fluid-full-scene-hdr");
+ const bloom = createBloom(device, width, height);
+ // the light theme presents the scene with this never-written (all zero) texture as its bloom
+ const blackBloom = sceneTexture(device, Math.max(1, Math.round(width / 2)), Math.max(1, Math.round(height / 2)), "fluid-black-bloom");
+ const present = createPresent(device, format);
+ const sim = createSimulation(device, noise, settings);
+ const particles = createParticles(device, sim, n);
+ return {
+ width,
+ height,
+ format,
+ resolution: n,
+ spectrumKey: undefined,
+ render(view, simTime, settings, pixelRatio, theme, needsInitialSpectrum) {
+ const key = `${settings.particles.resolution}:${settings.ocean.windSpeed}:${settings.ocean.windAngle}:${settings.ocean.amplitude}`;
+ const simEncoder = device.createCommandEncoder({ label: "fluid-full-sim-encoder" });
+ sim.encode(simEncoder, settings, simTime, needsInitialSpectrum || this.spectrumKey !== key);
+ device.queue.submit([simEncoder.finish()]);
+ this.spectrumKey = key;
+
+ const { view: viewMatrix, projection } = cameraMatrices(width, height, settings.camera);
+ const encoder = device.createCommandEncoder({ label: "fluid-full-frame" });
+ particles.encode(encoder, scene, { view: viewMatrix, projection, width, height, pixelRatio, settings, light: theme === "light" });
+ if (theme === "dark") {
+ bloom.encode(encoder, scene, settings);
+ present.encode(encoder, view, scene, bloom.composite);
+ } else {
+ present.encode(encoder, view, scene, blackBloom);
+ }
+ device.queue.submit([encoder.finish()]);
+ },
+ destroy() {
+ particles.destroy();
+ sim.destroy();
+ noise.destroy();
+ bloom.destroy();
+ blackBloom.destroy();
+ scene.destroy();
+ },
+ };
+}
+
+// ---------- the frame loop and the page's messages ----------
+
+let state;
+let initialized = false;
+const queued = [];
+let uncaptured = 0;
+
+const post = (message, transfer) => self.postMessage(message, transfer ?? []);
+const describe = (e) => ({ reason: e instanceof Error || typeof e?.message === "string" ? e.message : String(e), ts: Date.now() });
+
+function dimensionsOf(d) {
+ const finite = (v, fallback) => (Number.isFinite(v) ? v : fallback);
+ const dpr = Math.max(1, finite(d.dpr, 1));
+ const cssWidth = Math.max(1, Math.floor(finite(d.cssWidth, 1)));
+ const cssHeight = Math.max(1, Math.floor(finite(d.cssHeight, 1)));
+ return {
+ cssWidth,
+ cssHeight,
+ pixelWidth: Math.max(1, Math.floor(finite(d.pixelWidth, cssWidth * dpr))),
+ pixelHeight: Math.max(1, Math.floor(finite(d.pixelHeight, cssHeight * dpr))),
+ dpr,
+ };
+}
+
+function configure(context, device, format) {
+ context.configure({ device, format, alphaMode: "premultiplied" });
+}
+
+function schedule(s) {
+ if (s.disposed || s.lifecycle !== "active" || s.animationHandle !== undefined || s.timerHandle !== undefined) return;
+ if (typeof self.requestAnimationFrame === "function") {
+ s.animationHandle = self.requestAnimationFrame((t) => {
+ s.animationHandle = undefined;
+ tick(t);
+ });
+ return;
+ }
+ s.timerHandle = setTimeout(() => {
+ s.timerHandle = undefined;
+ tick(performance.now());
+ }, s.targetFrameMs);
+}
+
+function unschedule(s) {
+ if (s.animationHandle !== undefined) {
+ self.cancelAnimationFrame?.(s.animationHandle);
+ s.animationHandle = undefined;
+ }
+ if (s.timerHandle !== undefined) {
+ clearTimeout(s.timerHandle);
+ s.timerHandle = undefined;
+ }
+}
+
+function tick(now) {
+ const s = state;
+ if (!s || s.disposed || s.lifecycle !== "active") return;
+ schedule(s);
+ if (!(now - s.lastRenderAt >= s.targetFrameMs - 0.5)) return; // at most targetFps
+ const dt = s.lastTickAt === undefined ? 0 : (now - s.lastTickAt) / 1000;
+ s.lastTickAt = now;
+ s.lastRenderAt = now;
+ try {
+ if (s.pendingResize) {
+ s.dimensions = s.pendingResize;
+ s.pendingResize = undefined;
+ let changed = false;
+ if (s.canvas.width !== s.dimensions.pixelWidth) {
+ s.canvas.width = s.dimensions.pixelWidth;
+ changed = true;
+ }
+ if (s.canvas.height !== s.dimensions.pixelHeight) {
+ s.canvas.height = s.dimensions.pixelHeight;
+ changed = true;
+ }
+ if (changed) {
+ s.context.unconfigure();
+ configure(s.context, s.device, s.format);
+ }
+ }
+ // time runs at timeScale, and never jumps more than 50 ms per frame
+ s.simTime += Math.min(Number.isFinite(dt) ? Math.max(0, dt) : 0, 0.05) * s.settings.ocean.timeScale;
+ const needsInitialSpectrum = s.needsInitialSpectrum;
+ s.needsInitialSpectrum = false;
+ const { pixelWidth: width, pixelHeight: height, dpr } = s.dimensions;
+ const view = s.context.getCurrentTexture().createView();
+ if (!s.renderer || s.renderer.width !== width || s.renderer.height !== height || s.renderer.format !== s.format) {
+ s.renderer?.destroy();
+ s.renderer = createRenderer(s.device, s.format, width, height, s.settings);
+ }
+ s.renderer.render(view, s.simTime, s.settings, dpr, s.theme, needsInitialSpectrum);
+ if (!s.firstFrameSent) {
+ s.firstFrameSent = true;
+ post({ type: "firstFrame" });
+ }
+ const bitmap = s.canvas.transferToImageBitmap();
+ post({ type: "frame", bitmap }, [bitmap]);
+ } catch (e) {
+ post({ type: "error", stage: "render", ...describe(e) });
+ unschedule(s);
+ }
+}
+
+function dispose(stage) {
+ const s = state;
+ state = undefined;
+ if (!s) {
+ if (initialized) post({ type: "disposed" });
+ return;
+ }
+ s.disposed = true;
+ unschedule(s);
+ try {
+ s.renderer?.destroy();
+ s.device.destroy();
+ post({ type: "disposed" });
+ } catch (e) {
+ post({ type: "error", stage, ...describe(e) });
+ }
+}
+
+async function init(message) {
+ if (initialized || state) return post({ type: "error", stage: "init", ...describe("Ocean worker already initialized.") });
+ initialized = true;
+ let device;
+ try {
+ const gpu = navigator.gpu;
+ if (!gpu) return post({ type: "unsupported", ...describe("WebGPU is unavailable in this worker.") });
+ const dimensions = dimensionsOf(message.dimensions);
+ const canvas = new OffscreenCanvas(dimensions.pixelWidth, dimensions.pixelHeight);
+ const context = canvas.getContext("webgpu");
+ if (!context) return post({ type: "unsupported", ...describe("OffscreenCanvas WebGPU context is unavailable.") });
+ const adapter = await gpu.requestAdapter();
+ if (!adapter) throw new Error("WebGPU adapter unavailable.");
+ device = await adapter.requestDevice();
+ device.lost.then((info) => {
+ if (info.reason === "destroyed") return;
+ post({ type: "error", stage: "device", ...describe(`device lost: ${info.reason}${info.message ? ` ${info.message}` : ""}`) });
+ if (state) unschedule(state);
+ });
+ device.onuncapturederror = (e) => {
+ uncaptured += 1;
+ post({ type: "error", stage: "render", ...describe(e.error) });
+ if (uncaptured >= 3 && state) unschedule(state);
+ };
+ const format = gpu.getPreferredCanvasFormat();
+ configure(context, device, format);
+ const targetFps = message.isMobile ? 30 : 60;
+ state = {
+ canvas,
+ context,
+ device,
+ format,
+ renderer: undefined,
+ settings: resolveSettings(message.isMobile),
+ simTime: 0,
+ needsInitialSpectrum: true,
+ dimensions,
+ pendingResize: undefined,
+ theme: message.theme,
+ lifecycle: "active",
+ targetFrameMs: 1000 / targetFps,
+ animationHandle: undefined,
+ timerHandle: undefined,
+ lastRenderAt: -Infinity,
+ lastTickAt: undefined,
+ firstFrameSent: false,
+ disposed: false,
+ };
+ while (state && queued.length > 0) handle(queued.shift());
+ if (state && !state.disposed) {
+ post({ type: "ready" });
+ schedule(state);
+ }
+ } catch (e) {
+ const reason = describe(e).reason.toLowerCase();
+ const stage = reason.includes("webgpu") ? "capabilities" : reason.includes("adapter") ? "adapter" : reason.includes("device") ? "device" : reason.includes("context") ? "context" : "renderer";
+ if (stage === "capabilities") post({ type: "unsupported", ...describe(e) });
+ else post({ type: "error", stage, ...describe(e) });
+ if (state) dispose("dispose");
+ else device?.destroy();
+ } finally {
+ queued.length = 0;
+ }
+}
+
+function handle(message) {
+ if (message.type !== "init" && !state) return void queued.push(message);
+ const s = state;
+ switch (message.type) {
+ case "init":
+ return init(message);
+ case "resize":
+ if (s && !s.disposed) s.pendingResize = dimensionsOf(message.dimensions);
+ return;
+ case "theme":
+ if (s && !s.disposed) s.theme = message.theme;
+ return;
+ case "lifecycle":
+ if (!s || s.disposed) return;
+ {
+ const was = s.lifecycle;
+ s.lifecycle = message.lifecycle;
+ if (message.lifecycle === "active" && was !== "active") {
+ s.lastTickAt = undefined; // no jump in time after a pause
+ schedule(s);
+ } else if (message.lifecycle !== "active") unschedule(s);
+ if (message.lifecycle === "torn-down") dispose("dispose");
+ }
+ return;
+ case "dispose":
+ return dispose("dispose");
+ }
+}
+
+self.onmessage = (e) => {
+ Promise.resolve(handle(e.data)).catch((err) => post({ type: "error", stage: "render", ...describe(err) }));
+};
+self.addEventListener("error", (e) => post({ type: "error", stage: "render", ...describe(e.error ?? e.message ?? "Unhandled worker error.") }));
+self.onunhandledrejection = (e) => post({ type: "error", stage: "render", ...describe(e.reason ?? "Unhandled worker rejection.") });
diff --git a/site/public/examples/vercel-fluid/src/settings.js b/site/public/examples/vercel-fluid/src/settings.js
new file mode 100644
index 0000000..eeb1027
--- /dev/null
+++ b/site/public/examples/vercel-fluid/src/settings.js
@@ -0,0 +1,54 @@
+// The ocean's constants, as vercel.com/fluid ships them. Shared by the page and the worker.
+
+export const DEFAULTS = {
+ ocean: {
+ windSpeed: 12.9,
+ windAngle: 4.83,
+ amplitude: 1.3,
+ choppiness: 1.51,
+ displacementScale: 0.005,
+ foamThreshold: 0,
+ timeScale: 0.6, // simulated seconds per second
+ },
+ particles: {
+ pointSize: 0.75, // dot diameter is 2 × this × the pixel ratio, in device px
+ resolution: 256, // the grid is N × N dots; 512 on screens 1024 px and wider
+ snap: 50, // dots snap to a grid of (canvas height / 2 / snap) CSS px
+ fadeNear: 60,
+ fadeFar: 115,
+ fadePower: 3.2,
+ },
+ glow: { bloomStrength: 0.08, bloomRadius: 0.46, bloomThreshold: 0.55 },
+ camera: { eyeY: 19.3, pitchDegrees: -38.9 },
+};
+
+export const CAMERA = { eye: [0, 6, 60], target: [0, 4, -40], up: [0, 1, 0], fovDegrees: 60, near: 0.1, far: 2000 };
+export const G = 9.81;
+export const OCEAN_SIZE = 200; // the spectrum's patch size
+export const TIME_FACTOR = 0.5; // spectrum time = simTime × this
+export const PARTICLE_EXTENT = 400; // world size of the dot grid; also the normal pass's "worldSize"
+export const NOISE_SEED = 0x6f636561; // "ocea"
+export const LIGHT_DEFAULT = 0;
+export const COLORS = { ocean: linearRgb(0x0a0a0a), neon: linearRgb(0xffffff), foam: linearRgb(0xffffff) };
+
+function srgbToLinear(c) {
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+}
+function linearRgb(hex) {
+ return [srgbToLinear(((hex >> 16) & 255) / 255), srgbToLinear(((hex >> 8) & 255) / 255), srgbToLinear((hex & 255) / 255)];
+}
+
+/** Device pixel ratio, capped at 2 as on vercel.com. */
+export function capDpr(dpr) {
+ return !Number.isFinite(dpr) || dpr <= 0 ? 1 : Math.min(dpr, 2);
+}
+
+/** The settings for a phone-sized (narrower than 1024 px) or a desktop screen. */
+export function resolveSettings(isMobile) {
+ return {
+ ocean: { ...DEFAULTS.ocean },
+ particles: { ...DEFAULTS.particles, resolution: isMobile ? 256 : 512 },
+ glow: { ...DEFAULTS.glow },
+ camera: { ...DEFAULTS.camera },
+ };
+}
diff --git a/site/public/examples/vercel-fluid/src/shaders.js b/site/public/examples/vercel-fluid/src/shaders.js
new file mode 100644
index 0000000..6586058
--- /dev/null
+++ b/site/public/examples/vercel-fluid/src/shaders.js
@@ -0,0 +1,22 @@
+// The WGSL of vercel.com/fluid's ocean renderer, exactly as it ships (minified there, kept that way here).
+// Taken from the page's ocean worker chunk; see ocean.worker.js for how each module is used.
+
+export const PARTICLES_DARK = "@group(0) @binding(0) var<uniform> u:_vgsl_160545d3__ParticleUniforms;@group(0) @binding(1) var u_displacement:texture_2d<f32>;@group(0) @binding(2) var u_normalFoam:texture_2d<f32>;fn b(a:u32)-> vec2f{switch(a&3u){case 0u:{return vec2f(-1.0,-1.0);}case 1u:{return vec2f(1.0,-1.0);}case 2u:{return vec2f(-1.0,1.0);}default:{return vec2f(1.0,1.0);}}}@vertex fn vs_main(@builtin(vertex_index) a:u32,@builtin(instance_index) c:u32,)-> _vgsl_160545d3__VertexOut{let d=max(1u,u32(u.viewport.w));let e=c%d;let f=c/d;let g=vec2f(f32(e),f32(f))/f32(d);let h=vec2u(e,f);let i=textureLoad(u_displacement,h,0).xyz*u.misc.x;let j=textureLoad(u_normalFoam,h,0);let k=u.simulation.x*0.5;let l=vec3f(g.x*u.simulation.x-k,0.0,g.y*u.simulation.x-k);let m=l+i;let n=u.view*vec4f(m,1.0);let viewDir=-n.xyz;let o=-n.z;let p=1.0-smoothstep(u.fade.x,u.fade.y,o);let fade=pow(clamp(p,0.0,1.0),u.fade.z);let q=u.projection*n;var r=q.xy/q.w;let s=u.viewport.x/max(u.viewport.y,1e-3);var t=vec2f(r.x*s,r.y);t=floor(t*u.fade.w)/u.fade.w;t.x/=s;r=t;let v=b(a);let A=2.0*u.misc.y*u.viewport.z;let B=v*(A/u.viewport.xy)*q.w;let C=vec4f(r*q.w+B,q.z,q.w);var D:_vgsl_160545d3__VertexOut;D.position=C;D.pointCoord=v*0.5+vec2f(0.5);D.foam=j.w;D.normal=j.xyz;D.viewDir=viewDir;D.height=i.y;D.fade=fade;return D;}@fragment fn fs_main(a:_vgsl_160545d3__VertexOut)-> @location(0) vec4f{let c=a.pointCoord-vec2f(0.5);let d=dot(c,c);if(d>0.25){discard;}let e=normalize(a.normal);let f=normalize(a.viewDir);let g=pow(1.0-clamp(dot(e,f),0.0,1.0),5.0);let foam=clamp(a.foam,0.0,1.0);let h=smoothstep(-0.5,1.5,a.height);if(u.misc.z>0.5){let i=mix(u.neonColor.rgb,u.foamColor.rgb,foam);var j=0.06+h*0.42+g*0.12;j=mix(j,0.9,foam);j*=a.fade;return vec4f(i,clamp(j,0.0,1.0));}var k=u.oceanColor.rgb*0.5;k+=u.neonColor.rgb*h*0.5;k+=u.neonColor.rgb*g*0.15;k=mix(k,u.foamColor.rgb,foam);var l=0.02+h*0.06+g*0.04;l=mix(l,1.0,foam);k*=a.fade;l*=a.fade;return vec4f(k,clamp(l,0.0,1.0));}struct _vgsl_160545d3__ParticleUniforms{view:mat4x4f,projection:mat4x4f,viewport:vec4f,simulation:vec4f,fade:vec4f,oceanColor:vec4f,neonColor:vec4f,foamColor:vec4f,misc:vec4f,};struct _vgsl_160545d3__VertexOut{@builtin(position) position:vec4f,@location(0) pointCoord:vec2f,@location(1) foam:f32,@location(2) normal:vec3f,@location(3) viewDir:vec3f,@location(4) height:f32,@location(5) fade:f32,};";
+
+export const PARTICLES_LIGHT = "const _vgsl_0eaa7f74__LIGHT_ALPHA_BASE:f32=0.06;const _vgsl_0eaa7f74__LIGHT_ALPHA_CREST:f32=0.18;const _vgsl_0eaa7f74__LIGHT_ALPHA_FRESNEL:f32=0.12;const _vgsl_0eaa7f74__LIGHT_ALPHA_FOAM:f32=0.85;@group(0) @binding(0) var<uniform> u:_vgsl_160545d3__ParticleUniforms;@group(0) @binding(1) var u_displacement:texture_2d<f32>;@group(0) @binding(2) var u_normalFoam:texture_2d<f32>;@vertex fn vs_main(@builtin(vertex_index) f:u32,@builtin(instance_index) i:u32,)-> _vgsl_160545d3__VertexOut{return b(u,u_displacement,u_normalFoam,f,i);}@fragment fn fs_main(f:_vgsl_160545d3__VertexOut)-> @location(0) vec4f{if(c(f.pointCoord)){discard;}let i=d(f.normal,f.viewDir);let j=e(f.height);let foam=g(f.foam);var k=_vgsl_0eaa7f74__LIGHT_ALPHA_BASE+j*_vgsl_0eaa7f74__LIGHT_ALPHA_CREST+i*_vgsl_0eaa7f74__LIGHT_ALPHA_FRESNEL;k=mix(k,_vgsl_0eaa7f74__LIGHT_ALPHA_FOAM,foam);k*=f.fade*h(f.position,u.viewport.xy);return vec4f(0.0,0.0,0.0,clamp(k,0.0,1.0));}struct _vgsl_160545d3__ParticleUniforms{view:mat4x4f,projection:mat4x4f,viewport:vec4f,simulation:vec4f,fade:vec4f,oceanColor:vec4f,neonColor:vec4f,foamColor:vec4f,misc:vec4f,};struct _vgsl_160545d3__VertexOut{@builtin(position) position:vec4f,@location(0) pointCoord:vec2f,@location(1) foam:f32,@location(2) normal:vec3f,@location(3) viewDir:vec3f,@location(4) height:f32,@location(5) fade:f32,};fn a(f:u32)-> vec2f{switch(f&3u){case 0u:{return vec2f(-1.0,-1.0);}case 1u:{return vec2f(1.0,-1.0);}case 2u:{return vec2f(-1.0,1.0);}default:{return vec2f(1.0,1.0);}}}fn b(f:_vgsl_160545d3__ParticleUniforms,i:texture_2d<f32>,j:texture_2d<f32>,k:u32,l:u32,)-> _vgsl_160545d3__VertexOut{let m=max(1u,u32(f.viewport.w));let n=l%m;let o=l/m;let p=vec2f(f32(n),f32(o))/f32(m);let q=vec2u(n,o);let r=textureLoad(i,q,0).xyz*f.misc.x;let s=textureLoad(j,q,0);let t=f.simulation.x*0.5;let v=vec3f(p.x*f.simulation.x-t,0.0,p.y*f.simulation.x-t);let A=v+r;let B=f.view*vec4f(A,1.0);let viewDir=-B.xyz;let C=-B.z;let D=1.0-smoothstep(f.fade.x,f.fade.y,C);let fade=pow(clamp(D,0.0,1.0),f.fade.z);let E=f.projection*B;var F=E.xy/E.w;let G=f.viewport.x/max(f.viewport.y,1e-3);var H=vec2f(F.x*G,F.y);H=floor(H*f.fade.w)/f.fade.w;H.x/=G;F=H;let I=a(k);let J=2.0*f.misc.y*f.viewport.z;let K=I*(J/f.viewport.xy)*E.w;let L=vec4f(F*E.w+K,E.z,E.w);var M:_vgsl_160545d3__VertexOut;M.position=L;M.pointCoord=I*0.5+vec2f(0.5);M.foam=s.w;M.normal=s.xyz;M.viewDir=viewDir;M.height=r.y;M.fade=fade;return M;}fn c(f:vec2f)-> bool{let i=f-vec2f(0.5);let j=dot(i,i);return j>0.25;}fn d(f:vec3f,i:vec3f)-> f32{let j=normalize(f);let k=normalize(i);return pow(1.0-clamp(dot(j,k),0.0,1.0),5.0);}fn e(f:f32)-> f32{return smoothstep(-0.5,1.5,f);}fn g(f:f32)-> f32{return clamp(f,0.0,1.0);}fn h(f:vec4f,i:vec2f)-> f32{let j=f.xy/max(i,vec2f(1.0));return 1.0-smoothstep(0.62,0.98,j.y);}";
+
+export const BLOOM_BRIGHT = "struct VSOut{@builtin(position) pos:vec4f,@location(0) uv:vec2f,};struct BrightUniforms{luminosityThreshold:f32,smoothWidth:f32,_pad0:vec2f,};@group(0) @binding(0) var<uniform> uniforms:BrightUniforms;@group(0) @binding(1) var tDiffuse:texture_2d<f32>;@group(0) @binding(2) var linearSampler:sampler;@vertex fn vs_main(@builtin(vertex_index) a:u32)-> VSOut{var b=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));var c:VSOut;c.pos=vec4f(b[a],0.0,1.0);c.uv=b[a]*0.5+vec2f(0.5);return c;}fn luminance(a:vec3f)-> f32{return dot(a,vec3f(0.299,0.587,0.114));}@fragment fn fs_main(a:VSOut)-> @location(0) vec4f{let b=textureSample(tDiffuse,linearSampler,a.uv);let c=luminance(b.xyz);let d=vec4f(vec3f(0.0),0.0);let e=smoothstep(uniforms.luminosityThreshold,uniforms.luminosityThreshold+uniforms.smoothWidth,c);return mix(d,b,e);}";
+
+export const BLOOM_BLUR = "override KERNEL_RADIUS:u32=6u;struct VSOut{@builtin(position) pos:vec4f,@location(0) uv:vec2f,};struct BlurUniforms{direction:vec2f,invSize:vec2f,gaussianCoefficients0:vec4f,gaussianCoefficients1:vec4f,gaussianCoefficients2:vec4f,gaussianCoefficients3:vec4f,gaussianCoefficients4:vec4f,gaussianCoefficients5:vec4f,};@group(0) @binding(0) var<uniform> uniforms:BlurUniforms;@group(0) @binding(1) var colorTexture:texture_2d<f32>;@group(0) @binding(2) var linearSampler:sampler;@vertex fn vs_main(@builtin(vertex_index) a:u32)-> VSOut{var b=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));var c:VSOut;c.pos=vec4f(b[a],0.0,1.0);c.uv=b[a]*0.5+vec2f(0.5);return c;}fn coefficient(a:u32)-> f32{let b=array<f32,24>(uniforms.gaussianCoefficients0 .x,uniforms.gaussianCoefficients0 .y,uniforms.gaussianCoefficients0 .z,uniforms.gaussianCoefficients0 .w,uniforms.gaussianCoefficients1 .x,uniforms.gaussianCoefficients1 .y,uniforms.gaussianCoefficients1 .z,uniforms.gaussianCoefficients1 .w,uniforms.gaussianCoefficients2 .x,uniforms.gaussianCoefficients2 .y,uniforms.gaussianCoefficients2 .z,uniforms.gaussianCoefficients2 .w,uniforms.gaussianCoefficients3 .x,uniforms.gaussianCoefficients3 .y,uniforms.gaussianCoefficients3 .z,uniforms.gaussianCoefficients3 .w,uniforms.gaussianCoefficients4 .x,uniforms.gaussianCoefficients4 .y,uniforms.gaussianCoefficients4 .z,uniforms.gaussianCoefficients4 .w,uniforms.gaussianCoefficients5 .x,uniforms.gaussianCoefficients5 .y,uniforms.gaussianCoefficients5 .z,uniforms.gaussianCoefficients5 .w);return b[a];}@fragment fn fs_main(a:VSOut)-> @location(0) vec4f{var b=coefficient(0u);var c=textureSample(colorTexture,linearSampler,a.uv).rgb*b;for(var d=1u;d<KERNEL_RADIUS;d=d+1u){let e=f32(d);let f=coefficient(d);let g=uniforms.direction*uniforms.invSize*e;let h=textureSample(colorTexture,linearSampler,a.uv+g).rgb;let i=textureSample(colorTexture,linearSampler,a.uv-g).rgb;c=c+(h+i)*f;}return vec4f(c,1.0);}";
+
+export const BLOOM_COMPOSITE = "struct VSOut{@builtin(position) pos:vec4f,@location(0) uv:vec2f,};struct CompositeUniforms{bloomStrength:f32,bloomRadius:f32,_pad0:vec2f,bloomFactors0:vec4f,bloomFactors1:vec4f,};@group(0) @binding(0) var<uniform> uniforms:CompositeUniforms;@group(0) @binding(1) var blurTexture1:texture_2d<f32>;@group(0) @binding(2) var blurTexture2:texture_2d<f32>;@group(0) @binding(3) var blurTexture3:texture_2d<f32>;@group(0) @binding(4) var blurTexture4:texture_2d<f32>;@group(0) @binding(5) var blurTexture5:texture_2d<f32>;@group(0) @binding(6) var linearSampler:sampler;@vertex fn vs_main(@builtin(vertex_index) a:u32)-> VSOut{var b=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));var c:VSOut;c.pos=vec4f(b[a],0.0,1.0);c.uv=b[a]*0.5+vec2f(0.5);return c;}fn factor(a:u32)-> f32{let b=array<f32,8>(uniforms.bloomFactors0 .x,uniforms.bloomFactors0 .y,uniforms.bloomFactors0 .z,uniforms.bloomFactors0 .w,uniforms.bloomFactors1 .x,uniforms.bloomFactors1 .y,uniforms.bloomFactors1 .z,uniforms.bloomFactors1 .w);return b[a];}fn lerpBloomFactor(a:f32)-> f32{let b=1.2-a;return mix(a,b,uniforms.bloomRadius);}@fragment fn fs_main(a:VSOut)-> @location(0) vec4f{let c=3.0*uniforms.bloomStrength*(lerpBloomFactor(factor(0u))*textureSample(blurTexture1,linearSampler,a.uv).rgb+lerpBloomFactor(factor(1u))*textureSample(blurTexture2,linearSampler,a.uv).rgb+lerpBloomFactor(factor(2u))*textureSample(blurTexture3,linearSampler,a.uv).rgb+lerpBloomFactor(factor(3u))*textureSample(blurTexture4,linearSampler,a.uv).rgb+lerpBloomFactor(factor(4u))*textureSample(blurTexture5,linearSampler,a.uv).rgb);let d=max(c.r,max(c.g,c.b));return vec4f(c,d);}";
+
+export const PRESENT = "struct VSOut{@builtin(position) pos:vec4f,@location(0) uv:vec2f,};@group(0) @binding(0) var sceneHDR:texture_2d<f32>;@group(0) @binding(1) var bloomTexture:texture_2d<f32>;@group(0) @binding(2) var linearSampler:sampler;@vertex fn vs_main(@builtin(vertex_index) a:u32)-> VSOut{var b=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));var c:VSOut;c.pos=vec4f(b[a],0.0,1.0);c.uv=vec2f(b[a].x*0.5+0.5,0.5-b[a].y*0.5);return c;}fn LinearTosRGB(b:vec4f)-> vec4f{let c=b.rgb*12.92;let d=1.055*pow(b.rgb,vec3f(0.41666))-vec3f(0.055);let rgb=select(d,c,b.rgb<=vec3f(0.0031308));return vec4f(rgb,b.a);}@fragment fn fs_main(b:VSOut)-> @location(0) vec4f{let c=textureSample(sceneHDR,linearSampler,b.uv);let d=textureSample(bloomTexture,linearSampler,b.uv);return LinearTosRGB(vec4f(c.rgb+d.rgb,max(c.a,d.a)));}";
+
+export const INITIAL_SPECTRUM = "struct _vgsl_0b67735c__InitialSpectrumUniforms{resolution:f32,size:f32,windSpeed:f32,windAngle:f32,amplitude:f32,};@group(0) @binding(0) var<uniform> u:_vgsl_0b67735c__InitialSpectrumUniforms;@group(0) @binding(1) var u_noise:texture_2d<f32>;struct _vgsl_0b67735c__VSOut{@builtin(position) pos:vec4f};@vertex fn vs_main(@builtin(vertex_index) c:u32)-> _vgsl_0b67735c__VSOut{var d:_vgsl_0b67735c__VSOut;d.pos=b(c);return d;}fn a(c:vec2f)-> f32{let d=dot(c,c);if(d<1e-8){return 0.0;}let e=vec2f(cos(u.windAngle),sin(u.windAngle));let f=(u.windSpeed*u.windSpeed)/_vgsl_6774a90b__G;let g=dot(normalize(c),e);var h=u.amplitude*exp(-1.0/(d*f*f))/(d*d)*(g*g);let i=f*0.001;h*=exp(-d*i*i);if(g<0.0){h*=0.07;}return h;}@fragment fn fs_main(c:_vgsl_0b67735c__VSOut)-> @location(0) vec4f{let d=c.pos.xy-vec2f(0.5);let e=select(d.x-u.resolution,d.x,d.x<u.resolution*0.5);let f=select(d.y-u.resolution,d.y,d.y<u.resolution*0.5);let g=(2.0*_vgsl_6774a90b__PI/u.size)*vec2f(e,f);let h=textureLoad(u_noise,vec2u(d),0);let i=(1.0/sqrt(2.0))*vec2f(h.x,h.y)*sqrt(a(g));let j=(1.0/sqrt(2.0))*vec2f(h.z,h.w)*sqrt(a(-g));return vec4f(i,j.x,-j.y);}const _vgsl_6774a90b__PI:f32=3.141592653589793;const _vgsl_6774a90b__G:f32=9.81;fn b(c:u32)-> vec4f{var d=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));return vec4f(d[c],0.0,1.0);}";
+
+export const SPECTRUM = "struct _vgsl_339025fa__SpectrumUniforms{resolution:f32,size:f32,time:f32,choppiness:f32,};@group(0) @binding(0) var<uniform> u:_vgsl_339025fa__SpectrumUniforms;@group(0) @binding(1) var u_initialSpectrum:texture_2d<f32>;struct _vgsl_339025fa__VSOut{@builtin(position) pos:vec4f};@vertex fn vs_main(@builtin(vertex_index) a:u32)-> _vgsl_339025fa__VSOut{var b:_vgsl_339025fa__VSOut;b.pos=d(a);return b;}@fragment fn fs_main(a:_vgsl_339025fa__VSOut)-> @location(0) vec4f{let b=a.pos.xy-vec2f(0.5);let e=select(b.x-u.resolution,b.x,b.x<u.resolution*0.5);let f=select(b.y-u.resolution,b.y,b.y<u.resolution*0.5);let g=(2.0*_vgsl_6774a90b__PI/u.size)*vec2f(e,f);let h=length(g);let i=textureLoad(u_initialSpectrum,vec2u(b),0);let j=sqrt(_vgsl_6774a90b__G*h)*u.time;let k=vec2f(cos(j),sin(j));let l=vec2f(cos(j),-sin(j));let m=c(i.rg,k)+c(i.ba,l);var n=vec2f(0.0);if(h>0.0){n=g/h;}let o=vec2f(m.y,-m.x);let p=o*n.x*u.choppiness;let q=o*n.y*u.choppiness;let r=vec2f(p.x-m.y,p.y+m.x);let s=q;return vec4f(r,s);}const _vgsl_6774a90b__PI:f32=3.141592653589793;const _vgsl_6774a90b__G:f32=9.81;fn c(a:vec2f,b:vec2f)-> vec2f{return vec2f(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);}fn d(a:u32)-> vec4f{var b=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));return vec4f(b[a],0.0,1.0);}";
+
+export const IFFT_STAGE = "override IFFT_HORIZONTAL:u32=1u;struct _vgsl_860df637__IfftStageUniforms{resolution:f32,subtransformSize:f32,horizontal:f32,};@group(0) @binding(0) var<uniform> u:_vgsl_860df637__IfftStageUniforms;@group(0) @binding(1) var u_input:texture_2d<f32>;struct _vgsl_860df637__VSOut{@builtin(position) pos:vec4f};@vertex fn vs_main(@builtin(vertex_index) a:u32)-> _vgsl_860df637__VSOut{var b:_vgsl_860df637__VSOut;b.pos=f(a);return b;}@fragment fn fs_main(a:_vgsl_860df637__VSOut)-> @location(0) vec4f{let b=i32(u.resolution);let g=IFFT_HORIZONTAL==1u;let h=select(a.pos.y-0.5,a.pos.x-0.5,g);let i=floor(h/u.subtransformSize)*(u.subtransformSize*0.5)+(h%(u.subtransformSize*0.5));let j=select(vec2i(i32(a.pos.x-0.5),i32(i)),vec2i(i32(i),i32(a.pos.y-0.5)),g,);let k=select(vec2i(i32(a.pos.x-0.5),i32(i+u.resolution*0.5)),vec2i(i32(i+u.resolution*0.5),i32(a.pos.y-0.5)),g,);let l=e(u_input,j,b);let m=e(u_input,k,b);let n=2.0*_vgsl_6774a90b__PI*(h/u.subtransformSize);let o=vec2f(cos(n),sin(n));let p=l.xy+c(o,m.xy);let q=l.zw+c(o,m.zw);return vec4f(p,q);}const _vgsl_6774a90b__PI:f32=3.141592653589793;fn c(a:vec2f,b:vec2f)-> vec2f{return vec2f(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);}fn d(a:vec2i,b:i32)-> vec2u{let g=(a%vec2i(b)+vec2i(b))%vec2i(b);return vec2u(g);}fn e(a:texture_2d<f32>,b:vec2i,g:i32)-> vec4f{return textureLoad(a,d(b,g),0);}fn f(a:u32)-> vec4f{var b=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));return vec4f(b[a],0.0,1.0);}";
+
+export const NORMAL_FOAM = "struct _vgsl_c962e6e6__NormalFoamUniforms{resolution:f32,worldSize:f32,displacementScale:f32,choppiness:f32,foamThreshold:f32,};@group(0) @binding(0) var<uniform> u:_vgsl_c962e6e6__NormalFoamUniforms;@group(0) @binding(1) var u_displacement:texture_2d<f32>;struct _vgsl_c962e6e6__VSOut{@builtin(position) pos:vec4f};@vertex fn vs_main(@builtin(vertex_index) b:u32)-> _vgsl_c962e6e6__VSOut{var c:_vgsl_c962e6e6__VSOut;c.pos=e(b);return c;}@fragment fn fs_main(b:_vgsl_c962e6e6__VSOut)-> @location(0) vec4f{let c=i32(u.resolution);let f=vec2i(b.pos.xy-vec2f(0.5));let g=u.worldSize/u.resolution;let h=d(u_displacement,f,c).xyz*u.displacementScale;let i=d(u_displacement,f+vec2i(1,0),c).xyz*u.displacementScale;let j=d(u_displacement,f-vec2i(1,0),c).xyz*u.displacementScale;let k=d(u_displacement,f+vec2i(0,1),c).xyz*u.displacementScale;let l=d(u_displacement,f-vec2i(0,1),c).xyz*u.displacementScale;let m=(i.y-j.y)/(2.0*g);let n=(k.y-l.y)/(2.0*g);let o=normalize(vec3f(-m,1.0,-n));let p=(i.x-j.x)/(2.0*g);let q=(k.z-l.z)/(2.0*g);let r=(k.x-l.x)/(2.0*g);let s=(i.z-j.z)/(2.0*g);let t=(1.0+p)*(1.0+q)-r*s;let v=1.0-smoothstep(u.foamThreshold,u.foamThreshold+0.8,t);return vec4f(o,v);}fn a(b:vec2i,c:i32)-> vec2u{let f=(b%vec2i(c)+vec2i(c))%vec2i(c);return vec2u(f);}fn d(b:texture_2d<f32>,c:vec2i,f:i32)-> vec4f{return textureLoad(b,a(c,f),0);}fn e(b:u32)-> vec4f{var c=array<vec2f,3>(vec2f(-1.0,-3.0),vec2f(-1.0,1.0),vec2f(3.0,1.0));return vec4f(c[b],0.0,1.0);}";
diff --git a/site/public/examples/vercel-hero/assets/fonts/Geist-Variable.woff2 b/site/public/examples/vercel-hero/assets/fonts/Geist-Variable.woff2
new file mode 100644
index 0000000..1864b37
Binary files /dev/null and b/site/public/examples/vercel-hero/assets/fonts/Geist-Variable.woff2 differ
diff --git a/site/public/examples/vercel-hero/assets/fonts/LICENSE-geist.txt b/site/public/examples/vercel-hero/assets/fonts/LICENSE-geist.txt
new file mode 100644
index 0000000..8d003fe
--- /dev/null
+++ b/site/public/examples/vercel-hero/assets/fonts/LICENSE-geist.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2023 Vercel, in collaboration with basement.studio
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/public/examples/vercel-hero/index.html b/site/public/examples/vercel-hero/index.html
new file mode 100644
index 0000000..458de05
--- /dev/null
+++ b/site/public/examples/vercel-hero/index.html
@@ -0,0 +1,78 @@
+<!doctype html>
+<!--
+ vercel.com hero triangle, rebuilt with reanimate.
+ A black triangle lit by 72 LEDs along its edges. Soft lines of light run round it; move the pointer
+ near it and the edges facing the pointer light up, with a white rim on the floor. Drag a file over the
+ page and it turns into a prism: a red, green and blue glow spreads from its edges and "Drop to deploy"
+ appears. Click the triangle to switch the colours on and off; hover an item on the right to light one
+ edge. The canvas is vercel.com's own renderer (WebGL2 in a worker, its shaders unchanged), ported to
+ plain modules: see src/renderer.js and .reanimate/vercel-hero.
+-->
+<html lang="en" class="light-theme">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>vercel.com hero triangle, rebuilt with reanimate</title>
+ <meta name="robots" content="noindex">
+ <link rel="preload" href="./assets/fonts/Geist-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="stylesheet" href="./src/hero.css">
+ <script>
+ // ?embed: only the canvas box, scaled to the frame's width (for an iframe)
+ const params = new URLSearchParams(location.search);
+ if (params.has("embed")) document.documentElement.dataset.embed = "";
+ const fit = () => {
+ const w = params.has("embed") ? 1080 : 1440;
+ document.documentElement.style.setProperty("--fit", Math.min(1, innerWidth / w));
+ };
+ fit();
+ addEventListener("resize", fit);
+ </script>
+ <script type="module" src="./src/hero.js"></script>
+</head>
+<body>
+ <div class="vh-frame">
+ <main class="vh-page">
+ <section class="vh-section" data-cdp-scope="hero">
+ <div class="vh-hero" data-hero-drop-active="false" data-hero-drop-staging="false">
+ <div class="vh-shader">
+ <div class="vh-canvas-box">
+ <!-- shown until the canvas has faded in, then faded out -->
+ <div class="vh-fallback" aria-hidden="true">
+ <div class="vh-fallback__square">
+ <svg class="vh-fallback__svg" viewBox="-0.15238 -0.15238 0.30476 0.30476" style="overflow: visible">
+ <polygon points="0,-0.15238 -0.13197,0.07619 0.13197,0.07619" fill="#000" />
+ </svg>
+ </div>
+ </div>
+ <div class="vh-label" aria-hidden="true">
+ <span class="vh-label__drop">Drop to deploy</span>
+ <span class="vh-label__loading">Loading</span>
+ </div>
+ <div class="vh-shader-root" aria-hidden="true">
+ <canvas class="vh-canvas" data-triangle-led-4-hero-canvas="true"></canvas>
+ <div class="vh-pointer-area" aria-hidden="true"></div>
+ </div>
+ </div>
+ </div>
+
+ <header class="vh-header">
+ <h1 class="vh-title">Agentic Infrastructure</h1>
+ <div class="vh-buttons">
+ <a class="vh-button vh-button--primary" href="https://vercel.com/signup"><span>Deploy now</span></a>
+ <a class="vh-button vh-button--secondary" href="https://vercel.com/contact/sales"><span>Talk to sales</span></a>
+ </div>
+ </header>
+
+ <div class="vh-nav-wrap">
+ <nav class="vh-nav" aria-label="Platform capabilities" data-none>
+ <div class="vh-item"><span class="vh-item__text"><span class="vh-item__title">For coding agents</span><span class="vh-item__desc" aria-hidden="true"> to deploy in their native language, with Vercel's API, CLI, MCP, and Skills.</span></span></div>
+ <div class="vh-item"><span class="vh-item__text"><span class="vh-item__title">To ship apps and agents</span><span class="vh-item__desc" aria-hidden="true"> in Sandboxed VMs, with durable backends, powered by 400+ models.</span></span></div>
+ <div class="vh-item"><span class="vh-item__text"><span class="vh-item__title">Automated by agents</span><span class="vh-item__desc" aria-hidden="true"> who autonomously investigate errors, plan fixes, and open PRs.</span></span></div>
+ </nav>
+ </div>
+ </div>
+ </section>
+ </main>
+ </div>
+</body>
+</html>
diff --git a/site/public/examples/vercel-hero/src/config.js b/site/public/examples/vercel-hero/src/config.js
new file mode 100644
index 0000000..152b14e
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/config.js
@@ -0,0 +1,160 @@
+// Settings and triangle geometry of vercel.com's hero, ported from its bundle (modules 6552015, 2462e3
+// and 4077675 of the vercel-marketing build). Numbers are vercel.com's; names are ours.
+// Runs in the worker and on the page; each keeps its own camera zoom, as on vercel.com.
+
+/** Triangle height as a fraction of the simulation height, before the camera zoom. */
+export const TRIANGLE_HEIGHT = (180 / 630) * 0.8;
+export const LEDS_PER_SIDE = 24;
+export const LED_COUNT = 3 * LEDS_PER_SIDE;
+export const LED_ROWS = LED_COUNT;
+export const DESIGN_HEIGHT = 720;
+export const ZOOM_DESKTOP = 1.3;
+export const ZOOM_MOBILE = 1.6;
+export const FPS_DESKTOP = 60;
+export const FPS_MOBILE = 30;
+export const ANIMATION_CLOCK_START = 10;
+export const BRIGHTNESS_MIN_INSIDE = 4; // brightnessMin is multiplied by this while the pointer is inside
+export const BRIGHTNESS_MIN_SMOOTHING = 0.2;
+export const DROP_SMOOTHING = 0.25; // seconds, the drop factor's time constant
+export const STAGING_SMOOTHING = 0.25;
+export const DROP_SPEEDUP = 4; // the drop segments run up to 4x faster while staging
+export const DROP_SEGMENTS = 3;
+export const DROP_SEGMENT_SPEED = (72 * 0.3) / 1.2 * 0.5; // LEDs per second
+export const DROP_SEGMENT_HALF = 3.5;
+export const DROP_SEGMENT_CORE = 1;
+export const DROP_SEGMENT_GROW = 2;
+export const DROP_BASE_MIN = 0.5;
+export const DROP_BASE_MAX = 0.5;
+export const DROP_SEGMENT_SPEEDS = Array.from({ length: 3 }, (_, i) => {
+ const v = 43758.5453 * Math.sin(12.9898 * i + 78.233);
+ return 0.2 + 0.8 * (v - Math.floor(v));
+});
+export const LED_EMITTER_EXPAND = 1; // px the emitter quads grow past the LED shape
+export const LED_CLIP_EXPAND = 2;
+
+export const MODES = { coding: "coding", scan: "scan", pulse: "pulse", edge: "edge", lines: "lines", lines2: "lines2" };
+
+const HERO = { mode: MODES.lines, transitionDuration: 0.25, scanSpeed: 0.08, scanHeadWidth: 7.5, scanRedShift: 0.3, scanBlueShift: 0.3, scanHueRotationSpeed: 0.03, pulseSpeed: 0.25, pulseWidth: 4, edgeIndex: 0, edgeBaseBrightness: 0.05, edgeHighlightBrightness: 0.4 };
+export const BRUSH = { radius: 28, friction: 5, colour: { r: 1, g: 1, b: 1 }, glowEnabled: true, glowRadius: 165, glowStrength: 1, glowSmoothing: 0.23, glowFacingEnabled: true, glowFacingFullDeg: 90, glowFacingZeroDeg: 100, linesFadeDistance: 0.6 };
+export const TUNABLES = { darkFloorAlbedo: 1, lightFloorAlbedo: 1, ledIntensity: 1, noiseScale: 0.01, rotationSpeed: -0.2, brightnessMin: 0.09, brightnessMinDark: 0.05, brightnessMax: 1, brightnessMaxLight: 1.02, ledHitThreshold: 1, ledRaycastClipInsetPx: 2, particleExposureBoostMin: 5.2, particleExposureBoostMax: 60, particleSpawnSpread: 118, particleNoiseOffset: 1 };
+export const LED_CLIP_INSET_RANGE = { min: -4, max: 8 };
+export const HOVER_RGB = { enabled: true, amount: 1, radius: 173, power: 3, responseSmoothing: 0.2, deployDurationSeconds: 0.5, noiseBrightnessMin: 0.3, noiseBrightnessMax: 10, noiseBrightnessPower: 2, edgeRedLinear: { r: 0.896269, g: 0.027321, b: 0.051269 }, edgeGreenLinear: { r: 0, g: 0.40724, b: 0.048172 }, edgeBlueLinear: { r: 0, g: 0.278894, b: 1 }, edgeOverlap: 1 };
+export const PROBE_DISCARD = { lightAabbPadding: 0 };
+export const LIGHT_AO = { radiance: 0.07, contactOpacity: 0.1, contactSize: 3, contactFalloffPower: 1.6, highlightPower: 0.7, highlightStrength: 1.25 };
+export const RADIANCE_DEBUG = { enabled: false, redMultiplier: 1, greenMultiplier: 1, blueMultiplier: 1 };
+export const DARK_FLOOR = { sdfFadeDistanceScale: 0.75, sdfFadeEdgePx: 0, nearFalloffPower: 4, nearFalloffDistanceScale: 0.046, nearFalloffIntensity: 1.2, nearFalloffMapMin: 2.74, nearFalloffMapMax: 5, middleFalloffPower: 1, middleFalloffIntensity: 0.16, tailIntensity: 0.65, tailMapMin: 0, tailMapMax: 8.85, tailPower: 0.05, nearFalloffEnabled: true, middleFalloffEnabled: false, farFalloffEnabled: true, noiseEnabled: true, radianceJitterPx: 16, vibrancy: 2 };
+export const DARK_POST = { contrast: 1.05, exposure: 0.25 };
+export const LIGHT_GLOW = { nearDistanceScale: 0.268, nearIntensity: 4, nearMapMin: 0, nearMapMax: 20, nearPower: 8, nearEnabled: true, middleOuterScale: 3.95, middlePower: 3.3, middleIntensity: 1.6, highlightNoise: 0.5, highlightDebug: false, middleEnabled: true, farIntensity: 1.2, farMapMin: 0, farMapMax: 3, farPower: 0.71, farEnabled: true, fadeInner: 41, contrast: 1.06, nearDistanceScaleColor: 0.116, nearIntensityColor: 0.2, nearMapMinColor: 0.36, nearMapMaxColor: 4, nearPowerColor: 1.95, nearEnabledColor: true, middleOuterScaleColor: 3.95, middlePowerColor: 5.3, middleIntensityColor: 0.34, middleEnabledColor: true, farIntensityColor: 0.45, farMapMinColor: 0, farMapMaxColor: 1.25, farPowerColor: 0.22, farEnabledColor: true, fadeInnerColor: 0, contrastColor: 1.58, aoStrength: 0.18, aoRadiusScale: 0.8, aoPower: 4, aoEnabled: true, ao2Strength: 0.15, ao2RadiusScale: 0.14, ao2Power: 1.6, ao2Enabled: true, ao3Strength: 0.21, ao3RadiusScale: 0.18, ao3Power: 3.8, ao3Enabled: true, edgeRedRgb: { r: 0.8667, g: 0.2745, b: 0.302 }, edgeGreenRgb: { r: 0.3294, g: 0.698, b: 0.3255 }, edgeBlueRgb: { r: 0.1804, g: 0.3451, b: 1 }, edgeOverlap: 0.4 };
+export const OCCLUDER = { showOccluderTriangle: true };
+
+// Direct raycast pass (module 4077675): half-resolution probes.
+export const raycastSize = (sim) => ({ width: Math.max(1, Math.ceil(0.5 * sim.width)), height: Math.max(1, Math.ceil(0.5 * sim.height)) });
+
+// Hovering nav item 0, 1 or 2 lights one edge of the triangle; otherwise the lines run.
+const EDGE_FOR_ITEM = [0, 2, 1];
+export function heroModeFor(activeItem) {
+ if (activeItem === 0 || activeItem === 1 || activeItem === 2) return { mode: MODES.edge, edgeIndex: EDGE_FOR_ITEM[activeItem] };
+ return { mode: MODES.lines, edgeIndex: HERO.edgeIndex };
+}
+
+export function defaultSettings(activeItem = -1) {
+ return {
+ tunables: { ...TUNABLES },
+ hero: { ...HERO, ...heroModeFor(activeItem) },
+ brush: { ...BRUSH },
+ probeDiscard: { ...PROBE_DISCARD },
+ lightAo: { ...LIGHT_AO },
+ lightGlow: { ...LIGHT_GLOW },
+ radianceDebug: { ...RADIANCE_DEBUG },
+ darkFloor: { ...DARK_FLOOR },
+ darkPostprocess: { ...DARK_POST },
+ hoverRgbTint: { ...HOVER_RGB },
+ occluderTriangle: { ...OCCLUDER },
+ };
+}
+
+// ---------- camera zoom (each realm keeps its own, set from the canvas height) ----------
+let zoom = 1;
+let pointerCutoff = 0.2;
+export const setZoom = (z) => { zoom = Number.isFinite(z) && z > 0 ? z : 1; };
+export const setPointerCutoff = (v) => { pointerCutoff = Number.isFinite(v) && v >= 0 ? v : 0.2; };
+export const getPointerCutoff = () => pointerCutoff;
+/** Desktop canvases shorter than 560 px keep the triangle's on-screen size. */
+export const zoomFor = (base, cssHeight, mobile = false) =>
+ mobile || !Number.isFinite(cssHeight) || cssHeight <= 0 ? base : base * Math.min(1, 560 / cssHeight);
+/** The simulation is at least 360 px tall. */
+export const simScale = (cssHeight) => Math.max(1, 360 / Math.max(1, cssHeight));
+
+// ---------- triangle ----------
+export function triangle(size) {
+ const height = size.height * TRIANGLE_HEIGHT * zoom;
+ const circumradius = (2 * height) / 3;
+ const inradius = height / 3;
+ const sideLength = (2 * height) / Math.sqrt(3);
+ const cx = 0.5 * size.width;
+ const cy = 0.5 * size.height;
+ return {
+ center: { x: cx, y: cy },
+ top: { x: cx, y: cy - circumradius },
+ left: { x: cx - 0.5 * sideLength, y: cy + inradius },
+ right: { x: cx + 0.5 * sideLength, y: cy + inradius },
+ height, circumradius, inradius, sideLength,
+ };
+}
+export const ledRadius = (size) => 0.0236 * triangle(size).height;
+export function ledShape(size, perSide) {
+ const tri = triangle(size);
+ const cornerTrim = Math.min(2 * ledRadius(size) * Math.sqrt(3) + 1, 0.45 * triangle(size).sideLength);
+ const centerSpacing = Math.max(0, tri.sideLength - 2 * cornerTrim) / Math.max(1, perSide);
+ return { normalHalfThickness: 2 * ledRadius(size), tangentHalfLength: Math.max(0, 0.5 * centerSpacing - 0.5), cornerTrim, centerSpacing };
+}
+function scaleTriangle(tri, s) {
+ const c = tri.center;
+ const p = (v) => ({ x: c.x + (v.x - c.x) * s, y: c.y + (v.y - c.y) * s });
+ return { center: c, top: p(tri.top), left: p(tri.left), right: p(tri.right), height: tri.height * s, circumradius: tri.circumradius * s, inradius: tri.inradius * s, sideLength: tri.sideLength * s };
+}
+/** The LEDs sit 5 design px inside the triangle's edge. */
+function insetScale(tri) {
+ const ref = DESIGN_HEIGHT * TRIANGLE_HEIGHT;
+ const inset = (5 * Math.min(tri.height, ref)) / ref;
+ return tri.inradius > inset ? (tri.inradius - inset) / tri.inradius : 1;
+}
+export function insetTriangle(size) {
+ const tri = triangle(size);
+ return scaleTriangle(tri, insetScale(tri));
+}
+/** Centres and angles of the LEDs, 24 per side, clockwise from the top corner. */
+export function ledLayout(size, perSide) {
+ const tri = triangle(size);
+ const s = insetScale(tri);
+ const geometry = scaleTriangle(tri, s);
+ const { top, left, right, center } = geometry;
+ const scaled = { width: size.width, height: size.height * s };
+ const shape = ledShape(scaled, perSide);
+ const positions = [];
+ for (const [a, b] of [[top, left], [left, right], [right, top]]) {
+ const dx = b.x - a.x, dy = b.y - a.y, len = Math.hypot(dx, dy), angle = Math.atan2(dy, dx);
+ const trim = len > 0 ? shape.cornerTrim / len : 0;
+ const step = len > 0 ? shape.centerSpacing / len : 0;
+ for (let i = 0; i < perSide; i++) {
+ const u = trim + (i + 0.5) * step;
+ positions.push({ x: a.x + dx * u, y: a.y + dy * u, angle });
+ }
+ }
+ return { center, positions, geometry, ledRadius: ledRadius(scaled), ledShape: shape };
+}
+export const clampProbeDensity = (v, d = 2) => (v === undefined || !Number.isFinite(v) || v <= 0 ? d : Math.min(4, Math.max(0.5, v)));
+export function clampCascadeCount(v) {
+ if (v !== undefined && Number.isFinite(v) && !(v <= 0)) return Math.min(5, Math.max(1, Math.floor(v)));
+}
+export function cascadeCountFor(size) {
+ const diag = Math.hypot(size.width, size.height);
+ for (let k = 0; k < 16; k++) if ((4 ** (k + 1) - 1) / 3 > diag) return Math.min(k + 1, 5);
+ return 5;
+}
+export function cascadeFit(size, density = 2) {
+ const w = Math.max(1, Math.round(size.width * density));
+ const h = Math.max(1, Math.round(size.height * density));
+ return { originX: 0, originY: 0, width: w, height: h, fullWidth: w, fullHeight: h, alignment: 32, areaRatio: 1, originSceneX: 0, originSceneY: 0, widthScene: size.width, heightScene: size.height };
+}
+export const nonNegative = (v) => (Number.isFinite(v) ? Math.max(0, v) : 0);
diff --git a/site/public/examples/vercel-hero/src/frame.js b/site/public/examples/vercel-hero/src/frame.js
new file mode 100644
index 0000000..073d01a
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/frame.js
@@ -0,0 +1,110 @@
+// Per-frame state of vercel.com's hero (module 4519386): it smooths every input the LEDs and the floor
+// react to, on the frame clock, then updates the LEDs.
+// colour mix: 0 → 1 while a file is dragged over the page or after a click on the triangle, with a
+// 0.2 s time constant; it drives the floor's prism colours and the LEDs' base brightness
+// drop factor: 0 → 1 while a file is over the page, 0.25 s time constant; brings in the LED segments
+// drop phase: how far the segments have run, reset each time a drag starts
+// brightnessMin: x4 while the pointer is inside the triangle, 0.2 s time constant
+
+import { BRUSH, TUNABLES, PROBE_DISCARD, LIGHT_AO, LIGHT_GLOW, RADIANCE_DEBUG, DARK_FLOOR, DARK_POST, HOVER_RGB, MODES, BRIGHTNESS_MIN_INSIDE, BRIGHTNESS_MIN_SMOOTHING, DROP_SMOOTHING, STAGING_SMOOTHING, DROP_SPEEDUP } from "./config.js";
+import { clamp01, lerp } from "./leds.js";
+
+const HERO = { mode: MODES.lines, transitionDuration: 0.25, scanSpeed: 0.08, scanHeadWidth: 7.5, scanRedShift: 0.3, scanBlueShift: 0.3, scanHueRotationSpeed: 0.03, pulseSpeed: 0.25, pulseWidth: 4, edgeIndex: 0, edgeBaseBrightness: 0.05, edgeHighlightBrightness: 0.4 };
+const NO_POINTER = Object.freeze({ x: -1e3, y: -1e3, active: false, inside: false, isMouse: false });
+
+/** Exponential smoothing towards `target` with time constant `tau` seconds, steps capped at 0.25 s. */
+function smoother(clampTarget = true) {
+ let started = false, last = 0, value = 0;
+ return (target, time, tau) => {
+ const want = clampTarget ? clamp01(target) : target;
+ if (!started) { started = true; last = time; return (value = want); }
+ const dt = time - last;
+ last = time;
+ if (tau <= 0 || !Number.isFinite(tau)) return (value = want);
+ const k = 1 - Math.exp(-Math.min(0.25, Math.max(0, Number.isFinite(dt) ? dt : 0)) / tau);
+ value = lerp(value, want, k);
+ if (Math.abs(value - want) < 1e-4) value = want;
+ return value;
+ };
+}
+
+export function createFrameResolver() {
+ const staging = smoother(), dropping = smoother(), colour = smoother(), minimum = smoother(false);
+ let lastTime;
+ let wasEngaged = false, phase = 0;
+ let deploying = false, deployStart = 0, deployElapsed = 0;
+ // ledIntensity / brightnessMax follow mode changes with the LEDs' own cross-fade
+ let ready = false, fading = false, intensityFrom = 0, intensityTo = 0, intensity = 0, maxFrom = 0, maxTo = 0, max = 0;
+ const brush = { ...BRUSH, x: -1e3, y: -1e3, active: false };
+ const tunables = { ...TUNABLES }, hero = { ...HERO }, probeDiscard = { ...PROBE_DISCARD }, lightAo = { ...LIGHT_AO }, lightGlow = { ...LIGHT_GLOW };
+ const radianceDebug = { ...RADIANCE_DEBUG }, darkFloor = { ...DARK_FLOOR }, darkPostprocess = { ...DARK_POST }, hoverRgbTint = { ...HOVER_RGB };
+
+ return {
+ resolveFrame({ patch, tunables: tun, options, probeDiscard: pd, theme, time, updateLedsFor }) {
+ Object.assign(brush, BRUSH, NO_POINTER, patch);
+ Object.assign(tunables, TUNABLES, tun);
+ Object.assign(hero, HERO, options?.hero);
+ Object.assign(probeDiscard, PROBE_DISCARD, pd);
+ Object.assign(lightAo, LIGHT_AO, options?.lightAo);
+ Object.assign(lightGlow, LIGHT_GLOW, options?.lightGlow);
+ Object.assign(radianceDebug, RADIANCE_DEBUG, options?.radianceDebug);
+ Object.assign(darkFloor, DARK_FLOOR, options?.darkFloor);
+ Object.assign(darkPostprocess, DARK_POST, options?.darkPostprocess);
+ Object.assign(hoverRgbTint, HOVER_RGB, options?.hoverRgbTint);
+ hoverRgbTint.amount = theme === "light" ? 0 : clamp01(hoverRgbTint.amount);
+
+ const dropActive = options?.dropActive === true;
+ const dropStaging = options?.dropStaging === true;
+ const engaged = dropActive || dropStaging;
+ const boost = staging(+dropStaging, time, STAGING_SMOOTHING);
+ {
+ const dt = lastTime !== undefined ? time - lastTime : 0;
+ lastTime = time;
+ const step = Math.min(0.25, Math.max(0, Number.isFinite(dt) ? dt : 0));
+ const started = engaged && !wasEngaged;
+ if (started) phase = 0;
+ wasEngaged = engaged;
+ if (engaged || boost > 1e-4) {
+ const speed = lerp(1, DROP_SPEEDUP, clamp01(boost));
+ if (!started) phase += step * speed;
+ } else phase = 0;
+ }
+ const drop = dropping(+engaged, time, DROP_SMOOTHING);
+ const deploy = hoverRgbTint.enabled && (options?.hoverRgbDeployActive === true || engaged);
+ if (deploy && !deploying) { deployStart = time; deployElapsed = 0; }
+ deploying = deploy;
+ if (deploy) deployElapsed = Math.max(0, time - deployStart);
+ const colorMix = colour(+deploy, time, hoverRgbTint.responseSmoothing);
+ const minTarget = theme === "dark" ? tunables.brightnessMinDark : tunables.brightnessMin * colorMix;
+ tunables.brightnessMin = minimum(brush.active && brush.inside === true ? minTarget * BRIGHTNESS_MIN_INSIDE : minTarget, time, BRIGHTNESS_MIN_SMOOTHING);
+
+ const leds = updateLedsFor({
+ time, tunables, settings: hero,
+ hoverDeploy: { factor: colorMix, elapsed: deployElapsed, time, tint: hoverRgbTint },
+ dropActive: { factor: drop, phase, boost },
+ brush, theme,
+ });
+ const wantIntensity = tunables.ledIntensity;
+ const wantMax = hero.mode === MODES.scan ? 1 : hero.mode === MODES.pulse ? 0.5 : theme === "light" ? tunables.brightnessMaxLight : tunables.brightnessMax;
+ if (!ready) {
+ ready = true; fading = false;
+ intensityFrom = intensityTo = intensity = wantIntensity;
+ maxFrom = maxTo = max = wantMax;
+ } else {
+ let hold = false;
+ if (leds.modeChanged) { intensityFrom = intensity; intensityTo = wantIntensity; maxFrom = max; maxTo = wantMax; fading = leds.progress < 1; }
+ else if (!fading) { intensityTo = intensity = wantIntensity; maxTo = max = wantMax; hold = true; }
+ if (!hold) {
+ if (fading) {
+ intensity = lerp(intensityFrom, intensityTo, leds.easedProgress);
+ max = lerp(maxFrom, maxTo, leds.easedProgress);
+ if (leds.progress >= 1) fading = false;
+ } else { intensity = intensityTo; max = maxTo; }
+ }
+ }
+ tunables.ledIntensity = intensity;
+ tunables.brightnessMax = max;
+ return { brush, tunables, hero, probeDiscard, lightAo, lightGlow, radianceDebug, darkFloor, darkPostprocess, hoverRgbTint, colorMix };
+ },
+ };
+}
diff --git a/site/public/examples/vercel-hero/src/hero.css b/site/public/examples/vercel-hero/src/hero.css
new file mode 100644
index 0000000..121dc45
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/hero.css
@@ -0,0 +1,103 @@
+/* vercel.com's homepage hero at 1440x900, light theme: the boxes, fonts and transitions measured on the
+ page (.reanimate/vercel-hero/probe-dom.json). Narrower windows get the same layout scaled down. */
+
+@font-face {
+ font-family: "Geist";
+ src: url("../assets/fonts/Geist-Variable.woff2") format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+}
+
+:root {
+ --fit: 1;
+ --gray-1000: rgb(23, 23, 23);
+ --gray-900: rgb(77, 77, 77);
+ --bg: rgb(250, 250, 250);
+ --ease: cubic-bezier(0.4, 0, 0.2, 1);
+ --ease-out: cubic-bezier(0, 0, 0.2, 1);
+}
+
+html, body { margin: 0; background: var(--bg); }
+body {
+ color: var(--gray-1000);
+ font: 400 16px/24px "Geist", system-ui, sans-serif;
+ font-feature-settings: "calt" 0, "rlig", "ss11";
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ text-rendering: optimizeLegibility;
+}
+
+.vh-frame { width: calc(1440px * var(--fit)); height: calc(900px * var(--fit)); margin: 0 auto; overflow: hidden; }
+.vh-page { position: relative; width: 1440px; height: 900px; transform: scale(var(--fit)); transform-origin: 0 0; }
+.vh-section { position: absolute; left: 24px; top: 64px; width: 1392px; height: 836px; user-select: none; -webkit-user-select: none; }
+/* the hero row, 1392 x 728: heading left, capabilities right, both centred vertically as on vercel.com, so the
+ capabilities move up while one of them is open */
+.vh-hero { position: absolute; inset: 0 0 108px 0; box-sizing: border-box; padding: 40px 0; display: flex; align-items: center; justify-content: space-between; }
+
+/* the shader layer: a 3:2 box, 720 px tall, 20 px below the row's centre */
+.vh-shader { position: absolute; inset: 0; pointer-events: none; z-index: 0; }
+.vh-canvas-box { position: absolute; left: 156px; top: 24px; width: 1080px; height: 720px; }
+
+.vh-fallback { position: absolute; inset: 0; transition: opacity 700ms linear; }
+.vh-fallback[data-hidden] { opacity: 0; }
+.vh-fallback__square { position: absolute; left: 50%; top: 50%; height: 100%; max-height: 560px; aspect-ratio: 1; translate: -50% -50%; scale: 1.3; pointer-events: none; }
+.vh-fallback__svg { position: absolute; left: 50%; top: 50%; width: 30.47619047619048%; height: 30.47619047619048%; translate: -50% -50%; }
+
+.vh-label {
+ position: absolute; left: 50%; top: calc(50% + 20px + 20%); z-index: 20;
+ display: grid; translate: -50% 0; white-space: nowrap; text-align: center; pointer-events: none;
+ font-size: 24px; line-height: 32px; font-weight: 450; letter-spacing: -0.96px; color: var(--gray-1000);
+ opacity: 0; transition: opacity 300ms var(--ease);
+}
+.vh-label > span { grid-area: 1 / 1; justify-self: center; transition: opacity 300ms var(--ease); }
+.vh-label__loading { opacity: 0; }
+[data-hero-drop-active="true"] .vh-label { opacity: 1; }
+[data-hero-drop-staging="true"] .vh-label__drop { opacity: 0; }
+[data-hero-drop-staging="true"] .vh-label__loading { opacity: 1; }
+
+.vh-shader-root { position: absolute; inset: 0; z-index: 0; pointer-events: none; }
+.vh-canvas { position: absolute; inset: 0; display: block; width: 100%; height: 100%; opacity: 0; transition: opacity 1200ms linear; }
+.vh-pointer-area { position: absolute; inset: 0; pointer-events: none; }
+
+/* left: heading and buttons */
+.vh-header {
+ position: relative; width: 444px; z-index: 10;
+ display: flex; flex-direction: column; align-items: flex-start; gap: 32px; text-align: left;
+ user-select: text; -webkit-user-select: text;
+ transition: opacity 300ms var(--ease);
+}
+.vh-title { margin: 0; font-size: 64px; line-height: 64px; font-weight: 400; letter-spacing: -3.84px; text-wrap: balance; }
+.vh-buttons { display: flex; gap: 12px; }
+.vh-button {
+ display: flex; align-items: center; justify-content: center; height: 40px; padding: 0 12px; border-radius: 9999px;
+ font-size: 16px; line-height: 24px; font-weight: 500; text-decoration: none; white-space: nowrap;
+ transition: background 150ms var(--ease), color 150ms var(--ease), box-shadow 150ms var(--ease);
+}
+.vh-button > span { padding: 0 6px; }
+.vh-button--primary { background: var(--gray-1000); color: #fff; }
+.vh-button--primary:hover { background: rgb(56, 56, 56); }
+.vh-button--secondary { background: #fff; color: var(--gray-1000); box-shadow: rgb(235, 235, 235) 0 0 0 1px; }
+.vh-button--secondary:hover { background: rgb(242, 242, 242); }
+
+/* right: the three capabilities; hovering one lights an edge of the triangle */
+.vh-nav-wrap { position: relative; width: 364px; z-index: 10; transition: opacity 300ms var(--ease); }
+.vh-nav { display: flex; flex-direction: column; gap: 8px; padding: 32px 8px; }
+.vh-item { position: relative; z-index: 10; display: flex; align-items: flex-start; height: 24px; overflow: hidden; cursor: default; text-align: left; text-wrap: pretty; transition: height 200ms var(--ease-out); }
+.vh-item[data-open] { height: 84px; }
+.vh-item__text { display: block; }
+.vh-item__title { font-weight: 450; letter-spacing: -0.32px; color: var(--gray-900); transition: color 500ms var(--ease-out); }
+.vh-nav[data-none] .vh-item__title, .vh-item[data-open] .vh-item__title { color: var(--gray-1000); }
+.vh-item__desc { color: var(--gray-900); opacity: 0; transition: opacity 300ms var(--ease-out); }
+.vh-item[data-open] .vh-item__desc { opacity: 1; transition-duration: 500ms; }
+
+[data-hero-drop-active="true"] .vh-header,
+[data-hero-drop-active="true"] .vh-nav-wrap { opacity: 0; pointer-events: none; }
+
+@media (prefers-reduced-motion: reduce) {
+ .vh-label, .vh-label > span, .vh-header, .vh-nav-wrap { transition: none; }
+}
+
+/* ?embed: the canvas box alone */
+html[data-embed] .vh-frame { width: calc(1080px * var(--fit)); height: calc(720px * var(--fit)); margin: 0; }
+html[data-embed] .vh-page { left: calc(-180px * var(--fit)); top: calc(-88px * var(--fit)); position: relative; }
diff --git a/site/public/examples/vercel-hero/src/hero.js b/site/public/examples/vercel-hero/src/hero.js
new file mode 100644
index 0000000..99d68fc
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/hero.js
@@ -0,0 +1,248 @@
+// The page side of vercel.com's hero (its HeroShaderLayer, ported): starts the render worker, sends it the
+// canvas size, the pointer, clicks on the triangle, nav hovers and drag-and-drop, and draws the frames it
+// sends back. The canvas fades in over 1.2 s once the first frame is there; the static triangle behind it
+// then fades out. Without Worker + OffscreenCanvas + WebGL2 float targets, or with reduced motion, the
+// static triangle stays, as on vercel.com.
+
+import { ZOOM_DESKTOP, FPS_DESKTOP, FPS_MOBILE, TRIANGLE_HEIGHT, setZoom, zoomFor, triangle } from "./config.js";
+
+const hero = document.querySelector(".vh-hero");
+const box = document.querySelector(".vh-canvas-box");
+const root = document.querySelector(".vh-shader-root");
+const canvas = document.querySelector("[data-triangle-led-4-hero-canvas]");
+const area = document.querySelector(".vh-pointer-area");
+const fallback = document.querySelector(".vh-fallback");
+const nav = document.querySelector(".vh-nav");
+const items = [...document.querySelectorAll(".vh-item")];
+
+// the static triangle, with vercel.com's numbers
+{
+ const h = TRIANGLE_HEIGHT, r = (2 * h) / 3, n = h / 3, s = (2 * h) / Math.sqrt(3), d = 2 * r;
+ const svg = fallback.querySelector("svg");
+ svg.setAttribute("viewBox", `${-r} ${-r} ${d} ${d}`);
+ svg.querySelector("polygon").setAttribute("points", [{ x: 0, y: -r }, { x: -(0.5 * s), y: n }, { x: 0.5 * s, y: n }].map((p) => `${p.x},${p.y}`).join(" "));
+ svg.style.width = svg.style.height = `${100 * d}%`;
+}
+
+// vercel.com renders at 30 fps and at most 1.5x on small screens. ?embed is the desktop hero scaled into a
+// narrow frame, so there the screen decides, not the frame's width.
+const small = () => (document.documentElement.hasAttribute("data-embed") ? screen.width < 1024 : matchMedia("(max-width: 1023.98px)").matches);
+/** Canvas size in layout px (the page may be scaled down to fit) and device px. */
+function dimensions(el) {
+ const raw = Math.max(window.devicePixelRatio || 1, 1);
+ const dpr = small() ? Math.min(raw, 1.5) : raw;
+ const cssWidth = Math.max(1, Math.floor(el.offsetWidth));
+ const cssHeight = Math.max(1, Math.floor(el.offsetHeight));
+ return { cssWidth, cssHeight, pixelWidth: Math.max(1, Math.floor(cssWidth * dpr)), pixelHeight: Math.max(1, Math.floor(cssHeight * dpr)), dpr };
+}
+
+function webgl2() {
+ if (typeof OffscreenCanvas === "undefined") return false;
+ try {
+ const gl = new OffscreenCanvas(1, 1).getContext("webgl2");
+ return !!gl && !!gl.getExtension("EXT_color_buffer_float");
+ } catch {
+ return false;
+ }
+}
+function unavailable() {
+ if (typeof Worker === "undefined") return "Worker is unavailable.";
+ if (typeof OffscreenCanvas === "undefined") return "OffscreenCanvas is unavailable.";
+ if (!canvas.getContext("2d")) return "2D canvas rendering is unavailable.";
+ if (!webgl2()) return "WebGL2 is unavailable.";
+ if (matchMedia("(prefers-reduced-motion: reduce)").matches) return "Reduced motion is enabled.";
+}
+
+const problem = unavailable();
+if (problem) {
+ console.warn("Hero shader unavailable.", problem);
+} else start();
+
+function start() {
+ const ctx = canvas.getContext("2d");
+ const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
+ const send = (msg) => worker.postMessage(msg);
+ let pixelWidth = 0, pixelHeight = 0;
+ let dims = dimensions(root);
+ setZoom(zoomFor(ZOOM_DESKTOP, dims.cssHeight, false));
+
+ // ---------- frames ----------
+ worker.onmessage = ({ data }) => {
+ switch (data.type) {
+ case "firstFrame": {
+ canvas.style.opacity = "1";
+ let done = false;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ canvas.removeEventListener("transitionend", onEnd);
+ clearTimeout(timer);
+ fallback.dataset.hidden = "";
+ };
+ const onEnd = (e) => { if (e.propertyName === "opacity") finish(); };
+ canvas.addEventListener("transitionend", onEnd);
+ const timer = setTimeout(finish, 1300);
+ return;
+ }
+ case "frame": {
+ const bitmap = data.bitmap;
+ try {
+ if (pixelWidth < 1 || pixelHeight < 1) return;
+ if (canvas.width !== pixelWidth) canvas.width = pixelWidth;
+ if (canvas.height !== pixelHeight) canvas.height = pixelHeight;
+ const k = Math.max(pixelWidth / bitmap.width, pixelHeight / bitmap.height);
+ const w = bitmap.width * k, h = bitmap.height * k;
+ ctx.globalCompositeOperation = "copy";
+ ctx.drawImage(bitmap, (pixelWidth - w) * 0.5, (pixelHeight - h) * 0.5, w, h);
+ } finally {
+ bitmap.close();
+ }
+ return;
+ }
+ case "unsupported":
+ case "error":
+ console.warn("Hero shader unavailable.", data.stage ? `${data.stage}: ${data.reason}` : data.reason);
+ canvas.style.opacity = "";
+ worker.terminate();
+ return;
+ }
+ };
+ worker.onerror = (e) => {
+ console.warn("Hero shader unavailable.", e.message || "Hero shader worker failed.");
+ worker.terminate();
+ };
+
+ // ---------- size ----------
+ let sent;
+ const measure = () => {
+ const d = dimensions(root);
+ pixelWidth = d.pixelWidth;
+ pixelHeight = d.pixelHeight;
+ return d;
+ };
+ const resize = () => {
+ const d = measure();
+ dims = d;
+ setZoom(zoomFor(ZOOM_DESKTOP, d.cssHeight, false));
+ if (!sent || sent.cssWidth !== d.cssWidth || sent.cssHeight !== d.cssHeight || sent.pixelWidth !== d.pixelWidth || sent.pixelHeight !== d.pixelHeight || sent.dpr !== d.dpr) {
+ sent = d;
+ send({ type: "resize", dimensions: d });
+ }
+ };
+ let resizeTimer;
+ const later = () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(resize, 150); };
+ new ResizeObserver(() => { measure(); later(); }).observe(root);
+ addEventListener("resize", later);
+
+ send({
+ type: "init", dimensions: dims, theme: "light", activeClick: -1, probeDensity: 2,
+ targetFps: small() ? FPS_MOBILE : FPS_DESKTOP, cameraZoom: ZOOM_DESKTOP, heroMobile: false, dropActive: false, dropStaging: false,
+ });
+ resize();
+
+ // ---------- pointer: position over the canvas box, whether it is inside the triangle ----------
+ let paused = false, tracking = false, pointerCursor = false;
+ const baseCursor = document.documentElement.style.cursor;
+ const cursor = (on) => {
+ if (on === pointerCursor) return;
+ pointerCursor = on;
+ document.documentElement.style.cursor = on ? "pointer" : baseCursor;
+ };
+ const lost = () => {
+ if (!tracking && !pointerCursor) return;
+ tracking = false;
+ cursor(false);
+ send({ type: "pointer", pointer: { x: -1e3, y: -1e3, active: false, inside: false } });
+ };
+ const cross = (a, b, p) => (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
+ const pointer = (e) => {
+ if (paused) return false;
+ const r = area.getBoundingClientRect();
+ const w = Math.max(1, area.offsetWidth), h = Math.max(1, area.offsetHeight);
+ const sx = r.width > 0 ? w / r.width : 1, sy = r.height > 0 ? h / r.height : 1;
+ const x = (e.clientX - r.left) * sx, y = (e.clientY - r.top) * sy;
+ if (x < 0 || x > w || y < 0 || y > h) { lost(); return false; }
+ const { top, left, right } = triangle({ width: w, height: h });
+ const p = { x, y };
+ const s0 = cross(top, left, p), s1 = cross(left, right, p), s2 = cross(right, top, p);
+ const inside = (s0 <= 0 && s1 <= 0 && s2 <= 0) || (s0 >= 0 && s1 >= 0 && s2 >= 0);
+ tracking = true;
+ cursor(inside);
+ send({ type: "pointer", pointer: { x, y, active: true, inside, isMouse: e.pointerType === "mouse" } });
+ return inside;
+ };
+ document.addEventListener("pointermove", pointer, { passive: true });
+ // a click on the triangle switches the colours on or off
+ document.addEventListener("pointerup", (e) => {
+ if (paused) return;
+ if (e.target instanceof Element && e.target.closest('a,button,input,select,textarea,label,[role="button"],[contenteditable="true"]')) return;
+ if (pointer(e)) send({ type: "click", click: { kind: "toggle" } });
+ }, { passive: true });
+ addEventListener("blur", lost);
+ document.addEventListener("pointerleave", lost);
+
+ // ---------- visibility: render only while the hero is on screen ----------
+ let near = true;
+ const lifecycle = () => {
+ const active = near && !document.hidden;
+ paused = !active;
+ if (!active) lost();
+ send({ type: "lifecycle", lifecycle: active ? "active" : "paused" });
+ };
+ new IntersectionObserver(([e]) => { if (e.isIntersecting !== near) { near = e.isIntersecting; lifecycle(); } }, { rootMargin: "100px" }).observe(root);
+ document.addEventListener("visibilitychange", lifecycle);
+
+ // ---------- nav: hovering an item lights one edge (after 50 ms when coming from none) ----------
+ let active = -1, pending = null;
+ const setActive = (i) => {
+ if (i === active) return;
+ active = i;
+ items.forEach((el, k) => el.toggleAttribute("data-open", k === i));
+ nav.toggleAttribute("data-none", i === -1);
+ send({ type: "activeClick", activeClick: i });
+ };
+ const cancel = () => { if (pending !== null) { clearTimeout(pending); pending = null; } };
+ items.forEach((el, i) => {
+ el.addEventListener("mouseenter", () => {
+ cancel();
+ if (active === -1) pending = setTimeout(() => { pending = null; setActive(i); }, 50);
+ else setActive(i);
+ });
+ el.addEventListener("mouseleave", cancel);
+ });
+ nav.addEventListener("mouseleave", () => { cancel(); setActive(-1); });
+
+ // ---------- drag and drop: a file over the page, while the hero is at least half on screen ----------
+ let depth = 0, dragging = false, inView = false, dropShown = false;
+ const update = () => {
+ const on = dragging && inView;
+ hero.dataset.heroDropActive = on ? "true" : "false";
+ if (on !== dropShown) { dropShown = on; send({ type: "dropActive", active: on }); }
+ };
+ const files = (e) => e.dataTransfer?.types.includes("Files") ?? false;
+ document.addEventListener("dragenter", (e) => {
+ if (!files(e)) return;
+ if (!e.defaultPrevented) e.preventDefault();
+ depth += 1;
+ if (depth === 1) { dragging = true; update(); }
+ });
+ document.addEventListener("dragover", (e) => {
+ if (!files(e) || e.defaultPrevented) return;
+ e.preventDefault();
+ if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
+ });
+ document.addEventListener("dragleave", (e) => {
+ if (!files(e)) return;
+ depth -= 1;
+ if (depth <= 0) { depth = 0; dragging = false; update(); }
+ });
+ // this copy deploys nothing: a drop just ends the drag
+ document.addEventListener("drop", (e) => {
+ if (!files(e)) return;
+ e.preventDefault();
+ depth = 0;
+ dragging = false;
+ update();
+ });
+ new IntersectionObserver(([e]) => { inView = e.intersectionRatio >= 0.5; update(); }, { threshold: Array.from({ length: 21 }, (_, i) => i / 20) }).observe(box);
+}
diff --git a/site/public/examples/vercel-hero/src/leds.js b/site/public/examples/vercel-hero/src/leds.js
new file mode 100644
index 0000000..87286e2
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/leds.js
@@ -0,0 +1,360 @@
+// The 72 LEDs along the triangle's edges, ported from vercel.com's hero (modules 103584 and 4234513).
+// Every frame each LED gets a brightness and a colour: three soft lines of light run round the edges;
+// near the pointer the lines fade and the LEDs facing it light up instead; hovering a nav item lights
+// one edge; a dragged file brings three brighter segments that chase round; the colour mix tints them
+// (dark theme only). The result is uploaded as a 2x72 float texture the shaders read.
+//
+// Per LED, 8 floats: x, y, brightness, angle, r, g, b, 0. The typed arrays are Float32Array, as on
+// vercel.com, so values round the same way.
+
+import { LEDS_PER_SIDE, LED_COUNT, MODES, ANIMATION_CLOCK_START, ledLayout, DROP_BASE_MIN, DROP_BASE_MAX, DROP_SEGMENTS, DROP_SEGMENT_HALF, DROP_SEGMENT_GROW, DROP_SEGMENT_CORE, DROP_SEGMENT_SPEED, DROP_SEGMENT_SPEEDS } from "./config.js";
+
+export const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
+export const lerp = (a, b, t) => a + (b - a) * t;
+const remap = (value, inMin, inMax, outMin, outMax) => lerp(outMin, outMax, inMin === inMax ? 0 : (value - inMin) / (inMax - inMin));
+const smoothstep = (e0, e1, x) => {
+ const t = clamp01((x - e0) / (e1 - e0));
+ return t * t * (3 - 2 * t);
+};
+/** Signed distance from LED i to position c round the ring of `n`. */
+const ringDelta = (i, c, n) => (((i - c) % n) + n + n / 2) % n - n / 2;
+const wrap = (v) => ((v % LED_COUNT) + LED_COUNT) % LED_COUNT;
+
+// lines mode: three lines, their start positions and speeds (LEDs per second), widths and brightness
+// breathing on slow sines
+const LINE_START = [6, 6, 6];
+const LINE_SPEED = [-3.302, -2.355, -1.636];
+const WIDTH_MIN = LEDS_PER_SIDE;
+const WIDTH_MAX = 1.7 * LEDS_PER_SIDE;
+const WIDTH_MID = (WIDTH_MIN + WIDTH_MAX) / 2;
+const WIDTH_SWING = (WIDTH_MAX - WIDTH_MIN) / 2;
+const WIDTH_RATE = [0.41, 0.31, 0.23];
+const WIDTH_PHASE = [0, 2.1, 4.2];
+const LEVEL_RATE = [0.52, 0.38, 0.28];
+const LEVEL_PHASE = [Math.PI / 2, 0.4, -0.6];
+const DEFAULT_RED = { r: 0.896269, g: 0.027321, b: 0.051269 };
+const DEFAULT_GREEN = { r: 0, g: 0.40724, b: 0.048172 };
+const DEFAULT_BLUE = { r: 0, g: 0.278894, b: 1 };
+
+export function createLeds(sim, prev) {
+ const layout = ledLayout(sim, LEDS_PER_SIDE);
+ const n = layout.positions.length;
+ const data = new Float32Array(8 * n);
+ const local = new Float32Array(2 * n);
+ const normals = new Float32Array(2 * n);
+ for (const [i, p] of layout.positions.entries()) {
+ const o = 8 * i;
+ const angle = p.angle ?? 0;
+ data[o] = p.x; data[o + 1] = p.y; data[o + 2] = 0; data[o + 3] = angle;
+ data[o + 4] = 1; data[o + 5] = 1; data[o + 6] = 1; data[o + 7] = 0;
+ const dx = p.x - layout.center.x, dy = p.y - layout.center.y;
+ local[2 * i] = dx; local[2 * i + 1] = dy;
+ let nx = -Math.sin(angle), ny = Math.cos(angle);
+ if (nx * dx + ny * dy < 0) { nx = -nx; ny = -ny; } // outward
+ normals[2 * i] = nx; normals[2 * i + 1] = ny;
+ }
+ const g = layout.geometry;
+ const mid = (a, b) => ({ x: (a.x + b.x) * 0.5, y: (a.y + b.y) * 0.5 });
+ return {
+ data,
+ currentState: Float32Array.from(data),
+ targetState: Float32Array.from(data),
+ deployingState: Float32Array.from(data),
+ dropActiveState: Float32Array.from(data),
+ local, normals,
+ ledRadius: layout.ledRadius,
+ triangleHeight: g.height,
+ deployEdgeCenters: [mid(g.top, g.left), mid(g.left, g.right), mid(g.right, g.top)],
+ triangleVertices: [{ x: g.top.x, y: g.top.y }, { x: g.left.x, y: g.left.y }, { x: g.right.x, y: g.right.y }],
+ lastMode: prev?.lastMode,
+ lastEdgeIndex: prev?.lastEdgeIndex,
+ transitionStart: 0,
+ transitionDuration: 0,
+ transitionActive: false,
+ animationClock: prev?.animationClock ?? 0,
+ startupElapsed: prev?.startupElapsed ?? 0,
+ lastFrameTime: prev?.lastFrameTime,
+ lineCenters: prev?.lineCenters ?? Float32Array.from(LINE_START),
+ lineVelocities: prev?.lineVelocities ?? Float32Array.from(LINE_SPEED),
+ glowState: prev?.glowState ?? new Float32Array(LED_COUNT),
+ glowDecaying: prev?.glowDecaying ?? false,
+ hoverTransition: prev?.hoverTransition ?? 0,
+ hoverActive: prev?.hoverActive ?? false,
+ };
+}
+
+function setLed(arr, i, brightness, r, g, b) {
+ const o = 8 * i;
+ arr[o + 2] = brightness; arr[o + 4] = r; arr[o + 5] = g; arr[o + 6] = b;
+}
+function mixInto(out, from, to, t) {
+ for (let i = 0; i < out.length; i++) {
+ const a = from[i] ?? 0;
+ out[i] = a + ((to[i] ?? 0) - a) * t;
+ }
+}
+
+function linesTarget(leds, target, clock, dt) {
+ for (let k = 0; k < 3; k++) leds.lineCenters[k] = wrap((leds.lineCenters[k] ?? 0) + (leds.lineVelocities[k] ?? 0) * dt);
+ const t = clock - ANIMATION_CLOCK_START;
+ const width = [], core = [], level = [];
+ for (let k = 0; k < 3; k++) {
+ const w = Math.max(1, 0.5 * (WIDTH_MID + WIDTH_SWING * Math.sin(t * WIDTH_RATE[k] + WIDTH_PHASE[k])));
+ width[k] = w;
+ core[k] = 0.5 * w;
+ level[k] = 0.5 + 0.5 * Math.sin(t * LEVEL_RATE[k] + LEVEL_PHASE[k]);
+ }
+ for (let i = 0; i < LED_COUNT; i++) {
+ let v = 0;
+ for (let k = 0; k < 3; k++) {
+ const d = Math.abs(ringDelta(i, leds.lineCenters[k] ?? 0, LED_COUNT));
+ const w = width[k] ?? 1, c = core[k] ?? 0;
+ v = Math.max(v, (d <= c ? 1 : clamp01(1 - (d - c) / (w - c))) * (level[k] ?? 0));
+ }
+ setLed(target, i, clamp01(v), 1, 1, 1);
+ }
+}
+
+/** Signed distance from p to the triangle (negative inside). */
+function triangleDistance(px, py, [v0, v1, v2]) {
+ const e0x = v1.x - v0.x, e0y = v1.y - v0.y;
+ const e1x = v2.x - v1.x, e1y = v2.y - v1.y;
+ const e2x = v0.x - v2.x, e2y = v0.y - v2.y;
+ const p0x = px - v0.x, p0y = py - v0.y;
+ const p1x = px - v1.x, p1y = py - v1.y;
+ const p2x = px - v2.x, p2y = py - v2.y;
+ const t0 = clamp01((p0x * e0x + p0y * e0y) / (e0x * e0x + e0y * e0y || 1));
+ const t1 = clamp01((p1x * e1x + p1y * e1y) / (e1x * e1x + e1y * e1y || 1));
+ const t2 = clamp01((p2x * e2x + p2y * e2y) / (e2x * e2x + e2y * e2y || 1));
+ let a, b, c, d, e, f;
+ const dist = Math.sqrt(Math.min((a = p0x - e0x * t0) * a + (b = p0y - e0y * t0) * b, (c = p1x - e1x * t1) * c + (d = p1y - e1y * t1) * d, (e = p2x - e2x * t2) * e + (f = p2y - e2y * t2) * f));
+ const s = Math.sign(e0x * e2y - e0y * e2x);
+ return -dist * Math.sign(Math.min(s * (p0x * e0y - p0y * e0x), s * (p1x * e1y - p1y * e1x), s * (p2x * e2y - p2y * e2x)));
+}
+
+/** Pull towards each edge's colour by distance from the edge centres, normalised to luminance 1. */
+function deployTint(leds, i, tint) {
+ const amount = clamp01(tint?.amount ?? 1);
+ const radius = Math.max(tint?.radius ?? 1, 1);
+ const power = Math.max(tint?.power ?? 1, 1e-3);
+ const red = tint?.edgeRedLinear ?? DEFAULT_RED, green = tint?.edgeGreenLinear ?? DEFAULT_GREEN, blue = tint?.edgeBlueLinear ?? DEFAULT_BLUE;
+ const o = 8 * i;
+ const x = leds.data[o] ?? 0, y = leds.data[o + 1] ?? 0;
+ const [c0, c1, c2] = leds.deployEdgeCenters;
+ const sharp = 1 / Math.max(tint?.edgeOverlap ?? 1, 0.01);
+ const fall = (cx, cy) => (1 / (1 + Math.hypot(x - cx, y - cy) / radius)) ** power;
+ const w0 = fall(c0.x, c0.y) ** sharp, w1 = fall(c1.x, c1.y) ** sharp, w2 = fall(c2.x, c2.y) ** sharp;
+ const sum = Math.max(w0 + w1 + w2, 1e-4);
+ let r = (red.r * w0 + green.r * w1 + blue.r * w2) / sum;
+ let g = (red.g * w0 + green.g * w1 + blue.g * w2) / sum;
+ let b = (red.b * w0 + green.b * w1 + blue.b * w2) / sum;
+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ if (lum > 1e-4) { const k = 1 / lum; r *= k; g *= k; b *= k; }
+ return { r: lerp(1, r, amount), g: lerp(1, g, amount), b: lerp(1, b, amount) };
+}
+
+/**
+ * Advance the LEDs to `time` (seconds). Port of vercel.com's per-frame LED update, for the two modes
+ * the homepage uses (lines; edge while a nav item is hovered).
+ */
+export function updateLeds(leds, time, tunables, hero, hoverDeploy, brush, theme = "dark", drop) {
+ let modeChanged = false;
+ const first = leds.lastFrameTime === undefined;
+ const dt = first ? 0 : Math.max(0, Math.min(time - leds.lastFrameTime, 0.1));
+ leds.lastFrameTime = time;
+ // the LED clock runs up to 10x faster while the colours switch on or off
+ const clockDt = dt * (1 + 9 * Math.sin(clamp01(hoverDeploy?.factor ?? 0) * Math.PI));
+ if (first) leds.animationClock = ANIMATION_CLOCK_START;
+ leds.animationClock += clockDt;
+ leds.startupElapsed += dt;
+ const clock = leds.animationClock;
+ const edgeIndex = Number.isFinite(hero.edgeIndex) ? Math.max(0, Math.min(2, Math.round(hero.edgeIndex))) : 0;
+ const edgeChanged = hero.mode === MODES.edge && leds.lastEdgeIndex !== undefined && edgeIndex !== leds.lastEdgeIndex;
+ const isNewMode = leds.lastMode === undefined || hero.mode !== leds.lastMode;
+ if (leds.lastMode === undefined) {
+ leds.lastMode = hero.mode;
+ leds.lastEdgeIndex = edgeIndex;
+ leds.transitionActive = false;
+ } else if (hero.mode !== leds.lastMode || edgeChanged) {
+ modeChanged = true;
+ leds.currentState.set(leds.data);
+ leds.transitionStart = time;
+ leds.transitionDuration = Math.max(0, hero.transitionDuration);
+ leds.transitionActive = leds.transitionDuration > 0;
+ leds.lastMode = hero.mode;
+ leds.lastEdgeIndex = edgeIndex;
+ }
+ if (isNewMode && hero.mode === MODES.lines) leds.lineCenters.set(LINE_START);
+
+ if (hero.mode === MODES.edge) {
+ const lit = theme === "light" ? clamp01(hoverDeploy?.factor ?? 0) : 0;
+ const base = clamp01(0.125 * tunables.brightnessMin * (1 - 0.8 * lit));
+ const high = clamp01(hero.edgeHighlightBrightness * (1 + 2 * lit));
+ const from = edgeIndex * LEDS_PER_SIDE, to = from + LEDS_PER_SIDE;
+ for (let i = 0; i < LED_COUNT; i++) setLed(leds.targetState, i, i >= from && i < to ? high : base, 1, 1, 1);
+ } else {
+ linesTarget(leds, leds.targetState, clock, clockDt);
+ }
+
+ // near the triangle (outside it) the lines fade out over ~0.3 s, so the pointer glow reads clearly
+ const fades = hero.mode === MODES.lines && (brush?.linesFadeDistance ?? 0) > 0;
+ let fade = 0;
+ if (fades) {
+ let want = 0;
+ if (brush?.active === true && brush.isMouse === true && brush.inside !== true) {
+ const reach = (brush.linesFadeDistance ?? 0) * leds.triangleHeight;
+ const d = triangleDistance(brush.x, brush.y, leds.triangleVertices);
+ if (!leds.hoverActive && d < reach) leds.hoverActive = true;
+ else if (leds.hoverActive && d > 1.2 * reach) leds.hoverActive = false;
+ want = leds.hoverActive ? 1 : 0;
+ } else leds.hoverActive = false;
+ if (leds.hoverTransition > 1e-4 || want > 0) leds.hoverTransition += (want - leds.hoverTransition) * (1 - Math.exp(-dt / 0.3));
+ if ((fade = clamp01(leds.hoverTransition)) > 1e-4) {
+ const keep = 1 - fade;
+ for (let i = 0; i < LED_COUNT; i++) leds.targetState[8 * i + 2] *= keep;
+ }
+ } else if (leds.hoverTransition !== 0 || leds.hoverActive) {
+ leds.hoverTransition = 0;
+ leds.hoverActive = false;
+ }
+
+ // mode changes cross-fade with an ease-in over transitionDuration (0.25 s)
+ let progress = 1, eased = 1;
+ if (leds.transitionActive) {
+ progress = clamp01((time - leds.transitionStart) / leds.transitionDuration);
+ const p = clamp01(progress);
+ eased = p * p;
+ mixInto(leds.data, leds.currentState, leds.targetState, eased);
+ if (progress >= 1) leds.transitionActive = false;
+ } else leds.data.set(leds.targetState);
+
+ // colour tint (its amount is 0 in the light theme, where the floor shader does the colour)
+ const deploy = clamp01(hoverDeploy?.factor ?? 0);
+ if (deploy > 0) {
+ leds.deployingState.set(leds.data);
+ for (let i = 0; i < LED_COUNT; i++) {
+ const c = deployTint(leds, i, hoverDeploy?.tint);
+ const o = 8 * i;
+ leds.deployingState[o + 4] = c.r; leds.deployingState[o + 5] = c.g; leds.deployingState[o + 6] = c.b;
+ }
+ mixInto(leds.data, leds.data, leds.deployingState, deploy);
+ }
+
+ // a file dragged over the page: three segments chase round the edges over a half-lit base
+ const dropFactor = clamp01(drop?.factor ?? 0);
+ if (dropFactor > 1e-4) {
+ const state = leds.dropActiveState;
+ state.set(leds.data);
+ const phase = Number.isFinite(drop?.phase) ? Math.max(0, drop.phase) : 0;
+ const boost = clamp01(drop?.boost ?? 0);
+ const base = clamp01(lerp(DROP_BASE_MIN, DROP_BASE_MAX, boost));
+ const count = Math.max(1, Math.floor(DROP_SEGMENTS));
+ const spacing = LED_COUNT / count;
+ const half = Math.max(1e-3, Math.min(0.5 * spacing, DROP_SEGMENT_HALF * remap(boost, 0, 1, 1, DROP_SEGMENT_GROW)));
+ const core = Math.max(0, Math.min(half, DROP_SEGMENT_CORE));
+ const soft = Math.max(1e-3, half - core);
+ for (let i = 0; i < LED_COUNT; i++) {
+ let v = 0;
+ for (let k = 0; k < count; k++) {
+ const speed = DROP_SEGMENT_SPEEDS[k % DROP_SEGMENT_SPEEDS.length] ?? 1;
+ const d = Math.abs(ringDelta(i, wrap(k * spacing + phase * DROP_SEGMENT_SPEED * speed), LED_COUNT));
+ v = Math.max(v, d <= core ? 1 : clamp01(1 - (d - core) / soft));
+ }
+ state[8 * i + 2] = clamp01(base + (1 - base) * v);
+ }
+ mixInto(leds.data, leds.data, state, dropFactor);
+ }
+
+ // pointer glow: LEDs within glowRadius that face the pointer light up, smoothed over glowSmoothing
+ // (0.23 s); while the lines run it is scaled by their fade, so it shows near the triangle only
+ const glowScale = fades ? fade : 1;
+ const strength = brush?.glowStrength ?? 0;
+ const radius = brush?.glowRadius ?? 0;
+ const glowing = brush?.active === true && brush.isMouse === true && brush.glowEnabled === true && strength > 0 && radius > 0;
+ if (glowing || leds.glowDecaying) {
+ const smoothing = brush?.glowSmoothing ?? 0;
+ const k = smoothing > 0 ? 1 - Math.exp(-dt / smoothing) : 1;
+ const px = brush?.x ?? 0, py = brush?.y ?? 0;
+ const facing = brush?.glowFacingEnabled === true;
+ const full = Math.cos(((brush?.glowFacingFullDeg ?? 90) * Math.PI) / 180);
+ const zero = Math.cos(((brush?.glowFacingZeroDeg ?? 100) * Math.PI) / 180);
+ const span = full - zero;
+ let any = false;
+ for (let i = 0; i < LED_COUNT; i++) {
+ const o = 8 * i;
+ let want = 0;
+ if (glowing) {
+ const dx = (leds.data[o] ?? 0) - px, dy = (leds.data[o + 1] ?? 0) - py;
+ const d = Math.hypot(dx, dy);
+ want = strength * (1 - smoothstep(0, radius, d));
+ if (facing && want > 0 && d > 1e-4) {
+ const f = (leds.normals[2 * i] ?? 0) * (-dx / d) + (leds.normals[2 * i + 1] ?? 0) * (-dy / d);
+ want *= span > 1e-6 ? clamp01((f - zero) / span) : +(f >= full);
+ }
+ }
+ const g = (leds.glowState[i] ?? 0) + (want - (leds.glowState[i] ?? 0)) * k;
+ leds.glowState[i] = g;
+ if (g > 1e-4) {
+ any = true;
+ const v = g * glowScale;
+ if (v > 1e-4) leds.data[o + 2] = lerp(leds.data[o + 2] ?? 0, 1, v);
+ }
+ }
+ leds.glowDecaying = glowing || any;
+ }
+ return { mode: hero.mode, modeChanged, progress, easedProgress: eased, active: leds.transitionActive };
+}
+
+// ---------- emitter mesh: one quad per LED and a split cap in each corner ----------
+const basis = (angle) => {
+ const dir = { x: Math.cos(angle), y: Math.sin(angle) };
+ return { dir, normal: { x: -dir.y, y: dir.x } };
+};
+const offset = (p, d, k) => ({ x: p.x + d.x * k, y: p.y + d.y * k, n: k });
+const dist2 = (a, b) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;
+const farther = (a, b, from) => (dist2(a, from) >= dist2(b, from) ? a : b);
+function intersect(p, d, q, e) {
+ const den = d.x * e.y - d.y * e.x;
+ if (Math.abs(den) < 1e-6) return undefined;
+ const s = ((q.x - p.x) * e.y - (q.y - p.y) * e.x) / den;
+ return { x: p.x + d.x * s, y: p.y + d.y * s };
+}
+/** Vertices (x, y, local t, local n, LED index, 0) of the LED emitter triangles. */
+export function ledVertices(sim, expand) {
+ const layout = ledLayout(sim, LEDS_PER_SIDE);
+ const { tangentHalfLength: half, normalHalfThickness: thick } = layout.ledShape;
+ const ht = half + expand, hn = thick + expand;
+ const out = [];
+ const push = (i, x, y, t, n) => out.push(x, y, t, n, i, 0);
+ const quad = (i, c, dir, nor, t0, t1, n0, n1) => {
+ const k = [{ t: t0, n: n0 }, { t: t1, n: n0 }, { t: t1, n: n1 }, { t: t0, n: n1 }];
+ for (const j of [0, 1, 2, 0, 2, 3]) {
+ const v = k[j];
+ push(i, c.x + dir.x * v.t + nor.x * v.n, c.y + dir.y * v.t + nor.y * v.n, v.t, v.n);
+ }
+ };
+ for (const [i, p] of layout.positions.entries()) {
+ const b = basis(p.angle ?? 0);
+ quad(i, p, b.dir, b.normal, -ht, ht, -hn, hn);
+ }
+ const corners = [layout.geometry.top, layout.geometry.left, layout.geometry.right];
+ for (let e = 0; e < 3; e++) {
+ const prevIdx = ((e + 2) % 3) * LEDS_PER_SIDE + LEDS_PER_SIDE - 1;
+ const nextIdx = e * LEDS_PER_SIDE;
+ const prev = layout.positions[prevIdx], next = layout.positions[nextIdx], corner = corners[e];
+ if (!prev || !next || !corner) continue;
+ const pb = basis(prev.angle ?? 0), nb = basis(next.angle ?? 0);
+ const end = { x: prev.x + pb.dir.x * ht, y: prev.y + pb.dir.y * ht };
+ const start = { x: next.x - nb.dir.x * ht, y: next.y - nb.dir.y * ht };
+ let bx = end.x + start.x - 2 * corner.x, by = end.y + start.y - 2 * corner.y;
+ const bl = Math.hypot(bx, by);
+ if (bl <= 0) { bx = 0; by = 0; } else { bx /= bl; by /= bl; }
+ const tip = { x: corner.x + bx * (layout.ledShape.cornerTrim + ht), y: corner.y + by * (layout.ledShape.cornerTrim + ht) };
+ const s = farther(offset(end, pb.normal, -hn), offset(end, pb.normal, hn), start);
+ const f = farther(offset(start, nb.normal, -hn), offset(start, nb.normal, hn), end);
+ const w = intersect(s, pb.dir, f, nb.dir) ?? corner;
+ push(prevIdx, w.x, w.y, half, 0); push(prevIdx, s.x, s.y, ht, s.n); push(prevIdx, tip.x, tip.y, half, 0);
+ push(nextIdx, w.x, w.y, -half, 0); push(nextIdx, tip.x, tip.y, -half, 0); push(nextIdx, f.x, f.y, -ht, f.n);
+ }
+ return new Float32Array(out);
+}
diff --git a/site/public/examples/vercel-hero/src/renderer.js b/site/public/examples/vercel-hero/src/renderer.js
new file mode 100644
index 0000000..fd21406
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/renderer.js
@@ -0,0 +1,394 @@
+// WebGL2 renderer of vercel.com's hero (its WGSL renderer's WebGL port, worker chunk 01yx7m50w8_tu.js):
+// same targets, uniform-buffer layouts, pass order and blend state. One frame:
+// 1. light sources (simulation size, RGBA16F): the SDF of the LED segments and the black triangle in
+// alpha, baked once; then each LED's colour x brightness drawn into RGB by the emitter mesh
+// 2. direct raycast (half size, RGBA16F): rays from every probe gather the LED light
+// 3. floor (canvas size, RGBA8): the light (or dark) floor shader turns it into the picture
+// 4. present: blit to the canvas
+
+import * as GLSL from "./shaders.js";
+import { LEDS_PER_SIDE, LED_ROWS, LED_EMITTER_EXPAND, LED_CLIP_EXPAND, LED_CLIP_INSET_RANGE, TUNABLES, DESIGN_HEIGHT, cascadeFit, raycastSize, ledRadius, ledShape, triangle, insetTriangle, clampProbeDensity, clampCascadeCount, cascadeCountFor, getPointerCutoff, nonNegative } from "./config.js";
+import { createLeds, updateLeds, ledVertices } from "./leds.js";
+import { createFrameResolver } from "./frame.js";
+
+export class UnsupportedError extends Error { name = "WebglUnsupportedError"; }
+
+function compile(gl, type, src, label) {
+ const s = gl.createShader(type);
+ gl.shaderSource(s, src);
+ gl.compileShader(s);
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
+ const log = gl.getShaderInfoLog(s);
+ gl.deleteShader(s);
+ throw new Error(`Failed to compile shader ${label}: ${log ?? "unknown"}`);
+ }
+ return s;
+}
+function program(gl, vert, frag, label) {
+ const v = compile(gl, gl.VERTEX_SHADER, vert, `${label}.vert`);
+ const f = compile(gl, gl.FRAGMENT_SHADER, GLSL.FRAGMENT_PREFIX + GLSL.COMMON + frag, `${label}.frag`);
+ const p = gl.createProgram();
+ gl.attachShader(p, v); gl.attachShader(p, f); gl.linkProgram(p);
+ gl.detachShader(p, v); gl.detachShader(p, f); gl.deleteShader(v); gl.deleteShader(f);
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
+ const log = gl.getProgramInfoLog(p);
+ gl.deleteProgram(p);
+ throw new Error(`Failed to link program ${label}: ${log ?? "unknown"}`);
+ }
+ return p;
+}
+function target(gl, width, height, format, label) {
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texStorage2D(gl.TEXTURE_2D, 1, format, width, height);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ const framebuffer = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
+ gl.deleteFramebuffer(framebuffer); gl.deleteTexture(texture);
+ throw new UnsupportedError(`Float framebuffer ${label} is incomplete (status 0x${status.toString(16)}); float render targets are required.`);
+ }
+ return { framebuffer, texture, width, height };
+}
+const dropTarget = (gl, t) => { if (t) { gl.deleteFramebuffer(t.framebuffer); gl.deleteTexture(t.texture); } };
+function ubo(gl, bytes) {
+ const buffer = gl.createBuffer();
+ gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
+ gl.bufferData(gl.UNIFORM_BUFFER, bytes, gl.DYNAMIC_DRAW);
+ gl.bindBuffer(gl.UNIFORM_BUFFER, null);
+ return { buffer, byteLength: bytes };
+}
+const writeUbo = (gl, u, data) => { gl.bindBuffer(gl.UNIFORM_BUFFER, u.buffer); gl.bufferSubData(gl.UNIFORM_BUFFER, 0, data); gl.bindBuffer(gl.UNIFORM_BUFFER, null); };
+const bindBlock = (gl, p, name, index) => { const i = gl.getUniformBlockIndex(p, name); if (i !== gl.INVALID_INDEX) gl.uniformBlockBinding(p, i, index); };
+const sampler = (gl, p, name, unit) => { const l = gl.getUniformLocation(p, name); if (l) gl.uniform1i(l, unit); };
+const size = (w, h) => ({ width: Math.max(1, Math.floor(w)), height: Math.max(1, Math.floor(h)) });
+const same = (a, b) => a.width === b.width && a.height === b.height;
+const ratio = (v) => Math.max(1e-3, typeof v === "number" && Number.isFinite(v) ? v : 1);
+const cascades = (count, sim) => clampCascadeCount(count) ?? cascadeCountFor(sim);
+/** OKLab-ish cube roots of the edge colours, as the floor shader expects them. */
+const lms = (c) => ({
+ r: Math.cbrt(0.412165612 * c.r + 0.536275208 * c.g + 0.0514575653 * c.b),
+ g: Math.cbrt(0.21185911 * c.r + 0.6807189584 * c.g + 0.107406579 * c.b),
+ b: Math.cbrt(0.0883097947 * c.r + 0.2818474174 * c.g + 0.6302613616 * c.b),
+});
+
+export function createRenderer(gl) {
+ let programs;
+ let res; // size-dependent resources
+ let destroyed = false;
+ let firstEncode = true; // the particle target is cleared on the first frame
+ const frames = createFrameResolver();
+
+ function ensurePrograms() {
+ if (programs) return programs;
+ const lightSources = program(gl, GLSL.FULLSCREEN_VERT, GLSL.LIGHT_SOURCES_FRAG, "triangle-led-4-gl-light-sources");
+ const ledEmitters = program(gl, GLSL.LED_EMITTERS_VERT, GLSL.LED_EMITTERS_FRAG, "triangle-led-4-gl-led-emitters");
+ const directRaycast = program(gl, GLSL.FULLSCREEN_VERT, GLSL.DIRECT_RAYCAST_FRAG, "triangle-led-4-gl-direct-raycast");
+ const darkFloor = program(gl, GLSL.FULLSCREEN_VERT, GLSL.DARK_FLOOR_FRAG, "triangle-led-4-gl-dark-floor");
+ const lightFloor = program(gl, GLSL.FULLSCREEN_VERT, GLSL.LIGHT_FLOOR_FRAG, "triangle-led-4-gl-light-floor");
+ const floorNoise = program(gl, GLSL.FULLSCREEN_VERT, GLSL.FLOOR_NOISE_FRAG, "triangle-led-4-gl-floor-noise");
+ const present = program(gl, GLSL.PRESENT_VERT, GLSL.PRESENT_FRAG, "triangle-led-4-gl-present");
+ gl.useProgram(lightSources); sampler(gl, lightSources, "u_leds", 0);
+ gl.useProgram(ledEmitters); sampler(gl, ledEmitters, "u_leds", 0);
+ gl.useProgram(directRaycast); sampler(gl, directRaycast, "light_sources_tex", 0);
+ gl.useProgram(darkFloor);
+ sampler(gl, darkFloor, "radiance_tex", 1); sampler(gl, darkFloor, "light_sources_tex", 2); sampler(gl, darkFloor, "floor_noise_tex", 3); sampler(gl, darkFloor, "particle_tex", 4);
+ gl.useProgram(lightFloor);
+ sampler(gl, lightFloor, "radiance_tex", 1); sampler(gl, lightFloor, "light_sources_tex", 2); sampler(gl, lightFloor, "particle_tex", 4);
+ gl.useProgram(present); sampler(gl, present, "u_present", 0);
+ gl.useProgram(null);
+ for (const p of [lightSources, ledEmitters, directRaycast, darkFloor, lightFloor]) bindBlock(gl, p, "Config", 0);
+ bindBlock(gl, lightFloor, "LightGlow", 1);
+ const fullscreenVao = gl.createVertexArray();
+ // the dark floor's grain, baked once into a 500x500 texture
+ const noise = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, noise);
+ gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, 500, 500);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ const fb = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, noise, 0);
+ gl.viewport(0, 0, 500, 500);
+ gl.disable(gl.BLEND); gl.disable(gl.DEPTH_TEST); gl.colorMask(true, true, true, true);
+ gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(floorNoise); gl.bindVertexArray(fullscreenVao); gl.drawArrays(gl.TRIANGLES, 0, 3);
+ gl.bindVertexArray(null); gl.useProgram(null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.deleteFramebuffer(fb); gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.deleteProgram(floorNoise);
+ const presentSampler = gl.createSampler();
+ gl.samplerParameteri(presentSampler, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.samplerParameteri(presentSampler, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.samplerParameteri(presentSampler, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.samplerParameteri(presentSampler, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ programs = { lightSources, ledEmitters, directRaycast, darkFloor, lightFloor, present, fullscreenVao, floorNoise: noise, presentSampler };
+ return programs;
+ }
+
+ function simResources(sim, density, count, prevLeds) {
+ const fit = cascadeFit(sim, density);
+ const cascade = raycastSize(sim);
+ const leds = createLeds(sim, prevLeds);
+ const ledTexture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, ledTexture);
+ gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA32F, 2, LED_ROWS);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ const led = { texture: ledTexture, rows: LED_ROWS };
+ uploadLeds(led, leds.data);
+ const lightSources = target(gl, sim.width, sim.height, gl.RGBA16F, "triangle-led-4-gl-light-sources");
+ const directRaycast = target(gl, cascade.width, cascade.height, gl.RGBA16F, "triangle-led-4-gl-direct-raycast");
+ const verts = ledVertices(sim, LED_EMITTER_EXPAND);
+ const ledVertexBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, ledVertexBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW);
+ const ledVao = gl.createVertexArray();
+ gl.bindVertexArray(ledVao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, ledVertexBuffer);
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 24, 0);
+ gl.enableVertexAttribArray(1); gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 24, 8);
+ gl.enableVertexAttribArray(2); gl.vertexAttribPointer(2, 1, gl.FLOAT, false, 24, 16);
+ gl.bindVertexArray(null); gl.bindBuffer(gl.ARRAY_BUFFER, null);
+ const configUbo = ubo(gl, 112);
+ const directRaycastUbo = ubo(gl, 256);
+ // raycast constants, written once: the inset triangle, target sizes, ray length, step and hit settings
+ const tri = insetTriangle(sim);
+ const d = new Float32Array(64);
+ d.set([tri.top.x, tri.top.y, tri.left.x, tri.left.y], 0);
+ d.set([tri.right.x, tri.right.y, cascade.width, cascade.height], 4);
+ const scale = Math.min(sim.height, DESIGN_HEIGHT) / DESIGN_HEIGHT;
+ d.set([sim.width, sim.height, 1.5 * scale, 0.75 * scale], 8);
+ d.set([2 / sim.height, 1, 50, 1e-3], 12);
+ d.set([0.5, DESIGN_HEIGHT / Math.max(sim.height, 1), 0, 0], 16);
+ writeUbo(gl, directRaycastUbo, d);
+ return {
+ simulationSize: sim, probeDensity: density, cascadeFit: fit, cascade, count, leds, ledTexture: led, lightSources, directRaycast, ledVao, ledVertexBuffer,
+ ledVertexCount: verts.length / 6, ledRadius: ledRadius(sim), ledShape: ledShape(sim, LEDS_PER_SIDE), triangle: triangle(sim), configUbo, directRaycastUbo,
+ };
+ }
+ function uploadLeds(led, data) {
+ gl.bindTexture(gl.TEXTURE_2D, led.texture);
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 2, led.rows, gl.RGBA, gl.FLOAT, data);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ }
+ function release(r, next) {
+ if (next === undefined || next.leds !== r.leds) {
+ dropTarget(gl, r.lightSources); dropTarget(gl, r.directRaycast);
+ gl.deleteTexture(r.ledTexture.texture); gl.deleteVertexArray(r.ledVao); gl.deleteBuffer(r.ledVertexBuffer);
+ gl.deleteBuffer(r.configUbo.buffer); gl.deleteBuffer(r.directRaycastUbo.buffer);
+ }
+ dropTarget(gl, r.present); dropTarget(gl, r.particles);
+ gl.deleteBuffer(r.floorUbo.buffer); gl.deleteBuffer(r.lightGlowUbo.buffer);
+ }
+ function resources(sim, pres, pixelRatio, density, count) {
+ ensurePrograms();
+ if (res && same(res.simulationSize, sim) && same(res.presentationSize, pres) && res.pixelRatio === pixelRatio && res.probeDensity === density && res.count === count) return res;
+ const keep = res && same(res.simulationSize, sim) && res.probeDensity === density && res.count === count;
+ const base = keep
+ ? { simulationSize: res.simulationSize, probeDensity: res.probeDensity, cascadeFit: res.cascadeFit, cascade: res.cascade, count: res.count, leds: res.leds, ledTexture: res.ledTexture, lightSources: res.lightSources, directRaycast: res.directRaycast, ledVao: res.ledVao, ledVertexBuffer: res.ledVertexBuffer, ledVertexCount: res.ledVertexCount, ledRadius: res.ledRadius, ledShape: res.ledShape, triangle: res.triangle, configUbo: res.configUbo, directRaycastUbo: res.directRaycastUbo }
+ : simResources(sim, density, count, res?.leds);
+ const next = {
+ ...base,
+ presentationSize: pres, pixelRatio,
+ present: target(gl, pres.width, pres.height, gl.RGBA8, "triangle-led-4-gl-present"),
+ particles: target(gl, pres.width, pres.height, gl.R8, "triangle-led-4-gl-particles"),
+ floorUbo: ubo(gl, 256), lightGlowUbo: ubo(gl, 256),
+ };
+ if (res) release(res, next);
+ res = next;
+ return next;
+ }
+
+ function draw(p, r, f, theme, time, opts) {
+ const brush = f.brush, tun = f.tunables;
+ const occluder = opts?.renderBlackOccluder ?? true;
+ gl.disable(gl.DEPTH_TEST); gl.disable(gl.SCISSOR_TEST);
+ gl.bindVertexArray(p.fullscreenVao);
+ // 1. light sources
+ gl.bindFramebuffer(gl.FRAMEBUFFER, r.lightSources.framebuffer);
+ gl.viewport(0, 0, r.lightSources.width, r.lightSources.height);
+ const clip = Number.isFinite(tun.ledRaycastClipInsetPx) ? Math.min(LED_CLIP_INSET_RANGE.max, Math.max(LED_CLIP_INSET_RANGE.min, tun.ledRaycastClipInsetPx)) : TUNABLES.ledRaycastClipInsetPx;
+ const c = new Float32Array(28);
+ c.set([r.simulationSize.width, r.simulationSize.height, time, tun.darkFloorAlbedo], 0);
+ c.set([brush.x, brush.y, +!!brush.active, brush.radius], 4);
+ c.set([brush.colour.r, brush.colour.g, brush.colour.b, 0], 8);
+ c.set([tun.ledIntensity, tun.brightnessMin, tun.brightnessMax, r.ledRadius], 12);
+ c.set([r.triangle.center.x, r.triangle.center.y, r.triangle.circumradius, 0.5 * r.triangle.sideLength], 16);
+ c.set([+!!occluder, tun.ledHitThreshold, r.ledShape.tangentHalfLength, r.ledShape.normalHalfThickness], 20);
+ c.set([LED_CLIP_EXPAND, clip, 0, 0], 24);
+ writeUbo(gl, r.configUbo, c);
+ gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, r.configUbo.buffer);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, r.ledTexture.texture);
+ const key = `${+!!occluder}:${c[25]}`;
+ if (r.lightSourcesBakeKey !== key) {
+ r.lightSourcesBakeKey = key;
+ gl.disable(gl.BLEND); gl.colorMask(true, true, true, true);
+ gl.clearColor(0, 0, 0, 1e3); gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(p.lightSources); gl.drawArrays(gl.TRIANGLES, 0, 3);
+ }
+ gl.useProgram(p.ledEmitters);
+ gl.enable(gl.BLEND);
+ gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ONE);
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.MIN);
+ gl.colorMask(true, true, true, false);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, r.ledTexture.texture);
+ gl.bindVertexArray(r.ledVao);
+ gl.drawArrays(gl.TRIANGLES, 0, r.ledVertexCount);
+ gl.bindVertexArray(p.fullscreenVao);
+ gl.disable(gl.BLEND); gl.colorMask(true, true, true, true);
+ // 2. direct raycast
+ gl.bindFramebuffer(gl.FRAMEBUFFER, r.directRaycast.framebuffer);
+ gl.viewport(0, 0, r.directRaycast.width, r.directRaycast.height);
+ gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(p.directRaycast);
+ gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, r.directRaycastUbo.buffer);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, r.lightSources.texture);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ // particles (drop staging) are not part of this copy: their target is cleared once and stays empty
+ if (firstEncode) {
+ firstEncode = false;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, r.particles.framebuffer);
+ gl.viewport(0, 0, r.particles.width, r.particles.height);
+ gl.disable(gl.BLEND); gl.colorMask(true, true, true, true);
+ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
+ }
+ // 3. floor
+ const light = theme === "light";
+ gl.bindFramebuffer(gl.FRAMEBUFFER, r.present.framebuffer);
+ gl.viewport(0, 0, r.present.width, r.present.height);
+ gl.clearColor(0, 0, 0, +!light); gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(light ? p.lightFloor : p.darkFloor);
+ const floor = floorUniforms(r, f, theme, opts);
+ if (!r.floorUboCache || !equal(r.floorUboCache, floor)) { writeUbo(gl, r.floorUbo, floor); r.floorUboCache = floor; }
+ gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, r.floorUbo.buffer);
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, r.directRaycast.texture);
+ gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, r.lightSources.texture);
+ if (light) {
+ writeUbo(gl, r.lightGlowUbo, glowUniforms(f.lightGlow, f.colorMix));
+ gl.bindBufferBase(gl.UNIFORM_BUFFER, 1, r.lightGlowUbo.buffer);
+ } else {
+ gl.activeTexture(gl.TEXTURE3); gl.bindTexture(gl.TEXTURE_2D, p.floorNoise);
+ }
+ gl.activeTexture(gl.TEXTURE4); gl.bindTexture(gl.TEXTURE_2D, r.particles.texture);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ // 4. present
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, r.presentationSize.width, r.presentationSize.height);
+ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.useProgram(p.present);
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, r.present.texture);
+ gl.bindSampler(0, p.presentSampler);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ gl.bindSampler(0, null);
+ gl.bindVertexArray(null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ }
+
+ return {
+ get stats() { return { cascadeCount: res ? res.count : 0 }; },
+ /** Draws one frame at `time` seconds into the context's canvas. */
+ render(width, height, brushPatch, time, tunables, sim, options, probeDiscard) {
+ if (destroyed) return false;
+ const pres = size(width, height);
+ const simSize = size(sim?.simulationWidth ?? width, sim?.simulationHeight ?? height);
+ const pixelRatio = ratio(sim?.pixelRatio);
+ const density = clampProbeDensity(sim?.probeDensity);
+ const r = resources(simSize, pres, pixelRatio, density, cascades(sim?.cascadeCount, simSize));
+ const p = ensurePrograms();
+ const theme = options?.theme ?? "dark";
+ const f = frames.resolveFrame({
+ patch: brushPatch, tunables, options, probeDiscard, theme, time,
+ updateLedsFor: (x) => {
+ const out = updateLeds(r.leds, x.time, x.tunables, x.settings, x.hoverDeploy, x.brush, x.theme, x.dropActive);
+ uploadLeds(r.ledTexture, r.leds.data);
+ return out;
+ },
+ });
+ draw(p, r, f, theme, time, options);
+ return true;
+ },
+ destroy() {
+ destroyed = true;
+ if (res) release(res);
+ res = undefined;
+ if (programs) {
+ for (const k of ["lightSources", "ledEmitters", "directRaycast", "darkFloor", "lightFloor", "present"]) gl.deleteProgram(programs[k]);
+ gl.deleteVertexArray(programs.fullscreenVao); gl.deleteTexture(programs.floorNoise); gl.deleteSampler(programs.presentSampler);
+ }
+ programs = undefined;
+ },
+ };
+}
+
+function equal(a, b) {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
+ return true;
+}
+
+/** Floor pass "Config" block (64 floats). */
+function floorUniforms(r, f, theme, opts) {
+ const pres = r.presentationSize, sim = r.simulationSize, light = theme === "light";
+ const tun = f.tunables, ao = f.lightAo, dbg = f.radianceDebug, dark = f.darkFloor, post = f.darkPostprocess, fit = r.cascadeFit;
+ const k = new Float32Array(64);
+ const scale = Math.max(1e-3, pres.height / Math.max(1, sim.height));
+ const ox = (pres.width - sim.width * scale) * 0.5, oy = (pres.height - sim.height * scale) * 0.5;
+ const tri = triangle(sim);
+ const pad = f.probeDiscard.lightAabbPadding;
+ k.set([pres.width, pres.height, +light, r.pixelRatio], 0);
+ k.set([sim.width, sim.height, 0, light ? ao.contactOpacity : 0], 4);
+ k.set([tun.ledIntensity, light ? tun.lightFloorAlbedo : tun.darkFloorAlbedo, ao.radiance, light ? ao.contactSize : 0], 8);
+ k.set([ox + tri.center.x * scale, oy + tri.center.y * scale, tri.circumradius * scale, 0.5 * tri.sideLength * scale], 12);
+ k.set([pad * scale, pad * scale, +!!(opts?.showForegroundTriangle ?? true), nonNegative(tun.particleExposureBoostMax)], 16);
+ k.set([ox + fit.originSceneX * scale, oy + fit.originSceneY * scale, fit.widthScene * scale, fit.heightScene * scale], 20);
+ k.set([ao.contactFalloffPower, ao.highlightPower, ao.highlightStrength, 0], 24);
+ k.set([+!!dbg.enabled, dbg.redMultiplier, dbg.greenMultiplier, dbg.blueMultiplier], 28);
+ k.set([ox, oy, scale, getPointerCutoff()], 32);
+ k.set([dark.sdfFadeDistanceScale, dark.sdfFadeEdgePx, dark.nearFalloffPower, dark.tailPower], 36);
+ k.set([dark.tailIntensity, dark.vibrancy, dark.tailMapMin, dark.tailMapMax], 40);
+ k.set([dark.nearFalloffDistanceScale, dark.nearFalloffIntensity, dark.nearFalloffMapMin, dark.nearFalloffMapMax], 44);
+ const design = DESIGN_HEIGHT * Math.max(r.pixelRatio, 1e-4);
+ k.set([dark.middleFalloffPower, dark.middleFalloffIntensity, dark.radianceJitterPx, Math.min(pres.height, design) / design], 48);
+ k.set([+!!dark.nearFalloffEnabled, +!!dark.middleFalloffEnabled, +!!dark.farFalloffEnabled, post.contrast], 52);
+ k.set([getPointerCutoff(), post.exposure, 0, 0], 56);
+ k.set([+!!dark.noiseEnabled, 0, 0, 0], 60);
+ return k;
+}
+
+/** Light floor "LightGlow" block (64 floats). */
+function glowUniforms(g, colorMix) {
+ const t = new Float32Array(64);
+ t.set([g.nearDistanceScale, g.nearIntensity, g.nearMapMin, g.nearMapMax], 0);
+ t.set([g.middlePower, g.middleIntensity, g.highlightNoise, 0], 4);
+ t.set([g.farIntensity, colorMix, g.farMapMin, g.farMapMax], 8);
+ t.set([g.nearPower, g.middleOuterScale, g.farPower, g.fadeInner], 12);
+ t.set([+!!g.nearEnabled, +!!g.middleEnabled, +!!g.farEnabled, g.contrast], 16);
+ t.set([g.aoStrength, g.aoRadiusScale, g.aoPower, +!!g.aoEnabled], 20);
+ t.set([g.ao2Strength, g.ao2RadiusScale, g.ao2Power, +!!g.ao2Enabled], 24);
+ t.set([g.ao3Strength, g.ao3RadiusScale, g.ao3Power, +!!g.ao3Enabled], 28);
+ const red = lms(g.edgeRedRgb), green = lms(g.edgeGreenRgb), blue = lms(g.edgeBlueRgb);
+ t.set([red.r, red.g, red.b, 1 / Math.max(g.edgeOverlap, 0.01)], 32);
+ t.set([green.r, green.g, green.b, 0], 36);
+ t.set([blue.r, blue.g, blue.b, 0], 40);
+ t.set([g.nearDistanceScaleColor, g.nearIntensityColor, g.nearMapMinColor, g.nearMapMaxColor], 44);
+ t.set([g.middlePowerColor, g.middleIntensityColor, 0, 0], 48);
+ t.set([g.farIntensityColor, +!!g.highlightDebug, g.farMapMinColor, g.farMapMaxColor], 52);
+ t.set([g.nearPowerColor, g.middleOuterScaleColor, g.farPowerColor, g.fadeInnerColor], 56);
+ t.set([+!!g.nearEnabledColor, +!!g.middleEnabledColor, +!!g.farEnabledColor, g.contrastColor], 60);
+ return t;
+}
diff --git a/site/public/examples/vercel-hero/src/shaders.js b/site/public/examples/vercel-hero/src/shaders.js
new file mode 100644
index 0000000..55ae8aa
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/shaders.js
@@ -0,0 +1,1409 @@
+// The hero's GLSL ES 3.00 shaders, copied unchanged from vercel.com's hero worker (the WebGL2 port of
+// its WGSL renderer). Fragment shaders are compiled as FRAGMENT_PREFIX + COMMON + body, as on vercel.com.
+// Do not edit by hand: .reanimate/vercel-hero/tools/extract-shaders.mjs writes this file.
+
+export const FRAGMENT_PREFIX = "#version 300 es\nprecision highp float; precision highp int;\n";
+
+// Shared helpers prepended to every fragment shader (after the #version line).
+export const COMMON = `
+// ---------------------------------------------------------------------------
+// WebGL FBO read helper (Y-flip)
+// ---------------------------------------------------------------------------
+// WebGL2 framebuffers store row 0 at the BOTTOM, but every pass computes texel coords in the
+// WGSL/WebGPU TOP-LEFT space (pixel = v_uv * resolution, with v_uv top-left from FULLSCREEN_VERT).
+// A fragment that computed content for logical row Y is rasterized to physical row (H-1-Y), so a
+// later texelFetch at row Y would read the vertically MIRRORED content. Wrap reads of an
+// intermediate render-target (light_sources, radiance) with this to flip the row back. NOT needed
+// for floor_noise (tiles isotropically) or the CPU-uploaded LED data texture (row-per-LED).
+ivec2 fboTexel(in highp sampler2D tex, in ivec2 coord) {
+ return ivec2(coord.x, textureSize(tex, 0).y - 1 - coord.y);
+}
+
+// ---------------------------------------------------------------------------
+// hash.wgsl
+// ---------------------------------------------------------------------------
+float hash21(vec2 p) {
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
+}
+
+// ---------------------------------------------------------------------------
+// color-utils.wgsl
+// ---------------------------------------------------------------------------
+// OKLab transform matrices (column-major; identical layout to the WGSL mat3x3 constants).
+const mat3 OK_INV_B = mat3(
+ 0.4121656120, 0.2118591070, 0.0883097947,
+ 0.5362752080, 0.6807189584, 0.2818474174,
+ 0.0514575653, 0.1074065790, 0.6302613616
+);
+const mat3 OK_FWD_B = mat3(
+ 4.0767245293, -1.2681437731, -0.0041119885,
+ -3.3072168827, 2.6093323231, -0.7034763098,
+ 0.2307590544, -0.3411344290, 1.7068625689
+);
+const mat3 ACES_INPUT_MAT = mat3(
+ 0.59719, 0.07600, 0.02840,
+ 0.35458, 0.90834, 0.13383,
+ 0.04823, 0.01566, 0.83777
+);
+const mat3 ACES_OUTPUT_MAT = mat3(
+ 1.60475, -0.10208, -0.00327,
+ -0.53108, 1.10813, -0.07276,
+ -0.07367, -0.00605, 1.07602
+);
+
+vec3 rgb_to_oklab(vec3 c) {
+ vec3 lms = OK_INV_B * c;
+ return sign(lms) * pow(abs(lms), vec3(1.0 / 3.0));
+}
+
+vec3 oklab_to_rgb(vec3 c) {
+ vec3 lms = c * c * c;
+ return OK_FWD_B * lms;
+}
+
+vec3 col3(float v) {
+ return rgb_to_oklab(vec3(v));
+}
+
+vec3 col3v(vec3 v) {
+ return rgb_to_oklab(v);
+}
+
+vec3 rrt_and_odt_fit(vec3 v) {
+ vec3 a = v * (v + 0.0245786) - vec3(0.000090537);
+ vec3 b = v * (0.983729 * v + 0.4329510) + vec3(0.238081);
+ return a / b;
+}
+
+vec3 aces_fitted(vec3 color) {
+ vec3 c = ACES_INPUT_MAT * color;
+ c = rrt_and_odt_fit(c);
+ c = ACES_OUTPUT_MAT * c;
+ return clamp(c, vec3(0.0), vec3(1.0));
+}
+
+vec3 linear_to_srgb_pow(vec3 color) {
+ return pow(color, vec3(1.0 / 2.2));
+}
+
+// --- Tonemap operators -------------------------------------------------------
+// Each maps LINEAR HDR -> LINEAR [0,1], EXCEPT AgX (a full display transform) which
+// returns sRGB-display directly. The tonemap() dispatcher owns the sRGB encode so
+// every branch ends display-ready and there is no double gamma correction.
+const uint TONEMAP_ACES = 0u;
+const uint TONEMAP_HABLE = 1u;
+const uint TONEMAP_LOTTES = 2u;
+const uint TONEMAP_AGX = 3u;
+const uint TONEMAP_REINHARD = 4u;
+const uint TONEMAP = TONEMAP_LOTTES;
+
+vec3 tonemap_reinhard(vec3 c) {
+ return c / (c + vec3(1.0));
+}
+
+vec3 hable_partial(vec3 x) {
+ float a = 0.15;
+ float b = 0.50;
+ float c = 0.10;
+ float d = 0.20;
+ float e = 0.02;
+ float f = 0.30;
+ return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f;
+}
+
+vec3 tonemap_hable(vec3 color) {
+ float exposure_bias = 2.0;
+ vec3 curr = hable_partial(color * exposure_bias);
+ vec3 white_scale = vec3(1.0) / hable_partial(vec3(11.2));
+ return curr * white_scale;
+}
+
+vec3 tonemap_lottes(vec3 x) {
+ float a = 1.6;
+ float d = 0.977;
+ float hdr_max = 8.0;
+ float mid_in = 0.18;
+ float mid_out = 0.267;
+ float b =
+ (-pow(mid_in, a) + pow(hdr_max, a) * mid_out)
+ / ((pow(hdr_max, a * d) - pow(mid_in, a * d)) * mid_out);
+ float c =
+ (pow(hdr_max, a * d) * pow(mid_in, a) - pow(hdr_max, a) * pow(mid_in, a * d) * mid_out)
+ / ((pow(hdr_max, a * d) - pow(mid_in, a * d)) * mid_out);
+ return pow(x, vec3(a)) / (pow(x, vec3(a * d)) * b + c);
+}
+
+// Minimal AgX (Benjamin Wrensch / iolite-engine). Returns sRGB-display-encoded.
+vec3 agx_tonemap(vec3 color) {
+ mat3 agx_mat = mat3(
+ 0.842479062253094, 0.0423282422610123, 0.0423756549057051,
+ 0.0784335999999992, 0.878468636469772, 0.0784336,
+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104
+ );
+ mat3 agx_mat_inv = mat3(
+ 1.19687900512017, -0.0528968517574562, -0.0529716355144438,
+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,
+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116
+ );
+ float min_ev = -12.47393;
+ float max_ev = 4.026069;
+ vec3 val = agx_mat * color;
+ val = clamp(log2(max(val, vec3(1e-10))), vec3(min_ev), vec3(max_ev));
+ val = (val - min_ev) / (max_ev - min_ev);
+ // 6th-order polynomial fit of the AgX contrast sigmoid.
+ vec3 x2 = val * val;
+ vec3 x4 = x2 * x2;
+ vec3 res =
+ 15.5 * x4 * x2 - 40.14 * x4 * val + 31.96 * x4
+ - 6.868 * x2 * val + 0.4298 * x2 + 0.1191 * val - 0.00232;
+ res = agx_mat_inv * res;
+ return clamp(res, vec3(0.0), vec3(1.0));
+}
+
+// Dispatcher: LINEAR HDR in -> sRGB-display out. Default branch (ACES) is byte-identical
+// to the previous linear_to_srgb_pow(aces_fitted(color)).
+vec3 tonemap(vec3 color) {
+ // Clamp to the finite rgba16float range, not just max(_, 0): a bright COLORED LED in
+ // dark mode can overflow the half-float light texture to +Inf, which would reach the
+ // pow-based tonemaps and yield Inf/Inf = NaN -> a black ("burned") pixel. Anything past
+ // 65504 already saturates the tonemap to white, so this is lossless for finite values
+ // and turns the burn back into the intended white.
+ vec3 c = clamp(color, vec3(0.0), vec3(65504.0));
+ if (TONEMAP == TONEMAP_AGX) {
+ return agx_tonemap(c);
+ }
+ vec3 mapped;
+ if (TONEMAP == TONEMAP_HABLE) {
+ mapped = tonemap_hable(c);
+ } else if (TONEMAP == TONEMAP_LOTTES) {
+ mapped = tonemap_lottes(c);
+ } else if (TONEMAP == TONEMAP_REINHARD) {
+ mapped = tonemap_reinhard(c);
+ } else {
+ mapped = aces_fitted(c);
+ }
+ return linear_to_srgb_pow(clamp(mapped, vec3(0.0), vec3(1.0)));
+}
+
+float value_remap(float value, float minIn, float maxIn, float minOut, float maxOut) {
+ return minOut + (value - minIn) * (maxOut - minOut) / (maxIn - minIn);
+}
+
+float value_remap_clamp(float value, float minIn, float maxIn, float minOut, float maxOut) {
+ float remapped = value_remap(value, minIn, maxIn, minOut, maxOut);
+ return clamp(remapped, min(minOut, maxOut), max(minOut, maxOut));
+}
+
+// ---------------------------------------------------------------------------
+// geometry.wgsl
+// ---------------------------------------------------------------------------
+float sdf_segment(vec2 p, vec2 a, vec2 b) {
+ vec2 pa = p - a;
+ vec2 ba = b - a;
+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
+ return length(pa - ba * h);
+}
+
+float sdf_triangle_vertices(vec2 p, vec2 a, vec2 b, vec2 c) {
+ float d = min(min(sdf_segment(p, a, b), sdf_segment(p, b, c)), sdf_segment(p, c, a));
+ vec2 edge0 = b - a;
+ vec2 edge1 = c - b;
+ vec2 edge2 = a - c;
+ float side0 = edge0.x * (p.y - a.y) - edge0.y * (p.x - a.x);
+ float side1 = edge1.x * (p.y - b.y) - edge1.y * (p.x - b.x);
+ float side2 = edge2.x * (p.y - c.y) - edge2.y * (p.x - c.x);
+ bool inside = (side0 <= 0.0 && side1 <= 0.0 && side2 <= 0.0) || (side0 >= 0.0 && side1 >= 0.0 && side2 >= 0.0);
+ return inside ? -d : d;
+}
+
+// ---------------------------------------------------------------------------
+// floor-falloff.wgsl
+// ---------------------------------------------------------------------------
+// Smooth value map: input at/below lo reads 0, at/above hi reads 1 (lo > hi inverts).
+float value_map01(float value, float lo, float hi) {
+ float denom = hi - lo;
+ float safe_denom = abs(denom) < 0.0001 ? 0.001 : denom;
+ return clamp((value - lo) / safe_denom, 0.0, 1.0);
+}
+
+// CLOSE: remap the light first (so it follows the light shape), then mask with a thin SDF
+// band hugging the triangle to fake a thin line.
+// near = (outer-radius scale, intensity, light-map lo, light-map hi)
+float near_falloff(
+ float triangle_sdf,
+ float near_light,
+ float fade_inner,
+ float circumradius,
+ vec4 near,
+ float band_power,
+ float enabled
+) {
+ float mapped = value_map01(near_light, near.z, near.w);
+ float near_outer = max(circumradius * near.x, fade_inner + 0.001);
+ float near_fade = value_remap_clamp(triangle_sdf, near_outer, fade_inner, 0.0, 1.0);
+ float band = pow(near_fade, max(band_power, 0.001));
+ return mapped * band * near.y * enabled;
+}
+
+// MIDDLE: geometric SDF distance glow shaped by power/intensity, with a smoothstep SDF fade
+// on top (zero slope at 0 so high intensity never reveals a hard cutout).
+// middle = (power, intensity, _, _)
+float middle_falloff(
+ float triangle_sdf,
+ float fade_inner,
+ float circumradius,
+ float outer_scale,
+ vec4 middle,
+ float enabled
+) {
+ float middle_outer = max(circumradius * outer_scale, fade_inner + 0.001);
+ float middle_fade = value_remap_clamp(triangle_sdf, middle_outer, fade_inner, 0.0, 1.0);
+ float value = pow(middle_fade, max(middle.x, 0.001)) * middle.y;
+ return value * smoothstep(0.0, 1.0, middle_fade) * enabled;
+}
+
+// FAR: pure light fade (no SDF). Remap radiance luminance, shape with the tail power, scale
+// by intensity.
+// glow = (intensity, _, light-map lo, light-map hi)
+float far_falloff(
+ float near_light,
+ vec4 glow,
+ float power,
+ float enabled
+) {
+ float mapped = value_map01(near_light, glow.z, glow.w);
+ float shaped = pow(mapped, max(power, 0.001));
+ return shaped * glow.x * enabled;
+}
+`;
+
+// Fullscreen triangle with top-left-origin UVs, for the passes that draw it.
+export const FULLSCREEN_VERT = `#version 300 es
+precision highp float;
+
+out vec2 v_uv;
+
+void main() {
+ // Oversized triangle covering the clip rect, matching the WGSL passes' vertex array.
+ vec2 positions[3] = vec2[3](
+ vec2(-1.0, -3.0),
+ vec2(-1.0, 1.0),
+ vec2(3.0, 1.0)
+ );
+ vec2 p = positions[gl_VertexID];
+ // Top-left-origin UV: flip Y so v_uv.y = 0 at the top of the image (WGSL/WebGPU
+ // framebuffer convention). See the Y-FLIP CONVENTION note above.
+ v_uv = vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5);
+ gl_Position = vec4(p, 0.0, 1.0);
+}
+`;
+
+// Bakes the scene SDF (LED segments and the black occluder) into the alpha of the light-sources target.
+export const LIGHT_SOURCES_FRAG = `
+layout(std140) uniform Config {
+ vec2 resolution;
+ float time;
+ float floor_albedo;
+ vec4 brush;
+ vec4 colour;
+ vec4 tunables;
+ vec4 triangle;
+ vec4 options;
+ vec4 led_clip;
+};
+
+// LED storage buffer ported to a 2x72 RGBA32F data texture (column 0 = pos_brightness,
+// column 1 = color). Sampled with texelFetch \u2014 no float-texture extension required.
+uniform highp sampler2D u_leds;
+
+in vec2 v_uv;
+out vec4 frag_color;
+
+const uint LED_COUNT = 72u;
+// Keep the black occluder safely inside the visible triangle mesh.
+const float OCCLUDER_INSET_PX = 4.0;
+
+float signed_triangle_area(vec2 a, vec2 b, vec2 p) {
+ vec2 edge = b - a;
+ return edge.x * (p.y - a.y) - edge.y * (p.x - a.x);
+}
+
+bool inside_triangle(vec2 p, vec2 a, vec2 b, vec2 c) {
+ float side0 = signed_triangle_area(a, b, p);
+ float side1 = signed_triangle_area(b, c, p);
+ float side2 = signed_triangle_area(c, a, p);
+ return (side0 <= 0.0 && side1 <= 0.0 && side2 <= 0.0) || (side0 >= 0.0 && side1 >= 0.0 && side2 >= 0.0);
+}
+
+float segment_distance(vec2 p, vec2 a, vec2 b) {
+ vec2 pa = p - a;
+ vec2 ba = b - a;
+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
+ return length(pa - ba * h);
+}
+
+float triangle_sdf(vec2 p, vec2 a, vec2 b, vec2 c) {
+ float edge_dist = min(segment_distance(p, a, b), min(segment_distance(p, b, c), segment_distance(p, c, a)));
+ return inside_triangle(p, a, b, c) ? -edge_dist : edge_dist;
+}
+
+void main() {
+ vec2 pixel = v_uv * resolution;
+ vec2 top = vec2(triangle.x, triangle.y - triangle.z);
+ vec2 left = vec2(triangle.x - triangle.w, triangle.y + triangle.z * 0.5);
+ vec2 right = vec2(triangle.x + triangle.w, triangle.y + triangle.z * 0.5);
+ float tri_dist = triangle_sdf(pixel, top, left, right);
+ // Optionally fill the canonical triangle interior as a black non-emissive surface/occluder.
+ // LED RGB is overlaid by the generated emitter mesh after this SDF prepass.
+ bool render_black_occluder = options.x > 0.5;
+ float best_led_dist = 1e6;
+ for (uint i = 0u; i < LED_COUNT; i = i + 1u) {
+ vec4 led = texelFetch(u_leds, ivec2(0, int(i)), 0);
+ vec2 delta = pixel - led.xy;
+ vec2 edge_dir = vec2(cos(led.w), sin(led.w));
+ vec2 edge_normal = vec2(-edge_dir.y, edge_dir.x);
+ vec2 led_local = vec2(dot(delta, edge_dir), dot(delta, edge_normal));
+ float led_half_length = options.z;
+ float led_half_thickness = options.w;
+ float led_dist = max(
+ abs(led_local.x) - led_half_length,
+ abs(led_local.y) - led_half_thickness
+ );
+ // triangle_sdf is negative inside; positive inset moves only the LED SDF boundary inward.
+ float led_clip_dist = tri_dist + led_clip.y;
+ best_led_dist = min(best_led_dist, max(led_dist, led_clip_dist));
+ }
+ // triangle_sdf is negative inside; adding 4px moves only the black occluder boundary inward.
+ float inset_occluder_dist = tri_dist + OCCLUDER_INSET_PX;
+ float occluder_dist = render_black_occluder ? inset_occluder_dist : 1e6;
+ float best_dist = min(best_led_dist, occluder_dist);
+ // The fullscreen pass initializes the SDF/occluder contract. LED RGB is
+ // written afterward by the generated emitter mesh, including split corner caps
+ // that meet on each triangle-vertex bisector.
+ frag_color = vec4(vec3(0.0), best_dist);
+}
+`;
+
+// The 72 LED quads plus the three split corner caps.
+export const LED_EMITTERS_VERT = `#version 300 es
+precision highp float;
+
+layout(std140) uniform Config {
+ vec2 resolution;
+ float time;
+ float floor_albedo;
+ vec4 brush;
+ vec4 colour;
+ vec4 tunables;
+ vec4 triangle;
+ vec4 options;
+ vec4 led_clip;
+};
+
+layout(location = 0) in vec2 a_position;
+layout(location = 1) in vec2 a_local;
+layout(location = 2) in float a_led_index;
+
+out vec2 v_local;
+out float v_led_index;
+// Top-left-origin pixel space, forwarded so the fragment reconstructs WGSL's @builtin(position).
+out vec2 v_pixel;
+
+void main() {
+ vec2 clip = (a_position / resolution) * vec2(2.0, -2.0) + vec2(-1.0, 1.0);
+ gl_Position = vec4(clip, 0.0, 1.0);
+ v_local = a_local;
+ v_led_index = a_led_index;
+ v_pixel = a_position;
+}
+`;
+
+// Writes each LED's colour times brightness into the light-sources target (RGB only).
+export const LED_EMITTERS_FRAG = `
+layout(std140) uniform Config {
+ vec2 resolution;
+ float time;
+ float floor_albedo;
+ vec4 brush;
+ vec4 colour;
+ vec4 tunables;
+ vec4 triangle;
+ vec4 options;
+ vec4 led_clip;
+};
+
+// LED storage buffer ported to a 2x72 RGBA32F data texture (column 0 = pos_brightness,
+// column 1 = color). Sampled with texelFetch \u2014 no float-texture extension required.
+uniform highp sampler2D u_leds;
+
+in vec2 v_local;
+in float v_led_index;
+in vec2 v_pixel;
+out vec4 frag_color;
+
+const uint LED_COUNT = 72u;
+
+float signed_triangle_area(vec2 a, vec2 b, vec2 p) {
+ vec2 edge = b - a;
+ return edge.x * (p.y - a.y) - edge.y * (p.x - a.x);
+}
+
+bool inside_triangle(vec2 p, vec2 a, vec2 b, vec2 c) {
+ float side0 = signed_triangle_area(a, b, p);
+ float side1 = signed_triangle_area(b, c, p);
+ float side2 = signed_triangle_area(c, a, p);
+ return (side0 <= 0.0 && side1 <= 0.0 && side2 <= 0.0) || (side0 >= 0.0 && side1 >= 0.0 && side2 >= 0.0);
+}
+
+float segment_distance(vec2 p, vec2 a, vec2 b) {
+ vec2 pa = p - a;
+ vec2 ba = b - a;
+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
+ return length(pa - ba * h);
+}
+
+float triangle_sdf(vec2 p, vec2 a, vec2 b, vec2 c) {
+ float edge_dist = min(segment_distance(p, a, b), min(segment_distance(p, b, c), segment_distance(p, c, a)));
+ return inside_triangle(p, a, b, c) ? -edge_dist : edge_dist;
+}
+
+void main() {
+ vec2 pixel = v_pixel;
+ vec2 top = vec2(triangle.x, triangle.y - triangle.z);
+ vec2 left = vec2(triangle.x - triangle.w, triangle.y + triangle.z * 0.5);
+ vec2 right = vec2(triangle.x + triangle.w, triangle.y + triangle.z * 0.5);
+ float tri_dist = triangle_sdf(pixel, top, left, right);
+ // Positive expansion reveals emitter pixels outside the canonical triangle.
+ if (tri_dist - led_clip.x > 0.0) {
+ discard;
+ }
+
+ uint raw_index = uint(max(round(v_led_index), 0.0));
+ uint i = min(raw_index, LED_COUNT - 1u);
+ float n01 = clamp(texelFetch(u_leds, ivec2(0, int(i)), 0).z, 0.0, 1.0);
+ float intensity = mix(tunables.y, tunables.z, n01);
+ vec3 emit = texelFetch(u_leds, ivec2(1, int(i)), 0).rgb * tunables.x * intensity;
+ // Alpha (the LED SDF) is masked off by colorMask (RGB only) -- the fullscreen prepass owns the
+ // SDF -- so the led_dist that used to go here is never written. Skip computing it.
+ frag_color = vec4(emit, 0.0);
+}
+`;
+
+// Marches rays from every half-resolution probe through the light-sources SDF and gathers LED light.
+export const DIRECT_RAYCAST_FRAG = `
+layout(std140) uniform Config {
+ vec4 tri_a_b;
+ vec4 tri_c_target;
+ vec4 size_steps;
+ vec4 params;
+ vec4 target_info;
+};
+
+uniform highp sampler2D light_sources_tex;
+
+in vec2 v_uv;
+out vec4 frag_color;
+
+struct Interval { float start; float length; bool valid; };
+struct TraceHit { vec3 rgb; float distance; bool hit; };
+
+const uint MAX_RAYS = 24u;
+// Jitter amplitude as a fraction of one stratum width. 1.0 = full-width: adjacent
+// strata can swap which discrete LED they sample, maximizing per-pixel variance (the
+// clumpy chroma/luma noise at low ray counts). The half-res to full cubic upsample
+// already protects against banding, so we attenuate the jitter and let regular
+// stratification carry the signal -- each ray stays near its stratum center and
+// randomization only dithers residual stratum boundaries.
+const float JITTER_AMPLITUDE = 0.7;
+const float DT_PI = 3.141592653589793;
+const float DT_EPSILON = 1e-5;
+
+vec2 tri_a() { return tri_a_b.xy; }
+vec2 tri_b() { return tri_a_b.zw; }
+vec2 tri_c() { return tri_c_target.xy; }
+
+float cross2(vec2 a, vec2 b) {
+ return a.x * b.y - a.y * b.x;
+}
+
+float wrap_pi(float angle) {
+ return atan(sin(angle), cos(angle));
+}
+
+float triangle_signed_area(vec2 a, vec2 b, vec2 c) {
+ return cross2(b - a, c - a);
+}
+
+bool point_in_triangle(vec2 p, vec2 a, vec2 b, vec2 c) {
+ float area = triangle_signed_area(a, b, c);
+ if (abs(area) <= DT_EPSILON) {
+ return false;
+ }
+ float inv_area = 1.0 / area;
+ float u = cross2(b - p, c - p) * inv_area;
+ float v = cross2(c - p, a - p) * inv_area;
+ float w = 1.0 - u - v;
+ return u >= -DT_EPSILON && v >= -DT_EPSILON && w >= -DT_EPSILON;
+}
+
+float segment_distance(vec2 p, vec2 a, vec2 b) {
+ vec2 e = b - a;
+ vec2 v = p - a;
+ float h = clamp(dot(v, e) / max(dot(e, e), DT_EPSILON), 0.0, 1.0);
+ return length(v - e * h);
+}
+
+float triangle_edge_distance(vec2 p, vec2 a, vec2 b, vec2 c) {
+ return min(
+ segment_distance(p, a, b),
+ min(segment_distance(p, b, c), segment_distance(p, c, a))
+ );
+}
+
+Interval angular_interval(vec2 p, vec2 a, vec2 b, vec2 c) {
+ if (abs(triangle_signed_area(a, b, c)) <= DT_EPSILON) {
+ return Interval(0.0, 0.0, false);
+ }
+ if (point_in_triangle(p, a, b, c)) {
+ return Interval(0.0, 0.0, false);
+ }
+ if (triangle_edge_distance(p, a, b, c) <= size_steps.w) {
+ return Interval(0.0, 0.0, false);
+ }
+
+ vec2 center = (a + b + c) / 3.0;
+ float center_angle = atan(center.y - p.y, center.x - p.x);
+ float ra = wrap_pi(atan(a.y - p.y, a.x - p.x) - center_angle);
+ float rb = wrap_pi(atan(b.y - p.y, b.x - p.x) - center_angle);
+ float rc = wrap_pi(atan(c.y - p.y, c.x - p.x) - center_angle);
+ float min_rel = min(ra, min(rb, rc));
+ float max_rel = max(ra, max(rb, rc));
+ float len = max_rel - min_rel;
+ if (!(len > DT_EPSILON) || len >= DT_PI) {
+ return Interval(0.0, 0.0, false);
+ }
+ return Interval(wrap_pi(center_angle + min_rel), len, true);
+}
+
+// Interleaved gradient noise (Jimenez) -> [0,1] with blue-noise-like spectrum: spatially
+// high-frequency, so the per-pixel ray jitter it drives reads as fine grain (not white-noise
+// clumps) and is removed far better by the half-res to full cubic upsample + the floor dither.
+float ign(vec2 p) {
+ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));
+}
+
+vec4 load_light_source(vec2 sample_pos) {
+ ivec2 dims = textureSize(light_sources_tex, 0);
+ bool inside =
+ sample_pos.x >= 0.0 && sample_pos.x < float(dims.x) &&
+ sample_pos.y >= 0.0 && sample_pos.y < float(dims.y);
+ if (!inside) {
+ return vec4(0.0, 0.0, 0.0, 1000.0);
+ }
+ ivec2 px = clamp(ivec2(floor(sample_pos)), ivec2(0), dims - ivec2(1));
+ return texelFetch(light_sources_tex, fboTexel(light_sources_tex, px), 0);
+}
+
+// Per-edge ray/segment invariants (edge vector, origin->edge offset, their 2D cross) that don't
+// change across the ray sweep -- precomputed once per pixel and reused for all MAX_RAYS directions.
+struct EdgePrecomp { vec2 e; vec2 diff; float cross_diff_e; };
+
+EdgePrecomp precompute_edge(vec2 origin, vec2 p, vec2 q) {
+ vec2 e = q - p;
+ vec2 diff = p - origin;
+ return EdgePrecomp(e, diff, cross2(diff, e));
+}
+
+// Closed-form ray (origin + t*dir, t > minStep) vs segment -- dir-dependent part only; returns
+// t >= 0 at the hit or -1 (miss/parallel). One reciprocal feeds both t and u.
+float ray_segment_t(vec2 dir, EdgePrecomp pre) {
+ float denom = cross2(dir, pre.e);
+ if (abs(denom) < DT_EPSILON) { return -1.0; }
+ float inv = 1.0 / denom;
+ float t = pre.cross_diff_e * inv;
+ float u = cross2(pre.diff, dir) * inv;
+ if (t < size_steps.z || u < 0.0 || u > 1.0) { return -1.0; }
+ return t;
+}
+
+// Analytic: the LEDs sit on the triangle edges, and angular_interval already aimed this ray
+// into the triangle's arc, so the nearest ray<->edge intersection is the first lit edge it
+// can reach (nearest => the near edge occludes the far edges for free). One sample of the
+// LED color there replaces the SDF sphere-march -- no SDF / .w channel needed at all.
+TraceHit trace_light_source(vec2 origin, vec2 dir, EdgePrecomp pre_ab, EdgePrecomp pre_bc, EdgePrecomp pre_ca) {
+ float t = 1e30;
+ float t0 = ray_segment_t(dir, pre_ab);
+ float t1 = ray_segment_t(dir, pre_bc);
+ float t2 = ray_segment_t(dir, pre_ca);
+ if (t0 >= 0.0) { t = min(t, t0); }
+ if (t1 >= 0.0) { t = min(t, t1); }
+ if (t2 >= 0.0) { t = min(t, t2); }
+ if (t > 1e29) { return TraceHit(vec3(0.0), 0.0, false); }
+
+ vec4 source = load_light_source(origin + dir * t);
+ bool source_active = max(max(source.r, source.g), source.b) > params.w;
+ if (source_active) {
+ return TraceHit(source.rgb, t, true);
+ }
+ return TraceHit(vec3(0.0), 0.0, false);
+}
+
+void main() {
+ float target_scale = max(target_info.x, 1e-4);
+ // WGSL @builtin(position).xy (top-left pixel space of the half-res target) is
+ // reconstructed from the top-left-origin v_uv times the target dims.
+ vec2 frag_pos = v_uv * tri_c_target.zw;
+ vec2 pixel_sim = frag_pos / target_scale;
+ vec2 a = tri_a();
+ vec2 b = tri_b();
+ vec2 c = tri_c();
+ Interval interval = angular_interval(pixel_sim, a, b, c);
+ if (!interval.valid) {
+ frag_color = vec4(0.0, 0.0, 0.0, 1.0);
+ return;
+ }
+
+ float jitter = (ign(frag_pos) - 0.5) * JITTER_AMPLITUDE;
+ // The ray angle is exactly linear in i: angle = interval.start + interval.length * t with
+ // t = (i + 0.5 + jitter) / MAX_RAYS. The clamp never triggers because jitter in [-0.35, 0.35]
+ // (JITTER_AMPLITUDE 0.7) keeps t strictly inside (0, 1) for every i. So sweep the direction by
+ // rotating it one fixed angular step per ray -- 2 trig calls per pixel instead of 2 per ray
+ // (MAX_RAYS=24). The hit point (origin + dir*t) is invariant to any tiny magnitude drift since
+ // the ray/segment t absorbs it; only the angle matters, and that drifts ~MAX_RAYS ULP.
+ float inv_rays = 1.0 / float(MAX_RAYS);
+ float step_angle = interval.length * inv_rays;
+ float start_angle = interval.start + interval.length * (0.5 + jitter) * inv_rays;
+ float step_c = cos(step_angle);
+ float step_s = sin(step_angle);
+ vec2 dir = vec2(cos(start_angle), sin(start_angle));
+ // Hoist the per-edge ray/segment invariants out of the ray loop (origin + edges are fixed).
+ EdgePrecomp pre_ab = precompute_edge(pixel_sim, a, b);
+ EdgePrecomp pre_bc = precompute_edge(pixel_sim, b, c);
+ EdgePrecomp pre_ca = precompute_edge(pixel_sim, c, a);
+ vec3 sum = vec3(0.0);
+ for (uint i = 0u; i < MAX_RAYS; i = i + 1u) {
+ TraceHit hit = trace_light_source(pixel_sim, dir, pre_ab, pre_bc, pre_ca);
+ if (hit.hit) {
+ // Geometric spreading on distance NORMALIZED to the scene size (target_info.y =
+ // ref_height / sim_height) so the radiance is resolution-independent -- raw sim-px
+ // distance made shorter render targets read brighter/whiter. Beer-Lambert absorption
+ // (params.x already per-sim-height) eats far light through the smoke/atmosphere.
+ float falloff_dist = hit.distance * target_info.y;
+ float distance_weight =
+ pow(max(falloff_dist, 1.0), -params.y) * exp(-params.x * hit.distance);
+ sum += hit.rgb * distance_weight;
+ }
+ // Rotate the direction by one angular step for the next ray.
+ dir = vec2(dir.x * step_c - dir.y * step_s, dir.x * step_s + dir.y * step_c);
+ }
+
+ // Match the cascade path's directional average semantics: angular sample mean,
+ // independent of ray count. params.z remains the visual calibration knob.
+ vec3 radiance = (sum / float(MAX_RAYS)) * params.z;
+ frag_color = vec4(radiance, 1.0);
+}
+`;
+
+// Bakes the 500x500 grain texture the dark floor uses.
+export const FLOOR_NOISE_FRAG = `
+in vec2 v_uv;
+out vec4 fragColor;
+
+// Fixed bake resolution; the texture is created at 500x500 with no UBO.
+// Keep in lockstep with noiseSize in passes/main-scene-pass.ts.
+const float BAKE_SIZE = 500.0;
+
+void main() {
+ // Reconstruct WGSL's floor(in.pos.xy): top-left-origin pixel coordinate.
+ vec2 p = floor(v_uv * BAKE_SIZE);
+ float floor_noise = hash21(p) + hash21(floor(p * 2.12)) + hash21(floor(p * 3.15));
+ floor_noise *= 0.3;
+ floor_noise = clamp(floor_noise, 0.0, 1.0);
+ fragColor = vec4(vec3(floor_noise), 1.0);
+}
+`;
+
+// Dark theme floor.
+export const DARK_FLOOR_FRAG = `
+layout(std140) uniform Config {
+ vec4 screen; // (width, height, isLightTheme, dpr)
+ vec4 light_sources; // (simW, simH, _, contactAoStrength)
+ vec4 tunables; // (ledIntensity, floorAlbedo, lightAoRadiance, contactAoSize)
+ vec4 triangle; // (centerX, centerY, circumradiusY, halfSideX)
+ vec4 culling; // (aabbPadX, aabbPadY, showTriangle, _)
+ vec4 radiance_fit; // (originX, originY, width, height)
+ vec4 light_ao; // (contactFalloffPower, highlightPower, highlightStrength, _)
+ vec4 radiance_debug; // (enabled, redMul, greenMul, blueMul)
+ vec4 sim_transform; // (originX, originY, scale, edgeFadeFrac)
+ vec4 dark_floor; // (sdfFadeDistanceScale, sdfFadeEdgePx, nearFalloffPower, tailPower)
+ vec4 dark_glow; // (tailIntensity, vibrancy, tailMapMin, tailMapMax)
+ vec4 dark_near; // (nearDistanceScale, nearIntensity, nearMapMin, nearMapMax)
+ vec4 dark_middle; // (middlePower, middleIntensity, radianceJitterPx, jitterNorm)
+ vec4 dark_toggles; // (nearEnabled, middleEnabled, farEnabled, contrast)
+ vec4 dark_circle; // (edgeFadeFrac, exposure, _, _)
+ vec4 dark_noise; // (noiseEnabled, _, _, _)
+} cfg;
+
+uniform sampler2D radiance_tex;
+uniform sampler2D light_sources_tex;
+uniform sampler2D floor_noise_tex;
+uniform sampler2D particle_tex;
+
+in vec2 v_uv;
+out vec4 fragColor;
+
+const int FLOOR_NOISE_SIZE = 500;
+
+// Grain density in texels per CSS pixel. Anchoring to CSS px (not the device-pixel backing
+// store) keeps the grain the SAME visual size at any DPR.
+const float FLOOR_NOISE_DENSITY = 2.0;
+
+// At DPR 1 the tiling floor grain reads as a coarse, visibly-repeating PATTERN, so scale its
+// intensity down to this fraction there; DPR>1 (retina) keeps the full grain (1.0).
+const float DARK_FLOOR_GRAIN_DPR1_SCALE = 0.5;
+
+// Mitchell / cubic B-spline upsample coefficients. (B=1, C=0) is the cubic B-spline kernel
+// (max smoothing) used for the half-res radiance upsample.
+const float UPSAMPLE_B = 1.0;
+const float UPSAMPLE_C = 0.0;
+
+const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
+
+// On the mobile layout the canvas is a SQUARE; widen the top/bottom fade band by this factor.
+const float DARK_EDGE_FADE_MOBILE_BOOST = 2.0;
+
+int wrapNoiseCoord(int v) {
+ return ((v % FLOOR_NOISE_SIZE) + FLOOR_NOISE_SIZE) % FLOOR_NOISE_SIZE;
+}
+
+// Reads the tiling floor noise (r channel, [0,1]) at a DPR-independent position. p is device px;
+// cfg.screen.w is DPR, so p / dpr is CSS px.
+float sample_floor_noise(vec2 p) {
+ vec2 css_px = p / max(cfg.screen.w, 1e-4);
+ ivec2 noise_px = ivec2(floor(css_px * FLOOR_NOISE_DENSITY));
+ ivec2 noise_uv = ivec2(wrapNoiseCoord(noise_px.x), wrapNoiseCoord(noise_px.y));
+ return texelFetch(floor_noise_tex, noise_uv, 0).r;
+}
+
+// Cheap per-pixel hash (Dave Hoskins, hash12) -> [0,1]; picks the jitter angle.
+float hash12(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+
+// Sibling of hash12 with a different seed multiplier \u2014 independent values, used for the
+// radiance multisample blend weight.
+float hash12b(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1531);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+
+vec3 bg(vec2 p) {
+ // dark_noise.x gates the floor-noise lightness modulation. Off (static bake) -> flat albedo.
+ float floor_noise = sample_floor_noise(p) * cfg.dark_noise.x;
+ float grain_intensity = cfg.screen.w < 1.5 ? DARK_FLOOR_GRAIN_DPR1_SCALE : 1.0;
+ float floor_brightness =
+ mix(cfg.tunables.y, cfg.tunables.y * 0.5, floor_noise * grain_intensity);
+ // Floor base in RGB (gray); the oklab lift now happens only where an LED blends in (see main).
+ return vec3(floor_brightness);
+}
+
+struct TriangleCorners { vec2 top; vec2 left; vec2 right; };
+
+TriangleCorners triangle_corners() {
+ vec2 top = vec2(cfg.triangle.x, cfg.triangle.y - cfg.triangle.z);
+ vec2 left = vec2(cfg.triangle.x - cfg.triangle.w, cfg.triangle.y + cfg.triangle.z * 0.5);
+ vec2 right = vec2(cfg.triangle.x + cfg.triangle.w, cfg.triangle.y + cfg.triangle.z * 0.5);
+ return TriangleCorners(top, left, right);
+}
+
+// Reads the LED emitter/SDF texture in simulation space, blanking samples outside the sim rect.
+vec4 sample_light_sources(vec2 pixel_screen) {
+ vec2 sim_px = (pixel_screen - cfg.sim_transform.xy) / cfg.sim_transform.z;
+ ivec2 px = clamp(ivec2(floor(sim_px)), ivec2(0), ivec2(cfg.light_sources.xy) - ivec2(1));
+ bool inside_sim =
+ sim_px.x >= 0.0 && sim_px.x < cfg.light_sources.x &&
+ sim_px.y >= 0.0 && sim_px.y < cfg.light_sources.y;
+ vec4 light_sources = texelFetch(light_sources_tex, fboTexel(light_sources_tex, px), 0);
+ if (!inside_sim) {
+ light_sources = vec4(0.0, 0.0, 0.0, 1.0);
+ }
+ return light_sources;
+}
+
+// Mitchell-Netravali / BC-spline cubic weight.
+float bc_spline_weight(float x) {
+ float ax = abs(x);
+ float b = UPSAMPLE_B;
+ float c = UPSAMPLE_C;
+ if (ax < 1.0) {
+ return ((12.0 - 9.0 * b - 6.0 * c) * ax * ax * ax
+ + (-18.0 + 12.0 * b + 6.0 * c) * ax * ax
+ + (6.0 - 2.0 * b)) / 6.0;
+ }
+ if (ax < 2.0) {
+ return ((-b - 6.0 * c) * ax * ax * ax
+ + (6.0 * b + 30.0 * c) * ax * ax
+ + (-12.0 * b - 48.0 * c) * ax
+ + (8.0 * b + 24.0 * c)) / 6.0;
+ }
+ return 0.0;
+}
+
+// BC-spline (Mitchell-Netravali) 4x4 sampling for the half-resolution direct radiance target.
+vec3 sample_radiance_cubic(vec2 uv) {
+ ivec2 dims_u = textureSize(radiance_tex, 0);
+ vec2 dims = vec2(dims_u);
+ vec2 texel = clamp(uv, vec2(0.0), vec2(1.0)) * dims - vec2(0.5);
+ vec2 base = floor(texel);
+ vec2 f = texel - base;
+ vec3 sum = vec3(0.0);
+ float weight_sum = 0.0;
+ for (int y = -1; y <= 2; y = y + 1) {
+ float wy = bc_spline_weight(f.y - float(y));
+ for (int x = -1; x <= 2; x = x + 1) {
+ float wx = bc_spline_weight(f.x - float(x));
+ float w = wx * wy;
+ ivec2 tap = clamp(ivec2(base) + ivec2(x, y), ivec2(0), dims_u - ivec2(1));
+ sum += texelFetch(radiance_tex, fboTexel(radiance_tex, tap), 0).rgb * w;
+ weight_sum += w;
+ }
+ }
+ return max(sum / max(weight_sum, 1e-5), vec3(0.0));
+}
+
+// Samples the fitted radiance texture, blanking samples outside the fit rect.
+vec3 sample_radiance_at(vec2 pixel_screen) {
+ vec2 fitted_uv = (pixel_screen - cfg.radiance_fit.xy) / cfg.radiance_fit.zw;
+ bool inside_fit =
+ fitted_uv.x >= 0.0 && fitted_uv.x <= 1.0 &&
+ fitted_uv.y >= 0.0 && fitted_uv.y <= 1.0;
+ vec3 radiance = sample_radiance_cubic(fitted_uv);
+ if (!inside_fit) {
+ radiance = vec3(0.0);
+ }
+ return radiance;
+}
+
+// Noise-driven jittered multisample of the radiance.
+vec3 sample_radiance(vec2 pixel_screen, float triangle_sdf) {
+ vec3 base = sample_radiance_at(pixel_screen);
+ // dark_noise.x off (static bake) -> a single radiance sample, no noise-driven jitter dither.
+ if (cfg.dark_noise.x < 0.5) {
+ return base;
+ }
+ float light_intensity = dot(base, LUMA);
+ float offset_scale = value_remap_clamp(light_intensity, 0.2, 0.1, 0.0, 1.0);
+ offset_scale *= value_remap_clamp(triangle_sdf, 0.0, cfg.triangle.z * 0.9, 0.0, 1.0);
+
+ // Bright pixels (light_intensity >= 0.2) and the triangle edge clamp offset_scale to exactly
+ // 0, so the offset is zero and the jittered sample would read the same texel as base
+ // (mix(base, base, noise) == base to within a ULP). Skip the second 16-tap cubic fetch there.
+ if (offset_scale <= 0.0) {
+ return base;
+ }
+
+ float noise = hash12b(pixel_screen);
+ float angle = hash12(pixel_screen) * 6.2831853;
+ vec2 dir = vec2(cos(angle), sin(angle));
+ vec2 offset = dir * offset_scale * cfg.dark_middle.z * cfg.dark_middle.w;
+ vec3 jittered = sample_radiance_at(pixel_screen + offset);
+ return mix(base, jittered, noise);
+}
+
+// Combines the floor base colour with radiance, the LED surface, vibrancy saturation, and the
+// falloff envelope into the final linear-HDR colour.
+vec3 compose_floor(
+ vec3 base_colour,
+ vec3 radiance,
+ vec4 light_sources,
+ float surface,
+ float brightness_factor
+) {
+ vec3 colour = max(base_colour, vec3(0.0));
+ colour *= radiance;
+ colour = mix(colour, light_sources.rgb, surface);
+ float sat = 1.0 + (cfg.dark_glow.y - 1.0) * brightness_factor;
+ float luma = dot(colour, LUMA);
+ colour = max(mix(vec3(luma), colour, sat), vec3(0.0));
+ colour *= brightness_factor;
+ return colour;
+}
+
+// VERTICAL-ONLY screen-edge envelope: 1 across the interior, easing to 0 only near the TOP and
+// BOTTOM edges. The easing is t^0.5.
+float edge_fade(vec2 pixel_screen) {
+ float mobile_boost =
+ cfg.screen.x < cfg.screen.y * 1.25 ? DARK_EDGE_FADE_MOBILE_BOOST : 1.0;
+ float w = max(cfg.dark_circle.x * mobile_boost * cfg.screen.y, 1.0);
+ float d = min(pixel_screen.y, cfg.screen.y - pixel_screen.y);
+ float t = clamp(d / w, 0.0, 1.0);
+ return sqrt(t);
+}
+
+// Deep occluder-interior pixels are painted pure black; skip the whole floor body (incl. the
+// 16-tap radiance fetch) there. Margin keeps the ~1px anti-aliased silhouette on the full path.
+const float OCCLUDER_INTERIOR_MARGIN = 4.0;
+
+void main() {
+ vec2 pixel_screen = v_uv * cfg.screen.xy;
+ vec2 uv = pixel_screen / cfg.screen.xy;
+ vec2 pixel = uv * cfg.screen.xy - cfg.screen.xy * 0.5;
+ TriangleCorners tri = triangle_corners();
+ float triangle_sdf = sdf_triangle_vertices(pixel_screen, tri.top, tri.left, tri.right);
+
+ // The SDF screen-space gradient must be computed in uniform control flow (here, before any
+ // non-uniform branch) for correct derivatives. length(dFdx, dFdy) is the true gradient magnitude;
+ // fwidth's |dFdx|+|dFdy| over-widens diagonal edges by up to sqrt(2), so use length() for a true ~1px AA.
+ float occluder_edge = max(length(vec2(dFdx(triangle_sdf), dFdy(triangle_sdf))), 1e-4);
+
+ // Early-out to the exact interior value (occluder on, not radiance-debug). The gradient above is
+ // in uniform control flow, so this per-pixel branch is safe.
+ if (cfg.culling.z > 0.5 && cfg.radiance_debug.x <= 0.5 && triangle_sdf < -OCCLUDER_INTERIOR_MARGIN) {
+ fragColor = vec4(0.0, 0.0, 0.0, 1.0);
+ return;
+ }
+
+ vec4 light_sources = sample_light_sources(pixel_screen);
+ vec3 radiance = sample_radiance(pixel_screen, triangle_sdf);
+ if (cfg.radiance_debug.x > 0.5) {
+ fragColor = vec4(clamp(radiance * cfg.radiance_debug.yzw, vec3(0.0), vec3(1.0)), 1.0);
+ return;
+ }
+
+ // LED surface mask, derived from the emitter color itself.
+ float surface = smoothstep(
+ 4.0,
+ 4.02,
+ max(max(light_sources.r, light_sources.g), light_sources.b)
+ );
+ // Floor base in RGB; blend toward the LED color (cbrt-LMS space) only where an LED is present.
+ vec3 floor_rgb = bg(pixel);
+ vec3 base_rgb = floor_rgb;
+ if (surface > 0.0) {
+ base_rgb = oklab_to_rgb(mix(col3v(floor_rgb), col3v(light_sources.rgb), surface));
+ }
+
+ // Three glow layers, brightest first. Screen-blend the in-range [0,1] parts, then add any
+ // over-1 overflow additively (keeps the combination monotonic past 1).
+ float fade_inner = cfg.dark_floor.y;
+ float near_light = dot(radiance, LUMA);
+ float near = near_falloff(
+ triangle_sdf,
+ near_light,
+ fade_inner,
+ cfg.triangle.z,
+ cfg.dark_near,
+ cfg.dark_floor.z,
+ cfg.dark_toggles.x
+ );
+ // middle_falloff returns 0 when its toggle (dark_toggles.y) is off (shipping default) \u2014 skip it.
+ float middle = 0.0;
+ if (cfg.dark_toggles.y > 0.5) {
+ middle = middle_falloff(
+ triangle_sdf,
+ fade_inner,
+ cfg.triangle.z,
+ cfg.dark_floor.x,
+ cfg.dark_middle,
+ cfg.dark_toggles.y
+ );
+ }
+ float far = far_falloff(
+ near_light,
+ cfg.dark_glow,
+ cfg.dark_floor.w,
+ cfg.dark_toggles.z
+ );
+ float screen_blend =
+ 1.0 - (1.0 - min(near, 1.0)) * (1.0 - min(middle, 1.0)) * (1.0 - min(far, 1.0));
+ float overflow =
+ max(near - 1.0, 0.0) + max(middle - 1.0, 0.0) + max(far - 1.0, 0.0);
+ float brightness_factor = screen_blend + overflow;
+
+ vec3 colour = compose_floor(
+ base_rgb,
+ radiance,
+ light_sources,
+ surface,
+ brightness_factor
+ );
+
+ // Final output (no composite pass in dark mode): tonemap -> display contrast.
+ float particle_mask = texelFetch(particle_tex, fboTexel(particle_tex, ivec2(pixel_screen)), 0).r;
+ float exposure = cfg.dark_circle.y; // GUI: Dark \u2192 Glow \u2192 Exposure.
+ float particle_exposure_boost_max = cfg.culling.w; // GUI: Drop deploy \u2192 Particle boost max.
+ float contrast = cfg.dark_toggles.w; // GUI: Dark \u2192 Glow \u2192 Contrast.
+ float particle_exposure = 1.0 + particle_mask * particle_exposure_boost_max;
+ vec3 final_colour = tonemap(colour * exposure * particle_exposure);
+ final_colour = (final_colour - vec3(0.5)) * contrast + vec3(0.5);
+
+ // Foreground triangle occluder, drawn analytically from the same SDF. cfg.culling.z is the
+ // show-triangle flag (0/1).
+ float occluder = clamp(0.5 - triangle_sdf / occluder_edge, 0.0, 1.0) * cfg.culling.z;
+ final_colour = mix(final_colour, vec3(0.0), occluder);
+
+ // Screen-edge fade as a plain multiply (preserves hue).
+ final_colour = final_colour * edge_fade(pixel_screen);
+
+ fragColor = vec4(final_colour, 1.0);
+}
+`;
+
+// Light theme floor: the white rim, glow, contact shadows and, with colour mix, the prism colours.
+export const LIGHT_FLOOR_FRAG = `
+layout(std140) uniform Config {
+ vec4 screen; // (width, height, isLightTheme, dpr)
+ vec4 light_sources; // (simW, simH, _, contactAoStrength)
+ vec4 tunables; // (ledIntensity, lightFloorAlbedo, lightAoRadiance, contactAoSize)
+ vec4 triangle; // (centerX, centerY, circumradiusY, halfSideX)
+ vec4 culling; // (aabbPadX, aabbPadY, showTriangle, _)
+ vec4 radiance_fit; // (originX, originY, width, height)
+ vec4 light_ao; // (contactFalloffPower, highlightPower, highlightStrength, _)
+ vec4 radiance_debug; // (enabled, redMul, greenMul, blueMul)
+ vec4 sim_transform; // (originX, originY, scale, edgeFadeFrac)
+} cfg;
+
+layout(std140) uniform LightGlow {
+ vec4 near; // (distanceScale, intensity, mapMin, mapMax)
+ vec4 middle; // (power, intensity, highlightNoise, _)
+ vec4 glow; // (far intensity, colorMix, mapMin, mapMax)
+ vec4 params; // (nearPower, middleOuterScale, farPower, fadeInner)
+ vec4 toggles; // (nearEnabled, middleEnabled, farEnabled, contrast)
+ vec4 ao; // (strength, radiusScale, power, enabled)
+ vec4 ao2; // (strength, radiusScale, power, enabled)
+ vec4 ao3; // (strength, radiusScale, power, enabled)
+ vec4 edgeRed; // (r, g, b, invOverlap)
+ vec4 edgeGreen; // (r, g, b, _)
+ vec4 edgeBlue; // (r, g, b, _)
+ vec4 nearColor; // COLOR copy of near
+ vec4 middleColor; // COLOR copy of middle
+ vec4 glowColor; // COLOR copy of glow (.y = highlightDebug)
+ vec4 paramsColor; // COLOR copy of params
+ vec4 togglesColor; // COLOR copy of toggles
+} lg;
+
+uniform sampler2D radiance_tex;
+uniform sampler2D light_sources_tex;
+uniform sampler2D particle_tex;
+
+in vec2 v_uv;
+out vec4 fragColor;
+
+// corner-crease smoothing, as a fraction of the triangle circumradius
+const float AO_CORNER_SMOOTH = 0.25;
+
+// Smooth max: like max(a,b) but rounds the transition over a width k.
+float ao_smax(float a, float b, float k) {
+ float h = clamp(0.5 + 0.5 * (a - b) / max(k, 1e-4), 0.0, 1.0);
+ return mix(b, a, h) + k * h * (1.0 - h);
+}
+
+// Cheap per-pixel hashes (Dave Hoskins) -> [0,1]. Used to exaggerate the highlight mask.
+float hash12(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+float hash12b(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1531);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+
+// Catmull-Rom cubic weight (LOCAL to the light shader; the dark shader uses bc_spline).
+float catmull_rom_weight(float x) {
+ float ax = abs(x);
+ if (ax <= 1.0) {
+ return 1.5 * ax * ax * ax - 2.5 * ax * ax + 1.0;
+ }
+ if (ax < 2.0) {
+ return -0.5 * ax * ax * ax + 2.5 * ax * ax - 4.0 * ax + 2.0;
+ }
+ return 0.0;
+}
+
+// Catmull-Rom 4x4 sampling for the half-resolution direct radiance target.
+vec3 sample_radiance_cubic(vec2 uv) {
+ ivec2 dims_u = textureSize(radiance_tex, 0);
+ vec2 dims = vec2(dims_u);
+ vec2 texel = clamp(uv, vec2(0.0), vec2(1.0)) * dims - vec2(0.5);
+ vec2 base = floor(texel);
+ vec2 f = texel - base;
+ vec3 sum = vec3(0.0);
+ float weight_sum = 0.0;
+ for (int y = -1; y <= 2; y = y + 1) {
+ float wy = catmull_rom_weight(f.y - float(y));
+ for (int x = -1; x <= 2; x = x + 1) {
+ float wx = catmull_rom_weight(f.x - float(x));
+ float w = wx * wy;
+ ivec2 tap = clamp(ivec2(base) + ivec2(x, y), ivec2(0), dims_u - ivec2(1));
+ sum += texelFetch(radiance_tex, fboTexel(radiance_tex, tap), 0).rgb * w;
+ weight_sum += w;
+ }
+ }
+ return max(sum / max(weight_sum, 1e-5), vec3(0.0));
+}
+
+vec3 sample_radiance_at(vec2 pixel_screen) {
+ vec2 fitted_uv = (pixel_screen - cfg.radiance_fit.xy) / cfg.radiance_fit.zw;
+ bool inside_fit =
+ fitted_uv.x >= 0.0 && fitted_uv.x <= 1.0 &&
+ fitted_uv.y >= 0.0 && fitted_uv.y <= 1.0;
+ vec3 radiance = sample_radiance_cubic(fitted_uv);
+ if (!inside_fit) {
+ radiance = vec3(0.0);
+ }
+ return radiance;
+}
+
+// Triangular angular weight: 1 at theta_i, falling linearly to 0 at 120 degrees away.
+float angular_weight(float theta, float theta_i) {
+ float d = theta - theta_i;
+ float dist = abs(atan(sin(d), cos(d))); // shortest wrapped angular distance, [0, pi]
+ return max(0.0, 1.0 - dist / 2.0943951); // 2.0943951 = 120 degrees (2pi/3)
+}
+
+vec3 floor_edge_tint(vec2 pixel, vec2 top, vec2 left, vec2 right) {
+ // Conic gradient: the tint depends only on the angle around the triangle center.
+ vec2 center = cfg.triangle.xy;
+ float theta = atan(pixel.y - center.y, pixel.x - center.x);
+ vec2 red_center = (top + left) * 0.5;
+ vec2 green_center = (left + right) * 0.5;
+ vec2 blue_center = (right + top) * 0.5;
+ // Overlap control (lg.edgeRed.w = 1/overlap).
+ float inv_overlap = lg.edgeRed.w;
+ float wr = pow(angular_weight(theta, atan(red_center.y - center.y, red_center.x - center.x)), inv_overlap);
+ float wg = pow(angular_weight(theta, atan(green_center.y - center.y, green_center.x - center.x)), inv_overlap);
+ float wb = pow(angular_weight(theta, atan(blue_center.y - center.y, blue_center.x - center.x)), inv_overlap);
+ float wsum = max(wr + wg + wb, 1e-4);
+
+ // Vivid OKLCh-style blend: average lightness and chroma independently, take hue from the
+ // weighted sum of a/b vectors (short-arc circular mean), renormalize to the averaged chroma.
+ // Precomputed CPU-side (cbrt-LMS of the edge colors) and carried in edgeRed/Green/Blue.xyz.
+ vec3 lab_r = lg.edgeRed.xyz;
+ vec3 lab_g = lg.edgeGreen.xyz;
+ vec3 lab_b = lg.edgeBlue.xyz;
+ float l = (lab_r.x * wr + lab_g.x * wg + lab_b.x * wb) / wsum;
+ float chroma =
+ (length(lab_r.yz) * wr + length(lab_g.yz) * wg + length(lab_b.yz) * wb) / wsum;
+ vec2 ab_sum = lab_r.yz * wr + lab_g.yz * wg + lab_b.yz * wb;
+ float ab_len = length(ab_sum);
+ vec2 ab = vec2(0.0);
+ if (ab_len > 1e-5) {
+ ab = (ab_sum / ab_len) * chroma;
+ }
+ return clamp(oklab_to_rgb(vec3(l, ab.x, ab.y)), vec3(0.0), vec3(1.0));
+}
+
+// Smooth screen-edge envelope: 1 across the interior, easing to 0 near ALL FOUR edges. The fade
+// width (cfg.sim_transform.w, a fraction of canvas HEIGHT) is applied to ALPHA.
+float edge_fade(vec2 pixel_screen) {
+ float w = max(cfg.sim_transform.w * cfg.screen.y, 1.0);
+ float dy = min(pixel_screen.y, cfg.screen.y - pixel_screen.y);
+ float dx = min(pixel_screen.x, cfg.screen.x - pixel_screen.x);
+ return smoothstep(0.0, w, dy) * smoothstep(0.0, w, dx);
+}
+
+// Signed distance to one triangle edge's outward half-plane (positive outside the triangle).
+float ao_half_plane_distance(vec2 p, vec2 e0, vec2 e1, vec2 center) {
+ vec2 edge = e1 - e0;
+ vec2 n = normalize(vec2(-edge.y, edge.x));
+ if (dot(n, e0 - center) < 0.0) { n = -n; } // force outward (away from centroid)
+ return dot(p - e0, n);
+}
+
+// Triangle distance from its three edge half-planes (sharp/miter corners), smooth-maxed.
+float ao_triangle_plane_distance(vec2 p, vec2 a, vec2 b, vec2 c) {
+ vec2 center = (a + b + c) * (1.0 / 3.0);
+ float k = cfg.triangle.z * AO_CORNER_SMOOTH; // cfg.triangle.z = circumradius (screen px)
+ float dab = ao_half_plane_distance(p, a, b, center);
+ float dbc = ao_half_plane_distance(p, b, c, center);
+ float dca = ao_half_plane_distance(p, c, a, center);
+ return ao_smax(ao_smax(dab, dbc, k), dca, k);
+}
+
+void main() {
+ vec2 pixel_screen = v_uv * cfg.screen.xy;
+ vec2 uv = pixel_screen / cfg.screen.xy;
+ // colorMix: 0 = grayscale/idle (white light), 1 = colored/deploy-active.
+ float colorMix = clamp(lg.glow.y, 0.0, 1.0);
+
+ // Rebuild the triangle vertices in screen space.
+ vec2 top = vec2(cfg.triangle.x, cfg.triangle.y - cfg.triangle.z);
+ vec2 left = vec2(cfg.triangle.x - cfg.triangle.w, cfg.triangle.y + cfg.triangle.z * 0.5);
+ vec2 right = vec2(cfg.triangle.x + cfg.triangle.w, cfg.triangle.y + cfg.triangle.z * 0.5);
+ float triangle_sdf = sdf_triangle_vertices(pixel_screen, top, left, right);
+
+ // The SDF screen-space gradient in uniform control flow (top level) for correct derivatives.
+ // length(dFdx, dFdy) is the true gradient magnitude; fwidth's |dFdx|+|dFdy| over-widens diagonal
+ // edges by up to sqrt(2), so use length() for a true ~1px AA.
+ float occluder_edge = max(length(vec2(dFdx(triangle_sdf), dFdy(triangle_sdf))), 1e-4);
+
+ vec3 radiance = sample_radiance_at(pixel_screen);
+
+ if (cfg.radiance_debug.x > 0.5) {
+ fragColor = vec4(radiance, 1.0);
+ return;
+ }
+
+ // Combine the three falloffs the same way dark mode does.
+ float near_light = dot(radiance, vec3(0.2126, 0.7152, 0.0722));
+ // Per-layer MONO->COLOR param blend by colorMix.
+ vec4 near_p = mix(lg.near, lg.nearColor, colorMix);
+ vec4 middle_p = mix(lg.middle, lg.middleColor, colorMix);
+ vec4 glow_p = mix(lg.glow, lg.glowColor, colorMix);
+ vec4 params_p = mix(lg.params, lg.paramsColor, colorMix);
+ vec4 toggles_p = mix(lg.toggles, lg.togglesColor, colorMix);
+ float fade_inner = params_p.w;
+ // NEAR (colored only): a PURE LUMINANCE remap \u2014 NO SDF band.
+ float near = pow(value_map01(near_light, near_p.z, near_p.w), max(params_p.x, 0.001))
+ * near_p.y * toggles_p.x * colorMix;
+ float middle = middle_falloff(
+ triangle_sdf,
+ fade_inner,
+ cfg.triangle.z,
+ params_p.y,
+ middle_p,
+ toggles_p.y
+ ) * colorMix;
+ float far = far_falloff(
+ near_light,
+ glow_p,
+ params_p.z,
+ toggles_p.z
+ );
+ float screen_blend =
+ 1.0 - (1.0 - min(near, 1.0)) * (1.0 - min(middle, 1.0)) * (1.0 - min(far, 1.0));
+ float overflow =
+ max(near - 1.0, 0.0) + max(middle - 1.0, 0.0) + max(far - 1.0, 0.0);
+ float brightness_factor = screen_blend + overflow;
+
+ float alpha = 1.0;
+
+ // Foreground triangle occluder, drawn analytically from the same SDF. cfg.culling.z is the
+ // show-triangle flag (0/1).
+ float occluder = clamp(0.5 - triangle_sdf / occluder_edge, 0.0, 1.0) * cfg.culling.z;
+ alpha = mix(alpha, 0.0, occluder);
+
+ float highlight = near;
+ highlight = clamp(highlight, 0.0, 1.0);
+ highlight = pow(highlight, 0.5);
+ highlight *= 1.0 - occluder; // Don't highlight where the triangle occluder is.
+ // EXAGGERATE the highlight mask with per-pixel hash grain (lg.middle.z = highlightNoise).
+ float hl_grain = hash12b(pixel_screen) + 0.5 * hash12(pixel_screen); // ~[0, 1.5]
+ highlight = clamp(highlight * (1.0 + (hl_grain - 0.75) * lg.middle.z), 0.0, 1.0);
+ // DEBUG (lg.glowColor.y): render the raw highlight variable as opaque grayscale.
+ if (lg.glowColor.y > 0.5) {
+ fragColor = vec4(vec3(highlight), 1.0);
+ return;
+ }
+
+ // Apply dark-style contrast to the combined glow, then use it as the alpha.
+ float glow_contrast = toggles_p.w; // GUI: Light \u2192 Glow (mono/color) \u2192 Contrast, blended by colorMix.
+ float light_glow = (brightness_factor - 0.5) * glow_contrast + 0.5;
+ float glow_alpha = clamp(light_glow, 0.0, 1.0) * alpha;
+
+ // contrast when light is white. The old mix(pow(a,1.2)*1.2, a*1.5, 1.0) selected the second arg
+ // verbatim (blend factor 1.0), so the pow branch was dead -- it is just a * 1.5.
+ glow_alpha = glow_alpha * 1.5;
+ glow_alpha = clamp(glow_alpha, 0.0, 1.0);
+
+ // Screen-edge fade multiplies ALPHA (premultiplied compositing).
+ glow_alpha = glow_alpha * edge_fade(pixel_screen);
+
+ // Color output: white light or the per-edge brand tint, blended by colorMix.
+ vec3 edge_tint = floor_edge_tint(pixel_screen, top, left, right);
+ edge_tint += edge_tint * highlight;
+ edge_tint = clamp(edge_tint, vec3(0.0), vec3(1.0));
+ edge_tint = mix(edge_tint, vec3(1.0), pow(highlight, 2.2) * 0.7);
+ vec3 color = mix(vec3(1.0), edge_tint, clamp(lg.glow.y, 0.0, 1.0));
+ // Brightness boost only on the tinted floor: x1 at colorMix=0 ramping to x2 at colorMix=1.
+ color *= mix(1.0, 2.0, colorMix);
+
+ // Three-layer AO: all layers darken the ground near the triangle via premultiplied compositing.
+ float ao_outside = max(ao_triangle_plane_distance(pixel_screen, top, left, right), 0.0);
+ float ao_outside_sdf = max(triangle_sdf, 0.0);
+ float ao1 = lg.ao.x * pow(1.0 - clamp(ao_outside_sdf / max(cfg.triangle.z * lg.ao.y, 1e-4), 0.0, 1.0), max(lg.ao.z, 0.01)) * step(0.5, lg.ao.w);
+ float ao2 = lg.ao2.x * pow(1.0 - clamp(ao_outside / max(cfg.triangle.z * lg.ao2.y, 1e-4), 0.0, 1.0), max(lg.ao2.z, 0.01)) * step(0.5, lg.ao2.w);
+ float ao3 = lg.ao3.x * pow(1.0 - clamp(ao_outside / max(cfg.triangle.z * lg.ao3.y, 1e-4), 0.0, 1.0), max(lg.ao3.z, 0.01)) * step(0.5, lg.ao3.w);
+ float ao_dark = clamp(ao1 + ao2 + ao3, 0.0, 1.0) * (1.0 - colorMix) * (1.0 - occluder);
+ float out_alpha = glow_alpha + ao_dark * (1.0 - glow_alpha);
+ // Paint the foreground triangle as opaque black in the canvas (premultiplied "over" the floor).
+ float particle_mask = texelFetch(particle_tex, fboTexel(particle_tex, ivec2(pixel_screen)), 0).r;
+ float particle_exposure_boost_max = cfg.culling.w; // GUI: Drop deploy \u2192 Particle boost max.
+ float particle_exposure = 1.0 + particle_mask * particle_exposure_boost_max;
+ color *= particle_exposure;
+ vec3 final_rgb = color * glow_alpha * (1.0 - occluder);
+ float final_alpha = out_alpha * (1.0 - occluder) + occluder;
+ fragColor = vec4(final_rgb, final_alpha);
+}
+`;
+
+// Upload particles (drop staging).
+export const PARTICLES_VERT = `#version 300 es
+precision highp float;
+layout(location = 0) in vec2 a_position;
+layout(location = 1) in float a_intensity_t;
+layout(location = 2) in float a_fade_in;
+uniform vec4 u_origin_scale_strength;
+out float v_intensity_t;
+out float v_fade_in;
+uniform vec4 u_rt_size;
+void main() {
+ vec2 screen = a_position * u_origin_scale_strength.z + u_origin_scale_strength.xy;
+ vec2 ndc = vec2(screen.x / u_rt_size.x * 2.0 - 1.0, 1.0 - screen.y / u_rt_size.y * 2.0);
+ gl_Position = vec4(ndc, 0.0, 1.0);
+ v_intensity_t = a_intensity_t;
+ v_fade_in = a_fade_in;
+ gl_PointSize = 1.0;
+}
+`;
+
+// Upload particles (drop staging).
+export const PARTICLES_FRAG = `
+uniform vec4 u_origin_scale_strength;
+uniform vec4 u_rt_size;
+in float v_intensity_t;
+in float v_fade_in;
+out vec4 fragColor;
+void main() {
+ if (u_rt_size.w <= 0.0) {
+ fragColor = vec4(0.0, 0.0, 0.0, 1.0);
+ return;
+ }
+ float min_ratio = clamp(u_rt_size.z, 0.0, 1.0);
+ float particle_scale = mix(min_ratio, 1.0, clamp(v_intensity_t, 0.0, 1.0));
+ float fade_in = clamp(v_fade_in, 0.0, 1.0);
+ fragColor = vec4(u_origin_scale_strength.w * particle_scale * fade_in, 0.0, 0.0, 1.0);
+}
+`;
+
+// Final blit, flipping the present target's rows.
+export const PRESENT_VERT = `#version 300 es
+precision highp float;
+out vec2 v_uv;
+void main() {
+ vec2 positions[3] = vec2[3](
+ vec2(-1.0, -3.0),
+ vec2(-1.0, 1.0),
+ vec2(3.0, 1.0)
+ );
+ vec2 p = positions[gl_VertexID];
+ // Bottom-left UV: present FBO was written top-left; sampling with a bottom-left V flips it once.
+ v_uv = vec2(p.x * 0.5 + 0.5, p.y * 0.5 + 0.5);
+ gl_Position = vec4(p, 0.0, 1.0);
+}
+`;
+
+// Final blit.
+export const PRESENT_FRAG = `
+uniform sampler2D u_present;
+in vec2 v_uv;
+out vec4 fragColor;
+void main() {
+ fragColor = texture(u_present, v_uv);
+}
+`;
diff --git a/site/public/examples/vercel-hero/src/worker.js b/site/public/examples/vercel-hero/src/worker.js
new file mode 100644
index 0000000..bafa4cf
--- /dev/null
+++ b/site/public/examples/vercel-hero/src/worker.js
@@ -0,0 +1,172 @@
+// The hero's render worker, as on vercel.com: it owns an OffscreenCanvas with a WebGL2 context, renders
+// at the page's frame rate and posts each frame to the page as an ImageBitmap. The page tells it about
+// the canvas size, the pointer, clicks, drag-and-drop, nav hovers, theme and visibility.
+
+import { createRenderer, UnsupportedError } from "./renderer.js";
+import { defaultSettings, heroModeFor, clampProbeDensity, clampCascadeCount, setZoom, zoomFor, simScale, setPointerCutoff, FPS_MOBILE } from "./config.js";
+
+let state;
+let initialized = false;
+const queue = [];
+const post = (msg, transfer) => self.postMessage(msg, transfer ?? []);
+const reason = (e) => (e instanceof Error ? e.message : String(e));
+
+function dimensions(d) {
+ const finite = (v, f) => (Number.isFinite(v) ? v : f);
+ const dpr = Math.max(1, finite(d.dpr, 1));
+ const cssWidth = Math.max(1, Math.floor(finite(d.cssWidth, 1)));
+ const cssHeight = Math.max(1, Math.floor(finite(d.cssHeight, 1)));
+ return { cssWidth, cssHeight, pixelWidth: Math.max(1, Math.floor(finite(d.pixelWidth, cssWidth * dpr))), pixelHeight: Math.max(1, Math.floor(finite(d.pixelHeight, cssHeight * dpr))), dpr };
+}
+const sameDims = (a, b) => a?.cssWidth === b.cssWidth && a.cssHeight === b.cssHeight && a.pixelWidth === b.pixelWidth && a.pixelHeight === b.pixelHeight && a.dpr === b.dpr;
+/** The pointer in simulation px (the simulation is at least 360 px tall). */
+const brushFrom = (base, p) =>
+ p && p.active ? { ...base, x: p.x, y: p.y, active: true, inside: p.inside ?? false, isMouse: p.isMouse ?? false } : { ...base, x: -1e3, y: -1e3, active: false, inside: false, isMouse: false };
+
+function schedule(s) {
+ if (s.disposed || s.lifecycle !== "active" || s.animationHandle !== undefined || s.timerHandle !== undefined) return;
+ if (typeof self.requestAnimationFrame === "function") {
+ s.animationHandle = self.requestAnimationFrame((t) => { s.animationHandle = undefined; tick(t); });
+ return;
+ }
+ s.timerHandle = setTimeout(() => { s.timerHandle = undefined; tick(performance.now()); }, s.targetFrameMs);
+}
+function unschedule(s) {
+ if (s.animationHandle !== undefined) { self.cancelAnimationFrame?.(s.animationHandle); s.animationHandle = undefined; }
+ if (s.timerHandle !== undefined) { clearTimeout(s.timerHandle); s.timerHandle = undefined; }
+}
+
+function tick(now) {
+ const s = state;
+ if (!s || s.disposed || s.lifecycle !== "active") return;
+ schedule(s);
+ if (now - s.lastRenderAt < s.targetFrameMs - 0.5) return; // frame pacing (30 fps on small screens)
+ s.lastRenderAt = now;
+ try {
+ // resizes are applied at most every 66 ms
+ const pending = s.pendingResizeDimensions;
+ if (pending) {
+ if (sameDims(s.dimensions, pending)) s.pendingResizeDimensions = undefined;
+ else {
+ const since = s.lastResizeCommitAt === undefined ? 66 : now - s.lastResizeCommitAt;
+ if (s.lastResizeCommitAt === undefined || !(since < 66)) {
+ s.pendingResizeDimensions = undefined;
+ s.dimensions = pending;
+ s.lastResizeCommitAt = now;
+ if (s.canvas.width !== pending.pixelWidth) s.canvas.width = pending.pixelWidth;
+ if (s.canvas.height !== pending.pixelHeight) s.canvas.height = pending.pixelHeight;
+ setZoom(zoomFor(s.baseCameraZoom, pending.cssHeight, s.heroMobile));
+ }
+ }
+ }
+ const time = (now - s.pauseTimeOffset) / 1e3;
+ const { cssWidth, cssHeight, dpr } = s.dimensions;
+ const k = simScale(cssHeight);
+ const sim = { simulationWidth: cssWidth * k, simulationHeight: cssHeight * k, pixelRatio: dpr, probeDensity: s.probeDensity, ...(s.cascadeCount !== undefined ? { cascadeCount: s.cascadeCount } : {}) };
+ const options = {
+ renderBlackOccluder: s.settings.occluderTriangle.showOccluderTriangle,
+ hero: s.settings.hero, theme: s.theme, lightAo: s.settings.lightAo, lightGlow: s.settings.lightGlow, radianceDebug: s.settings.radianceDebug,
+ darkFloor: s.settings.darkFloor, darkPostprocess: s.settings.darkPostprocess, hoverRgbTint: s.settings.hoverRgbTint,
+ hoverRgbDeployActive: s.rgbDeployActive, dropActive: s.dropActive, dropStaging: s.dropStaging,
+ showForegroundTriangle: s.settings.occluderTriangle.showOccluderTriangle,
+ };
+ if (!s.renderer.render(s.canvas.width, s.canvas.height, s.brush, time, s.settings.tunables, sim, options, s.settings.probeDiscard)) return;
+ if (!s.firstFrameSent && s.renderer.stats.cascadeCount > 0) { s.firstFrameSent = true; post({ type: "firstFrame" }); }
+ const bitmap = s.canvas.transferToImageBitmap();
+ post({ type: "frame", bitmap }, [bitmap]);
+ } catch (e) {
+ post({ type: "error", stage: "render", reason: reason(e) });
+ unschedule(s);
+ }
+}
+
+function dispose(stage) {
+ const s = state;
+ state = undefined;
+ if (!s) { if (initialized) post({ type: "disposed" }); return; }
+ s.disposed = true;
+ unschedule(s);
+ try { s.renderer.destroy(); post({ type: "disposed" }); } catch (e) { post({ type: "error", stage, reason: reason(e) }); }
+}
+const withState = (stage, fn) => { const s = state; if (s && !s.disposed) try { fn(s); } catch (e) { post({ type: "error", stage, reason: reason(e) }); } };
+
+async function init(msg) {
+ if (initialized || state) return post({ type: "error", stage: "init", reason: "Hero worker already initialized." });
+ initialized = true;
+ await Promise.resolve();
+ let renderer;
+ try {
+ const dims = dimensions(msg.dimensions);
+ const canvas = new OffscreenCanvas(dims.pixelWidth, dims.pixelHeight);
+ const gl = canvas.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false, preserveDrawingBuffer: false, depth: false, stencil: false });
+ if (!gl) throw new UnsupportedError("OffscreenCanvas WebGL2 context is unavailable.");
+ if (!gl.getExtension("EXT_color_buffer_float")) throw new UnsupportedError("WebGL2 EXT_color_buffer_float is unavailable; float render targets are required.");
+ gl.getExtension("OES_texture_float_linear");
+ const settings = defaultSettings(msg.activeClick);
+ Object.assign(settings.hero, heroModeFor(msg.activeClick));
+ const fps = msg.targetFps === undefined || !Number.isFinite(msg.targetFps) || msg.targetFps <= 0 ? 60 : Math.min(120, Math.max(1, msg.targetFps));
+ setPointerCutoff(fps <= FPS_MOBILE ? 0.1 : 0.2);
+ const baseCameraZoom = msg.cameraZoom ?? 1;
+ const heroMobile = msg.heroMobile ?? false;
+ setZoom(zoomFor(baseCameraZoom, dims.cssHeight, heroMobile));
+ renderer = createRenderer(gl);
+ state = {
+ canvas, gl, renderer, settings, dimensions: dims, pendingResizeDimensions: undefined, lastResizeCommitAt: undefined,
+ theme: msg.theme, lifecycle: "active", brush: brushFrom(settings.brush), rgbDeployActive: false,
+ dropActive: msg.dropActive === true, dropStaging: msg.dropStaging === true, activeClick: msg.activeClick,
+ probeDensity: clampProbeDensity(msg.probeDensity), cascadeCount: clampCascadeCount(msg.cascadeCount), baseCameraZoom, heroMobile,
+ targetFps: fps, targetFrameMs: 1e3 / fps, animationHandle: undefined, timerHandle: undefined, lastRenderAt: -Infinity,
+ pauseTimeOffset: 0, pausedAt: undefined, firstFrameSent: false, disposed: false,
+ };
+ while (state && queue.length) handle(queue.shift());
+ if (state && !state.disposed) { post({ type: "ready" }); schedule(state); }
+ } catch (e) {
+ post({ type: e instanceof UnsupportedError ? "unsupported" : "error", stage: "init", reason: reason(e) });
+ if (state) dispose("dispose"); else renderer?.destroy();
+ } finally {
+ queue.length = 0;
+ }
+}
+
+function handle(msg) {
+ if (msg.type !== "init" && !state) return void queue.push(msg);
+ switch (msg.type) {
+ case "init": return void init(msg);
+ case "resize":
+ return withState("resize", (s) => {
+ s.pendingResizeDimensions = dimensions(msg.dimensions);
+ if (msg.cameraZoom !== undefined) s.baseCameraZoom = msg.cameraZoom;
+ if (msg.heroMobile !== undefined) s.heroMobile = msg.heroMobile;
+ });
+ case "pointer":
+ return withState("render", (s) => {
+ const k = simScale(s.dimensions.cssHeight);
+ s.brush = brushFrom(s.settings.brush, { ...msg.pointer, x: msg.pointer.x * k, y: msg.pointer.y * k });
+ });
+ case "click":
+ return withState("render", (s) => { s.rgbDeployActive = msg.click.kind === "toggle" ? !s.rgbDeployActive : msg.click.deployed; });
+ case "dropActive": return withState("render", (s) => { s.dropActive = msg.active; });
+ case "dropStaging": return withState("render", (s) => { s.dropStaging = msg.active; });
+ case "activeClick":
+ return withState("render", (s) => { s.activeClick = msg.activeClick; Object.assign(s.settings.hero, heroModeFor(msg.activeClick)); });
+ case "theme": return withState("render", (s) => { s.theme = msg.theme; });
+ case "lifecycle":
+ return withState("render", (s) => {
+ const was = s.lifecycle;
+ s.lifecycle = msg.lifecycle;
+ if (msg.lifecycle !== "active" && was === "active") s.pausedAt = performance.now();
+ else if (msg.lifecycle === "active" && was !== "active") {
+ if (s.pausedAt !== undefined) { s.pauseTimeOffset += performance.now() - s.pausedAt; s.pausedAt = undefined; }
+ schedule(s);
+ }
+ if (msg.lifecycle !== "active") unschedule(s);
+ if (msg.lifecycle === "torn-down") dispose("dispose");
+ });
+ case "dispose": return void dispose("dispose");
+ default: throw new Error(`Unhandled hero worker message: ${String(msg?.type)}`);
+ }
+}
+
+self.onmessage = (e) => {
+ try { handle(e.data); } catch (err) { post({ type: "error", stage: "render", reason: reason(err) }); }
+};
diff --git a/site/public/examples/vercel-previews/assets/avatars/johnphamous.webp b/site/public/examples/vercel-previews/assets/avatars/johnphamous.webp
new file mode 100644
index 0000000..903c924
Binary files /dev/null and b/site/public/examples/vercel-previews/assets/avatars/johnphamous.webp differ
diff --git a/site/public/examples/vercel-previews/assets/avatars/rauno.webp b/site/public/examples/vercel-previews/assets/avatars/rauno.webp
new file mode 100644
index 0000000..579ea0d
Binary files /dev/null and b/site/public/examples/vercel-previews/assets/avatars/rauno.webp differ
diff --git a/site/public/examples/vercel-previews/assets/avatars/zeejab.webp b/site/public/examples/vercel-previews/assets/avatars/zeejab.webp
new file mode 100644
index 0000000..f97f247
Binary files /dev/null and b/site/public/examples/vercel-previews/assets/avatars/zeejab.webp differ
diff --git a/site/public/examples/vercel-previews/assets/fonts/Geist-Variable.woff2 b/site/public/examples/vercel-previews/assets/fonts/Geist-Variable.woff2
new file mode 100644
index 0000000..1864b37
Binary files /dev/null and b/site/public/examples/vercel-previews/assets/fonts/Geist-Variable.woff2 differ
diff --git a/site/public/examples/vercel-previews/assets/fonts/LICENSE-geist.txt b/site/public/examples/vercel-previews/assets/fonts/LICENSE-geist.txt
new file mode 100644
index 0000000..4c9d2f0
--- /dev/null
+++ b/site/public/examples/vercel-previews/assets/fonts/LICENSE-geist.txt
@@ -0,0 +1,93 @@
+Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)
+(Geist 1.800, the build vercel.com serves; earlier versions: Copyright (c) 2023 Vercel, in collaboration with basement.studio)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/public/examples/vercel-previews/index.html b/site/public/examples/vercel-previews/index.html
new file mode 100644
index 0000000..72f3ca9
--- /dev/null
+++ b/site/public/examples/vercel-previews/index.html
@@ -0,0 +1,95 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>vercel.com/products/previews hero toolbar, rebuilt with reanimate</title>
+ <meta name="robots" content="noindex">
+ <!--
+ The visual beside "A deployment for every idea" on vercel.com/products/previews: a dark Vercel Toolbar pill
+ between seven tilted tags. On load the tags and the toolbar's groups fade in one after another, 150 ms apart.
+ Hover a group and its tag takes its colour while the other tags blur and the other icons dim; leave and all of
+ it settles back. Grab the toolbar and drag it: the tags blur with the distance, and on release it glides home.
+ Plain HTML + CSS + one ES module (src/toolbar.js ports the page's own React component); the markup, the class
+ names of its CSS module and the Geist icons are vercel.com's.
+ With &embed (?embed works too) the page is framed for an iframe: no scrolling, the visual centred.
+ -->
+ <link rel="preload" href="./assets/fonts/Geist-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="stylesheet" href="./src/toolbar.css">
+ <script>
+ const params = new URLSearchParams(location.search);
+ if (params.has("embed")) document.documentElement.dataset.embed = "";
+ // narrower than the visual (a phone): scaled down to fit, 16px from the sides
+ const fit = () => {
+ const z = Math.min(1, (innerWidth - 32) / 520);
+ document.documentElement.style.setProperty("--fit", z);
+ document.documentElement.toggleAttribute("data-fit", z < 1);
+ };
+ fit();
+ addEventListener("resize", fit);
+ </script>
+ <script type="module" src="./src/toolbar.js"></script>
+</head>
+<body>
+ <main class="vp-page">
+ <div class="vp-visual">
+ <div class="vp-hero">
+ <div class="vp-row" data-side="top">
+ <span class="vp-tag text-label-16" data-color="blue" data-hover="false" style="transform: rotate(-4deg) translateY(0px); animation-delay: 0ms">Comments</span>
+ <span class="vp-tag text-label-16" data-color="purple" data-hover="false" style="transform: rotate(-1deg) translateY(-14px); animation-delay: 300ms">CMS Drafts</span>
+ <span class="vp-tag text-label-16" data-color="green" data-hover="false" style="transform: rotate(1deg) translateY(-14px); animation-delay: 600ms">Accessibility</span>
+ <span class="vp-tag text-label-16" data-color="pink" data-hover="false" style="transform: rotate(4deg) translateY(0px); animation-delay: 900ms">Share</span>
+ </div>
+
+ <div class="cursor-grab touch-none">
+ <div data-animate="true" class="_9BHB5W_root">
+ <div aria-label="This element represents the full suite of the Vercel Toolbar, including various actions and meta-data." class="_9BHB5W_toolbar dark-theme">
+ <div class="vp-group" aria-label="Comments" data-fade="false" data-highlight="false" style="animation-delay: 0ms">
+ <div class="_9BHB5W_fade">
+ <li class="_9BHB5W_action" aria-label="Comment">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><path fill="currentColor" fill-rule="evenodd" d="m2.9 10.4.08.23a5.27 5.27 0 0 1 .4 3.42 8 8 0 0 0 2.33-1.3l.51-.43.67.1q.54.08 1.11.08c3.78 0 6.5-2.64 6.5-5.5S11.78 1.5 8 1.5 1.5 4.14 1.5 7c0 1.18.44 2.3 1.23 3.22zm-.09 5.37A9 9 0 0 1 1 16s.43-.69.73-1.56c.15-.46.27-.96.27-1.44 0-.62-.2-1.27-.4-1.81A6.4 6.4 0 0 1 0 7c0-3.87 3.58-7 8-7s8 3.13 8 7-3.58 7-8 7q-.68 0-1.33-.1a8.7 8.7 0 0 1-3.86 1.87" clip-rule="evenodd"/></svg></div>
+ </li>
+ <li class="_9BHB5W_action" aria-label="Inbox">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><circle cx="13.5" cy="2.5" r="2.5" fill="var(--ds-blue-900)"/><path fill="currentColor" fill-rule="evenodd" d="m15.29 6.08.6 1.2q.1.22.11.46V12a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12V7.74a1 1 0 0 1 .1-.45L3 1.5h6.63a4 4 0 0 0-.1 1.5h-5.6L1.68 7.5h5.07v.75a1.25 1.25 0 1 0 2.5 0V7.5h5.07l-.5-1.01a4 4 0 0 0 1.47-.41M1.5 12V9h3.85a2.75 2.75 0 0 0 5.3 0h3.85v3a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1" clip-rule="evenodd"/></svg></div>
+ </li>
+ </div>
+ </div>
+ <hr>
+ <li class="_9BHB5W_action" style="animation-delay: 150ms" aria-label="Feature Flags" data-fade="false" data-highlight="false">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><path fill="currentColor" fill-rule="evenodd" d="M8.57 4.5H11a3.5 3.5 0 1 1 0 7H8.57a5 5 0 0 0 0-7M5 4.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7M0 8a5 5 0 0 1 5-5h6a5 5 0 0 1 0 10H5a5 5 0 0 1-5-5" clip-rule="evenodd"/></svg></div>
+ </li>
+ <li class="_9BHB5W_action" style="animation-delay: 300ms" aria-label="CMS Drafts" data-fade="false" data-highlight="false">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><path fill="currentColor" fill-rule="evenodd" d="M6.51 3.16c.97-.29 2-.29 2.98 0l.42-1.44a7 7 0 0 0-3.82 0zm4.34.62q.61.4 1.13.99L13.05 6l1.13-.98-1.07-1.24q-.65-.76-1.45-1.27zm-6.83.99q.51-.6 1.13-.99l-.81-1.26q-.8.52-1.45 1.27L1.82 5.03l1.13.98zm10.1 2.48.64.75-.65.75 1.14.98 1.07-1.24V7.5l-1.07-1.24zm-12.23 0L1.24 8l.65.75-1.14.98-1.07-1.24V7.5L.75 6.27zm11.16 2.74-1.07 1.24q-.51.6-1.13.99l.81 1.26a7 7 0 0 0 1.45-1.27l1.07-1.24zm-9.03 1.24L2.95 10l-1.13.98 1.07 1.24q.65.75 1.45 1.27l.81-1.26q-.61-.4-1.13-.99m5.89 3.05-.42-1.44c-.97.29-2 .29-2.98 0l-.42 1.44a7 7 0 0 0 3.82 0M6.5 8a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0M8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6" clip-rule="evenodd"/></svg></div>
+ </li>
+ <hr>
+ <div class="_9BHB5W_collaborators" aria-label="Collaborators" data-fade="false" data-highlight="false" style="animation-delay: 450ms">
+ <div>
+ <span class="_9BHB5W_user" aria-label="Avatar for JohnPhamous" role="img" style="--color: var(--ds-amber-800)"><img alt="Avatar for JohnPhamous" title="Avatar for JohnPhamous" width="37" height="37" decoding="sync" loading="eager" src="./assets/avatars/johnphamous.webp"></span>
+ <span class="_9BHB5W_user" aria-label="Avatar for zeejab" role="img" style="--color: var(--ds-red-800)"><img alt="Avatar for zeejab" title="Avatar for zeejab" width="37" height="37" decoding="sync" loading="eager" src="./assets/avatars/zeejab.webp"></span>
+ <span class="_9BHB5W_user" aria-label="Avatar for rauno" role="img" style="--color: var(--ds-teal-900)"><img alt="Avatar for rauno" title="Avatar for rauno" width="37" height="37" decoding="sync" loading="eager" src="./assets/avatars/rauno.webp"></span>
+ </div>
+ </div>
+ <hr>
+ <li class="_9BHB5W_action" style="animation-delay: 600ms" aria-label="Accessibility" data-fade="false" data-highlight="false">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><path fill="currentColor" d="M8 3a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3M4.67 6a2 2 0 0 1 1.98 2.3l-.22 1.43q-.15.73-.43 1.41L4.33 15.2l1.6.69 1.66-3.97c.14-.32.68-.32.82 0l1.67 3.97 1.59-.69L10 11.14q-.3-.68-.43-1.4l-.29-1.31A2 2 0 0 1 11.24 6H14V4.5H2V6z"/></svg></div>
+ </li>
+ <li class="_9BHB5W_action" style="animation-delay: 750ms" aria-label="Layout Shift" data-fade="false" data-highlight="false">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><path fill="currentColor" fill-rule="evenodd" d="M2.25 14.5H3V16h-.75C1.01 16 0 15 0 13.75V12.5h1.5v1.25c0 .41.34.75.75.75m1.75 0h2V16H4zM6 0H4v1.5h2zM1.5 2.25V3.5H0V2.25C0 1.01 1 0 2.25 0H3v1.5h-.75a.75.75 0 0 0-.75.75m0 9.25v-3H0v3zm0-7v3H0v-3zm5 9.25c0 1.24 1 2.25 2.25 2.25h5c1.24 0 2.25-1 2.25-2.25V2.25C16 1.01 15 0 13.75 0h-5C7.51 0 6.5 1 6.5 2.25zm2.25.75a.75.75 0 0 1-.75-.75V2.25c0-.41.34-.75.75-.75h5c.41 0 .75.34.75.75v11.5c0 .41-.34.75-.75.75z" clip-rule="evenodd"/></svg></div>
+ </li>
+ <li class="_9BHB5W_action" style="animation-delay: 900ms" aria-label="Share" data-fade="false" data-highlight="false">
+ <div aria-hidden="true"><svg viewBox="0 0 16 16" height="16" width="16" data-slot="geist-icon"><path fill="currentColor" fill-rule="evenodd" d="M7.3 1.4a1 1 0 0 1 1.4 0l3.08 3.07.53.53-1.06 1.06-.53-.53-1.97-1.97V11h-1.5V3.56L5.28 5.53l-.53.53L3.69 5l.53-.53zm6.2 7.85v4.25h-11v-5H1V14a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8.5h-1.5z" clip-rule="evenodd"/></svg></div>
+ </li>
+ </div>
+ </div>
+ </div>
+
+ <div class="vp-row" data-side="bottom">
+ <span class="vp-tag text-label-16" data-color="teal" data-hover="false" style="transform: rotate(2deg) translateY(7px); animation-delay: 150ms">Feature Flags</span>
+ <span class="vp-tag text-label-16" data-color="amber" data-hover="false" style="transform: rotate(0deg) translateY(14px); animation-delay: 450ms">Collaborators</span>
+ <span class="vp-tag text-label-16" data-color="red" data-hover="false" style="transform: rotate(-2deg) translateY(7px); animation-delay: 750ms">Layout Shift</span>
+ </div>
+ </div>
+ </div>
+ </main>
+</body>
+</html>
diff --git a/site/public/examples/vercel-previews/src/toolbar.css b/site/public/examples/vercel-previews/src/toolbar.css
new file mode 100644
index 0000000..b8ebbc0
--- /dev/null
+++ b/site/public/examples/vercel-previews/src/toolbar.css
@@ -0,0 +1,197 @@
+/* vercel.com/products/previews hero: the Vercel Toolbar between seven tags.
+ Values are vercel.com's resolved Geist tokens and the rules of its CSS module (class names kept, _9BHB5W_*),
+ at the size the page shows them: the toolbar's root is an inline-size container of width 0, so the module's
+ "@container (max-width: 560px)" sizes always apply (32px buttons, 16px icons, 42px tall).
+ The font is Geist 1.800 (SIL OFL), the build vercel.com serves: older Geist builds set these labels up to
+ 2.5 px wider. */
+
+@font-face {
+ font-family: "GeistSans";
+ src: url(../assets/fonts/Geist-Variable.woff2) format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+}
+
+:root {
+ --hero-duration: 350ms;
+ --hero-easing: cubic-bezier(0.455, 0.03, 0.515, 0.955);
+ /* Geist light theme */
+ --ds-background-200: hsla(0, 0%, 98%, 1);
+ --ds-gray-200: hsla(0, 0%, 92%, 1);
+ --ds-gray-400: hsla(0, 0%, 92%, 1);
+ --ds-gray-700: hsla(0, 0%, 56%, 1);
+ --ds-gray-1000: hsla(0, 0%, 9%, 1);
+ --ds-gray-alpha-300: #0000001a;
+ --ds-gray-alpha-400: #00000014;
+ --ds-blue-700: hsla(212, 100%, 48%, 1);
+ --ds-blue-900: hsla(211, 100%, 42%, 1);
+ --ds-purple-700: hsla(272, 51%, 54%, 1);
+ --ds-green-700: hsla(131, 41%, 46%, 1);
+ --ds-pink-700: hsla(336, 80%, 58%, 1);
+ --ds-red-700: hsla(358, 75%, 59%, 1);
+ --ds-red-800: hsla(358, 70%, 52%, 1);
+ --ds-teal-700: hsla(173, 80%, 36%, 1);
+ --ds-teal-900: hsla(174, 91%, 25%, 1);
+ --ds-amber-800: hsla(35, 100%, 52%, 1);
+ --ds-shadow-modal: 0 0 0 1px #00000014, 0px 1px 1px #00000005, 0px 8px 16px -4px #0000000a, 0px 24px 32px -8px #0000000f, 0 0 0 1px hsla(0, 0%, 98%, 1);
+}
+
+/* Geist dark theme, which the toolbar switches to */
+.dark-theme {
+ --ds-gray-200: hsla(0, 0%, 12%, 1);
+ --ds-gray-400: hsla(0, 0%, 18%, 1);
+ --ds-gray-1000: hsla(0, 0%, 93%, 1);
+ --ds-gray-alpha-300: #ffffff21;
+ --ds-gray-alpha-400: #ffffff24;
+ --ds-blue-900: hsla(210, 100%, 66%, 1);
+ --ds-red-800: hsla(358, 69%, 52%, 1);
+ --ds-teal-900: hsla(174, 90%, 41%, 1);
+ --ds-shadow-modal: 0 0 0 1px #ffffff25, 0px 1px 1px #00000005, 0px 8px 16px -4px #0000000a, 0px 24px 32px -8px #0000000f, 0 0 0 1px hsla(0, 0%, 0%, 1);
+}
+
+*, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; }
+img, svg { display: block; vertical-align: middle; }
+
+html {
+ font-family: "GeistSans", Arial, sans-serif;
+ font-feature-settings: "calt" 0, "rlig", "ss11";
+ line-height: 1.5;
+ -webkit-font-smoothing: antialiased;
+ text-rendering: optimizeLegibility;
+ -webkit-text-size-adjust: 100%;
+ color: var(--ds-gray-1000);
+ background: var(--ds-background-200);
+}
+
+/* the page: the visual in the middle of the window, in a box as wide as its column on vercel.com */
+.vp-page { min-height: 100vh; display: flex; align-items: center; justify-content: center; }
+.vp-visual { flex: none; width: min(802px, 100%); display: flex; align-items: center; justify-content: center; }
+/* narrower than the visual (index.html sets --fit): scaled down to fit, 16px from the sides */
+html[data-fit] .vp-visual { width: 520px; zoom: var(--fit); }
+/* &embed: the visual centred in the frame, no scrolling (the reanimate site can show it in an iframe) */
+html[data-embed] { overflow: hidden; }
+
+.vp-hero { display: flex; width: 100%; flex-direction: column; align-items: center; justify-content: center; }
+
+/* ---------- tags ---------- */
+.vp-row { display: flex; flex-direction: row; align-items: stretch; justify-content: center; gap: 32px; }
+.vp-row[data-side="top"] { margin-bottom: 28px; }
+.vp-row[data-side="bottom"] { margin-top: 28px; }
+
+.vp-tag {
+ display: inline-flex;
+ align-items: center;
+ height: 28px;
+ padding: 0 10px;
+ border-radius: 8px;
+ font-size: 16px;
+ line-height: 28px;
+ font-weight: 500;
+ white-space: nowrap;
+ color: #fff;
+ background-color: var(--ds-gray-700);
+ box-shadow: 0px 1px 1px #00000005, 0px 4px 8px #0000000a;
+ opacity: 0;
+ animation: fade-in var(--hero-duration) var(--hero-easing) both;
+ transition: filter 250ms cubic-bezier(0, 0, 0.2, 1), background-color 250ms cubic-bezier(0, 0, 0.2, 1);
+}
+.vp-tag[data-hover="true"][data-color="amber"] { background-color: var(--ds-amber-800); }
+.vp-tag[data-hover="true"][data-color="blue"] { background-color: var(--ds-blue-700); }
+.vp-tag[data-hover="true"][data-color="green"] { background-color: var(--ds-green-700); }
+.vp-tag[data-hover="true"][data-color="pink"] { background-color: var(--ds-pink-700); }
+.vp-tag[data-hover="true"][data-color="purple"] { background-color: var(--ds-purple-700); }
+.vp-tag[data-hover="true"][data-color="red"] { background-color: var(--ds-red-700); }
+.vp-tag[data-hover="true"][data-color="teal"] { background-color: var(--ds-teal-700); }
+.vp-tag[data-fade="true"] { filter: blur(4px); background-color: var(--ds-gray-700) !important; }
+
+@keyframes fade-in { 0% { opacity: 0; } to { opacity: 1; } }
+
+@media (prefers-reduced-motion: reduce) {
+ .vp-tag { animation: none; opacity: 1; }
+}
+
+/* ---------- toolbar (vercel.com's CSS module) ---------- */
+.cursor-grab { cursor: grab; }
+.touch-none { touch-action: none; }
+.geist-grabbing { cursor: grabbing; }
+.geist-grabbing * { -webkit-user-select: none; user-select: none; pointer-events: none; }
+
+._9BHB5W_root {
+ display: flex; flex-direction: row; align-items: center; justify-content: center; flex: 0 1 auto;
+ z-index: 5; width: 100%; position: relative; container-type: inline-size;
+}
+._9BHB5W_root[data-animate="true"] ._9BHB5W_toolbar > :not(hr) {
+ opacity: 0;
+ filter: blur(2px);
+ transform: translateY(-2px);
+ animation-name: _9BHB5W_fade;
+ animation-duration: var(--hero-duration);
+ animation-timing-function: var(--hero-easing);
+ animation-fill-mode: forwards;
+}
+@keyframes _9BHB5W_fade { to { opacity: 1; filter: blur(0); transform: translateY(0); } }
+
+._9BHB5W_toolbar {
+ --action-size: 32px;
+ --icon-size: 16px;
+ display: flex; flex-direction: row; align-items: center; justify-content: space-between; flex: 0 1 auto;
+ background: var(--ds-gray-200);
+ height: 42px;
+ box-shadow: var(--ds-shadow-modal);
+ border: 2px solid var(--ds-gray-400);
+ z-index: 2;
+ border-radius: 9999px;
+ padding: 0 5px;
+ list-style: none;
+ position: relative;
+}
+._9BHB5W_toolbar hr { flex: none; background: var(--ds-gray-alpha-400); border: 0; width: 2px; height: 24px; margin: 0 4px; }
+._9BHB5W_toolbar [data-highlight="true"] { background: var(--ds-gray-alpha-300); border-radius: inherit; transition: background 0.25s ease-out; }
+._9BHB5W_toolbar [data-fade="true"] > div { opacity: 0.25 !important; }
+
+.vp-group, ._9BHB5W_fade { display: flex; flex-direction: row; align-items: stretch; justify-content: flex-start; flex: 0 1 auto; }
+
+._9BHB5W_action {
+ display: flex; flex-direction: column; align-items: center; justify-content: center; flex: 0 1 auto;
+ width: var(--action-size); height: var(--action-size); color: var(--ds-gray-1000); border-radius: inherit;
+}
+._9BHB5W_action > div { display: flex; flex-direction: column; align-items: center; justify-content: center; flex: 0 1 auto; }
+._9BHB5W_action svg { width: var(--icon-size); height: var(--icon-size); }
+._9BHB5W_action > div, ._9BHB5W_fade, ._9BHB5W_collaborators > div { transition: opacity 0.25s ease-out; }
+
+._9BHB5W_collaborators {
+ display: flex; flex-direction: row; align-items: center; justify-content: flex-start; flex: 0 1 auto;
+ white-space: nowrap; height: var(--action-size); margin: 0 -3px; padding: 0 8px;
+}
+._9BHB5W_collaborators > div { display: flex; flex-direction: row; align-items: stretch; justify-content: flex-start; flex: 0 1 auto; }
+
+/* Geist avatar, with the module's coloured ring */
+._9BHB5W_user {
+ --border-width: 2px;
+ position: relative;
+ display: inline-block;
+ flex-shrink: 0;
+ width: 26px;
+ height: 26px;
+ line-height: 0;
+ vertical-align: top;
+ overflow: hidden;
+ border-radius: calc(infinity * 1px);
+ border: var(--border-width) solid var(--color);
+ box-shadow: 0 0 0 var(--border-width) var(--ds-gray-200);
+ transition: background 200ms cubic-bezier(0.4, 0, 0.2, 1);
+}
+._9BHB5W_user::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ border-radius: calc(infinity * 1px);
+ border: 1px solid var(--ds-gray-alpha-400);
+}
+._9BHB5W_user img { position: relative; width: 100%; height: 100%; max-width: 100%; color: transparent; }
+._9BHB5W_user:not(:first-of-type) { margin-left: -8px; }
+._9BHB5W_user:first-of-type { z-index: 2; }
+._9BHB5W_user:nth-of-type(2) { z-index: 1; }
diff --git a/site/public/examples/vercel-previews/src/toolbar.js b/site/public/examples/vercel-previews/src/toolbar.js
new file mode 100644
index 0000000..1ffb42e
--- /dev/null
+++ b/site/public/examples/vercel-previews/src/toolbar.js
@@ -0,0 +1,100 @@
+// vercel.com/products/previews hero toolbar: hover and drag, ported from the page's React component (HeroToolbar).
+//
+// State, as on vercel.com:
+// hovered the pointer is inside the toolbar's wrapper. Every tag gets data-hover="true", which on its own
+// gives each tag its colour (you see that when the pointer comes in over the pill's edge).
+// feature the toolbar group the pointer last entered. Its tag keeps its colour, the other tags get
+// data-fade="true" (blur 4px, grey) and the other groups data-fade="true" (icons at 25 %); the group
+// itself gets data-highlight="true". Separators and padding do not clear it, only leaving the wrapper does.
+// Drag: press on the toolbar and move. The wrapper follows the pointer and both rows of tags blur by
+// (|dx| + |dy|) / 10 px, at most 5 px. On release it glides back in 500 ms and the blur clears in 250 ms.
+// All the transitions themselves are CSS (toolbar.css); this file only sets attributes and inline styles.
+
+const wrapper = document.querySelector(".cursor-grab");
+const rows = [...document.querySelectorAll(".vp-row")];
+const tags = [...document.querySelectorAll(".vp-tag")];
+const groups = [...document.querySelectorAll("._9BHB5W_toolbar > [aria-label]")];
+
+let hovered = false;
+let feature = null;
+
+function render() {
+ for (const tag of tags) {
+ tag.dataset.hover = String(hovered);
+ if (feature) tag.dataset.fade = String(feature !== tag.textContent);
+ else delete tag.dataset.fade;
+ }
+ for (const group of groups) {
+ const name = group.getAttribute("aria-label");
+ group.dataset.fade = String(!!feature && feature !== name);
+ group.dataset.highlight = String(feature === name);
+ }
+}
+
+// React gives mouseenter/mouseleave updates "continuous" priority: they render in a Scheduler task (a
+// MessageChannel message) after the event, not inside it. Rendering the same way keeps the transitions starting
+// on the same frame as on vercel.com.
+const channel = new MessageChannel();
+let queued = false;
+channel.port1.onmessage = () => {
+ queued = false;
+ render();
+};
+const update = () => {
+ if (queued) return;
+ queued = true;
+ channel.port2.postMessage(null);
+};
+
+for (const group of groups) {
+ group.addEventListener("mouseenter", () => {
+ feature = group.getAttribute("aria-label");
+ update();
+ });
+}
+wrapper.addEventListener("mouseenter", () => {
+ hovered = true;
+ update();
+});
+wrapper.addEventListener("mouseleave", () => {
+ feature = null;
+ hovered = false;
+ update();
+});
+
+// ---------- drag ----------
+let grab = null;
+const blurRows = (px) => {
+ const filter = px <= 0 ? "" : `blur(${px}px)`;
+ for (const row of rows) row.style.filter = filter;
+};
+const transitionRows = (value) => {
+ for (const row of rows) row.style.transition = value;
+};
+const release = (e) => {
+ if (!grab) return;
+ grab = null;
+ wrapper.releasePointerCapture(e.pointerId);
+ document.body.classList.remove("geist-grabbing");
+ wrapper.style.transition = "transform 500ms ease-out";
+ wrapper.style.transform = "";
+ transitionRows("filter 250ms ease-out");
+ blurRows(0);
+};
+
+wrapper.addEventListener("pointerdown", (e) => {
+ wrapper.setPointerCapture(e.pointerId);
+ grab = { x: e.clientX, y: e.clientY };
+ wrapper.style.transition = "none";
+ transitionRows("none");
+ document.body.classList.add("geist-grabbing");
+});
+wrapper.addEventListener("pointermove", (e) => {
+ if (!grab) return;
+ const dx = e.clientX - grab.x;
+ const dy = e.clientY - grab.y;
+ wrapper.style.transform = `translate(${dx}px, ${dy}px)`;
+ blurRows(Math.min(5, Math.max(0, (Math.abs(dx) + Math.abs(dy)) / 10)));
+});
+wrapper.addEventListener("pointerup", release);
+wrapper.addEventListener("pointercancel", release);
diff --git a/site/public/examples/vercel-workflow/assets/fonts/GeistMono-Variable.woff2 b/site/public/examples/vercel-workflow/assets/fonts/GeistMono-Variable.woff2
new file mode 100644
index 0000000..cf24126
Binary files /dev/null and b/site/public/examples/vercel-workflow/assets/fonts/GeistMono-Variable.woff2 differ
diff --git a/site/public/examples/vercel-workflow/assets/fonts/GeistSans-Variable.woff2 b/site/public/examples/vercel-workflow/assets/fonts/GeistSans-Variable.woff2
new file mode 100644
index 0000000..1864b37
Binary files /dev/null and b/site/public/examples/vercel-workflow/assets/fonts/GeistSans-Variable.woff2 differ
diff --git a/site/public/examples/vercel-workflow/assets/fonts/LICENSE-geist.txt b/site/public/examples/vercel-workflow/assets/fonts/LICENSE-geist.txt
new file mode 100644
index 0000000..8d003fe
--- /dev/null
+++ b/site/public/examples/vercel-workflow/assets/fonts/LICENSE-geist.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2023 Vercel, in collaboration with basement.studio
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/public/examples/vercel-workflow/index.html b/site/public/examples/vercel-workflow/index.html
new file mode 100644
index 0000000..5210567
--- /dev/null
+++ b/site/public/examples/vercel-workflow/index.html
@@ -0,0 +1,154 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>vercel.com/workflow run inspector, rebuilt with reanimate</title>
+ <meta name="robots" content="noindex">
+ <!--
+ The "Inspect every run end-to-end" panel of vercel.com/workflow: a mock of the Vercel dashboard showing one run
+ of order-workflow. When the trace scrolls into view the run plays: the status turns to Running, the Duration
+ counts up to 925ms while the six spans grow one after another with their timers, and the status flips to
+ Completed. Each bar keeps its own clock and only advances while at least 35 % of it is on screen, as on
+ vercel.com. Plain HTML + an ES module; src/run.js ports the page's loop and tween code. The structure, the bars'
+ inline styles and the SVG icons are vercel.com's; the fonts are the Geist and Geist Mono builds it serves (OFL).
+ ?pushdown puts the panel below the fold, as the site films it, so the run plays as it scrolls in.
+ -->
+ <link rel="preload" href="./assets/fonts/GeistSans-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="preload" href="./assets/fonts/GeistMono-Variable.woff2" as="font" type="font/woff2" crossorigin>
+ <link rel="stylesheet" href="./src/dashboard.css">
+ <script>
+ if (new URLSearchParams(location.search).has("pushdown")) document.documentElement.dataset.pushdown = "";
+ </script>
+ <script type="module" src="./src/run.js"></script>
+</head>
+<body>
+
+ <main class="vw-page">
+ <div class="vw-frame">
+ <div class="vw-defer">
+ <div class="vw-wrap">
+ <div class="vw-glow" aria-hidden="true"></div>
+ <div class="vw-panel" role="img" aria-label="Vercel dashboard preview showing workflow observability and run timing">
+
+ <div class="vw-side" aria-hidden="true">
+ <div class="vw-side__logo"><span class="vw-tri"></span></div>
+ <span class="vw-side__team">Acme</span><span class="vw-side__plan">Pro</span>
+ <svg class="vw-side__switch" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M8.7 2.4a1 1 0 0 0-1.4 0L4.46 5.22l-.53.53L5 6.81l.53-.53L8 3.81l2.47 2.47.53.53 1.06-1.06-.53-.53zM5.54 9.72 5 9.19l-1.06 1.06.53.53 2.82 2.82a1 1 0 0 0 1.42 0l2.82-2.82.53-.53L11 9.19l-.53.53L8 12.19z" clip-rule="evenodd"></path></svg>
+ <div class="vw-find">
+ <svg class="vw-find__icon" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M1.5 6.5a5 5 0 1 1 10 0 5 5 0 0 1-10 0m5-6.5a6.5 6.5 0 1 0 4.04 11.6l3.43 3.43.53.53 1.06-1.06-.53-.53-3.43-3.43A6.5 6.5 0 0 0 6.5 0" clip-rule="evenodd"></path></svg>
+ <span class="vw-find__text">Find…</span><span class="vw-find__key">F</span>
+ </div>
+ <div class="vw-nav" style="top:76px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m5.25.1.42.28 4.5 3 .33.22V5h-.95L6 7.17v6.42l-1.14-.7-4.5-2.75L0 9.92V3.6l.33-.22 4.5-3zm0 5.77 3.1-1.9-3.1-2.07-3.1 2.07zM1.5 5.34l3 1.83v3.74l-3-1.83zM13.23 12q-.05 1.22-.32 2.43a3.3 3.3 0 0 0 1.8-2.43zm-1.43 2.74a3 3 0 0 1-.6 0q-.38-1.36-.43-2.74h1.46q-.06 1.38-.43 2.74M13.23 11q-.05-1.22-.32-2.43a3.3 3.3 0 0 1 1.8 2.43zm-1 0q-.06-1.38-.43-2.74a3 3 0 0 0-.6 0q-.38 1.36-.43 2.74zm-2.46 0q.05-1.22.32-2.43A3.3 3.3 0 0 0 8.29 11zm.32 3.43q-.27-1.2-.32-2.43H8.29a3.3 3.3 0 0 0 1.8 2.43M11.5 16a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">Domains</span></div>
+ <div class="vw-nav" style="top:116px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M13.75 1.9a2.5 2.5 0 0 0-1.92-.9H4.17a2.5 2.5 0 0 0-1.92.9L1.08 3.3A2.5 2.5 0 0 0 .5 4.9V15h15V4.9c0-.58-.2-1.15-.58-1.6zM14 5v-.1a1 1 0 0 0-.23-.64l1.15-.96-1.15.96-1.17-1.4a1 1 0 0 0-.77-.36H4.17a1 1 0 0 0-.77.36l-1.17 1.4a1 1 0 0 0-.23.65V5a1.5 1.5 0 1 0 3 0h1.5a1.5 1.5 0 1 0 3 0H11a1.5 1.5 0 0 0 3 0m0 2.6a3 3 0 0 1-3.75-.62 3 3 0 0 1-4.5 0A3 3 0 0 1 2 7.6v5.9h4V12a2 2 0 1 1 4 0v1.5h4zM8.5 12v1.5h-1V12a.5.5 0 0 1 1 0" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">Integrations</span></div>
+ <div class="vw-nav" style="top:156px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M3.3.79C4.54.29 6.2 0 8 0s3.46.29 4.7.79a5 5 0 0 1 1.57.94c.41.39.73.9.73 1.52v9.5a2 2 0 0 1-.73 1.52 5 5 0 0 1-1.57.94c-1.24.5-2.9.79-4.7.79s-3.46-.29-4.7-.79a5 5 0 0 1-1.57-.94A2 2 0 0 1 1 12.75v-9.5c0-.62.32-1.13.73-1.52A5 5 0 0 1 3.3.8m-.8 4.54V8c0 .07.03.22.26.43q.33.33 1.1.64c1.02.41 2.49.68 4.14.68s3.12-.27 4.14-.68q.77-.31 1.1-.64c.23-.21.26-.36.26-.43V5.33a6 6 0 0 1-.8.38c-1.24.5-2.9.79-4.7.79s-3.46-.29-4.7-.79a6 6 0 0 1-.8-.38m11-2.08c0 .07-.03.22-.26.43q-.33.33-1.1.64C11.12 4.73 9.65 5 8 5s-3.12-.27-4.14-.68q-.77-.31-1.1-.64c-.23-.21-.26-.36-.26-.43s.03-.22.26-.43q.33-.33 1.1-.64C4.88 1.77 6.35 1.5 8 1.5s3.12.27 4.14.68q.77.31 1.1.64c.23.21.26.36.26.43m0 6.83a6 6 0 0 1-.8.38c-1.24.5-2.9.79-4.7.79s-3.46-.29-4.7-.79a6 6 0 0 1-.8-.38v2.67c0 .07.03.22.26.43q.33.33 1.1.64c1.02.41 2.49.68 4.14.68s3.12-.27 4.14-.68q.77-.31 1.1-.64c.23-.21.26-.36.26-.43z" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">Storage</span></div>
+ <div class="vw-nav" style="top:196px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m2.5 2.38.6-.33c.58-.28 1.4-.55 2.4-.55.87 0 1.52.42 2.26.98l.16.11q.48.38 1.03.71c.44.25.95.45 1.55.45a9 9 0 0 0 3-.63v5.7q-.2.1-.52.23c-.57.22-1.4.45-2.42.45-.9 0-1.45-.33-2.13-.76l-.03-.01c-.7-.44-1.55-.98-2.9-.98-1.25 0-2.27.33-3 .67zm0 7.75V16H1V1.65l.27-.22.48.57-.48-.57v-.01l.03-.02.3-.22q.3-.2.85-.48C3.18.35 4.23 0 5.5 0c1.4 0 2.4.7 3.16 1.27l.17.13q.47.36.86.6.44.25.81.25c.73 0 1.57-.22 2.27-.46a13 13 0 0 0 1.13-.46h.02L15 .8v8.84l-.32.22-.43-.61.43.61-.01.01-.02.01-.3.18q-.29.17-.82.39c-.71.28-1.73.55-2.97.55-1.36 0-2.2-.54-2.9-.98l-.03-.01c-.69-.43-1.22-.76-2.13-.76a5.6 5.6 0 0 0-3 .88m-.27.2" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">Flags</span></div>
+ <div class="vw-nav" style="top:236px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" d="M2 11.64a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5m4 0a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5m4 0a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5m4 0a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5M4 8.18a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5m4 0a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5m4 0a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5M6 4.7a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5m4 0a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5M8 1.25a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5"></path></svg></span><span class="vw-nav__label">Agent</span></div>
+ <div class="vw-nav" style="top:276px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M10.5 4a1.5 1.5 0 1 0 3 0 1.5 1.5 0 0 0-3 0M9.42 5.52a3 3 0 1 1 1.06 1.06l-3.9 3.9Q7 11.15 7 12a3 3 0 1 1-1.48-2.58zM2.5 12a1.5 1.5 0 1 0 3 0 1.5 1.5 0 0 0-3 0" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">AI Gateway</span><svg class="vw-nav__more" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m5.5 1.94.53.53 4.82 4.82a1 1 0 0 1 0 1.42l-4.82 4.82-.53.53L4.44 13l.53-.53L9.44 8 4.97 3.53 4.44 3z" clip-rule="evenodd"></path></svg></div>
+ <div class="vw-nav" style="top:316px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" d="M14.5 2.25a.75.75 0 0 0-.75-.75H10.5V0h3.25C14.99 0 16 1 16 2.25V5.5h-1.5zM0 2.25C0 1.01 1 0 2.25 0H5.5v1.5H2.25a.75.75 0 0 0-.75.75V5.5H0zm2.94 8L5.19 8 2.94 5.75 4 4.69l2.6 2.6a1 1 0 0 1 0 1.42L4 11.3zm4.93-.62h4.63v1.5H7.87zm2.63 4.87h3.25c.41 0 .75-.34.75-.75V10.5H16v3.25c0 1.24-1 2.25-2.25 2.25H10.5zM2.25 16C1.01 16 0 15 0 13.75V10.5h1.5v3.25c0 .41.34.75.75.75H5.5V16z"></path></svg></span><span class="vw-nav__label">Sandboxes</span></div>
+ <div class="vw-nav vw-nav--on" style="top:356px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" d="m5.75 7 .67.34-1.57 3.13c.54.3.9.87.9 1.53v2c0 .97-.78 1.75-1.75 1.75H2c-.97 0-1.75-.78-1.75-1.75v-2c0-.97.78-1.75 1.75-1.75h1.29l1.79-3.58zM14 10.25c.97 0 1.75.78 1.75 1.75v2c0 .97-.78 1.75-1.75 1.75h-2c-.88 0-1.6-.65-1.73-1.5H7v-1.5h3.25V12c0-.97.78-1.75 1.75-1.75zm-12 1.5a.25.25 0 0 0-.25.25v2c0 .14.11.25.25.25h2c.14 0 .25-.11.25-.25v-2a.25.25 0 0 0-.25-.25zm10 0a.25.25 0 0 0-.25.25v2q.02.23.25.25h2q.23-.02.25-.25v-2a.25.25 0 0 0-.25-.25zM9 .25c.97 0 1.75.78 1.75 1.75v2q-.02.69-.44 1.16l1.9 3.48-1.32.72-1.97-3.61H7c-.97 0-1.75-.78-1.75-1.75V2c0-.97.78-1.75 1.75-1.75zm-2 1.5a.25.25 0 0 0-.25.25v2c0 .14.11.25.25.25h2c.14 0 .25-.11.25-.25V2A.25.25 0 0 0 9 1.75z"></path></svg></span><span class="vw-nav__label">Workflows</span></div>
+ <div class="vw-side__rule"></div>
+ <div class="vw-nav" style="top:408px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M14.46 8.75a6.5 6.5 0 1 1-7.21-7.2v6.2a1 1 0 0 0 1 1zm0-1.5H8.75v-5.7a6.5 6.5 0 0 1 5.7 5.7M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">Usage</span></div>
+ <div class="vw-nav" style="top:448px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m2.9 10.4.08.23a5.27 5.27 0 0 1 .4 3.42 8 8 0 0 0 2.33-1.3l.51-.43.67.1q.54.08 1.11.08c3.78 0 6.5-2.64 6.5-5.5S11.78 1.5 8 1.5 1.5 4.14 1.5 7c0 1.18.44 2.3 1.23 3.22zm-.09 5.37A9 9 0 0 1 1 16s.43-.69.73-1.56c.15-.46.27-.96.27-1.44 0-.62-.2-1.27-.4-1.81A6.4 6.4 0 0 1 0 7c0-3.87 3.58-7 8-7s8 3.13 8 7-3.58 7-8 7q-.68 0-1.33-.1a8.7 8.7 0 0 1-3.86 1.87" clip-rule="evenodd"></path></svg></span><span class="vw-nav__label">Support</span></div>
+ <div class="vw-nav" style="top:488px"><span class="vw-nav__icon"><svg viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" d="M9.77 1.46q.07.28.35.4.38.12.72.3.27.12.53-.04l1.23-.84 2.12 2.12-.84 1.23a.5.5 0 0 0-.03.53q.17.35.3.72.1.28.39.35L16 6.5v3l-1.46.27a.5.5 0 0 0-.4.35q-.12.38-.3.72a.5.5 0 0 0 .04.53l.84 1.23-2.12 2.12-1.23-.84a.5.5 0 0 0-.53-.03q-.34.17-.72.3a.5.5 0 0 0-.35.39L9.5 16h-3l-.27-1.46a.5.5 0 0 0-.29-.37l-.06-.02a7 7 0 0 1-.72-.3.5.5 0 0 0-.53.03l-1.23.84-2.12-2.12.84-1.23q.14-.21.06-.46l-.03-.07a7 7 0 0 1-.3-.72.5.5 0 0 0-.32-.33l-.07-.02L0 9.5v-3l1.46-.27q.25-.05.37-.29l.02-.06q.14-.38.3-.72a.5.5 0 0 0 0-.47l-.03-.06-.84-1.23L3.4 1.28l1.23.84q.26.16.53.03L5.5 2l.37-.14a.5.5 0 0 0 .33-.32l.02-.07L6.5 0h3zm-2.07.28a2 2 0 0 1-1.33 1.53l-.28.1-.4.18c-.6.25-1.31.22-1.9-.2l-.2-.13-.37.36.14.2c.4.6.44 1.32.2 1.92l-.18.39-.1.28c-.23.65-.8 1.19-1.54 1.33l-.24.04v.51l.24.05c.7.13 1.24.62 1.49 1.21l.04.12.1.28.18.4c.25.6.22 1.31-.2 1.9l-.13.2.36.37.2-.14.12-.08a2 2 0 0 1 1.8-.11l.39.17.28.1c.65.23 1.19.8 1.33 1.54l.04.24h.52l.04-.24.03-.13c.18-.69.7-1.2 1.3-1.4l.28-.1.4-.18c.6-.25 1.31-.21 1.9.2l.2.13.37-.37-.14-.2c-.4-.59-.44-1.3-.2-1.9l.18-.4.1-.28c.23-.65.8-1.19 1.54-1.33l.24-.05v-.5l-.24-.05a2 2 0 0 1-1.53-1.33l-.1-.28-.18-.4c-.25-.6-.21-1.31.2-1.9l.13-.2-.37-.37-.2.14c-.59.4-1.3.44-1.9.2l-.4-.18-.28-.1A2 2 0 0 1 8.3 1.73l-.04-.24h-.52zM8 5a3 3 0 1 1 0 6 3 3 0 0 1 0-6m0 1.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3"></path></svg></span><span class="vw-nav__label">Settings</span><svg class="vw-nav__more" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m5.5 1.94.53.53 4.82 4.82a1 1 0 0 1 0 1.42l-4.82 4.82-.53.53L4.44 13l.53-.53L9.44 8 4.97 3.53 4.44 3z" clip-rule="evenodd"></path></svg></div>
+ <div class="vw-side__fade"></div>
+ </div>
+
+ <div class="vw-main">
+ <div class="vw-top">
+ <div class="vw-top__project" aria-hidden="true">
+ <span class="vw-top__logo"><span class="vw-top__mark"><span class="vw-tri vw-tri--lg"></span></span></span><span class="vw-top__name">acme-store</span>
+ <svg class="vw-top__switch" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="M8.7 2.4a1 1 0 0 0-1.4 0L4.46 5.22l-.53.53L5 6.81l.53-.53L8 3.81l2.47 2.47.53.53 1.06-1.06-.53-.53zM5.54 9.72 5 9.19l-1.06 1.06.53.53 2.82 2.82a1 1 0 0 0 1.42 0l2.82-2.82.53-.53L11 9.19l-.53.53L8 12.19z" clip-rule="evenodd"></path></svg>
+ </div>
+ <span class="vw-top__title">Workflows</span>
+ <div class="vw-top__ask" aria-hidden="true">
+ <span class="vw-dots"><span style="left:14.75px;top:9.25px"></span><span style="left:12.75px;top:12.714px"></span><span style="left:16.75px;top:12.714px"></span><span style="left:10.75px;top:16.179px"></span><span style="left:14.75px;top:16.179px"></span><span style="left:18.75px;top:16.179px"></span><span style="left:8.75px;top:19.643px"></span><span style="left:12.75px;top:19.643px"></span><span style="left:16.75px;top:19.643px"></span><span style="left:20.75px;top:19.643px"></span></span><span class="vw-top__ask-label">Ask Vercel</span>
+ </div>
+ </div>
+
+ <div class="vw-body" aria-hidden="true">
+ <div class="vw-run">
+ <div class="vw-head">
+ <div class="vw-head__line">
+ <span class="vw-head__name">order-workflow</span>
+ <div class="vw-head__id">
+ <span class="vw-head__run">wrun_01KC7XRJ</span>
+ <svg class="vw-head__copy" viewBox="0 0 16 16" width="14" height="14"><path fill="currentColor" fill-rule="evenodd" d="M8.25 2c.14 0 .25.11.25.25V3H10v-.75C10 1.28 9.22.5 8.25.5h-5.5C1.78.5 1 1.28 1 2.25v7.5c0 .97.78 1.75 1.75 1.75H4.5V10H2.75a.25.25 0 0 1-.25-.25v-7.5c0-.14.11-.25.25-.25zm5 4c.14 0 .25.11.25.25v7.5q-.02.23-.25.25h-5.5a.25.25 0 0 1-.25-.25v-7.5c0-.14.11-.25.25-.25zm0 9.5c.97 0 1.75-.78 1.75-1.75v-7.5c0-.97-.78-1.75-1.75-1.75h-5.5C6.78 4.5 6 5.28 6 6.25v7.5c0 .97.78 1.75 1.75 1.75z" clip-rule="evenodd"></path></svg>
+ </div>
+ <div class="vw-head__rule"></div>
+ <div class="vw-status" data-status="idle">
+ <span class="vw-status__dot"></span><span class="vw-status__label"><span class="vw-status__text">Running</span></span>
+ </div>
+ <div class="vw-head__fill"></div>
+ </div>
+ <div class="vw-facts">
+ <div class="vw-fact"><span class="vw-fact__k">Created</span><span class="vw-fact__v">2m ago</span></div>
+ <div class="vw-fact"><span class="vw-fact__k">Completed</span><span class="vw-fact__v">1m ago</span></div>
+ <div class="vw-fact"><span class="vw-fact__k">Duration</span><span class="vw-fact__v" data-duration>0<!-- -->ms</span></div>
+ </div>
+ </div>
+
+ <div class="vw-trace">
+ <div class="vw-trace__head">
+ <div class="vw-search">
+ <svg class="vw-search__icon" viewBox="0 0 16 16" width="14" height="14"><path fill="currentColor" fill-rule="evenodd" d="M1.5 6.5a5 5 0 1 1 10 0 5 5 0 0 1-10 0m5-6.5a6.5 6.5 0 1 0 4.04 11.6l3.43 3.43.53.53 1.06-1.06-.53-.53-3.43-3.43A6.5 6.5 0 0 0 6.5 0" clip-rule="evenodd"></path></svg><span class="vw-search__text">Search spans…</span>
+ </div>
+ <div class="vw-axis">
+ <div class="vw-axis__inner">
+ <span class="vw-tick vw-tick--start">0ms</span><span class="vw-tick" style="left:25%">230ms</span><span class="vw-tick" style="left:50%">460ms</span><span class="vw-tick" style="left:75%">690ms</span><span class="vw-tick vw-tick--end">925ms</span>
+ </div>
+ </div>
+ </div>
+ <div class="vw-trace__body">
+ <div class="vw-rows">
+ <div class="vw-row"><div class="vw-row__name"><svg class="vw-row__icon vw-row__icon--run" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" d="m5.75 7 .67.34-1.57 3.13c.54.3.9.87.9 1.53v2c0 .97-.78 1.75-1.75 1.75H2c-.97 0-1.75-.78-1.75-1.75v-2c0-.97.78-1.75 1.75-1.75h1.29l1.79-3.58zM14 10.25c.97 0 1.75.78 1.75 1.75v2c0 .97-.78 1.75-1.75 1.75h-2c-.88 0-1.6-.65-1.73-1.5H7v-1.5h3.25V12c0-.97.78-1.75 1.75-1.75zm-12 1.5a.25.25 0 0 0-.25.25v2c0 .14.11.25.25.25h2c.14 0 .25-.11.25-.25v-2a.25.25 0 0 0-.25-.25zm10 0a.25.25 0 0 0-.25.25v2q.02.23.25.25h2q.23-.02.25-.25v-2a.25.25 0 0 0-.25-.25zM9 .25c.97 0 1.75.78 1.75 1.75v2q-.02.69-.44 1.16l1.9 3.48-1.32.72-1.97-3.61H7c-.97 0-1.75-.78-1.75-1.75V2c0-.97.78-1.75 1.75-1.75zm-2 1.5a.25.25 0 0 0-.25.25v2c0 .14.11.25.25.25h2c.14 0 .25-.11.25-.25V2A.25.25 0 0 0 9 1.75z"></path></svg><span class="vw-row__label">workflow</span></div><span class="vw-row__ms">925ms</span></div>
+ <div class="vw-row"><div class="vw-row__name"><svg class="vw-row__icon" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m4.22 12.53.53.53L5.81 12l-.53-.53L1.81 8l3.47-3.47.53-.53-1.06-1.06-.53.53L.4 7.29a1 1 0 0 0 0 1.42zm7.56 0-.53.53L10.19 12l.53-.53L14.19 8l-3.47-3.47-.53-.53 1.06-1.06.53.53 3.82 3.82a1 1 0 0 1 0 1.42z" clip-rule="evenodd"></path></svg><span class="vw-row__label">fetchOrder</span></div><span class="vw-row__ms">230ms</span></div>
+ <div class="vw-row"><div class="vw-row__name"><svg class="vw-row__icon" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m4.22 12.53.53.53L5.81 12l-.53-.53L1.81 8l3.47-3.47.53-.53-1.06-1.06-.53.53L.4 7.29a1 1 0 0 0 0 1.42zm7.56 0-.53.53L10.19 12l.53-.53L14.19 8l-3.47-3.47-.53-.53 1.06-1.06.53.53 3.82 3.82a1 1 0 0 1 0 1.42z" clip-rule="evenodd"></path></svg><span class="vw-row__label">validate</span></div><span class="vw-row__ms">155ms</span></div>
+ <div class="vw-row"><div class="vw-row__name"><svg class="vw-row__icon" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m4.22 12.53.53.53L5.81 12l-.53-.53L1.81 8l3.47-3.47.53-.53-1.06-1.06-.53.53L.4 7.29a1 1 0 0 0 0 1.42zm7.56 0-.53.53L10.19 12l.53-.53L14.19 8l-3.47-3.47-.53-.53 1.06-1.06.53.53 3.82 3.82a1 1 0 0 1 0 1.42z" clip-rule="evenodd"></path></svg><span class="vw-row__label">enrichWithPricing</span></div><span class="vw-row__ms">230ms</span></div>
+ <div class="vw-row"><div class="vw-row__name"><svg class="vw-row__icon" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m4.22 12.53.53.53L5.81 12l-.53-.53L1.81 8l3.47-3.47.53-.53-1.06-1.06-.53.53L.4 7.29a1 1 0 0 0 0 1.42zm7.56 0-.53.53L10.19 12l.53-.53L14.19 8l-3.47-3.47-.53-.53 1.06-1.06.53.53 3.82 3.82a1 1 0 0 1 0 1.42z" clip-rule="evenodd"></path></svg><span class="vw-row__label">saveOrder</span></div><span class="vw-row__ms">155ms</span></div>
+ <div class="vw-row"><div class="vw-row__name"><svg class="vw-row__icon" viewBox="0 0 16 16" width="16" height="16"><path fill="currentColor" fill-rule="evenodd" d="m4.22 12.53.53.53L5.81 12l-.53-.53L1.81 8l3.47-3.47.53-.53-1.06-1.06-.53.53L.4 7.29a1 1 0 0 0 0 1.42zm7.56 0-.53.53L10.19 12l.53-.53L14.19 8l-3.47-3.47-.53-.53 1.06-1.06.53.53 3.82 3.82a1 1 0 0 1 0 1.42z" clip-rule="evenodd"></path></svg><span class="vw-row__label">sendEmail</span></div><span class="vw-row__ms">155ms</span></div>
+ </div>
+ <div class="vw-chart">
+ <!-- positions are fractions of the 925 ms run, as on vercel.com; the bar boxes keep its inline styles -->
+ <div class="vw-chart__inner">
+ <div class="vw-grid" style="left:24.864864864864867%"></div>
+ <div class="vw-grid" style="left:49.72972972972973%"></div>
+ <div class="vw-grid" style="left:74.5945945945946%"></div>
+ <div>
+ <div class="vw-bar" data-start="0" data-duration="925" style="left:0;top:8px;width:100%"><div class="vw-bar__track"><div class="vw-bar__fill"><div class="vw-badge vw-badge--blue"><div class="vw-badge__ms">0ms</div></div></div></div></div>
+ </div>
+ <div>
+ <div class="vw-link vw-link--h" style="left:0%;top:59.5px"></div><div class="vw-link vw-link--v" style="left:0%;top:52px"></div>
+ <div class="vw-bar" data-start="0" data-duration="230" style="left:calc(0% + 14px);top:48px;width:max(12px, calc(24.864864864864867% - 14px))"><div class="vw-bar__track"><div class="vw-bar__fill"><div class="vw-badge vw-badge--green"><div class="vw-badge__ms">0ms</div></div></div></div></div>
+ </div>
+ <div>
+ <div class="vw-link vw-link--h" style="left:24.864864864864867%;top:99.5px"></div><div class="vw-link vw-link--v" style="left:24.864864864864867%;top:92px"></div>
+ <div class="vw-bar" data-start="230" data-duration="155" style="left:calc(24.864864864864867% + 14px);top:88px;width:max(12px, calc(16.756756756756758% - 14px))"><div class="vw-bar__track"><div class="vw-bar__fill"><div class="vw-badge vw-badge--green"><div class="vw-badge__ms">0ms</div></div></div></div></div>
+ </div>
+ <div>
+ <div class="vw-link vw-link--h" style="left:41.62162162162162%;top:139.5px"></div><div class="vw-link vw-link--v" style="left:41.62162162162162%;top:132px"></div>
+ <div class="vw-bar" data-start="385" data-duration="230" style="left:calc(41.62162162162162% + 14px);top:128px;width:max(12px, calc(24.864864864864867% - 14px))"><div class="vw-bar__track"><div class="vw-bar__fill"><div class="vw-badge vw-badge--green"><div class="vw-badge__ms">0ms</div></div></div></div></div>
+ </div>
+ <div>
+ <div class="vw-link vw-link--h" style="left:66.48648648648648%;top:179.5px"></div><div class="vw-link vw-link--v" style="left:66.48648648648648%;top:172px"></div>
+ <div class="vw-bar" data-start="615" data-duration="155" style="left:calc(66.48648648648648% + 14px);top:168px;width:max(12px, calc(16.756756756756758% - 14px))"><div class="vw-bar__track"><div class="vw-bar__fill"><div class="vw-badge vw-badge--green"><div class="vw-badge__ms">0ms</div></div></div></div></div>
+ </div>
+ <div>
+ <div class="vw-link vw-link--h" style="left:83.24324324324324%;top:219.5px"></div><div class="vw-link vw-link--v" style="left:83.24324324324324%;top:212px"></div>
+ <div class="vw-bar" data-start="770" data-duration="155" style="left:calc(83.24324324324324% + 14px);top:208px;width:max(12px, calc(16.756756756756758% - 14px))"><div class="vw-bar__track"><div class="vw-bar__fill"><div class="vw-badge vw-badge--green"><div class="vw-badge__ms">0ms</div></div></div></div></div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="vw-fade" aria-hidden="true"></div>
+ </div>
+ </div>
+ </div>
+ </main>
+</body>
+</html>
diff --git a/site/public/examples/vercel-workflow/src/dashboard.css b/site/public/examples/vercel-workflow/src/dashboard.css
new file mode 100644
index 0000000..9416986
--- /dev/null
+++ b/site/public/examples/vercel-workflow/src/dashboard.css
@@ -0,0 +1,352 @@
+/* The run inspector panel of vercel.com/workflow. Sizes, colours and type are the computed values on vercel.com
+ at a 1440 px wide window; the breakpoints are its container queries (md 601 px, lg 961 px of page width). */
+
+@font-face {
+ font-family: "Geist";
+ src: url(../assets/fonts/GeistSans-Variable.woff2) format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+}
+@font-face {
+ font-family: "Geist Mono";
+ src: url(../assets/fonts/GeistMono-Variable.woff2) format("woff2");
+ font-weight: 100 900;
+ font-style: normal;
+ font-display: block;
+}
+
+:root {
+ --bg-100: #fff;
+ --bg-200: #fafafa;
+ --gray-100: #f2f2f2;
+ --gray-500: #c9c9c9;
+ --gray-700: #8f8f8f;
+ --gray-800: #7d7d7d;
+ --gray-900: #4d4d4d;
+ --gray-1000: #171717;
+ --gray-a200: rgb(0 0 0 / 0.08);
+ --gray-a300: rgb(0 0 0 / 0.1);
+ --gray-a400: rgb(0 0 0 / 0.08);
+ --blue-200: #ebf5ff;
+ --blue-700: #0072f5;
+ --green-100: #effbef;
+ --green-600: #6cda75;
+ --green-900: #297a3a;
+ --warning: #f5a623;
+ --cyan: #50e3c2;
+ --sans: "Geist", "Geist Fallback", Arial, sans-serif;
+ --mono: "Geist Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace;
+}
+
+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; }
+
+html {
+ font-family: var(--sans);
+ font-size: 16px;
+ line-height: 24px;
+ color: var(--gray-1000);
+ background: var(--bg-200);
+ font-feature-settings: "calt" 0, "rlig", "ss11";
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ text-rendering: optimizeLegibility;
+ text-size-adjust: 100%;
+}
+body { padding: 120px 0; }
+[data-pushdown] body { padding: 1800px 0 900px; }
+svg { display: block; flex-shrink: 0; overflow: hidden; vertical-align: middle; shape-rendering: crispEdges; }
+svg path { shape-rendering: geometricPrecision; } /* both as vercel.com sets them */
+
+/* the page column: 1400 px + 24 px margins, the container the breakpoints measure */
+.vw-page { max-width: 1448px; margin: 0 auto; padding: 0 24px; container-type: inline-size; }
+/* vercel.com renders the section and the panel lazily (content-visibility: auto, as its <Defer> does). Besides
+ skipping off-screen work, that clips the glow and the fade to the panel's box, and it is why the run starts
+ a frame after the panel scrolls in: the observers see the bars on the frame after the panel is rendered. */
+.vw-frame { padding: 0 1px; content-visibility: auto; contain-intrinsic-height: auto 540px; }
+.vw-defer { content-visibility: auto; contain-intrinsic-height: auto 520px; }
+.vw-wrap { position: relative; padding: 1px; }
+
+.vw-glow {
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: -2%;
+ height: 52%;
+ z-index: -1;
+ background: radial-gradient(ellipse at center, var(--gray-100) 0%, transparent 70%);
+}
+.vw-fade {
+ position: absolute;
+ bottom: 0;
+ left: -1px;
+ right: -1px;
+ height: 20%;
+ pointer-events: none;
+ background: linear-gradient(rgb(250 250 250 / 0), var(--bg-200));
+}
+
+.vw-panel {
+ position: relative;
+ display: flex;
+ align-items: stretch;
+ overflow: hidden;
+ background: var(--bg-200);
+ border-radius: 16px 16px 0 0;
+ box-shadow: 0 1px 0 0 var(--bg-200), 0 0 0 1px var(--gray-a400);
+}
+
+/* ---------- sidebar ---------- */
+
+.vw-side {
+ position: relative;
+ display: none;
+ flex-shrink: 0;
+ width: 256px;
+ height: 536px;
+ overflow: hidden;
+ background: var(--bg-200);
+ border-right: 1px solid var(--gray-a400);
+}
+@container (min-width: 961px) { .vw-side { display: block; } }
+
+.vw-side__logo {
+ position: absolute;
+ left: 18px;
+ top: 18px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border-radius: calc(infinity * 1px);
+ background: var(--gray-1000);
+}
+.vw-tri {
+ display: block;
+ width: 0;
+ height: 0;
+ margin-top: -2px;
+ border-left: 4px solid transparent;
+ border-right: 4px solid transparent;
+ border-bottom: 7px solid var(--bg-100);
+}
+.vw-tri--lg { border-left-width: 4.5px; border-right-width: 4.5px; border-bottom-width: 8px; }
+
+.vw-side__team { position: absolute; left: 48.28px; top: 18px; font-size: 14px; line-height: 20px; font-weight: 500; }
+.vw-side__plan {
+ position: absolute;
+ left: 94px;
+ top: 18px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 20px;
+ border-radius: calc(infinity * 1px);
+ background: var(--blue-200);
+ color: var(--blue-700);
+ font-size: 12px;
+ line-height: 16px;
+ font-weight: 500;
+}
+.vw-side__switch { position: absolute; right: 20px; top: 20px; color: var(--gray-1000); }
+
+.vw-find {
+ position: absolute;
+ left: 8px;
+ top: 56px;
+ z-index: 10;
+ width: 240px;
+ height: 40px;
+ border-radius: 6px;
+ background: var(--bg-100);
+ box-shadow: 0 0 0 1px var(--gray-a400);
+}
+.vw-find__icon { position: absolute; left: 12px; top: 12px; color: var(--gray-700); }
+.vw-find__text { position: absolute; left: 41.288px; top: 10px; font-size: 14px; line-height: 20px; color: var(--gray-700); }
+.vw-find__key {
+ position: absolute;
+ right: 9px;
+ top: 9px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border: 1px solid var(--gray-a400);
+ border-radius: 6px;
+ background: var(--bg-100);
+ color: var(--gray-900);
+ font-size: 12px;
+ line-height: 16px;
+ font-weight: 500;
+}
+
+.vw-nav {
+ position: absolute;
+ left: 8px;
+ display: flex;
+ align-items: center;
+ width: 240px;
+ height: 40px;
+ padding: 0 12px;
+ border-radius: 6px;
+}
+.vw-nav--on { background: var(--gray-a200); }
+.vw-nav__icon { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 16px; height: 16px; color: var(--gray-900); }
+.vw-nav--on .vw-nav__icon { color: var(--gray-800); }
+.vw-nav__label { margin-left: 13.288px; font-size: 14px; line-height: 20px; }
+.vw-nav__more { margin-left: auto; } /* text-gray-900 on vercel.com, overridden by its inline color: currentColor */
+
+.vw-side__rule { position: absolute; left: 20px; top: 401px; width: 216px; height: 1px; background: var(--gray-a400); }
+.vw-side__fade {
+ position: absolute;
+ left: 8px;
+ bottom: 8px;
+ width: 240px;
+ height: 8px;
+ pointer-events: none;
+ background: linear-gradient(rgb(250 250 250 / 0), var(--bg-200));
+}
+
+/* ---------- top bar ---------- */
+
+.vw-main { display: flex; flex: 1 1 0%; flex-direction: column; min-width: 0; }
+
+.vw-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 16px;
+ border-bottom: 1px solid var(--gray-a400);
+}
+.vw-top__project { display: flex; align-items: center; height: 32px; }
+.vw-top__logo { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 32px; height: 32px; }
+.vw-top__mark { display: flex; align-items: center; justify-content: center; width: 20px; height: 20px; border-radius: calc(infinity * 1px); background: var(--gray-1000); }
+.vw-top__name { margin-left: 4.588px; font-size: 14px; line-height: 20px; font-weight: 500; }
+.vw-top__switch { margin-left: 6px; } /* same */
+.vw-top__title { display: none; font-size: 14px; line-height: 20px; font-weight: 500; }
+@container (min-width: 601px) { .vw-top__title { display: inline; } }
+.vw-top__ask { display: flex; align-items: center; width: 117px; height: 32px; }
+.vw-dots { position: relative; flex-shrink: 0; width: 32px; height: 32px; }
+.vw-dots > span { position: absolute; width: 2.5px; height: 2.5px; border-radius: calc(infinity * 1px); background: currentColor; }
+.vw-top__ask-label { margin-left: 2.28px; font-size: 14px; line-height: 20px; font-weight: 500; }
+
+/* ---------- run ---------- */
+
+.vw-body { flex: 1 1 0%; }
+.vw-run { position: relative; display: flex; flex-direction: column; height: 100%; overflow: hidden; background: var(--bg-100); }
+
+.vw-head {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ flex-shrink: 0;
+ gap: 12px;
+ padding: 16px 20px;
+ background: var(--bg-200);
+}
+.vw-head__line { display: flex; align-items: center; gap: 8px; width: 100%; overflow: hidden; }
+.vw-head__name { flex-shrink: 0; font-size: 16px; line-height: 20px; font-weight: 500; }
+.vw-head__id { display: flex; align-items: center; gap: 4px; min-width: 0; overflow: hidden; }
+/* text-label-16-mono has no rule on vercel.com, so the run id is set in the page's 16 px sans */
+.vw-head__run { display: none; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-weight: 500; color: var(--gray-900); }
+@container (min-width: 601px) { .vw-head__run { display: inline; } }
+.vw-head__copy { color: var(--gray-900); }
+.vw-head__rule { flex-shrink: 0; width: 1px; height: 16px; background: var(--gray-a400); }
+.vw-head__fill { flex: 1 1 0%; min-width: 1px; height: 1px; }
+
+.vw-status { display: flex; align-items: center; flex-shrink: 0; gap: 8px; overflow: hidden; }
+.vw-status__dot {
+ flex: none;
+ width: 8px;
+ height: 8px;
+ border-radius: calc(infinity * 1px);
+ opacity: 0;
+ background: var(--warning);
+ transition: background-color 150ms cubic-bezier(0.4, 0, 0.2, 1), opacity 150ms cubic-bezier(0.4, 0, 0.2, 1);
+}
+.vw-status:not([data-status="idle"]) .vw-status__dot { opacity: 1; }
+.vw-status[data-status="completed"] .vw-status__dot { background: var(--cyan); }
+.vw-status__label { overflow: hidden; font-size: 16px; line-height: 20px; font-weight: 500; }
+.vw-status[data-status="idle"] .vw-status__text { opacity: 0; }
+@media (prefers-reduced-motion: no-preference) {
+ .vw-status:not([data-status="idle"]) .vw-status__text { animation: vw-fade-slide-in 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
+}
+@keyframes vw-fade-slide-in {
+ 0% { opacity: 0; transform: translateY(-8px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.vw-facts { display: flex; align-items: flex-start; gap: 32px; overflow: hidden; white-space: nowrap; }
+.vw-fact { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
+.vw-fact__k, .vw-fact__v { font-size: 14px; line-height: 20px; }
+.vw-fact__k { color: var(--gray-900); }
+
+/* ---------- trace ---------- */
+
+.vw-trace { display: flex; flex: 1 1 0%; flex-direction: column; min-height: 0; border-top: 1px solid var(--gray-a400); background: var(--bg-100); }
+.vw-trace__head { display: flex; flex-shrink: 0; height: 40px; border-bottom: 1px solid var(--gray-a400); background: var(--bg-100); }
+.vw-trace__body { display: flex; flex: 1 1 0%; align-items: flex-start; min-height: 0; overflow: hidden; background: var(--bg-100); }
+
+.vw-search, .vw-rows { flex-shrink: 0; width: 180px; overflow: hidden; }
+@container (min-width: 601px) { .vw-search, .vw-rows { width: 220px; } }
+@container (min-width: 961px) { .vw-search, .vw-rows { width: 260px; } }
+.vw-search { display: flex; align-items: center; gap: 6px; height: 100%; padding: 0 8px 0 16px; }
+.vw-search__icon { color: var(--gray-700); }
+.vw-search__text { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 14px; line-height: 20px; color: var(--gray-700); }
+
+.vw-axis { position: relative; flex: 1 1 0%; min-width: 0; height: 100%; border-left: 1px solid var(--gray-a400); }
+.vw-axis__inner { position: absolute; left: 15px; right: 15px; top: 0; height: 100%; }
+.vw-tick { position: absolute; top: 22px; translate: -50% 0; font-family: var(--mono); font-size: 12px; line-height: 16px; color: var(--gray-900); }
+.vw-tick--start { left: 0; translate: none; }
+.vw-tick--end { right: 0; translate: none; display: none; }
+@container (min-width: 601px) { .vw-tick--end { display: inline; } }
+
+.vw-rows { display: flex; flex-direction: column; height: 100%; background: var(--bg-100); }
+.vw-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-shrink: 0;
+ gap: 8px;
+ height: 40px;
+ padding: 0 8px 0 16px;
+ overflow: hidden;
+ border-bottom: 1px solid var(--gray-a400);
+}
+.vw-row__name { display: flex; align-items: center; gap: 8px; min-width: 0; overflow: hidden; }
+.vw-row__icon { color: var(--green-900); }
+.vw-row__icon--run { color: var(--blue-700); }
+.vw-row__label { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-family: var(--mono); font-size: 13px; line-height: 20px; }
+.vw-row__ms { display: none; flex-shrink: 0; font-size: 14px; line-height: 20px; color: var(--gray-900); }
+@container (min-width: 601px) { .vw-row__ms { display: inline; } }
+
+.vw-chart { position: relative; flex: 1 1 0%; min-width: 0; height: 100%; overflow: hidden; border-left: 1px solid var(--gray-a400); background: var(--bg-100); }
+.vw-chart__inner { position: absolute; left: 15px; right: 15px; top: 0; bottom: 0; }
+.vw-grid { position: absolute; top: 0; width: 1px; height: 100%; background: var(--gray-a300); }
+.vw-link { position: absolute; background: var(--gray-500); }
+.vw-link--h { width: 14px; height: 1px; }
+.vw-link--v { width: 1px; height: 16px; }
+
+/* a span: the slot (inline left/top/width), its fill that grows from 0 to 100 % of the slot, the badge inside */
+.vw-bar { position: absolute; height: 24px; }
+.vw-bar__track { position: relative; width: 100%; height: 100%; }
+.vw-bar__fill { width: 0; height: 100%; overflow: hidden; opacity: 0; }
+.vw-badge {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ height: 100%;
+ padding: 0 5px;
+ border: 1px solid;
+ border-radius: 6px;
+ font-family: var(--mono);
+ font-size: 13px;
+ line-height: 20px;
+}
+@container (min-width: 961px) { .vw-badge { border-radius: 8px; } }
+.vw-badge--blue { background: var(--blue-200); border-color: var(--blue-700); color: var(--gray-1000); }
+.vw-badge--green { background: var(--green-100); border-color: var(--green-600); color: var(--green-900); }
diff --git a/site/public/examples/vercel-workflow/src/run.js b/site/public/examples/vercel-workflow/src/run.js
new file mode 100644
index 0000000..5936082
--- /dev/null
+++ b/site/public/examples/vercel-workflow/src/run.js
@@ -0,0 +1,324 @@
+// The run of order-workflow, played the way vercel.com plays it.
+//
+// Every span bar has its own clock. It only advances while at least 35 % of the bar is on screen, one animation
+// frame at a time (the first frame counts 16.67 ms, no frame more than 40 ms), so a bar that is scrolled away
+// pauses and picks up where it left off. A span starts when its clock passes `start`, and grows linearly over
+// its duration; the whole 925 ms run is played over 2000 ms. The workflow bar drives the status: Running when it
+// starts, Completed when it ends. The Duration counts 0 → 925 linearly over 2000 ms from the frame after the start.
+//
+// The timing code is a port of what vercel.com runs: a shared requestAnimationFrame clock, tickers that drop to
+// 30 fps after three slow frames or while the window is unfocused, IntersectionObservers shared per option set,
+// and status changes applied in a task after the frame (as a React state update is).
+
+const RUN_MS = 925; // the run, as the trace shows it
+const PLAY_MS = 2000; // how long it takes on screen
+const IN_VIEW = 0.35; // share of a bar that has to be visible for its clock to run
+
+const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
+const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
+
+// ---------- a task after the current one, as React's scheduler runs a state update ----------
+
+const channel = new MessageChannel();
+const tasks = [];
+channel.port1.onmessage = () => tasks.splice(0).forEach((fn) => fn());
+function defer(fn) {
+ tasks.push(fn);
+ if (tasks.length === 1) channel.port2.postMessage(0);
+}
+
+// ---------- shared animation-frame clock: one rAF, every ticker gets the same timestamp ----------
+
+const clock = { raf: null, frame: 0, time: 0, ticks: new Map() };
+function onFrame(now) {
+ clock.time = now;
+ clock.frame++;
+ clock.raf = clock.ticks.size ? requestAnimationFrame(onFrame) : null;
+ // a tick added during frame N first runs on frame N + 1
+ clock.ticks.forEach((added, fn) => added < clock.frame && fn(clock.time));
+ idle();
+}
+function idle() {
+ if (clock.ticks.size === 0 && clock.raf !== null) {
+ cancelAnimationFrame(clock.raf);
+ clock.raf = null;
+ }
+}
+function addTick(fn) {
+ clock.ticks.set(fn, clock.frame);
+ if (clock.raf === null) clock.raf = requestAnimationFrame(onFrame);
+}
+function removeTick(fn) {
+ clock.ticks.delete(fn);
+ idle();
+}
+
+// ---------- IntersectionObservers, one per option set, shared by every element observed with it ----------
+
+const observers = new Map();
+function observe(el, options, cb) {
+ const key = `${options.rootMargin}|${[].concat(options.threshold).join(",")}`;
+ let entry = observers.get(key);
+ if (!entry) {
+ const callbacks = new Map();
+ const io = new IntersectionObserver((list) => list.forEach((e) => callbacks.get(e.target)?.forEach((f) => f(e))), options);
+ entry = { io, callbacks };
+ observers.set(key, entry);
+ }
+ let set = entry.callbacks.get(el);
+ if (!set) entry.callbacks.set(el, (set = new Set()));
+ set.add(cb);
+ entry.io.observe(el);
+ return () => {
+ set.delete(cb);
+ if (set.size === 0) {
+ entry.io.unobserve(el);
+ entry.callbacks.delete(el);
+ }
+ };
+}
+const STEPS_20 = Array.from({ length: 21 }, (_, i) => i / 20);
+
+// ---------- ticker: per-frame delta, optional fps cap ----------
+
+function createTicker(onTick, fps) {
+ let interval = fps ? 1000 / fps : 0;
+ let maxDelta = interval + 40;
+ let last = -1;
+ let next = 0;
+ let elapsed = 0;
+ let count = 0;
+ let state = "idle";
+ const info = { time: 0, delta: 0, elapsed: 0, frame: 0 };
+ function tick(now) {
+ if (now < next) return;
+ const first = last < 0;
+ const delta = first ? interval || 16.67 : now - last;
+ last = now;
+ if (interval > 0) {
+ if (first) next = now + interval;
+ else {
+ const due = next + interval;
+ const late = now - due;
+ next = late < interval ? due : due + Math.floor(late / interval) * interval;
+ }
+ }
+ info.time = now;
+ info.delta = delta > maxDelta ? maxDelta : delta;
+ elapsed += info.delta;
+ info.elapsed = elapsed;
+ info.frame = ++count;
+ onTick(info);
+ }
+ return {
+ get state() {
+ return state;
+ },
+ start() {
+ state = "running";
+ last = -1;
+ next = 0;
+ elapsed = 0;
+ count = 0;
+ addTick(tick);
+ },
+ pause() {
+ if (state !== "running") return;
+ state = "paused";
+ removeTick(tick);
+ },
+ resume() {
+ if (state !== "paused") return;
+ state = "running";
+ last = -1;
+ next = 0;
+ addTick(tick);
+ },
+ stop() {
+ state = "stopped";
+ removeTick(tick);
+ },
+ setFps(f) {
+ interval = f ? 1000 / f : 0;
+ maxDelta = interval + 40;
+ next = last < 0 ? 0 : last + interval;
+ },
+ };
+}
+
+// ---------- loop: a ticker that runs while its element intersects the viewport and the tab is visible ----------
+
+function createLoop(el, onTick) {
+ let degraded = false;
+ let unfocused = false;
+ let slow = 0;
+ let frameMs = 1000 / 60;
+ let visible = false;
+ let stopped = false;
+ let ticker = null;
+ const fps = () => (degraded ? 30 : undefined);
+ function quality() {
+ const next = unfocused || slow >= 3;
+ if (next === degraded) return;
+ degraded = next;
+ frameMs = 1000 / (fps() ?? 60);
+ ticker?.setFps(fps());
+ }
+ function frame(info) {
+ if (info.delta <= 1.5 * frameMs) slow = 0;
+ else if (++slow >= 3) quality();
+ onTick(info);
+ }
+ function update() {
+ if (stopped) return;
+ if (visible && !document.hidden) {
+ if (!ticker) {
+ ticker = createTicker(frame, fps());
+ ticker.start();
+ } else ticker.resume();
+ } else ticker?.pause();
+ }
+ const focus = () => {
+ unfocused = !document.hasFocus();
+ quality();
+ };
+ addEventListener("focus", focus);
+ addEventListener("blur", focus);
+ document.addEventListener("visibilitychange", update);
+ const unobserve = observe(el, { rootMargin: "0px", threshold: 0 }, (e) => {
+ visible = e.isIntersecting;
+ update();
+ });
+ return function stop() {
+ if (stopped) return;
+ stopped = true;
+ ticker?.stop();
+ unobserve();
+ removeEventListener("focus", focus);
+ removeEventListener("blur", focus);
+ document.removeEventListener("visibilitychange", update);
+ };
+}
+
+// ---------- a span bar ----------
+
+function playBar(el, { delay, duration, target, onStart, onFinish }) {
+ const watched = el.querySelector(".vw-bar__track");
+ const fill = el.querySelector(".vw-bar__fill");
+ const label = el.querySelector(".vw-badge__ms");
+ let clock = 0;
+ let started = false;
+ let done = false;
+ let shown = "";
+ let inView = false;
+ let stopLoop = null;
+
+ function render(p) {
+ fill.style.width = `${p * 100}%`;
+ const text = `${Math.round(target * p)}ms`;
+ if (text !== shown) label.textContent = shown = text;
+ }
+ function start() {
+ if (started) return;
+ started = true;
+ fill.style.opacity = "1";
+ if (onStart) queueMicrotask(onStart);
+ }
+ function finish() {
+ if (done) return;
+ render(1);
+ done = true;
+ if (onFinish) queueMicrotask(onFinish);
+ sync();
+ }
+ function sync() {
+ const run = inView && !reduced && !done;
+ if (run && !stopLoop)
+ stopLoop = createLoop(watched, ({ delta }) => {
+ if (done) return;
+ clock += delta;
+ const t = clock - delay;
+ if (t < 0) return;
+ const p = clamp01(t / duration);
+ render(p);
+ start();
+ if (p >= 1) finish();
+ });
+ else if (!run && stopLoop) {
+ stopLoop();
+ stopLoop = null;
+ }
+ }
+
+ fill.style.opacity = "0";
+ render(reduced ? 1 : 0);
+ if (reduced) {
+ start();
+ finish();
+ return;
+ }
+ let ratio = 0;
+ observe(watched, { rootMargin: "0px", threshold: STEPS_20 }, (e) => {
+ if (e.intersectionRatio === ratio) return;
+ ratio = e.intersectionRatio;
+ inView = ratio >= IN_VIEW;
+ sync();
+ });
+}
+
+// ---------- the run header: status and duration ----------
+
+const status = document.querySelector(".vw-status");
+// the value is two text nodes, "0" and "ms", as React renders it on vercel.com; only the number changes
+const durationNumber = document.querySelector("[data-duration]").firstChild;
+let state = "idle";
+let tweenRaf = 0;
+
+function setStatus(next) {
+ if (next === state || (state === "completed" && next === "running")) return;
+ state = next;
+ status.dataset.status = next;
+ // a new element, so the fade-slide-in plays again
+ const old = status.querySelector(".vw-status__text");
+ const text = document.createElement("span");
+ text.className = "vw-status__text";
+ text.textContent = next === "completed" ? "Completed" : "Running";
+ old.replaceWith(text);
+ if (next === "running") countUp();
+ else {
+ cancelAnimationFrame(tweenRaf);
+ durationNumber.data = String(RUN_MS);
+ }
+}
+
+// Duration: 0 → 925 linearly over 2000 ms, timed by animation frames from the first frame after the start
+function countUp() {
+ let t0 = null;
+ let value = 0;
+ const step = (now) => {
+ if (t0 === null) t0 = now;
+ const p = clamp01((now - t0) / PLAY_MS);
+ const v = p === 1 ? RUN_MS : RUN_MS * p;
+ if (v !== value) {
+ value = v;
+ defer(() => state === "running" && (durationNumber.data = String(Math.round(value))));
+ }
+ if (p < 1) tweenRaf = requestAnimationFrame(step);
+ };
+ tweenRaf = requestAnimationFrame(step);
+}
+
+// ---------- the trace ----------
+
+for (const el of document.querySelectorAll(".vw-bar")) {
+ const start = Number(el.dataset.start);
+ const span = Number(el.dataset.duration);
+ const isRun = span === RUN_MS && start === 0 && el.querySelector(".vw-badge--blue");
+ playBar(el, {
+ delay: (PLAY_MS * start) / RUN_MS,
+ duration: (PLAY_MS * span) / RUN_MS,
+ target: span,
+ onStart: isRun ? () => defer(() => setStatus("running")) : undefined,
+ onFinish: isRun ? () => defer(() => setStatus("completed")) : undefined,
+ });
+}
diff --git a/site/public/media/nextjs-optimizations/poster.webp b/site/public/media/nextjs-optimizations/poster.webp
new file mode 100644
index 0000000..8ef94b0
Binary files /dev/null and b/site/public/media/nextjs-optimizations/poster.webp differ
diff --git a/site/public/media/nextjs-rsc/poster.webp b/site/public/media/nextjs-rsc/poster.webp
new file mode 100644
index 0000000..c116291
Binary files /dev/null and b/site/public/media/nextjs-rsc/poster.webp differ
diff --git a/site/public/media/nextjs-streaming/poster.webp b/site/public/media/nextjs-streaming/poster.webp
new file mode 100644
index 0000000..578935a
Binary files /dev/null and b/site/public/media/nextjs-streaming/poster.webp differ
diff --git a/site/public/media/turborepo-gauge/poster.webp b/site/public/media/turborepo-gauge/poster.webp
new file mode 100644
index 0000000..0b61a1b
Binary files /dev/null and b/site/public/media/turborepo-gauge/poster.webp differ
diff --git a/site/public/media/vercel-fluid/compare.mp4 b/site/public/media/vercel-fluid/compare.mp4
new file mode 100644
index 0000000..a843eb3
Binary files /dev/null and b/site/public/media/vercel-fluid/compare.mp4 differ
diff --git a/site/public/media/vercel-fluid/poster.webp b/site/public/media/vercel-fluid/poster.webp
new file mode 100644
index 0000000..c7a389d
Binary files /dev/null and b/site/public/media/vercel-fluid/poster.webp differ
diff --git a/site/public/media/vercel-hero/poster.webp b/site/public/media/vercel-hero/poster.webp
new file mode 100644
index 0000000..f2dbee8
Binary files /dev/null and b/site/public/media/vercel-hero/poster.webp differ
diff --git a/site/public/media/vercel-previews/poster.webp b/site/public/media/vercel-previews/poster.webp
new file mode 100644
index 0000000..2a558d1
Binary files /dev/null and b/site/public/media/vercel-previews/poster.webp differ
diff --git a/site/public/media/vercel-workflow/compare.mp4 b/site/public/media/vercel-workflow/compare.mp4
new file mode 100644
index 0000000..309bc1e
Binary files /dev/null and b/site/public/media/vercel-workflow/compare.mp4 differ
diff --git a/site/public/media/vercel-workflow/poster.webp b/site/public/media/vercel-workflow/poster.webp
new file mode 100644
index 0000000..2407122
Binary files /dev/null and b/site/public/media/vercel-workflow/poster.webp differ
diff --git a/site/scripts/record-media.ts b/site/scripts/record-media.ts
index 7057b08..cd4f894 100644
--- a/site/scripts/record-media.ts
+++ b/site/scripts/record-media.ts
@@ -10,7 +10,7 @@
// Needs Playwright's Chromium (bunx playwright install chromium), ffmpeg, cwebp and webpmux on PATH.
import { chromium, type Browser } from "playwright";
import { spawnSync } from "node:child_process";
-import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parseArgs } from "node:util";
@@ -20,12 +20,36 @@ type Clip = {
reference: string;
clone: string; // path on the local site
select: string[]; // what to film: the crop is these elements' union plus PAD, on both pages
- trigger: "scroll" | "hover"; // scroll: the entrance as they scroll into view; hover: HOVER_PATH over the first
+ trigger: "scroll" | "hover" | "drop"; // scroll: the entrance as they scroll into view; hover: HOVER_PATH over the first; drop: DROP_POINTER_PATH, then a file dragged over the first (DROP_PATH)
+ path?: [number, number, number][]; // hover: this pointer path instead of HOVER_PATH (same format)
+ ms?: number; // hover: how long to film, instead of HOVER_MS
+ still?: boolean; // the page rests between pointer moves: the speck keeps repainting while filming, so frames come at 60 fps
pin?: number; // Math.random returns this from just before the trigger, so random picks come out the same on both pages
sync?: boolean; // the motion is a loop each page starts when its scene is ready, not on the trigger: line the takes up by their frames
};
const bento = (card: string) => `.modular-solutions-bento__card-${card}`;
+// In from the left over each group of the Vercel Toolbar in turn (comments, feature flags, CMS drafts,
+// collaborators, accessibility, layout shift, share), then out to the right. Fractions of the toolbar's box.
+const VERCEL_TOOLBAR_PATH: [number, number, number][] = [
+ [0, -0.25, 0.5],
+ [300, -0.25, 0.5],
+ [650, 0.115, 0.5],
+ [1200, 0.115, 0.5],
+ [1450, 0.285, 0.5],
+ [2000, 0.285, 0.5],
+ [2200, 0.379, 0.5],
+ [2750, 0.379, 0.5],
+ [3050, 0.562, 0.5],
+ [3600, 0.562, 0.5],
+ [3900, 0.744, 0.5],
+ [4450, 0.744, 0.5],
+ [4650, 0.838, 0.5],
+ [5200, 0.838, 0.5],
+ [5400, 0.932, 0.5],
+ [5950, 0.932, 0.5],
+ [6400, 1.25, 0.5],
+];
const CLIPS: Clip[] = [
{ slug: "stripe-bento", reference: "https://stripe.com/", clone: "/examples/stripe-bento/", select: ["agentic-commerce", "issuing", "crypto"].map(bento), trigger: "scroll" },
{ slug: "stripe-agentic-commerce", reference: "https://stripe.com/", clone: "/examples/stripe-bento/", select: [bento("agentic-commerce")], trigger: "hover" },
@@ -34,8 +58,20 @@ const CLIPS: Clip[] = [
{ slug: "workos-atlas", reference: "https://workos.com/atlas", clone: "/examples/workos-atlas/", select: ['[aria-label^="Atlas reaching out"]'], trigger: "scroll", pin: 0.37 },
{ slug: "liveblocks-comments", reference: "https://liveblocks.io/comments", clone: "/examples/liveblocks-comments/", select: ['.select-none[class*="aspect-1208/770"]'], trigger: "scroll", sync: true },
{ slug: "resend-cube", reference: "https://resend.com/", clone: "/examples/resend-cube/", select: [".animate-webgl-scale-in-fade"], trigger: "scroll", sync: true },
+ // the toolbar comes first: the pointer path is in its box; the outermost tags set the crop
+ { slug: "vercel-previews", reference: "https://vercel.com/products/previews", clone: "/examples/vercel-previews/", select: ['[aria-label^="This element represents the full suite"]', '[data-side="top"] > [data-color="blue"]', '[data-side="top"] > [data-color="purple"]', '[data-side="top"] > [data-color="pink"]', '[data-side="bottom"] > [data-color="amber"]'], trigger: "hover", path: VERCEL_TOOLBAR_PATH, ms: 7400, still: true },
// the preview is an iframe on the original; one selector list finds it there and the copy's canvas here
{ slug: "reactbits-fading-stars", reference: "https://pro.reactbits.dev/docs/components/fading-stars?browse=components", clone: "/examples/reactbits-fading-stars/", select: ['iframe[title="Preview"], .fading-stars'], trigger: "hover" },
+ { slug: "vercel-hero", reference: "https://vercel.com/", clone: "/examples/vercel-hero/", select: ["[data-triangle-led-4-hero-canvas]"], trigger: "drop" },
+ // the sea runs from page load on both pages and never repeats; the same frame gives the same pixels, so sync lines the takes up
+ { slug: "vercel-fluid", reference: "https://vercel.com/fluid", clone: "/examples/vercel-fluid/", select: ["[data-ocean-hero] ~ div .grid-cols-12"], trigger: "scroll", sync: true },
+ // a run plays once on scroll-in; its first changes are too faint for contentAppears, so sync lines the takes up by their frames
+ { slug: "vercel-workflow", reference: "https://vercel.com/workflow", clone: "/examples/vercel-workflow/", select: ['[aria-label^="Vercel dashboard preview"]'], trigger: "scroll", sync: true, still: true },
+ { slug: "turborepo-gauge", reference: "https://turborepo.com/", clone: "/examples/turborepo-gauge/", select: ['svg[viewBox="0 0 480 340"]'], trigger: "hover", still: true },
+ // nextjs.org's cards: the first lights up under the pointer; the other two loop from scroll-in, too faintly for contentAppears
+ { slug: "nextjs-optimizations", reference: "https://nextjs.org/", clone: "/examples/nextjs-features/", select: ['a[href$="/getting-started/images"]'], trigger: "hover", still: true },
+ { slug: "nextjs-streaming", reference: "https://nextjs.org/", clone: "/examples/nextjs-features/", select: ['a[href$="/fetching-data#streaming"]'], trigger: "scroll", sync: true },
+ { slug: "nextjs-rsc", reference: "https://nextjs.org/", clone: "/examples/nextjs-features/", select: ['a[href$="/server-and-client-components"]'], trigger: "scroll", sync: true },
];
const { values: args } = parseArgs({
@@ -73,6 +109,29 @@ const HOVER_PATH: [number, number, number][] = [
[3350, 0.7, 0.7],
[3700, 1.12, 0.82],
];
+// The drop clip: the pointer passes close to the element first (beside the left edge of vercel.com's
+// triangle, over its top, beside its right corner, out below), then a file is dragged in from outside
+// the window: dragenter, dragover every 50 ms along DROP_PATH, dragleave at its end. Never dropped, so
+// vercel.com does not start a deploy. Fractions of the element's box and ms, as in HOVER_PATH.
+const DROP_POINTER_PATH: [number, number, number][] = [
+ [0, -0.04, 0.52],
+ [300, -0.04, 0.52],
+ [800, 0.37, 0.56],
+ [1500, 0.37, 0.56],
+ [2000, 0.5, 0.3],
+ [2600, 0.5, 0.3],
+ [3100, 0.66, 0.62],
+ [3600, 0.66, 0.62],
+ [4000, 0.62, 1.1],
+];
+const DROP_PATH: [number, number, number][] = [
+ [4300, 0.24, 0.82],
+ [5000, 0.44, 0.52],
+ [5700, 0.44, 0.52],
+ [6400, 0.6, 0.58],
+ [7300, 0.6, 0.58],
+];
+const DROP_MS = 8300;
// A visible pointer, so viewers can see what the hover clips react to. Drawn in the page, ignored by
// hit testing, identical on both sites.
@@ -81,7 +140,14 @@ const CURSOR = `addEventListener("DOMContentLoaded", () => {
el.innerHTML = '<svg width="22" height="28" viewBox="0 0 22 28" xmlns="http://www.w3.org/2000/svg"><path d="M2 2v20.5l5.4-5.2 3.6 8.4 3.5-1.5-3.6-8.3H18z" fill="#0a0a0a" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg>';
el.style.cssText = "position:fixed;left:0;top:0;z-index:2147483647;pointer-events:none;display:none;filter:drop-shadow(0 1px 2px rgb(0 0 0 / .3))";
document.documentElement.append(el);
- addEventListener("mousemove", (e) => { el.style.display = "block"; el.style.transform = "translate(" + (e.clientX - 2) + "px," + (e.clientY - 2) + "px)"; }, { capture: true, passive: true });
+ const move = (e) => { el.style.display = "block"; el.style.transform = "translate(" + (e.clientX - 2) + "px," + (e.clientY - 2) + "px)"; };
+ addEventListener("mousemove", move, { capture: true, passive: true });
+ // a dragged file: the pointer with a document under it, following dragover
+ const file = el.appendChild(document.createElement("div"));
+ file.innerHTML = '<svg width="22" height="28" viewBox="0 0 22 28" xmlns="http://www.w3.org/2000/svg"><path d="M1.5 1.5h12l7 7v18h-19z" fill="#fff" stroke="#8f8f8f" stroke-width="1.4" stroke-linejoin="round"/><path d="M13.5 1.5v7h7" fill="none" stroke="#8f8f8f" stroke-width="1.4" stroke-linejoin="round"/></svg>';
+ file.style.cssText = "position:absolute;left:12px;top:18px;display:none";
+ addEventListener("dragover", (e) => { file.style.display = "block"; move(e); }, { capture: true, passive: true });
+ addEventListener("dragleave", () => { file.style.display = "none"; el.style.display = "none"; }, { capture: true, passive: true });
});`;
// Example pages hold little more than the clone itself; pad them so it starts below the fold and
@@ -134,14 +200,17 @@ async function film(browser: Browser, clip: Clip, side: Side): Promise<Take> {
const right = Math.max(...boxes.map((b) => b.x + b.width));
const top = Math.min(...boxes.map((b) => b.y));
const bottom = Math.max(...boxes.map((b) => b.y + b.height));
- const crop = { x: left - PAD, y: TOP - PAD, width: right - left + 2 * PAD, height: bottom - top + 2 * PAD };
- const scrollY = top - TOP;
+ // An element that can't be scrolled to TOP (a hero less than TOP from the top of the page, like vercel.com's,
+ // or one near the bottom) stays where the page lets it be: the crop and the pointer follow the element.
+ const maxScroll = await page.evaluate(() => document.documentElement.scrollHeight - innerHeight);
+ const scrollY = Math.min(Math.max(0, maxScroll), Math.max(0, top - TOP));
+ const crop = { x: left - PAD, y: top - scrollY - PAD, width: right - left + 2 * PAD, height: bottom - top + 2 * PAD };
const scrollIn = () => page.evaluate((y) => window.scrollTo({ top: y, behavior: "instant" }), scrollY);
// Pinned after load: the pages' other code calls Math.random a different number of times, so a seed
// would not line the picks up.
if (clip.pin !== undefined) await page.evaluate((v) => (Math.random = () => v), clip.pin);
- if (clip.trigger === "hover") {
+ if (clip.trigger === "hover" || clip.trigger === "drop") {
await scrollIn();
await sleep(6000); // let the entrance finish
}
@@ -181,11 +250,11 @@ async function film(browser: Browser, clip: Clip, side: Side): Promise<Take> {
tick();
});
for (let i = 0; wide < 5; i++) {
- if (i === 20) throw new Error(`${clip.slug} ${side}: the window would not zoom (frame widths: ${seen.slice(-12).join(" ") || "none"})`);
+ if (i === 60) throw new Error(`${clip.slug} ${side}: the window would not zoom (frame widths: ${seen.slice(-12).join(" ") || "none"})`);
await zoom();
await sleep(250);
}
- await page.evaluate(() => document.getElementById("record-media-tick")?.remove());
+ if (!clip.still) await page.evaluate(() => document.getElementById("record-media-tick")?.remove());
recording = true;
await sleep(300);
@@ -201,23 +270,61 @@ async function film(browser: Browser, clip: Clip, side: Side): Promise<Take> {
// Mouse input lands in the zoomed window's coordinates, so CSS px are scaled up to match.
const box = boxes[0];
const at = (fx: number, fy: number) => ({ x: (box.x + box.width * fx) * SCALE, y: (box.y - scrollY + box.height * fy) * SCALE });
- const p0 = at(HOVER_PATH[0][1], HOVER_PATH[0][2]);
+ const glide = (path: [number, number, number][], t: number) => {
+ const i = path.findIndex(([when]) => when > t);
+ if (i <= 0) return null;
+ const [t0, x0, y0] = path[i - 1];
+ const [t1, x1, y1] = path[i];
+ const k = (t - t0) / (t1 - t0);
+ const e = k * k * (3 - 2 * k); // smoothstep: the pointer speeds up and settles like a hand
+ return [x0 + (x1 - x0) * e, y0 + (y1 - y0) * e];
+ };
+ // Drag events are dispatched in the page, in CSS px, with a File in their DataTransfer.
+ const drag = (type: string, fx: number, fy: number) =>
+ page.evaluate(
+ ({ type, x, y }) => {
+ const w = window as typeof window & { __recordMediaFile?: DataTransfer };
+ if (!w.__recordMediaFile) {
+ w.__recordMediaFile = new DataTransfer();
+ w.__recordMediaFile.items.add(new File(["x"], "site.zip", { type: "application/zip" }));
+ }
+ (document.elementFromPoint(x, y) ?? document.body).dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, composed: true, clientX: x, clientY: y, dataTransfer: w.__recordMediaFile }));
+ },
+ { type, x: box.x + box.width * fx, y: box.y - scrollY + box.height * fy },
+ );
+ const path = clip.trigger === "drop" ? DROP_POINTER_PATH : clip.path ?? HOVER_PATH;
+ const p0 = at(path[0][1], path[0][2]);
await page.mouse.move(p0.x, p0.y);
start = Date.now();
- ms = HOVER_MS;
+ ms = clip.trigger === "drop" ? DROP_MS : clip.ms ?? HOVER_MS;
+ let dragging: "before" | "on" | "done" = clip.trigger === "drop" ? "before" : "done";
+ let lastOver = -Infinity;
for (;;) {
const t = Date.now() - start;
- const i = HOVER_PATH.findIndex(([when]) => when > t);
- if (i < 0) break;
- const [t0, x0, y0] = HOVER_PATH[i - 1];
- const [t1, x1, y1] = HOVER_PATH[i];
- const k = (t - t0) / (t1 - t0);
- const e = k * k * (3 - 2 * k); // smoothstep: the pointer speeds up and settles like a hand
- const p = at(x0 + (x1 - x0) * e, y0 + (y1 - y0) * e);
- await page.mouse.move(p.x, p.y);
+ const p = glide(path, t);
+ if (p) {
+ const q = at(p[0], p[1]);
+ await page.mouse.move(q.x, q.y);
+ }
+ const [first, last] = [DROP_PATH[0], DROP_PATH.at(-1)!];
+ if (dragging === "before" && t >= first[0]) {
+ await drag("dragenter", first[1], first[2]);
+ dragging = "on";
+ }
+ if (dragging === "on") {
+ if (t >= last[0]) {
+ await drag("dragleave", last[1], last[2]);
+ dragging = "done";
+ } else if (t - lastOver >= 50) {
+ const q = glide(DROP_PATH, t) ?? [first[1], first[2]];
+ await drag("dragover", q[0], q[1]);
+ lastOver = t;
+ }
+ }
+ if (!p && dragging === "done") break;
await sleep(8);
}
- await sleep(HOVER_MS - (Date.now() - start) + 500);
+ await sleep(ms - (Date.now() - start) + 500);
}
await cdp.send("Page.stopScreencast");
await context.close();
@@ -374,7 +481,7 @@ for (const clip of CLIPS) {
takes[side] = { file, appear: clip.trigger === "scroll" && !clip.sync ? contentAppears(file) : 0 };
}
const lead = Math.min(ENTRANCE_LEAD_MS, ...SIDES.map((s) => takes[s].appear));
- const ms = clip.trigger === "scroll" ? ENTRANCE_MS : HOVER_MS;
+ const ms = clip.trigger === "scroll" ? ENTRANCE_MS : clip.trigger === "drop" ? DROP_MS : clip.ms ?? HOVER_MS;
for (const side of SIDES) masters[`${clip.slug}-${side}`] = { file: takes[side].file, from: takes[side].appear - lead };
if (clip.sync) {
// start the take that runs behind later, by as much as it runs behind
@@ -384,7 +491,15 @@ for (const clip of CLIPS) {
console.log(`${clip.slug}: the original's loop runs ${behind.toFixed(0)} ms behind the copy's`);
}
compareMp4(SIDES.map((side) => masters[`${clip.slug}-${side}`]), ms, join(out, "compare.mp4"));
- // At rest: the end of an entrance, the start of a hover.
+ // With --keep: the takes, lined up as in compare.mp4, for other uses (video/scripts/clips.ts --masters cuts
+ // the Vercel video's pairs from them), added to what earlier runs into the same folder kept.
+ if (args.keep) {
+ const file = join(WORK, "masters.json");
+ const kept = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
+ kept[clip.slug] = { ms, reference: masters[`${clip.slug}-reference`], clone: masters[`${clip.slug}-clone`] };
+ writeFileSync(file, JSON.stringify(kept, null, 2) + "\n");
+ }
+ // At rest: the end of an entrance, the start of a hover or a drop.
const cloneFrom = masters[`${clip.slug}-clone`].from;
poster(takes.clone.file, clip.trigger === "scroll" ? cloneFrom + ms - 100 : cloneFrom, join(out, "poster.webp"));
}
diff --git a/site/src/app/page.tsx b/site/src/app/page.tsx
index 9c9d390..b77e0ea 100644
--- a/site/src/app/page.tsx
+++ b/site/src/app/page.tsx
@@ -195,8 +195,8 @@ export default function Home() {
<Section id="examples" n={5} title="Examples">
<p>
- Hover a clerk.com card to play it, or on a phone just scroll to it. The copies use the free Geist font, so only the lettering differs. For the others, the original plays on the left or on top, and the copy next to it or
- below.
+ The copies that react to you run live in the page: hover them, or on a phone tap or scroll to them, and drag any file onto the vercel.com triangle. The clerk.com copies use the free Geist font, so only their lettering
+ differs. For the others, the original plays on the left or on top, and the copy next to it or below.
</p>
<nav className="strip" aria-label="Examples">
{examples.map((e) => (
@@ -214,8 +214,8 @@ export default function Home() {
</h3>
<Details e={e} />
</div>
- {e.show.kind === "video" && e.show.height > e.show.width ? (
- // wider than tall: the two takes are stacked
+ {e.show.kind === "video" && (e.show.stacked || e.show.height > e.show.width) ? (
+ // the two takes are stacked
<figure className="figure">
<CompareVideo src={media(e.slug, "compare.mp4")} width={e.show.width} height={e.show.height} label={`${e.title}: ${e.source.name} on top, the copy below`} />
<figcaption className="figure__caption">
@@ -233,10 +233,10 @@ export default function Home() {
</figure>
) : (
<figure className="figure">
- <LiveCard src={`${e.live}&embed`} width={e.show.width} height={e.show.height} label={`${e.title}, the copy, running live`} />
+ <LiveCard src={`${e.live}&embed`} width={e.show.width} height={e.show.height} background={e.show.background} label={`${e.title}, the copy, running live`} />
<figcaption className="figure__caption">
<span>
- the copy, <span className="on-hover">hover it</span>
+ the copy, <span className="on-hover">{e.show.try ?? "hover it"}</span>
<span className="on-touch">tap it</span> ·{" "}
<a href={e.live} target="_blank" rel="noreferrer">
open on its own ↗
@@ -257,8 +257,8 @@ export default function Home() {
<a href={REPO}>GitHub</a> · MIT licence · built with reanimate
</span>
<span>
- The examples recreate parts of stripe.com, workos.com, clerk.com, liveblocks.io, resend.com and pro.reactbits.dev as a study of the technique. Not affiliated with or endorsed by Stripe, WorkOS, Clerk, Liveblocks, Resend or React Bits. All trademarks belong
- to their owners.
+ The examples recreate parts of vercel.com, nextjs.org, turborepo.com, stripe.com, workos.com, clerk.com, liveblocks.io, resend.com and pro.reactbits.dev as a study of the technique. Not affiliated with or endorsed by
+ Vercel, Stripe, WorkOS, Clerk, Liveblocks, Resend or React Bits. All trademarks belong to their owners.
</span>
</footer>
</main>
diff --git a/site/src/components/LiveCard.tsx b/site/src/components/LiveCard.tsx
index a40facf..f5f175c 100644
--- a/site/src/components/LiveCard.tsx
+++ b/site/src/components/LiveCard.tsx
@@ -5,7 +5,7 @@ import { useEffect, useRef, useState } from "react";
// The clone itself, running in the page: hover it to play (touch screens play it while it's on screen).
// Shown at its real size, scaled down only when the column is narrower.
-export function LiveCard({ src, width, height, label }: { src: string; width: number; height: number; label: string }) {
+export function LiveCard({ src, width, height, label, background }: { src: string; width: number; height: number; label: string; background?: string }) {
const box = useRef<HTMLDivElement>(null);
const [scale, setScale] = useState(1);
@@ -18,7 +18,7 @@ export function LiveCard({ src, width, height, label }: { src: string; width: nu
}, [width]);
return (
- <div ref={box} className="livecard" style={{ height: height * scale }}>
+ <div ref={box} className="livecard" style={{ height: height * scale, background }}>
<iframe src={src} title={label} width={width} height={height} loading="lazy" style={{ transform: `scale(${scale})` }} />
</div>
);
diff --git a/site/src/examples.ts b/site/src/examples.ts
index 5dae8c6..ade4555 100644
--- a/site/src/examples.ts
+++ b/site/src/examples.ts
@@ -14,8 +14,11 @@ export type Example = {
/** Shown as a margin note next to `about`. */
note?: string;
/** What the page shows: "video", compare.mp4 at this size in CSS px (the file is 2x); or "live", the
- * clone itself in an iframe of this size (`live` with &embed). */
- show: { kind: "video" | "live"; width: number; height: number };
+ * clone itself in an iframe of this size (`live` with &embed). `stacked`: the two takes are one above the
+ * other (scripts/record-media.ts stacks recordings wider than tall); assumed when taller than wide.
+ * `background`: the live frame's colour around and behind the iframe (default: the clerk.com cards' dark).
+ * `try`: what to do with a live copy on a desktop, under it (default "hover it"; on a phone it says "tap it"). */
+ show: { kind: "video" | "live"; width: number; height: number; stacked?: boolean; background?: string; try?: string };
/** The clone running on its own. */
live: string;
/** What was measured, how, and the number. */
@@ -23,8 +26,128 @@ export type Example = {
};
const CLERK = { name: "clerk.com", url: "https://clerk.com/" };
+const NEXTJS = { name: "nextjs.org", url: "https://nextjs.org/" };
export const examples: Example[] = [
+ {
+ slug: "vercel-previews",
+ title: "Vercel Toolbar",
+ source: { name: "vercel.com", url: "https://vercel.com/products/previews" },
+ about:
+ "A dark toolbar floats between seven tilted tags, and they all fade in one after another. Hover a button and its tag takes its colour while the other tags blur and the other icons dim. Grab the toolbar and drag it: the tags blur as it moves, and it glides back when you let go.",
+ note: "vercel.com updates the hover a moment after the pointer arrives, when React gets to it. The copy waits the same moment, so every change starts on the same frame.",
+ show: { kind: "live", width: 560, height: 260, background: "#fafafa" },
+ live: "/examples/vercel-previews/?",
+ results: [
+ ["Frame match", "frames identical: the entrance, all seven buttons, a drag", "417 of 417"],
+ ["Timing", "start and end of every fade, blur and colour change", "0 ms"],
+ ["Layout", "every element, at rest and in each hover state", "≤ 0.02 px"],
+ ],
+ },
+ {
+ slug: "vercel-hero",
+ title: "Drop to deploy",
+ source: { name: "vercel.com", url: "https://vercel.com/" },
+ about:
+ "A black triangle sits in vercel.com’s hero, lit by 72 LEDs along its edges while soft lines of light run round it. Bring the pointer close and the edges facing it light up. Drag a file over the page and it turns into a prism: red, green and blue light spreads from its edges and “Drop to deploy” fades in.",
+ note: "This is vercel.com’s own renderer, read from the page: the same shaders, run in a worker as on vercel.com. vercel.com draws it with WebGPU where it can and the copy with WebGL, vercel.com’s own fallback; the two place the grain on the triangle’s rim differently, and nothing else.",
+ show: { kind: "live", width: 560, height: 373, background: "#fafafa", try: "drag any file onto it" },
+ live: "/examples/vercel-hero/?",
+ results: [
+ ["Frame match", "pixels that differ, 803 frames: entrance, pointer, drop, click, nav", "≤ 1 level"],
+ ["Drop timing", "label, text and colours, in and out", "0 ms"],
+ ["WebGPU original", "pixels more than 8 levels off, same as vercel.com’s own WebGL", "0.16 %"],
+ ],
+ },
+ {
+ slug: "vercel-fluid",
+ title: "Fluid ocean",
+ source: { name: "vercel.com", url: "https://vercel.com/fluid" },
+ about:
+ "Behind the hero, a grid of 512 × 512 tiny dots rolls like a slow sea. Each dot snaps to a 4.4 px grid, so the waves read as a dot matrix. It fades in over 0.7 s once the first frame is ready. Without WebGPU you get a still of the same sea.",
+ note: "This is vercel.com’s own WebGPU renderer, ported: the same shaders, constants and seeded noise. Started on the same frame, it draws the same pixels, in light and dark.",
+ show: { kind: "video", width: 560, height: 376, stacked: true },
+ live: "/examples/vercel-fluid/",
+ results: [
+ ["Frame match", "pixels that differ over 12 s of sea, light and dark, at 1x and 2x", "0 px"],
+ ["Speed", "simulated seconds per second (vercel.com: 0.600)", "0.600"],
+ ["Fade-in", "opacity, frame by frame", "identical"],
+ ],
+ },
+ {
+ slug: "vercel-workflow",
+ title: "Inspect every run",
+ source: { name: "vercel.com", url: "https://vercel.com/workflow" },
+ about:
+ "A copy of the Vercel dashboard shows one run of a workflow. When it scrolls into view the run plays: the status turns to Running, the duration counts up to 925 ms and the six steps fill in one after another, each with its own timer. Then the status turns to Completed.",
+ note: "Each bar keeps its own clock and only moves while at least 35 % of it is on screen, as on vercel.com. Scroll away mid-run and it waits for you.",
+ show: { kind: "video", width: 560, height: 454, stacked: true },
+ live: "/examples/vercel-workflow/",
+ results: [
+ ["Frame match", "pixels that differ over 3 s after scroll-in", "0.0001 %"],
+ ["Bars", "width of all six spans, every frame", "0 px"],
+ ["Timing", "start and end of every span and status change", "0 ms"],
+ ],
+ },
+ {
+ slug: "turborepo-gauge",
+ title: "Speedometer",
+ source: { name: "turborepo.com", url: "https://turborepo.com/" },
+ about:
+ "A speedometer sits next to the headline, its needle resting near the red end. Point at it and the needle revs into the red, hits the end stop and settles; move away and it drops back. Below, the compute hours saved roll up to the live count once the page loads, then tick up every 10 s.",
+ note: "The gauge is turborepo.com’s own SVG and the needle runs the page’s own spring. The hours are live on turborepo.com; the copy starts from the count read on 30 October 2026 and grows at the rate measured then, so its last digits differ.",
+ show: { kind: "live", width: 560, height: 500, background: "#fafafa" },
+ live: "/examples/turborepo-gauge/?",
+ results: [
+ ["Frame match", "pixels that differ over 4 s of hovering, at 1x and 2x, light and dark", "0 px"],
+ ["Pointer", "from the pointer to the needle’s first move (turborepo.com: 32–34 ms)", "31–33 ms"],
+ ["Counter", "start of the roll after the first frame (turborepo.com: 466–608 ms)", "456–469 ms"],
+ ],
+ },
+ {
+ slug: "nextjs-optimizations",
+ title: "Built-in Optimizations",
+ source: NEXTJS,
+ about:
+ "Three image frames, from the original down to a 375 px copy, each with a dotted mountain drawn on a canvas. Move the pointer over them and the dots within 40 px light up in six bands of blue, darkest at the centre.",
+ note: "This is nextjs.org’s own canvas code, ported line for line with its dot data, so it draws the same pixels.",
+ show: { kind: "live", width: 496, height: 514, background: "#fafafa" },
+ live: "/examples/nextjs-features/?card=optimizations",
+ results: [
+ ["Frame match", "frames identical while the pointer crosses it, at 2x", "129 of 131"],
+ ["At rest", "canvas pixels against nextjs.org’s, 150 frames", "identical"],
+ ["Pointer", "glow, arrow and text colour against nextjs.org", "≤ 17 ms"],
+ ],
+ },
+ {
+ slug: "nextjs-streaming",
+ title: "Dynamic HTML Streaming",
+ source: NEXTJS,
+ about:
+ "A wireframe page sits on a grid. Once the card is well into view, four streaks of blue run along the grid lines into the page, each on its own loop. Every 5 s the image turns into an avatar and back, and every 8 s the content blocks change layout. Hover it and the streaks restart on a quicker 2 s loop.",
+ note: "nextjs.org runs it on Motion. The copy ports the part it uses, down to Motion’s rounding of time to whole milliseconds.",
+ show: { kind: "live", width: 496, height: 514, background: "#fafafa" },
+ live: "/examples/nextjs-features/?card=streaming",
+ results: [
+ ["Timing", "start of every streak, swap and layout change", "0 ms"],
+ ["Motion", "40 animated values, every frame for 10 s", "identical"],
+ ["Frame match", "frames identical at 2x over 6 s", "148 of 150"],
+ ],
+ },
+ {
+ slug: "nextjs-rsc",
+ title: "React Server Components",
+ source: NEXTJS,
+ about:
+ "Dashes flow down two edges of a tree of six nodes while blue arcs glide round three of them and pulse. Hover the card and both speed up and the arcs thicken, easing back over about a second when you leave. It pauses while off screen.",
+ show: { kind: "live", width: 496, height: 514, background: "#fafafa" },
+ live: "/examples/nextjs-features/?card=rsc",
+ results: [
+ ["Motion", "17 animated values, every frame for 10 s", "identical"],
+ ["Frame match", "frames identical at 2x over 6 s", "146 of 150"],
+ ["Hover", "speed-up and slow-down against nextjs.org", "≤ 17 ms"],
+ ],
+ },
{
slug: "stripe-agentic-commerce",
title: "Agentic commerce",