Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

perf(3d): run model previews only while someone is looking at them

nirholasfab53e3cfecb
diff --git a/pages/create.html b/pages/create.html
index 3d5796129..5d03e66a0 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -1448,8 +1448,16 @@
</span>
</div>
<div class="hero-card-preview">
+ <!-- data-src, not src: decoding this 748 KB avatar is one
+ unbreakable 852 ms main-thread task, and it used to run while
+ the page was still trying to become usable. The poster is a
+ render of the same model at the same camera, so the card
+ looks finished from the first frame; the live, rotatable
+ model loads the moment the visitor hovers, focuses or taps
+ the card (src/shared/attended-rotation.js). -->
<model-viewer
- src="/avatars/default.glb"
+ data-src="/avatars/default.glb"
+ poster="/avatars/default-poster.webp"
alt="Customizable 3D base avatar"
auto-rotate
auto-rotate-delay="0"
@@ -1464,6 +1472,7 @@
environment-image="neutral"
camera-orbit="15deg 80deg auto"
loading="eager"
+ data-attended-rotate=".hero-card"
></model-viewer>
</div>
</div>
diff --git a/pages/forge.html b/pages/forge.html
index 617889c50..886a6eeb8 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -41,16 +41,14 @@
<link rel="preload" href="/fonts/space-grotesk-latin.woff2" as="font" type="font/woff2" crossorigin />
<link rel="stylesheet" href="/style.css" />
<link rel="preconnect" href="https://ajax.googleapis.com" />
- <!-- Deferred, and placed BEFORE the model-viewer module: defer scripts and
- module scripts execute in document order, so the meshopt shim still
- registers its decoder before model-viewer's define runs. -->
+ <!-- The meshopt decoder shim has to register before any model-viewer
+ starts loading, so it stays a plain deferred script here. model-viewer
+ itself is NOT loaded on arrival: this page's landing state has no 3D on
+ screen, and parsing the 955 KB CDN bundle ahead of the first paint was
+ the whole of its 1.5 s FCP. src/shared/model-viewer-loader.js fetches
+ it (with CDN failover) the moment a generation starts, or when a
+ showcase card needs a live preview. -->
<script src="/model-viewer-meshopt.js" defer></script>
- <script
- type="module"
- src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
- integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"
- crossorigin="anonymous"
- ></script>
<style>
/* No per-surface accent override — forge uses the global monochrome tokens. */
diff --git a/pages/home.html b/pages/home.html
index edd65cf4b..54be53498 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -1352,6 +1352,7 @@
</div>
</section>
<script type="module">
+import { attendRotation } from '/src/shared/attended-rotation.js';
(function() {
var track = document.getElementById('hcf-track');
if (!track) return;
@@ -1421,6 +1422,10 @@
var poster = wrap.querySelector('.hcf-poster');
if (poster) poster.remove();
wrap.appendChild(mv);
+ // The strip holds a card per community model. Left alone every one of
+ // them rotates for the life of the tab, and model-viewer blits each
+ // element's pixels every frame; they spin while looked at instead.
+ attendRotation(mv);
}
// A card with its real prompt, link and gradient, but a poster image instead
@@ -2300,6 +2305,7 @@
</div>
</section>
<script type="module">
+import { attendRotation } from '/src/shared/attended-rotation.js';
(async () => {
let renderQRToCanvas;
try {
@@ -2575,6 +2581,9 @@
skeleton.style.display = 'none';
wrap.insertBefore(mv, nav);
+ // One showcase viewer, but the same perpetual-rotation cost: turn while
+ // the section is on screen and being looked at, then settle.
+ attendRotation(mv);
buildDots();
loadModel(models[0]);
diff --git a/public/avatars/default-poster.webp b/public/avatars/default-poster.webp
new file mode 100644
index 000000000..9328b9320
Binary files /dev/null and b/public/avatars/default-poster.webp differ
diff --git a/public/discover/discover.js b/public/discover/discover.js
index eb3a8a7fa..dba29f44a 100644
--- a/public/discover/discover.js
+++ b/public/discover/discover.js
@@ -231,31 +231,65 @@ if ('IntersectionObserver' in window && els.sentinel) {
io.observe(els.sentinel);
}
-// Card previews render one frame and hold still; a card spins only while the
-// visitor is on it. A continuously auto-rotating <model-viewer> re-renders and
-// copies its pixels every frame for as long as the tab is open, and four of
-// them in one grid cost 31 s of main-thread time in a 40 s Lighthouse run.
+// Attended rotation, the same policy as src/shared/attended-rotation.js (this
+// file ships from public/ verbatim, so it cannot import it). A card turns when
+// it scrolls into view, settles once it has turned far enough to read as 3D,
+// and turns again on hover or focus. Before this every card in the grid rotated
+// for the life of the tab, and model-viewer blits each element's pixels every
+// frame: four of them cost 31 s of main-thread time in a 40 s Lighthouse run
+// and the page never went quiet enough to answer input.
+const MV_SEL = 'model-viewer.explore-card-mv';
+const SETTLE_MS = 12_000;
+const reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function setCardRotation(mv, on) {
if (!mv) return;
- if (on) mv.setAttribute('auto-rotate', '');
+ if (on && !reduceMotion) mv.setAttribute('auto-rotate', '');
else mv.removeAttribute('auto-rotate');
}
-const cardViewer = (target) => (target && target.closest ? target.closest('model-viewer.explore-card-mv') : null);
-els.grid.addEventListener('pointerover', (e) => setCardRotation(cardViewer(e.target), true));
+function turnCard(mv) {
+ if (!mv || reduceMotion) return;
+ setCardRotation(mv, true);
+ clearTimeout(mv._settleTimer);
+ mv._settleTimer = setTimeout(() => {
+ if (!mv.matches(':hover') && !mv.closest('article')?.contains(document.activeElement)) {
+ setCardRotation(mv, false);
+ }
+ }, SETTLE_MS);
+}
+const cardViewer = (target) => (target && target.closest ? target.closest(MV_SEL) : null);
+els.grid.addEventListener('pointerover', (e) => turnCard(cardViewer(e.target)));
els.grid.addEventListener('pointerout', (e) => {
const mv = cardViewer(e.target);
if (mv && !(e.relatedTarget && mv.contains(e.relatedTarget))) setCardRotation(mv, false);
});
els.grid.addEventListener('focusin', (e) => {
const card = e.target && e.target.closest ? e.target.closest('article') : null;
- setCardRotation(card && card.querySelector('model-viewer.explore-card-mv'), true);
+ turnCard(card && card.querySelector(MV_SEL));
});
els.grid.addEventListener('focusout', (e) => {
const card = e.target && e.target.closest ? e.target.closest('article') : null;
if (card && !(e.relatedTarget && card.contains(e.relatedTarget))) {
- setCardRotation(card.querySelector('model-viewer.explore-card-mv'), false);
+ setCardRotation(card.querySelector(MV_SEL), false);
}
});
+// Cards arrive from an infinite-scroll feed, so the observer is re-applied
+// after every page render (see renderPage below); bound viewers are skipped.
+const cardTurnObserver = 'IntersectionObserver' in window && !reduceMotion
+ ? new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting) turnCard(entry.target);
+ else setCardRotation(entry.target, false);
+ }
+ }, { rootMargin: '80px 0px' })
+ : null;
+function observeCardTurns() {
+ if (!cardTurnObserver) return;
+ for (const mv of els.grid.querySelectorAll(MV_SEL)) {
+ if (mv.dataset.turnObserved === '1') continue;
+ mv.dataset.turnObserved = '1';
+ cardTurnObserver.observe(mv);
+ }
+}
// Delegated copy-URI click
els.grid.addEventListener('click', (e) => {
@@ -370,6 +404,7 @@ async function loadPage() {
for (const item of items) {
els.grid.appendChild(renderCard(item));
}
+ observeCardTurns();
state.cursor = data.nextCursor;
els.loadMore.hidden = !state.cursor;
diff --git a/scripts/render-glb-poster.mjs b/scripts/render-glb-poster.mjs
new file mode 100644
index 000000000..1e8b08f5e
--- /dev/null
+++ b/scripts/render-glb-poster.mjs
@@ -0,0 +1,131 @@
+#!/usr/bin/env node
+/**
+ * Render a local GLB to a local poster image.
+ *
+ * A <model-viewer> card that ships with `src` set pays the whole model cost
+ * during page load: /create's hero card spent 852 ms of unbroken main-thread
+ * time decoding the 748 KB base avatar before the page could answer input. A
+ * poster lets the card paint the finished frame immediately and load the live
+ * model only when the visitor engages with it.
+ *
+ * Reuses scripts/glb-thumbnail-harness.html (the same headless model-viewer the
+ * asset pipelines render their thumbnails with) so a poster matches the framing
+ * and lighting of every other rendered thumbnail on the platform. Unlike
+ * scripts/render-glb-thumbnails.mjs, which reads and writes R2, this one works
+ * entirely on local files.
+ *
+ * Usage:
+ * node scripts/render-glb-poster.mjs public/avatars/default.glb public/avatars/default-poster.webp
+ * node scripts/render-glb-poster.mjs <in.glb> <out.(webp|png)> [--size=768] [--quality=82]
+ *
+ * Camera and lighting default to the shared harness's. Override them to match
+ * the viewer the poster stands in for, so the live model does not visibly jump
+ * when it loads over the poster:
+ * --orbit="15deg 80deg auto" --fov=30deg --exposure=0.95
+ * --shadow=0.4 --shadow-softness=0.8 --environment=neutral
+ */
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { createServer } from 'node:http';
+import { resolve, dirname, extname, basename } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = resolve(here, '..');
+const HARNESS = resolve(here, 'glb-thumbnail-harness.html');
+
+const positional = process.argv.slice(2).filter((a) => !a.startsWith('--'));
+const flags = Object.fromEntries(
+ process.argv
+ .slice(2)
+ .filter((a) => a.startsWith('--'))
+ .map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return [m[1], m[2] ?? true];
+ }),
+);
+const [inPath, outPath] = positional;
+if (!inPath || !outPath) {
+ console.error('usage: node scripts/render-glb-poster.mjs <in.glb> <out.(webp|png)> [--size=768] [--quality=82] [--orbit=…] [--fov=…] [--exposure=…] [--shadow=…] [--shadow-softness=…] [--environment=…]');
+ process.exit(2);
+}
+const glb = resolve(root, inPath);
+const out = resolve(root, outPath);
+if (!existsSync(glb)) {
+ console.error(`[poster] no such GLB: ${glb}`);
+ process.exit(2);
+}
+const size = Number(flags.size) || 768;
+const quality = Number(flags.quality) || 82;
+
+// The harness loads the model from a URL, and model-viewer applies the same
+// cross-origin rules a browser would, so both files are served from one
+// short-lived same-origin server on an ephemeral port.
+const glbName = basename(glb);
+// Most three.ws GLBs (this one included) ship EXT_meshopt_compression, which
+// model-viewer does not wire a decoder for on its own, so the shared shim is
+// injected ahead of the model-viewer module exactly as every page does it.
+const MESHOPT_SHIM = resolve(root, 'public/model-viewer-meshopt.js');
+const MV_TAG = '<script type="module" src="https://ajax.googleapis.com';
+const server = createServer((req, res) => {
+ // '/model/' with the slash: '/model-viewer-meshopt.js' also starts with
+ // '/model', and serving it the GLB's bytes made the shim fail to parse and
+ // the decoder never register.
+ if (req.url.startsWith('/model/')) {
+ res.writeHead(200, { 'content-type': 'model/gltf-binary' });
+ res.end(readFileSync(glb));
+ return;
+ }
+ if (req.url.startsWith('/model-viewer-meshopt.js')) {
+ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' });
+ res.end(readFileSync(MESHOPT_SHIM));
+ return;
+ }
+ const html = readFileSync(HARNESS, 'utf8').replace(
+ MV_TAG,
+ `<script src="/model-viewer-meshopt.js"></script>${MV_TAG}`,
+ );
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ res.end(html);
+});
+await new Promise((r) => server.listen(0, '127.0.0.1', r));
+const origin = `http://127.0.0.1:${server.address().port}`;
+
+const { chromium } = await import('playwright');
+const browser = await chromium.launch({
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--enable-unsafe-swiftshader'],
+});
+try {
+ const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 });
+ page.on('console', (m) => console.error('[poster][page]', m.type(), m.text().slice(0, 300)));
+ page.on('pageerror', (e) => console.error('[poster][pageerror]', String(e).slice(0, 300)));
+ await page.goto(origin, { waitUntil: 'load', timeout: 60_000 });
+ await page.waitForFunction(() => window.__ready === true, null, { timeout: 60_000 });
+ // A poster is a still of the live viewer's first frame, so it has to be shot
+ // with that viewer's camera and lighting or the model visibly jumps when the
+ // real thing loads over it. These override the harness defaults.
+ const look = {
+ 'camera-orbit': flags.orbit,
+ 'field-of-view': flags.fov,
+ exposure: flags.exposure,
+ 'shadow-intensity': flags.shadow,
+ 'shadow-softness': flags['shadow-softness'],
+ 'environment-image': flags.environment,
+ };
+ await page.evaluate((attrs) => {
+ const mv = document.getElementById('mv');
+ for (const [k, v] of Object.entries(attrs)) if (v) mv.setAttribute(k, String(v));
+ }, look);
+ const dataUrl = await page.evaluate((u) => window.__renderGlb(u).catch((e) => { throw new Error(String(e && e.message || e)); }), `${origin}/model/${glbName}`);
+ const png = Buffer.from(String(dataUrl).split(',')[1], 'base64');
+ const sharp = (await import('sharp')).default;
+ const img = sharp(png).resize({ width: size, height: size, fit: 'inside', withoutEnlargement: true });
+ const bytes = extname(out).toLowerCase() === '.webp'
+ ? await img.webp({ quality }).toBuffer()
+ : await img.png({ compressionLevel: 9 }).toBuffer();
+ writeFileSync(out, bytes);
+ const meta = await sharp(bytes).metadata();
+ console.log(`[poster] ${inPath} -> ${outPath} (${meta.width}x${meta.height}, ${(bytes.length / 1024).toFixed(1)} KiB)`);
+} finally {
+ await browser.close();
+ server.close();
+}
diff --git a/src/create.js b/src/create.js
index 7bb163f42..034f321c7 100644
--- a/src/create.js
+++ b/src/create.js
@@ -1,4 +1,5 @@
import { apiFetch } from './account.js';
+import { attendRotationIn } from './shared/attended-rotation.js';
import { AvatarCreator } from './avatar-creator.js';
import { stage as stageGuestAvatar } from './guest-avatar.js';
import { createFromTemplate } from './shared/template-picker.js';
@@ -238,6 +239,9 @@ function showFatal({ title, body, retryLabel, onRetry }) {
}
async function boot() {
+ // The hero card's rotating avatar is decorative: spin it while the visitor
+ // is on it, not for the life of the tab (src/shared/attended-rotation.js).
+ attendRotationIn(document);
probeFeatures();
const creator = new AvatarCreator(document.body, (blob, meta = {}) => {
const provider = meta.provider || 'avaturn';
diff --git a/src/forge-showcase.js b/src/forge-showcase.js
index 83f3b5cc3..1c516feed 100644
--- a/src/forge-showcase.js
+++ b/src/forge-showcase.js
@@ -12,6 +12,7 @@
// The section stays hidden when the deployment has no durable store or the
// feed is empty — a first-time visitor never sees a broken or hollow strip.
+import { ensureModelViewer } from './shared/model-viewer-loader.js';
import { resizedImageUrl } from './shared/image-url.js';
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
ensureStateKitStyles();
@@ -149,7 +150,15 @@ function enqueueCaptureFromGlb(card, glbUrl) {
}
async function captureFromGlb(card, glbUrl) {
- if (!window.customElements?.get('model-viewer')) return null;
+ // This page no longer ships model-viewer on arrival, so Plan B fetches it
+ // the first time a card actually needs a capture. If every CDN is blocked
+ // the loader rejects and the card keeps its gradient (Plan C), which is
+ // what used to happen silently whenever the element was simply absent.
+ try {
+ await ensureModelViewer();
+ } catch {
+ return null;
+ }
return new Promise((resolve) => {
const viewer = document.createElement('model-viewer');
// Render at a real resolution off-screen — model-viewer sizes its WebGL
@@ -545,14 +554,23 @@ function teardownHoverPreview() {
}
function attachHoverPreview(card, c) {
- if (!c.glb_url || !window.customElements?.get('model-viewer')) return;
+ if (!c.glb_url) return;
if (matchMedia('(hover: none)').matches) return;
card.addEventListener('mouseenter', () => {
teardownHoverPreview();
- previewTimer = setTimeout(() => {
+ // Hovering for 300 ms is the signal that this card is worth a live
+ // preview, and it is also when the viewer bundle is worth fetching.
+ previewTimer = setTimeout(async () => {
+ try {
+ await ensureModelViewer();
+ } catch {
+ return;
+ }
const thumb = card.querySelector('.thumb');
- if (!thumb) return;
+ // The pointer can leave during the load; teardownHoverPreview() clears
+ // previewTimer, so a cleared timer means this hover is stale.
+ if (!thumb || previewTimer === null) return;
const viewer = document.createElement('model-viewer');
viewer.className = 'showcase-preview';
viewer.setAttribute('src', c.glb_url);
diff --git a/src/forge.js b/src/forge.js
index 95c791197..b6d4de40f 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -1,4 +1,5 @@
// Forge — text / image / multi-view → 3D generator (browser client).
+import { ensureModelViewerOrFallback } from './shared/model-viewer-loader.js';
import { resizedImageUrl } from './shared/image-url.js';
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
import {
@@ -350,6 +351,14 @@ const REDUCED_MOTION =
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
function showState(name) {
+ // The 3D viewer only exists in the generating/result states, and the CDN
+ // bundle is 955 KB, so it is fetched the first time the page heads there
+ // rather than on arrival (see the head of pages/forge.html). Fire and
+ // forget: #viewer reads its attributes when the element finally upgrades,
+ // and the loader has its own CDN failover and error state.
+ if (name === 'generating' || name === 'result') {
+ ensureModelViewerOrFallback(els.states.result || document);
+ }
for (const [key, node] of Object.entries(els.states)) {
node.classList.toggle('is-hidden', key !== name);
}
diff --git a/src/shared/attended-rotation.js b/src/shared/attended-rotation.js
new file mode 100644
index 000000000..cdb140696
--- /dev/null
+++ b/src/shared/attended-rotation.js
@@ -0,0 +1,152 @@
+// Spin a <model-viewer> while someone is actually looking at it.
+//
+// `auto-rotate` runs forever. model-viewer draws every element through one
+// shared WebGL canvas and blits the result into the element's own canvas each
+// frame (its `copyPixels`), so a decorative preview that never stops rotating
+// keeps the main thread busy for as long as the tab is open: 2.4 s of scripting
+// per 35 s on /create, from a single card in the hero, and the page never
+// quiets down enough to read as interactive.
+//
+// A preview only has to move while it is being looked at. This keeps the spin
+// where it earns its place (the element is on screen, the tab is in front) and
+// retires it once it has turned far enough to read as 3D, then brings it back
+// on hover, focus, or the next time the element scrolls into view. Nothing is
+// removed from the page and no interaction changes.
+//
+// Two entry points: `attendRotation` takes one viewer element, and
+// `attendRotationIn` takes a root and claims every `[data-attended-rotate]`
+// viewer under it (safe to call again after new cards render). A viewer
+// authored with `data-src` + `poster` instead of `src` also has its model
+// loaded on first attention, so an untouched card costs a poster and nothing
+// else.
+//
+// Only elements authored with `auto-rotate` are touched, so marking a viewer is
+// opt-in and reversible.
+
+// Long enough to read as a deliberate turn (a 20deg/s viewer sweeps ~240
+// degrees), short enough that an unattended tab stops working.
+const DEFAULT_SETTLE_MS = 12_000;
+// Rotation resumes a little before the element scrolls back in, so the first
+// frame a visitor sees is already moving.
+const ROOT_MARGIN = '100px 0px';
+
+function prefersReducedMotion() {
+ try {
+ return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Manage one <model-viewer>'s `auto-rotate` so it only spins while attended.
+ * @param {Element|null} el a <model-viewer> authored with `auto-rotate`
+ * @param {{ settleMs?: number, attention?: Element|null }} [opts]
+ * `settleMs` is how long an unattended spin runs. `attention` is the element
+ * whose hover and focus count as attention, for a viewer that sits inside a
+ * larger card: a visitor aims at the card, not at the canvas, and a viewer
+ * with no camera controls cannot take keyboard focus itself.
+ * @returns {() => void} detaches every listener and leaves rotation on
+ */
+export function attendRotation(el, { settleMs = DEFAULT_SETTLE_MS, attention = null } = {}) {
+ const noop = () => {};
+ if (!el || typeof el.hasAttribute !== 'function' || !el.hasAttribute('auto-rotate')) return noop;
+ if (el.dataset.attendedRotateBound === '1') return noop;
+ el.dataset.attendedRotateBound = '1';
+
+ // Reduced motion: never spin. The model still renders, poses, and answers
+ // camera controls; it just does not move on its own.
+ if (prefersReducedMotion()) {
+ el.removeAttribute('auto-rotate');
+ return noop;
+ }
+
+ let onScreen = typeof IntersectionObserver === 'undefined';
+ let attended = false;
+ let settled = false;
+ let timer = 0;
+ let rotating = true;
+
+ const apply = () => {
+ const want = onScreen && document.visibilityState !== 'hidden' && (attended || !settled);
+ if (want === rotating) return;
+ rotating = want;
+ if (want) el.setAttribute('auto-rotate', '');
+ else el.removeAttribute('auto-rotate');
+ };
+ // The settle timer starts when a turn starts, so an element that spends its
+ // first ten seconds off screen still gets its full turn on arrival.
+ const arm = () => {
+ clearTimeout(timer);
+ settled = false;
+ if (settleMs > 0) timer = setTimeout(() => { settled = true; apply(); }, settleMs);
+ apply();
+ };
+ // A viewer can also defer its model until someone engages with it: author it
+ // with `data-src` instead of `src` and give it a poster. Decoding a GLB is
+ // one long, unbreakable main-thread task (852 ms for /create's 748 KB base
+ // avatar), so a card that may never be looked at should not spend it during
+ // page load. The poster shows the finished frame either way.
+ const promoteSource = () => {
+ if (!el.dataset.src || el.getAttribute('src')) return;
+ el.setAttribute('src', el.dataset.src);
+ delete el.dataset.src;
+ };
+ const attend = () => { attended = true; promoteSource(); arm(); };
+ const release = (e) => {
+ if (e?.relatedTarget && (attention || el).contains(e.relatedTarget)) return;
+ attended = false;
+ apply();
+ };
+
+ const host = attention || el;
+ host.addEventListener('pointerenter', attend);
+ host.addEventListener('pointerleave', release);
+ host.addEventListener('focusin', attend);
+ host.addEventListener('focusout', release);
+ document.addEventListener('visibilitychange', apply);
+
+ let io = null;
+ if (typeof IntersectionObserver !== 'undefined') {
+ io = new IntersectionObserver((entries) => {
+ const next = entries.some((entry) => entry.isIntersecting);
+ if (next === onScreen) return;
+ onScreen = next;
+ // Arriving on screen is what starts a turn; leaving just stops it.
+ if (next) arm();
+ else apply();
+ }, { rootMargin: ROOT_MARGIN });
+ io.observe(el);
+ } else {
+ arm();
+ }
+
+ return () => {
+ clearTimeout(timer);
+ io?.disconnect();
+ host.removeEventListener('pointerenter', attend);
+ host.removeEventListener('pointerleave', release);
+ host.removeEventListener('focusin', attend);
+ host.removeEventListener('focusout', release);
+ document.removeEventListener('visibilitychange', apply);
+ delete el.dataset.attendedRotateBound;
+ el.setAttribute('auto-rotate', '');
+ };
+}
+
+/**
+ * Apply attended rotation to every `[data-attended-rotate]` viewer under `root`.
+ * Safe to call again after new cards render: bound elements are skipped.
+ * @param {ParentNode} [root]
+ * @param {{ settleMs?: number }} [opts]
+ */
+export function attendRotationIn(root = document, opts) {
+ if (!root || typeof root.querySelectorAll !== 'function') return;
+ for (const el of root.querySelectorAll('model-viewer[data-attended-rotate]')) {
+ // `data-attended-rotate="<selector>"` names the card that owns the
+ // viewer, so hovering or tabbing to the card is what wakes it.
+ const sel = el.getAttribute('data-attended-rotate');
+ const attention = sel ? el.closest(sel) : null;
+ attendRotation(el, { ...opts, attention });
+ }
+}