A Claude Code skill that reverse-engineers any animation frame by frame, then proves the copy moves the same.
Build the motion-clone site
NiazMorshed20076f5df4f24340
diff --git a/.env.production b/.env.productionnew file mode 100644index 0000000..f41c21d--- /dev/null+++ b/.env.production@@ -0,0 +1,2 @@+# Public URL of the deployed site, used for Open Graph and canonical links.+SITE_URL=diff --git a/.gitignore b/.gitignoreindex 5ef6a52..9fd2713 100644--- a/.gitignore+++ b/.gitignore@@ -39,3 +39,10 @@ yarn-error.log*# typescript*.tsbuildinfonext-env.d.ts+!.env.production++# vendored at build by scripts/vendor-examples.mjs+/public/examples/*/vendor/++# wrangler+.wrangler/diff --git a/README.md b/README.mdindex e215bc4..a058ff9 100644--- a/README.md+++ b/README.md@@ -1,36 +1,49 @@-This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).+# motion-clone site-## Getting Started+The website for [motion-clone](https://github.com/NiazMorshed2007/motion-clone), a Claude Code skill that clones animations frame by frame. Next.js 16, exported as static files and served by a Cloudflare Worker (static assets only, no server code).-First, run the development server:+## Develop-```bash-npm run dev-# or-yarn dev-# or-pnpm dev-# or-bun dev+```sh+bun install+bun run dev # http://localhost:3000```-Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.+`predev` and `prebuild` copy three.js and the Inter font from `node_modules` into `public/examples/stripe-bento/vendor/` (git-ignored), because the live examples are plain HTML pages loaded in iframes.-You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.+## Build and preview like production-This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.+```sh+bun run preview # next build, then wrangler dev on http://localhost:8787+```++## Deploy to Cloudflare Workers++Set the public URL first, so the Open Graph and canonical links are absolute:++```sh+# .env.production+SITE_URL=https://motion-clone.<your-subdomain>.workers.dev+```-## Learn More+Then either:-To learn more about Next.js, take a look at the following resources:+- **From this machine:** `npx wrangler login` once (or export `CLOUDFLARE_API_TOKEN` with the "Edit Cloudflare Workers" template), then `bun run deploy`.+- **On every push:** in the Cloudflare dashboard, Workers & Pages → Create → Import a repository → this repo. Build command `bun run build`, deploy command `npx wrangler deploy`. Add `SITE_URL` as a build variable.-- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.-- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.+`wrangler.jsonc` names the Worker `motion-clone` and serves `./out`, with `404.html` for unknown paths.-You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!+## Layout-## Deploy on Vercel+| Path | What it is |+|---|---|+| `src/app/page.tsx` | The whole page: copy, sections, tables. |+| `src/components/` | `LiveExample` (scaled or cropped iframe of a live clone), `CompareVideo` (drag to compare stripe.com and the clone), `Nav`, `Sidenote`, `CopyCommand`. |+| `public/examples/stripe-bento/` | The three cloned stripe.com cards as a standalone page; `?card=agentic-commerce\|issuing\|crypto` shows one. |+| `public/media/` | Comparison recordings (stripe.com and clone, same capture command) and the comparison sheet. |+| `public/og.png` | Social preview image. |+| `marketing/launch.md` | Launch post drafts. |-The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.+## About the examples-Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.+The live examples recreate three cards from stripe.com as a study of the technique. They use Inter instead of Stripe's licensed Söhne, but the widget code ports Stripe's shaders and uses Stripe's images. Not affiliated with or endorsed by Stripe.diff --git a/bun.lock b/bun.lockindex e88ed36..6aaac8d 100644--- a/bun.lock+++ b/bun.lock@@ -8,8 +8,10 @@"next": "16.4.3","react": "19.3.0","react-dom": "19.3.0",+ "three": "0.178.0",},"devDependencies": {+ "@fontsource-variable/inter": "^5.3.0","@tailwindcss/turbopack": "^4","@types/node": "^20","@types/react": "^19",@@ -18,12 +20,15 @@"eslint-config-next": "16.4.3","tailwindcss": "^4","typescript": "^5",+ "wrangler": "^4.155.0",},},},"trustedDependencies": [+ "esbuild","sharp","unrs-resolver",+ "workerd",],"packages": {"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA=="],@@ -60,12 +65,80 @@"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.11", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ=="],+ "@cloudflare/kv-asset-handler": ["@cloudflare/[email protected]", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="],++ "@cloudflare/unenv-preset": ["@cloudflare/[email protected]", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ=="],++ "@cloudflare/workerd-darwin-64": ["@cloudflare/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-lsEx0i7nR0PNG/erUFFHmQmiidEhLfDE5uQmAL9421/y4/ycuxDDOSaxu3VGGYFFPK5sduyUeMmjIlX4CwOBFg=="],++ "@cloudflare/workerd-darwin-arm64": ["@cloudflare/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5e79fHgabdDD8EgmjOhJ1S+xMsf6DbC7fL7IgTBizMnzOp0P2isDn7pYmUxI9AJZE9FVQ4RUilH/I36YNg+GQQ=="],++ "@cloudflare/workerd-linux-64": ["@cloudflare/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-VHQ6jKFSihjR2+x1buby8XTdBLLJztVnYiB7OLOTYO8aDXB+c1Rd2410PdgFuFYc4AgFEk6PCJLyCLL5L1KBnw=="],++ "@cloudflare/workerd-linux-arm64": ["@cloudflare/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-ilpRHzfDN8YFRM5CLRKuFw40x/LJBS89yVdhdQmxehlVDuBqjKpJB++zPFbTgKRRFaNupgnXc8RHktXAIhgCmQ=="],++ "@cloudflare/workerd-windows-64": ["@cloudflare/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-279WLVjNsMycAwr0EZNiNEf0l2SY6NUtsN80NwZzbTHzakmiN+WSx4w38muxPm+PAU0oSPPAPXKVD+H6Hya8xw=="],++ "@cspotcode/source-map-support": ["@cspotcode/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],+"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],"@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],+ "@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],++ "@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="],++ "@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="],++ "@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="],++ "@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="],++ "@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="],++ "@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="],++ "@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="],++ "@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="],++ "@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="],++ "@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="],++ "@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="],++ "@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="],++ "@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="],++ "@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="],++ "@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="],++ "@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="],++ "@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="],++ "@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="],++ "@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="],++ "@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="],++ "@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="],++ "@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="],++ "@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="],++ "@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="],++ "@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="],+"@eslint-community/eslint-utils": ["@eslint-community/[email protected]", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ=="],"@eslint-community/regexpp": ["@eslint-community/[email protected]", "", {}, "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew=="],@@ -84,6 +157,8 @@"@eslint/plugin-kit": ["@eslint/[email protected]", "", { "dependencies": { "@eslint/core": "^0.17.0", "levn": "^0.4.1" } }, "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA=="],+ "@fontsource-variable/inter": ["@fontsource-variable/[email protected]", "", {}, "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA=="],+"@humanfs/core": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="],"@humanfs/node": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="],@@ -188,8 +263,18 @@"@nolyfill/is-core-module": ["@nolyfill/[email protected]", "", {}, "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA=="],+ "@poppinss/colors": ["@poppinss/[email protected]", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="],++ "@poppinss/dumper": ["@poppinss/[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="],++ "@poppinss/exception": ["@poppinss/[email protected]", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="],+"@rtsao/scc": ["@rtsao/[email protected]", "", {}, "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g=="],+ "@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="],++ "@speed-highlight/core": ["@speed-highlight/[email protected]", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="],+"@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="],"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],@@ -342,6 +427,8 @@"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA=="],+ "blake3-wasm": ["[email protected]", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="],+"brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw=="],"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],@@ -370,6 +457,8 @@"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],+ "cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],+"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],@@ -402,6 +491,8 @@"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw=="],+ "error-stack-parser-es": ["[email protected]", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="],+"es-abstract": ["[email protected]", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg=="],"es-abstract-get": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "es-object-atoms": "^1.1.2", "is-callable": "^1.2.7", "object-inspect": "^1.13.4" } }, "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg=="],@@ -420,6 +511,8 @@"es-to-primitive": ["[email protected]", "", { "dependencies": { "es-abstract-get": "^1.0.0", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "is-callable": "^1.2.7", "is-date-object": "^1.1.0", "is-symbol": "^1.1.1" } }, "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw=="],+ "esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],+"escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],"escape-string-regexp": ["[email protected]", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],@@ -480,6 +573,8 @@"for-each": ["[email protected]", "", { "dependencies": { "is-callable": "^1.2.7" } }, "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg=="],+ "fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],+"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],"function.prototype.name": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "functions-have-names": "^1.2.3", "has-property-descriptors": "^1.0.2", "hasown": "^2.0.4", "is-callable": "^1.2.7", "is-document.all": "^1.0.0" } }, "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew=="],@@ -614,6 +709,8 @@"keyv": ["[email protected]", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],+ "kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],+"language-subtag-registry": ["[email protected]", "", {}, "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ=="],"language-tags": ["[email protected]", "", { "dependencies": { "language-subtag-registry": "^0.3.20" } }, "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA=="],@@ -660,6 +757,8 @@"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],+ "miniflare": ["[email protected]", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", "undici": "7.30.1", "workerd": "1.20261023.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-sXpZloQnIUe4raXXdwwqd2ioRHox9a/1B4nB2/p4JWKDwGuVgEK4DugCNgIeQf0iVuSgBItdYpodJe4iwY6SrQ=="],+"minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],@@ -710,6 +809,10 @@"path-parse": ["[email protected]", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="],+ "path-to-regexp": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],++ "pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],+"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],"picomatch": ["[email protected]", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],@@ -808,6 +911,8 @@"tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],+ "three": ["[email protected]", "", {}, "sha512-ybFIB0+x8mz0wnZgSGy2MO/WCO6xZhQSZnmfytSPyNpM0sBafGRVhdaj+erYh5U+RhQOAg/eXqw5uVDiM2BjhQ=="],+"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],@@ -834,8 +939,12 @@"unbox-primitive": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-bigints": "^1.0.2", "has-symbols": "^1.1.0", "which-boxed-primitive": "^1.1.1" } }, "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw=="],+ "undici": ["[email protected]", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="],+"undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],+ "unenv": ["[email protected]", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="],+"unrs-resolver": ["[email protected]", "", { "dependencies": { "napi-postinstall": "^0.3.4" }, "optionalDependencies": { "@unrs/resolver-binding-android-arm-eabi": "1.12.2", "@unrs/resolver-binding-android-arm64": "1.12.2", "@unrs/resolver-binding-darwin-arm64": "1.12.2", "@unrs/resolver-binding-darwin-x64": "1.12.2", "@unrs/resolver-binding-freebsd-x64": "1.12.2", "@unrs/resolver-binding-linux-arm-gnueabihf": "1.12.2", "@unrs/resolver-binding-linux-arm-musleabihf": "1.12.2", "@unrs/resolver-binding-linux-arm64-gnu": "1.12.2", "@unrs/resolver-binding-linux-arm64-musl": "1.12.2", "@unrs/resolver-binding-linux-loong64-gnu": "1.12.2", "@unrs/resolver-binding-linux-loong64-musl": "1.12.2", "@unrs/resolver-binding-linux-ppc64-gnu": "1.12.2", "@unrs/resolver-binding-linux-riscv64-gnu": "1.12.2", "@unrs/resolver-binding-linux-riscv64-musl": "1.12.2", "@unrs/resolver-binding-linux-s390x-gnu": "1.12.2", "@unrs/resolver-binding-linux-x64-gnu": "1.12.2", "@unrs/resolver-binding-linux-x64-musl": "1.12.2", "@unrs/resolver-binding-openharmony-arm64": "1.12.2", "@unrs/resolver-binding-wasm32-wasi": "1.12.2", "@unrs/resolver-binding-win32-arm64-msvc": "1.12.2", "@unrs/resolver-binding-win32-ia32-msvc": "1.12.2", "@unrs/resolver-binding-win32-x64-msvc": "1.12.2" } }, "sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ=="],"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A=="],@@ -854,22 +963,36 @@"word-wrap": ["[email protected]", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],+ "workerd": ["[email protected]", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261023.1", "@cloudflare/workerd-darwin-arm64": "1.20261023.1", "@cloudflare/workerd-linux-64": "1.20261023.1", "@cloudflare/workerd-linux-arm64": "1.20261023.1", "@cloudflare/workerd-windows-64": "1.20261023.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-NeofJFyaYNpqKpFRJW3ApuonaerPd6/JWlfTtLDYf2A6ygqrDEFnYgEXmc0hhOxqnJsSM+kXJN6VebPojzRrsg=="],++ "wrangler": ["[email protected]", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.2", "blake3-wasm": "2.1.5", "esbuild": "0.28.2", "miniflare": "5.20261023.2-beta", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20261023.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20261023.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js", "cf-wrangler": "bin/cf-wrangler.js" } }, "sha512-gBKtAg2e0abQDvXPRQu611YMTd/cfAaJTOLAs/89tTxFxEeUyC260MRJRK+m3gLmQjDYWFwJv+ErwuJ/GuALpA=="],++ "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],+"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],"yocto-queue": ["[email protected]", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],+ "youch": ["[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="],++ "youch-core": ["[email protected]", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="],+"zod": ["[email protected]", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="],"zod-validation-error": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ=="],"@babel/core/json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],+ "@cspotcode/source-map-support/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="],+"@eslint-community/eslint-utils/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],"@eslint/eslintrc/globals": ["[email protected]", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],"@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],+ "@poppinss/dumper/supports-color": ["[email protected]", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],+"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],diff --git a/marketing/launch.md b/marketing/launch.mdnew file mode 100644index 0000000..e46b6d6--- /dev/null+++ b/marketing/launch.md@@ -0,0 +1,51 @@+# Launch drafts++Replace `<site>` with the deployed URL. Attach `public/og.png`, or better, one of the comparison recordings (`public/media/hover-issuing-*.mp4` side by side, or the README's animated webps).++## X / Threads / Bluesky++**Single post**++> I made a Claude Code skill that clones animations frame by frame, then proves the copy moves the same.+>+> It rebuilt three cards from the stripe.com homepage, WebGL included, and measured every one against the original: timing within 43 ms, tilt within 0.4 px.+>+> npx skills add NiazMorshed2007/motion-clone+> <site>++**Thread**++1. I made a Claude Code skill that clones animations frame by frame, then proves the copy moves the same. Here it is rebuilding three cards from stripe.com 👇 [video: entrance, stripe.com vs clone]+2. Copying motion by eye always ends the same way: looks right in a screenshot, feels off in motion. The easing is sharper, something starts a beat late. motion-clone measures instead: it records the reference, writes every timing and easing down, builds, records the copy the same way and compares.+3. The loop doesn't end until the numbers agree: timing error, pixel mismatch, easing fit, side-by-side sheets. If a row still fails after 5 rounds it says so, with the numbers. [image: comparison sheet]+4. Works from a live URL, a screen recording, an mp4 or a gif. Say "match it exactly" for pixel-level, or "clone X and add Y" to mix in your own parts. It writes in whatever your project already uses.+5. Install: npx skills add NiazMorshed2007/motion-clone. Live demos (the clones run in the page, hover them): <site>+++> Animations are the hardest part of a UI to copy well. A screenshot can match while the motion feels wrong, and nobody can say why.+>+> I built motion-clone, a skill for Claude Code that treats an animation as something to measure. It records the reference (a live site, a video, a gif), reads it frame by frame, rebuilds it in your codebase, then records the copy the same way and compares the two until timing, easing and layout agree.+>+> To test it, I had it rebuild three cards from the stripe.com homepage, including two three.js scenes. Every card came back with numbers: chat timing within 43 ms of the original, the card tilt within 0.4 px, the globe's pose exact.+>+> Open source, MIT: <site>++## Show HN++**Title:** Show HN: motion-clone – a Claude Code skill that clones animations and verifies them frame by frame++**First comment:**++> Hi HN. motion-clone is a skill (a folder of instructions and scripts) for Claude Code. You point it at an animation on a site, in a video or in a gif, and it records it with Playwright, writes a spec (one row per element per property: start, duration, easing), rebuilds it in your stack, then records the clone with the same command and compares: timing error, pixel mismatch per frame, easing curve fits, and side-by-side sheets. It iterates until the rows pass, and reports any that don't after five rounds.+>+> The demo page has three cards from stripe.com rebuilt by it, running live, next to recordings of the originals. Two of them are three.js scenes, so it had to recover shaders and timings from the page's scripts rather than from CSS.+>+> Limits: WebGL is compared as pixels, random content is judged against two recordings of the reference, and headless WebGL frame pacing differs from a real screen. Install with `npx skills add NiazMorshed2007/motion-clone`.++## Where to post++- skills.sh lists skills automatically from installs through the skills CLI; nothing to submit.+- r/ClaudeAI and r/ClaudeCode: the thread text, with the entrance video.+- awesome-claude-code style lists on GitHub: open a PR adding the repo under Skills.+- Hacker News (Show HN) on a weekday morning US time.diff --git a/next.config.ts b/next.config.tsindex a0cf0c7..fa5a40d 100644--- a/next.config.ts+++ b/next.config.ts@@ -1,9 +1,10 @@import type { NextConfig } from "next";+// Static export: the whole site is prebuilt HTML/CSS/JS, served by Cloudflare Workers static assets.const nextConfig: NextConfig = {- /* config options here */- cacheComponents: true,- partialPrefetching: true,+ output: "export",+ trailingSlash: true,+ images: { unoptimized: true },turbopack: {rules: {"*.css": {diff --git a/package.json b/package.jsonindex a249a9a..640a52f 100644--- a/package.json+++ b/package.json@@ -3,17 +3,23 @@"version": "0.1.0","private": true,"scripts": {+ "vendor": "node scripts/vendor-examples.mjs",+ "predev": "node scripts/vendor-examples.mjs","dev": "next dev",+ "prebuild": "node scripts/vendor-examples.mjs","build": "next build",- "start": "next start",+ "preview": "bun run build && wrangler dev",+ "deploy": "bun run build && wrangler deploy","lint": "eslint"},"dependencies": {"next": "16.4.3","react": "19.3.0",- "react-dom": "19.3.0"+ "react-dom": "19.3.0",+ "three": "0.178.0"},"devDependencies": {+ "@fontsource-variable/inter": "^5.3.0","@tailwindcss/turbopack": "^4","@types/node": "^20","@types/react": "^19",@@ -21,7 +27,8 @@"eslint": "^9","eslint-config-next": "16.4.3","tailwindcss": "^4",- "typescript": "^5"+ "typescript": "^5",+ "wrangler": "^4.155.0"},"packageManager": "[email protected]","ignoreScripts": [@@ -29,7 +36,9 @@"unrs-resolver"],"trustedDependencies": [+ "esbuild","sharp",- "unrs-resolver"+ "unrs-resolver",+ "workerd"]}diff --git a/public/examples/stripe-bento/assets/img/agentic-particles.webp b/public/examples/stripe-bento/assets/img/agentic-particles.webpnew file mode 100644index 0000000..8ec50d4Binary files /dev/null and b/public/examples/stripe-bento/assets/img/agentic-particles.webp differdiff --git a/public/examples/stripe-bento/assets/img/hoodie-navy-160.webp b/public/examples/stripe-bento/assets/img/hoodie-navy-160.webpnew file mode 100644index 0000000..fa67905Binary files /dev/null and b/public/examples/stripe-bento/assets/img/hoodie-navy-160.webp differdiff --git a/public/examples/stripe-bento/assets/img/hoodie-navy-320.webp b/public/examples/stripe-bento/assets/img/hoodie-navy-320.webpnew file mode 100644index 0000000..9963a55Binary files /dev/null and b/public/examples/stripe-bento/assets/img/hoodie-navy-320.webp differdiff --git a/public/examples/stripe-bento/assets/img/hoodie-navy.png b/public/examples/stripe-bento/assets/img/hoodie-navy.pngnew file mode 100644index 0000000..ddbc887Binary files /dev/null and b/public/examples/stripe-bento/assets/img/hoodie-navy.png differdiff --git a/public/examples/stripe-bento/assets/img/issuing-card-placeholder.webp b/public/examples/stripe-bento/assets/img/issuing-card-placeholder.webpnew file mode 100644index 0000000..813307cBinary files /dev/null and b/public/examples/stripe-bento/assets/img/issuing-card-placeholder.webp differdiff --git a/public/examples/stripe-bento/assets/img/issuing-palette.webp b/public/examples/stripe-bento/assets/img/issuing-palette.webpnew file mode 100644index 0000000..a55f440Binary files /dev/null and b/public/examples/stripe-bento/assets/img/issuing-palette.webp differdiff --git a/public/examples/stripe-bento/assets/img/issuing_card_bg.png b/public/examples/stripe-bento/assets/img/issuing_card_bg.pngnew file mode 100644index 0000000..4293c5aBinary files /dev/null and b/public/examples/stripe-bento/assets/img/issuing_card_bg.png differdiff --git a/public/examples/stripe-bento/assets/img/issuing_card_bg.webp b/public/examples/stripe-bento/assets/img/issuing_card_bg.webpnew file mode 100644index 0000000..002bc90Binary files /dev/null and b/public/examples/stripe-bento/assets/img/issuing_card_bg.webp differdiff --git a/public/examples/stripe-bento/assets/img/issuing_card_fg.png b/public/examples/stripe-bento/assets/img/issuing_card_fg.pngnew file mode 100644index 0000000..a6d8950Binary files /dev/null and b/public/examples/stripe-bento/assets/img/issuing_card_fg.png differdiff --git a/public/examples/stripe-bento/assets/img/issuing_card_fg.webp b/public/examples/stripe-bento/assets/img/issuing_card_fg.webpnew file mode 100644index 0000000..4537d35Binary files /dev/null and b/public/examples/stripe-bento/assets/img/issuing_card_fg.webp differdiff --git a/public/examples/stripe-bento/assets/img/map-dots.png b/public/examples/stripe-bento/assets/img/map-dots.pngnew file mode 100644index 0000000..aaa0f17Binary files /dev/null and b/public/examples/stripe-bento/assets/img/map-dots.png differdiff --git a/public/examples/stripe-bento/assets/img/money-movement-fallback_2x.png b/public/examples/stripe-bento/assets/img/money-movement-fallback_2x.pngnew file mode 100644index 0000000..ba971e5Binary files /dev/null and b/public/examples/stripe-bento/assets/img/money-movement-fallback_2x.png differdiff --git a/public/examples/stripe-bento/assets/img/point_spritesheet.png b/public/examples/stripe-bento/assets/img/point_spritesheet.pngnew file mode 100644index 0000000..bb4e719Binary files /dev/null and b/public/examples/stripe-bento/assets/img/point_spritesheet.png differdiff --git a/public/examples/stripe-bento/assets/img/point_spritesheet.webp b/public/examples/stripe-bento/assets/img/point_spritesheet.webpnew file mode 100644index 0000000..0f89f3dBinary files /dev/null and b/public/examples/stripe-bento/assets/img/point_spritesheet.webp differdiff --git a/public/examples/stripe-bento/assets/img/shirt-blue-160.webp b/public/examples/stripe-bento/assets/img/shirt-blue-160.webpnew file mode 100644index 0000000..c976c0fBinary files /dev/null and b/public/examples/stripe-bento/assets/img/shirt-blue-160.webp differdiff --git a/public/examples/stripe-bento/assets/img/shirt-blue-320.webp b/public/examples/stripe-bento/assets/img/shirt-blue-320.webpnew file mode 100644index 0000000..3cf9cbcBinary files /dev/null and b/public/examples/stripe-bento/assets/img/shirt-blue-320.webp differdiff --git a/public/examples/stripe-bento/assets/img/shirt-blue.png b/public/examples/stripe-bento/assets/img/shirt-blue.pngnew file mode 100644index 0000000..a325a8eBinary files /dev/null and b/public/examples/stripe-bento/assets/img/shirt-blue.png differdiff --git a/public/examples/stripe-bento/index.html b/public/examples/stripe-bento/index.htmlnew file mode 100644index 0000000..282a518--- /dev/null+++ b/public/examples/stripe-bento/index.html@@ -0,0 +1,115 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>stripe.com bento cards, rebuilt with motion-clone</title>+ <meta name="robots" content="noindex">+ <script type="importmap">+ { "imports": { "three": "./vendor/three/three.module.js", "three/addons/": "./vendor/three/addons/" } }+ </script>+ <link rel="stylesheet" href="./src/bento.css">+ <link rel="stylesheet" href="./src/widgets/agentic-commerce.css">+ <link rel="stylesheet" href="./src/widgets/issuing.css">+ <link rel="stylesheet" href="./src/widgets/crypto.css">+ <script>+ // ?card=agentic-commerce|issuing|crypto shows a single card+ const card = new URLSearchParams(location.search).get("card");+ if (card) document.documentElement.dataset.card = card;+ </script>+ <script type="module" src="./src/bento.js"></script>+</head>+<body>++ <section class="modular-solutions-bento">+ <div class="modular-solutions-bento__layout">+ <button type="button" class="modular-solutions-bento-card modular-solutions-bento__card-agentic-commerce"+ data-bento-card-root data-widget="agentic-commerce"+ aria-labelledby="bento-card-title-agentic-commerce">+ <div class="modular-solutions-bento-card__dialog-entry">+ <div class="modular-solutions-bento-card__dialog-entry-wrapper">+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">+ <path d="M13.75 6.75L10.25 6.75L10.25 5L15.5 5L15.5 10.25L13.75 10.25L13.75 6.75Z"/>+ <path d="M6.75 10.25L5 10.25L5 15.5L10.25 15.5L10.25 13.75L6.75 13.75L6.75 10.25Z"/>+ </svg>+ </div>+ </div>+ <div class="modular-solutions-bento-card__text">+ <h3 class="modular-solutions-bento-card__title" id="bento-card-title-agentic-commerce">Monetize through agentic commerce</h3>+ </div>+ <div class="modular-solutions-bento-card__border">+ <div class="modular-solutions-bento-card__border-color"><div class="modular-solutions-bento-card__border-color-gradient"></div></div>+ </div>+ <div class="modular-solutions-bento-card__inner">+ <div class="modular-solutions-bento-card__content">+ <div class="modular-solutions-bento-card__content-inner">+ <div class="modular-solutions-bento-card__graphic">+ <div class="lazy-animation lazy-bento-graphic" data-slot="graphic"></div>+ </div>+ <div class="modular-solutions-bento-card__background">+ <div class="lazy-animation lazy-bento-graphic" data-slot="background"></div>+ </div>+ </div>+ </div>+ </div>+ </button>++ <button type="button" class="modular-solutions-bento-card modular-solutions-bento__card-issuing"+ data-bento-card-root data-widget="issuing"+ aria-labelledby="bento-card-title-issuing">+ <div class="modular-solutions-bento-card__dialog-entry">+ <div class="modular-solutions-bento-card__dialog-entry-wrapper">+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">+ <path d="M13.75 6.75L10.25 6.75L10.25 5L15.5 5L15.5 10.25L13.75 10.25L13.75 6.75Z"/>+ <path d="M6.75 10.25L5 10.25L5 15.5L10.25 15.5L10.25 13.75L6.75 13.75L6.75 10.25Z"/>+ </svg>+ </div>+ </div>+ <div class="modular-solutions-bento-card__text">+ <h3 class="modular-solutions-bento-card__title" id="bento-card-title-issuing">Create a card issuing program</h3>+ </div>+ <div class="modular-solutions-bento-card__border">+ <div class="modular-solutions-bento-card__border-color"><div class="modular-solutions-bento-card__border-color-gradient"></div></div>+ </div>+ <div class="modular-solutions-bento-card__inner">+ <div class="modular-solutions-bento-card__content">+ <div class="modular-solutions-bento-card__content-inner">+ <div class="modular-solutions-bento-card__background">+ <div class="lazy-animation lazy-bento-graphic" data-slot="background"></div>+ </div>+ </div>+ </div>+ </div>+ </button>++ <button type="button" class="modular-solutions-bento-card modular-solutions-bento__card-crypto"+ data-bento-card-root data-widget="crypto"+ aria-labelledby="bento-card-title-crypto">+ <div class="modular-solutions-bento-card__dialog-entry">+ <div class="modular-solutions-bento-card__dialog-entry-wrapper">+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">+ <path d="M13.75 6.75L10.25 6.75L10.25 5L15.5 5L15.5 10.25L13.75 10.25L13.75 6.75Z"/>+ <path d="M6.75 10.25L5 10.25L5 15.5L10.25 15.5L10.25 13.75L6.75 13.75L6.75 10.25Z"/>+ </svg>+ </div>+ </div>+ <div class="modular-solutions-bento-card__text">+ <h3 class="modular-solutions-bento-card__title" id="bento-card-title-crypto">Access borderless money movement with stablecoins and crypto</h3>+ </div>+ <div class="modular-solutions-bento-card__border">+ <div class="modular-solutions-bento-card__border-color"><div class="modular-solutions-bento-card__border-color-gradient"></div></div>+ </div>+ <div class="modular-solutions-bento-card__inner">+ <div class="modular-solutions-bento-card__content">+ <div class="modular-solutions-bento-card__content-inner">+ <div class="modular-solutions-bento-card__background">+ <div class="lazy-animation lazy-bento-graphic" data-slot="background"></div>+ </div>+ </div>+ </div>+ </div>+ </button>+ </div>+ </section>+</body>+</html>diff --git a/public/examples/stripe-bento/src/bento.css b/public/examples/stripe-bento/src/bento.cssnew file mode 100644index 0000000..98db306--- /dev/null+++ b/public/examples/stripe-bento/src/bento.css@@ -0,0 +1,311 @@+/* Bento card shell: frame, border glow, expand button, hover growth, lazy fade-in.+ Values are stripe.com's resolved design tokens at the desktop breakpoint. */++/* stripe.com uses its licensed Söhne; this public build uses Inter (SIL OFL) instead. */+@font-face {+ font-family: "Inter Variable";+ src: url(../vendor/fonts/inter-latin-wght-normal.woff2) format("woff2-variations");+ font-weight: 100 900;+ font-display: block;+}++:root {+ --color-brand-25: #f5f5ff;+ --color-brand-400: #7f7dfc;+ --color-brand-600: #533afd;+ --color-magenta-350: #f44bcc;+ --color-neutral-0: #fff;+ --color-neutral-50: #e5edf5;+ --color-heading: #061b31;+ --focus-outline: 3px solid #5452fbbf;+}++*, *::before, *::after { box-sizing: border-box; }++html, body {+ margin: 0;+ background: #fff;+ font-family: "Inter Variable", "SF Pro Display", sans-serif;+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ color: var(--color-heading);+}++/* Embedded on the motion-clone site: room for the 6px hover growth, and ?card=<name> shows one card. */+body { padding: 18px 0; overflow: hidden; }+html[data-card] .modular-solutions-bento__layout { justify-content: center; }+html[data-card="agentic-commerce"] .modular-solutions-bento-card:not([data-widget="agentic-commerce"]),+html[data-card="issuing"] .modular-solutions-bento-card:not([data-widget="issuing"]),+html[data-card="crypto"] .modular-solutions-bento-card:not([data-widget="crypto"]) { display: none; }++/* stripe.com's page gutter: 16px on phones, 33px from 640px; the bento content caps at 1232px */+.modular-solutions-bento {+ --bento-gutter: 16px;+ position: relative;+ max-width: calc(1232px + 2 * var(--bento-gutter));+ margin: 0 auto;+ padding-inline: var(--bento-gutter);+}+@media (min-width: 640px) {+ .modular-solutions-bento { --bento-gutter: 33px; }+}+.modular-solutions-bento__layout {+ display: flex;+ flex-wrap: wrap;+ gap: 16px;+ width: 100%;+}++/* ---------- card ---------- */++.modular-solutions-bento-card {+ --card-ease: cubic-bezier(0.165, 0.84, 0.44, 1);+ --card-duration: 800ms;+ --card-shift-x: 0;+ --card-shift-y: 0;+ --card-grow-x: 0px;+ --card-grow-y: 0px;+ --card-radius: 6px;+ position: relative;+ display: flex;+ flex: 1;+ flex-basis: 100%;+ max-height: 576px;+ aspect-ratio: 344/504;+ transition: z-index 0.1s step-end;+ cursor: pointer;+ contain: layout style;+ border: none;+ background: none;+ -webkit-appearance: none;+ appearance: none;+ border-radius: 0;+ text-align: inherit;+ padding: 0;+ color: inherit;+ font: inherit;+}+@media (min-width: 640px) {+ /* two per row; on stripe.com the crypto card shares its row with Connect, so cap growth at half */+ .modular-solutions-bento-card { flex-basis: calc(50% - 16px); max-width: calc(50% - 8px); max-height: 100%; }+}+@media (min-width: 940px) {+ .modular-solutions-bento-card {+ aspect-ratio: 400/676;+ max-width: 400px;+ max-height: 676px;+ flex-basis: calc(33.333% - 12px);+ }+ .modular-solutions-bento__card-crypto { flex-basis: calc(33.333% - 8px); }+}++.modular-solutions-bento-card:focus-visible { outline: none; }+.modular-solutions-bento-card:focus-visible .modular-solutions-bento-card__dialog-entry-wrapper {+ outline: var(--focus-outline);+ border-radius: 4px;+ outline-offset: 1px;+}+.modular-solutions-bento-card img,+.modular-solutions-bento-card svg { pointer-events: none; }++.modular-solutions-bento-card__inner {+ pointer-events: none;+ position: absolute;+ inset: 0;+ z-index: 2;+ border-radius: calc(var(--card-radius) - 1px);+ background: #fff;+}+.modular-solutions-bento-card__content {+ position: absolute;+ z-index: 2;+ inset: 0;+ border-radius: calc(var(--card-radius) - 1px);+ overflow: hidden;+}+.modular-solutions-bento-card__content-inner { width: 100%; height: 100%; }+.modular-solutions-bento-card__graphic,+.modular-solutions-bento-card__background { position: absolute; inset: 0; }+.modular-solutions-bento-card__graphic { z-index: 1; }++/* title */+.modular-solutions-bento-card__text {+ pointer-events: none;+ position: absolute;+ z-index: 3;+ top: 16px;+ left: 16px;+ max-width: min((100% - 80px), 21ch);+ font-size: 1.625rem;+}+.modular-solutions-bento-card__title {+ margin: 0;+ font-size: 1.625rem;+ font-weight: 300;+ line-height: 1.12;+ letter-spacing: -0.01em;+ color: var(--color-heading);+ text-wrap: balance;+}+@media (min-width: 640px) {+ .modular-solutions-bento-card__text { max-width: min((100% - 100px), 21ch); }+ .modular-solutions-bento-card__title { font-size: min(1.625rem, 2.75vw); }+}+@media (min-width: 840px) {+ .modular-solutions-bento-card__text { max-width: min((100% - 120px), 21ch); }+ .modular-solutions-bento-card__title { font-size: min(1.625rem, 3.3vw); }+}+@media (min-width: 940px) {+ .modular-solutions-bento-card__text { max-width: 21ch; padding-right: 60px; top: 24px; left: 24px; }+ .modular-solutions-bento-card__title { font-size: min(1.625rem, 2.1vw); }+}++/* expand button (opens the product dialog on stripe.com) */+.modular-solutions-bento-card__dialog-entry {+ position: absolute;+ right: 16px;+ top: 16px;+ width: 38px;+ height: 38px;+ z-index: 3;+ pointer-events: none;+}+.modular-solutions-bento-card__dialog-entry::before,+.modular-solutions-bento-card__dialog-entry::after {+ content: "";+ position: absolute;+ display: block;+ inset: 0;+ border-radius: 4px;+}+.modular-solutions-bento-card__dialog-entry::before { opacity: 0; background: var(--color-brand-600); }+.modular-solutions-bento-card__dialog-entry::after { background: var(--color-brand-25); }+.modular-solutions-bento-card__dialog-entry-wrapper {+ position: relative;+ z-index: 1;+ width: 100%;+ height: 100%;+ display: flex;+ align-items: center;+ justify-content: center;+ will-change: background-color;+}+.modular-solutions-bento-card__dialog-entry svg path { fill: var(--color-brand-600); }++/* border + pointer-following glow */+.modular-solutions-bento-card__border {+ position: absolute;+ inset: -1px;+ z-index: 1;+ border-radius: var(--card-radius);+ background: var(--color-neutral-50);+ overflow: hidden;+ pointer-events: none;+}+.modular-solutions-bento-card__border-color {+ position: absolute;+ top: 50%;+ left: 50%;+ height: 80%;+ aspect-ratio: 1;+ opacity: 0;+ transform: translate(-50%, -50%);+ display: none;+}+.modular-solutions-bento-card__border-color-gradient {+ position: absolute;+ inset: 0;+ opacity: 0.5;+ background: radial-gradient(circle, var(--color-brand-400), var(--color-magenta-350) 33%, var(--color-neutral-50) 66%);+ transform: translate3d(var(--card-mouse-x, 0), var(--card-mouse-y, 0), 0) scale(var(--border-scale, 1));+}+@media (min-width: 940px) {+ .modular-solutions-bento-card__border-color { display: block; }+}++/* motion */+@media (prefers-reduced-motion: no-preference) {+ .modular-solutions-bento-card__content-inner,+ .modular-solutions-bento-card__title,+ .modular-solutions-bento-card__graphic,+ .modular-solutions-bento-card__dialog-entry {+ transition: transform var(--card-duration) var(--card-ease);+ }+ .modular-solutions-bento-card__dialog-entry::before,+ .modular-solutions-bento-card__dialog-entry::after {+ transition: opacity 0.6s cubic-bezier(0.16, 1, 0.3, 1);+ }+ .modular-solutions-bento-card__dialog-entry svg path {+ transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1);+ }+ .modular-solutions-bento-card__border-color { transition: opacity 0.25s linear; }+ .modular-solutions-bento-card__border-color-gradient {+ transition: transform 1s cubic-bezier(0.16, 1, 0.3, 1);+ will-change: transform;+ }+}++/* Hover growth: inner and border are drawn grown by --card-grow-* and clipped back to+ the card box; hovering animates the clip open so the card grows 12px without layout shift. */+@supports selector(:has(*)) {+ @media (min-width: 940px) {+ .modular-solutions-bento-card__inner {+ inset: calc(-1 * var(--card-grow-y)) calc(-1 * var(--card-grow-x));+ border-radius: 0;+ clip-path: inset(var(--card-grow-y) var(--card-grow-x) round calc(var(--card-radius) - 1px));+ }+ .modular-solutions-bento-card__border {+ inset: calc(-1 * var(--card-grow-y) - 1px) calc(-1 * var(--card-grow-x) - 1px);+ clip-path: inset(var(--card-grow-y) var(--card-grow-x) round var(--card-radius));+ }+ }+ @media (min-width: 940px) and (prefers-reduced-motion: no-preference) {+ .modular-solutions-bento-card__inner,+ .modular-solutions-bento-card__border {+ transition: clip-path var(--card-duration) var(--card-ease);+ }+ }+}++@media (pointer: fine) {+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry svg path { fill: var(--color-neutral-0); }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry svg path:first-child { transform: translate(1px, -1px); }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry svg path:nth-child(2) { transform: translate(-1px, 1px); }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry::before { opacity: 1; }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry::after { opacity: 0; }+}+@media (min-width: 940px) and (pointer: fine) and (prefers-reduced-motion: no-preference) {+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__border-color { opacity: 1; }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry svg path:first-child { transform: translate(2px, -2px); }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry svg path:nth-child(2) { transform: translate(-2px, 2px); }+}+@supports selector(:has(*)) {+ @media (min-width: 940px) and (pointer: fine) and (prefers-reduced-motion: no-preference) {+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__title {+ transform: translate(var(--card-shift-x), var(--card-shift-y));+ }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__dialog-entry {+ transform: translate(calc(var(--card-shift-x) * -1), var(--card-shift-y));+ }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__inner {+ clip-path: inset(0 round calc(var(--card-radius) - 1px));+ }+ .modular-solutions-bento-card:hover .modular-solutions-bento-card__border {+ clip-path: inset(0 round var(--card-radius));+ }+ }+}++/* lazy mount fade */+.lazy-animation {+ opacity: 0;+ transition: opacity 0.5s cubic-bezier(0.33, 1, 0.68, 1);+}+.lazy-animation--loaded { opacity: 1; }+.lazy-bento-graphic {+ display: flex;+ justify-content: flex-end;+ flex-direction: column;+ width: 100%;+ height: 100%;+}diff --git a/public/examples/stripe-bento/src/bento.js b/public/examples/stripe-bento/src/bento.jsnew file mode 100644index 0000000..67356f5--- /dev/null+++ b/public/examples/stripe-bento/src/bento.js@@ -0,0 +1,90 @@+// Bento card shell: hover growth variables, pointer-following border glow, lazy widget mount.+// Each card names its widget in data-widget; src/widgets/<name>.js exports+// mount(container, { card, slot }) where slot is "graphic" (foreground DOM) or "background" (canvas),+// called once per .lazy-animation in the card. It may return a promise that resolves when the+// first frame is ready; the container fades in two frames later.++const EXPAND_AMOUNT = 12; // px the card grows on hover, split over both edges+const LAZY_ROOT_MARGIN = "800px";+const MOUSE_THROTTLE_MS = 50;++function pageRect(el) {+ const r = el.getBoundingClientRect();+ return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height };+}++function debounce(fn, ms) {+ let id;+ return () => {+ clearTimeout(id);+ id = setTimeout(fn, ms);+ };+}++// Where a ray from the card centre towards the pointer leaves the card box.+function edgePoint(dirX, dirY, halfW, halfH) {+ const tx = dirX > 0 ? halfW / dirX : dirX < 0 ? -halfW / dirX : Infinity;+ const ty = dirY > 0 ? halfH / dirY : dirY < 0 ? -halfH / dirY : Infinity;+ const t = Math.min(tx, ty);+ return Number.isFinite(t) ? { x: dirX * t, y: dirY * t } : null;+}++function setupCard(card) {+ const gradient = card.querySelector(".modular-solutions-bento-card__border-color-gradient");+ let rect = pageRect(card);++ const measure = () => {+ rect = pageRect(card);+ const growY = EXPAND_AMOUNT / 2;+ const growX = (rect.width / rect.height) * growY;+ card.style.setProperty("--card-shift-x", `${-growX}px`);+ card.style.setProperty("--card-shift-y", `${-growY}px`);+ card.style.setProperty("--card-grow-x", `${growX}px`);+ card.style.setProperty("--card-grow-y", `${growY}px`);+ };+ measure();+ new ResizeObserver(debounce(measure, 300)).observe(document.body);++ if (!matchMedia("(min-width: 940px)").matches) return;+ let last = 0;+ card.addEventListener(+ "mousemove",+ (e) => {+ const now = performance.now();+ if (now - last < MOUSE_THROTTLE_MS) return;+ last = now;+ const dx = e.pageX - (rect.x + rect.width / 2);+ const dy = e.pageY - (rect.y + rect.height / 2);+ const len = Math.hypot(dx, dy);+ if (!len) return;+ const p = edgePoint(dx / len, dy / len, rect.width / 2, rect.height / 2);+ if (!p) return;+ gradient.style.setProperty("--card-mouse-x", `${p.x}px`);+ gradient.style.setProperty("--card-mouse-y", `${p.y}px`);+ },+ { passive: true },+ );+}++function setupLazy(card) {+ const name = card.dataset.widget;+ if (!name) return;+ for (const container of card.querySelectorAll(".lazy-animation")) {+ const io = new IntersectionObserver(+ async (entries) => {+ if (!entries.some((e) => e.isIntersecting)) return;+ io.disconnect();+ const mod = await import(`./widgets/${name}.js`);+ await mod.mount(container, { card, slot: container.dataset.slot });+ requestAnimationFrame(() => requestAnimationFrame(() => container.classList.add("lazy-animation--loaded")));+ },+ { rootMargin: LAZY_ROOT_MARGIN },+ );+ io.observe(container);+ }+}++for (const card of document.querySelectorAll("[data-bento-card-root]")) {+ setupCard(card);+ setupLazy(card);+}diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce.css b/public/examples/stripe-bento/src/widgets/agentic-commerce.cssnew file mode 100644index 0000000..b06127a--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce.css@@ -0,0 +1,240 @@+/* "Monetize through agentic commerce" card: chat graphic + particle ring background.+ Values are stripe.com's resolved design tokens at the desktop breakpoint. */++.modular-solutions-bento__card-agentic-commerce {+ --agentic-font-weight-normal: 300;+ --agentic-font-weight-bold: 400;+ --agentic-radius: 6px;+ --agentic-stroke: rgba(229, 237, 245, 0.5);+ --agentic-neutral-25: #f8fafd;+ --agentic-neutral-600: #50617a;+ --agentic-border-quiet: #e5edf5;+}++/* ---------- chat graphic ---------- */++.agentic-commerce-graphic__wrapper {+ position: absolute;+ inset: 12vw 0 0 0;+ display: flex;+ align-items: center;+ justify-content: center;+ opacity: 0;+ /* inherited text defaults inside the graphic on stripe.com */+ color: #000;+ font-family: "Inter Variable", "SF Pro Display", sans-serif;+ font-size: 16px;+ font-weight: 400;+ line-height: normal;+}+@media (min-width: 640px) {+ .agentic-commerce-graphic__wrapper { top: 6vw; }+}+@media (min-width: 940px) {+ .agentic-commerce-graphic__wrapper { top: min(6vw, 60px); }+}+.agentic-commerce-graphic__wrapper--showing { opacity: 1; }++/* DomGraphic: fixed design size, scaled to fit. Low specificity (Stripe keeps these in a base layer),+ so the graphic's own width below wins. */+:where(.agentic-commerce-graphic__wrapper) .dom-graphic {+ --graphic-source-width: 0;+ --graphic-source-height: 0;+ --graphic-aspect-ratio: 1/1;+ --graphic-scale: 1;+ --graphic-max-width: 100%;+ position: relative;+ width: 100%;+ max-width: var(--graphic-max-width);+ margin: 0 auto;+ -webkit-user-select: none;+ user-select: none;+ aspect-ratio: var(--graphic-aspect-ratio);+}+:where(.agentic-commerce-graphic__wrapper) .dom-graphic__content {+ --horizontal-scale-left: 0;+ --horizontal-transform: 0;+ position: absolute;+ top: 0;+ left: var(--horizontal-scale-left);+ width: var(--graphic-source-width);+ height: var(--graphic-source-height);+ transform: scale(var(--graphic-scale)) translateX(var(--horizontal-transform));+ transform-origin: top left;+}++.agentic-commerce-graphic {+ --agentic-box-shadow: 0 20.187px 40.374px -20.187px rgba(0, 0, 0, 0.1);+ width: 82%;+}+.agentic-commerce-graphic__layout {+ display: flex;+ flex-direction: column;+ padding: 0 24px;+ gap: 16px;+}+.agentic-commerce-graphic__chat {+ display: flex;+ flex-direction: column;+ gap: 24px;+}+.agentic-commerce-graphic__chat-bubble {+ background: #fff;+ border-radius: var(--agentic-radius);+ outline: 1px solid var(--agentic-stroke);+ box-shadow: var(--agentic-box-shadow);+ font-family: "Inter Variable", "SF Pro Display", sans-serif;+ font-size: 11px;+ font-weight: var(--agentic-font-weight-normal);+ line-height: 1.4;+ padding: 7px 15px;+}+.agentic-commerce-graphic__chat-bubble--user {+ align-self: flex-end;+ background: var(--agentic-neutral-25);+ max-width: 230px;+}+.agentic-commerce-graphic__chat-bubble--agent { max-width: 250px; }++.agentic-commerce-graphic__products {+ background: #fff;+ border-radius: var(--agentic-radius);+ box-shadow: var(--agentic-box-shadow);+ outline: 1px solid var(--agentic-stroke);+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 8px;+}+.agentic-commerce-graphic__products-grid {+ display: grid;+ grid-column-gap: 10px;+ grid-row-gap: 0;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-template-rows: repeat(4, auto);+ position: relative;+ padding: 1px;+}+.agentic-commerce-graphic__product-cards__layout {+ position: absolute;+ inset: 0;+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-template-rows: 1fr;+ grid-column-gap: 8px;+}+.agentic-commerce-graphic__product-card {+ position: relative;+ border-radius: var(--agentic-radius);+ background: var(--agentic-border-quiet);+ overflow: hidden;+}+.agentic-commerce-graphic__product-card::after {+ display: block;+ position: absolute;+ inset: 1px;+ content: "";+ background: #fff;+ border-radius: calc(var(--agentic-radius) - 1px);+}+.agentic-commerce-graphic__product-card:hover::before { opacity: 1; }++.agentic-commerce-graphic__product-image {+ position: relative;+ display: grid;+ place-items: center;+ padding: 10px;+ overflow: hidden;+ pointer-events: none;+ border-top-left-radius: var(--agentic-radius);+ border-top-right-radius: var(--agentic-radius);+ background-color: #ecf0f4;+}+.agentic-commerce-graphic__product-image img {+ display: block;+ aspect-ratio: 1;+ width: 92px;+ max-width: 100%;+ height: auto;+}+.agentic-commerce-graphic__product-brand,+.agentic-commerce-graphic__product-description,+.agentic-commerce-graphic__product-price,+.agentic-commerce-graphic__product-variant {+ position: relative;+ pointer-events: none;+ font-family: "Inter Variable", "SF Pro Display", sans-serif;+ font-size: 9px;+ font-weight: var(--agentic-font-weight-normal);+ line-height: 1;+ padding: 0 8px;+}+.agentic-commerce-graphic__product-price { font-weight: var(--agentic-font-weight-bold); }+.agentic-commerce-graphic__product-brand {+ color: var(--agentic-neutral-600);+ padding-bottom: var(--agentic-radius);+}+.agentic-commerce-graphic__product-description {+ margin-block-start: 10px;+ margin-block-end: 3px;+}+.agentic-commerce-graphic__product-variant { color: var(--agentic-neutral-600); }+.agentic-commerce-graphic__product-price,+.agentic-commerce-graphic__product-variant { margin-bottom: 8px; }+.agentic-commerce-graphic .tabular-nums--tight {+ font-feature-settings: "tnum";+ font-variant-numeric: tabular-nums;+ letter-spacing: -0.03em;+}++.agentic-commerce-graphic__cta {+ background: rgba(40, 99, 177, 0.1);+ border-radius: var(--agentic-radius);+}+.agentic-commerce-graphic__cta:hover { background: rgba(40, 99, 177, 0.125); }+.agentic-commerce-graphic__cta-button {+ color: #2863b1;+ font-family: "Inter Variable", "SF Pro Display", sans-serif;+ font-size: 11px;+ font-weight: var(--agentic-font-weight-bold);+ line-height: 1.4;+ padding: 10px 0 12px;+ text-align: center;+}++/* ---------- particle background ---------- */++.agentic-graphic__background {+ position: absolute;+ inset: -20px;+ background: #fff;+ display: flex;+ align-items: center;+}+.agentic-graphic__background::before {+ display: block;+ content: "";+ position: absolute;+ inset: 0;+ background: radial-gradient(+ circle,+ hsla(24, 92%, 70%, 0) 0,+ rgba(249, 109, 149, 0.075) 45%,+ rgba(153, 61, 240, 0.05) 55%,+ rgba(125, 31, 255, 0) 80%+ );+}+/* The ::before glow is positioned, so it paints over the (unpositioned) canvas, as on stripe.com. */+.agentic-graphic__background-canvas {+ width: 100%;+ height: 100%;+}+.agentic-graphic__background-static {+ position: relative;+ width: 100%;+}+.agentic-graphic__background-static img {+ display: block;+ width: 100%;+ height: auto;+}diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce.js b/public/examples/stripe-bento/src/widgets/agentic-commerce.jsnew file mode 100644index 0000000..b7cf3e3--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce.js@@ -0,0 +1,76 @@+// "Monetize through agentic commerce" bento card: a chat graphic (slot "graphic") over a particle ring+// (slot "background"), both ported from stripe.com. See agentic-commerce/ for the parts.++import { mountChat } from "./agentic-commerce/chat.js";+import { AgenticParticles } from "./agentic-commerce/particles.js";+import { warmUpRenderLoop } from "./agentic-commerce/render-loop.js";+import { gpuSupportsWebGL } from "./agentic-commerce/webgl-support.js";++const FALLBACK_IMAGE = new URL("../../assets/img/agentic-particles.webp", import.meta.url).href;++warmUpRenderLoop();++function background(className, child) {+ const el = document.createElement("div");+ el.className = "agentic-graphic__background";+ const inner = document.createElement(child);+ inner.className = className;+ el.append(inner);+ return el;+}++// Static picture of the ring for GPUs that cannot run the live canvas.+function mountFallback(container) {+ const el = background("agentic-graphic__background-static", "div");+ const img = document.createElement("img");+ Object.assign(img, { src: FALLBACK_IMAGE, width: 1028, height: 1468, alt: "", loading: "lazy" });+ el.firstElementChild.append(img);+ container.replaceChildren(el);+}++function mountParticles(container) {+ if (!gpuSupportsWebGL()) return mountFallback(container);+ const el = background("agentic-graphic__background-canvas", "canvas");+ const canvas = el.firstElementChild;+ canvas.setAttribute("aria-hidden", "true");+ container.append(el);++ let particles;+ try {+ particles = new AgenticParticles(canvas);+ } catch {+ return mountFallback(container);+ }++ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");+ let visible = false;+ const sync = () => {+ particles.paused = !visible || reducedMotion.matches;+ };+ reducedMotion.addEventListener("change", sync);++ // Like stripe.com: the scene starts once 10 % of the ring area is visible, and the ring "thinks"+ // (pulls tight and sweeps) from 1 s to 3 s after that. The container fades in once the sprite sheet+ // is loaded, so the particles fade in with it as they do on stripe.com.+ return new Promise((resolve) => {+ const io = new IntersectionObserver(+ (entries) => {+ const entry = entries[0];+ if (!entry || !entry.isIntersecting || entry.intersectionRatio < 0.1) return;+ io.disconnect();+ visible = true;+ particles.initScene();+ sync();+ particles.think(2000, 1000);+ resolve(particles.ready);+ },+ { threshold: 0.1 },+ );+ io.observe(el);+ });+}++export function mount(container, { slot }) {+ if (slot === "graphic") return mountChat(container);+ if (slot === "background") return mountParticles(container);+}diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce/chat.js b/public/examples/stripe-bento/src/widgets/agentic-commerce/chat.jsnew file mode 100644index 0000000..5a651b9--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce/chat.js@@ -0,0 +1,155 @@+// The chat in the agentic-commerce card, ported from stripe.com (AgenticCommerceGraphic + DomGraphic).+//+// The graphic is laid out at a fixed 324x378 design size and scaled down to its box when narrower.+// When 10 % of it is visible the entrance sequence plays once: the user bubble rises in, the agent+// bubble follows and its words fade in one after another, then the product card rises in.++const IMG = new URL("../../../assets/img/", import.meta.url).href;+const SOURCE_WIDTH = 324;+const SOURCE_HEIGHT = 378;+const RESIZE_THROTTLE_MS = 500;++const USER_MESSAGE = "I’m refreshing my wardrobe. Can you recommend some cozy, comfortable basics in size M?";+const AGENT_MESSAGE = "Absolutely. Here are a few comfy essentials that pair well and could be a good starting point:";+const DESCRIPTION =+ "AI chatbot interface showing a user request to purchase specific items. The chatbot interface offers a “Buy now” option for these selected items.";+const BRAND = "Cartsy";+const PRODUCTS = [+ { description: "Deluxe Shirt", variant: "Blue - Medium", price: "$26.00", image: "shirt-blue" },+ { description: "Essential Hoodie", variant: "Navy - Medium", price: "$48.00", image: "hoodie-navy" },+];++// Easings from stripe.com's easing table and motion's defaults.+const EASE_OUT_QUART = "cubic-bezier(0.165, 0.84, 0.44, 1)";+const EASE_OUT = "cubic-bezier(0, 0, 0.58, 1)"; // motion "easeOut", the default for sequence segments+const RISE_FROM = { opacity: 0, transform: "translateY(20px)" };+const RISE_TO = { opacity: 1, transform: "translateY(0)" };++// Entrance sequence (seconds), as in stripe.com's motion `animate` sequence.+const SEQUENCE = {+ user: { at: 0.25, duration: 0.75 },+ agent: { at: 1.0, duration: 0.35 },+ words: { at: 1.2, duration: 0.1, stagger: 0.06 },+ products: { at: 1.4, duration: 0.5 },+};++const html = String.raw;+const C = "agentic-commerce-graphic";++function template() {+ const words = AGENT_MESSAGE.split(" ").map((word) => html`<span>${word} </span>`).join("");+ const each = (render) => PRODUCTS.map(render).join("");+ return html`+ <div class="${C}__wrapper">+ <div class="dom-graphic dom-graphic--variant-default ${C}" data-status="measuring" role="img" aria-label="${DESCRIPTION}"+ style="--graphic-source-width: ${SOURCE_WIDTH}px; --graphic-source-height: ${SOURCE_HEIGHT}px; --graphic-aspect-ratio: ${SOURCE_WIDTH} / ${SOURCE_HEIGHT}; --graphic-scale: 1; --graphic-max-width: ${SOURCE_WIDTH}px;">+ <div class="dom-graphic__content dom-graphic__content--horizontal-scale-left" aria-hidden="true">+ <div class="${C}__layout">+ <div class="${C}__chat">+ <div class="${C}__chat-bubble ${C}__chat-bubble--user">${USER_MESSAGE}</div>+ <div class="${C}__chat-bubble ${C}__chat-bubble--agent">${words}</div>+ </div>+ <div class="${C}__products">+ <div class="${C}__products-grid">+ <div class="${C}__product-cards__layout">${each(() => html`<div class="${C}__product-card"></div>`)}</div>+ ${each((p) => html`<div class="${C}__product-image"><picture>+ <source type="image/webp" srcset="${IMG}${p.image}-160.webp 1x, ${IMG}${p.image}-320.webp 2x">+ <img loading="lazy" width="320" height="228" alt="" src="${IMG}${p.image}-160.webp">+ </picture></div>`)}+ ${each((p) => html`<div class="${C}__product-description">${p.description}</div>`)}+ ${each((p) => html`<div class="${C}__product-variant">${p.variant}</div>`)}+ ${each((p) => html`<div class="${C}__product-price tabular-nums--tight">${p.price}</div>`)}+ ${each(() => html`<div class="${C}__product-brand">${BRAND}</div>`)}+ </div>+ <div class="${C}__cta"><div class="${C}__cta-button">Buy now</div></div>+ </div>+ </div>+ </div>+ </div>+ </div>`;+}++// DomGraphic: scale the fixed-size content down to the measured width, and report "ready" once measured.+function fitToWidth(graphic) {+ let last = 0;+ let pending = null;+ const apply = () => {+ pending = null;+ last = performance.now();+ const width = Math.round(graphic.getBoundingClientRect().width);+ if (width <= 0) return;+ graphic.style.setProperty("--graphic-scale", String(Math.min(1, width / SOURCE_WIDTH)));+ graphic.dataset.status = "ready";+ };+ apply();+ new ResizeObserver(() => {+ if (pending) return;+ const wait = Math.max(0, RESIZE_THROTTLE_MS - (performance.now() - last));+ pending = setTimeout(apply, wait);+ }).observe(graphic);+}++const reducedMotionQuery = matchMedia("(prefers-reduced-motion: reduce)");++function playEntrance(root) {+ const q = (sel) => root.querySelector(sel);+ const user = q(`.${C}__chat-bubble--user`);+ const agent = q(`.${C}__chat-bubble--agent`);+ const products = q(`.${C}__products`);+ const words = [...agent.children];+ const animations = [];++ // The starting state applies at once (the sequence's zero-length first steps). The timeline starts+ // two frames later, as on stripe.com: motion reads the keyframes in the next frame and its clock+ // starts on the frame after that (measured lag ≈ 50 ms behind the starting state there).+ // The rest state is then set inline (as motion leaves it) and each animation fills backwards, so an+ // element holds its starting state until its own start time.+ const steps = [];+ const run = (el, from, to, { at, duration }, easing) => {+ Object.assign(el.style, from);+ steps.push(() => {+ Object.assign(el.style, to);+ animations.push(el.animate([from, to], { duration: duration * 1000, delay: at * 1000, easing, fill: "backwards" }));+ });+ };+ run(user, RISE_FROM, RISE_TO, SEQUENCE.user, EASE_OUT_QUART);+ run(agent, RISE_FROM, RISE_TO, SEQUENCE.agent, EASE_OUT_QUART);+ run(products, RISE_FROM, RISE_TO, SEQUENCE.products, EASE_OUT_QUART);+ const { at, duration, stagger } = SEQUENCE.words;+ words.forEach((word, i) => run(word, { opacity: 0 }, { opacity: 1 }, { at: at + i * stagger, duration }, EASE_OUT));+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ if (reducedMotionQuery.matches) return finish();+ for (const step of steps) step();+ }),+ );++ // Turning reduced motion on mid-sequence jumps to the end state.+ const finish = () => {+ for (const el of [user, agent, products, ...words]) el.style.cssText = "";+ for (const a of animations) a.cancel();+ reducedMotionQuery.removeEventListener("change", onChange);+ };+ const onChange = () => {+ if (reducedMotionQuery.matches) finish();+ };+ reducedMotionQuery.addEventListener("change", onChange);+}++export function mountChat(container) {+ container.innerHTML = template().trim().replace(/>\s+</g, "><");+ const wrapper = container.firstElementChild;+ fitToWidth(wrapper.querySelector(".dom-graphic"));++ const io = new IntersectionObserver(+ (entries) => {+ const entry = entries[0];+ if (!entry || !entry.isIntersecting || entry.intersectionRatio < 0.1) return;+ io.disconnect();+ wrapper.classList.add(`${C}__wrapper--showing`);+ if (!reducedMotionQuery.matches) playEntrance(wrapper);+ },+ { threshold: 0.1 },+ );+ io.observe(wrapper);+}diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce/particles.js b/public/examples/stripe-bento/src/widgets/agentic-commerce/particles.jsnew file mode 100644index 0000000..8d36605--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce/particles.js@@ -0,0 +1,330 @@+// Particle ring behind the agentic-commerce chat, ported from stripe.com (AgenticGraphicBackground, three r178).+//+// 10 000 point sprites sit on a 180 px circle with random depth. The vertex shader scatters them along+// the radius with simplex noise; `u_scatterPower` sets how tight the ring is (1 = loose cloud, 12 = thin+// ring), a rotating "thinking" vector tightens and ripples the part of the ring it points at, and the+// pointer pulls nearby points back onto the ring. All targets are approached with a first-order lag.++import * as THREE from "three";+import { vertexShader, fragmentShader } from "./shaders.js";+import { createRenderLoop } from "./render-loop.js";+import { createRenderer, webglDisabledByQuery } from "./webgl-support.js";++const SPRITESHEET_URL = new URL("../../../assets/img/point_spritesheet.webp", import.meta.url).href;+const RING_RADIUS = 180;+const RING_DEPTH = 100;+const POINTS_DESKTOP = 10000;+const POINTS_TOUCH = 6000;+const POINT_SIZE_DESKTOP = 6;+const POINT_SIZE_TOUCH = 8;+const FRAME_INTERVAL = 2; // render every other frame+const LAG = 0.002; // per-ms rate towards scatter / mouse-strength / thinking targets+const MOUSE_LAG = 0.004 * 3; // per-ms rate of the pointer position+const THINKING_TURN = -0.1 * 0.06; // radians per ms (clockwise)+const SCATTER_REST = 3;+const SCATTER_THINKING = 12;++const isTouch = () => matchMedia("(pointer: coarse)").matches && "ontouchstart" in window;+// Camera zoom shrinks the ring on narrow canvases; the vertical offset centres it on short ones.+const cameraZoom = (width) => THREE.MathUtils.clamp(width / 400, 0, 1);+const cameraY = (height) => 240 * (1 - THREE.MathUtils.clamp(height / 646, 0, 1));++function pageRect(el) {+ const r = el.getBoundingClientRect();+ if (getComputedStyle(el).position === "fixed") return r;+ return new DOMRect(r.left + scrollX, r.top + scrollY, r.width, r.height);+}++function debounce(fn, ms) {+ let id;+ return (...args) => {+ clearTimeout(id);+ id = setTimeout(() => fn(...args), ms);+ };+}++export class AgenticParticles {+ constructor(canvas) {+ if (webglDisabledByQuery()) throw new Error("WebGL disabled by query param");+ this.canvas = canvas;+ this.canvasRect = new DOMRect();+ this.dpr = Math.min(devicePixelRatio, 2);+ this.bentoCardRoot = canvas.closest("[data-bento-card-root]");++ this.thinkingVector = new THREE.Vector2(1, 0);+ this.thinkingTimeout = undefined;+ this.targetMousePosition = new THREE.Vector3();+ this.currentMousePosition = new THREE.Vector3();+ this.targetScatterPower = 1;+ this.currentScatterPower = 1;+ this.targetMouseStrength = 0;+ this.currentMouseStrength = 0;+ this.targetThinkingStrength = 0;+ this.currentThinkingStrength = 0;++ this.firstDrawTime = null;+ this.lastDrawTime = null;+ this.resumedAtTime = null;+ this.pausedAtTime = null;+ this.pausedTime = 0;+ this.loaded = false;+ this.initialized = false;+ this._paused = true;+ this.renderLoop = null;+ this.resizeObserver = null;+ this.texture = null;+ // settles once the sprite sheet has loaded (or failed) and the points are in the scene+ this.ready = new Promise((resolve) => (this.resolveReady = resolve));++ const { renderer, hasMajorPerformanceCaveat, hasRequiredCapabilities } = createRenderer(THREE, {+ canvas,+ antialias: false,+ alpha: true,+ powerPreference: "high-performance",+ });+ if (!renderer || !hasRequiredCapabilities || hasMajorPerformanceCaveat) {+ renderer?.dispose();+ throw new Error("WebGL disabled based on capabilities check");+ }+ this.renderer = renderer;+ renderer.autoClear = false;+ renderer.autoClearColor = false;+ renderer.autoClearDepth = false;+ renderer.setClearColor(0xffffff, 0);+ renderer.setPixelRatio(this.dpr);++ this.scene = new THREE.Scene();+ this.raycaster = new THREE.Raycaster();+ this.camera = new THREE.OrthographicCamera(0, 0, 0, 0, 1, 10000);+ this.material = new THREE.ShaderMaterial({+ uniforms: {+ u_frame: { value: 0 },+ u_mouse: { value: new THREE.Vector3() },+ u_time: { value: 0 },+ u_pointSize: { value: isTouch() ? POINT_SIZE_TOUCH : POINT_SIZE_DESKTOP },+ u_pixelRatio: { value: this.dpr },+ u_pointSpriteSheet: { value: new THREE.Texture() },+ u_resolution: { value: new THREE.Vector2() },+ u_mousePosition: { value: new THREE.Vector2() },+ u_mouseStrength: { value: 0 },+ u_thinkingVector: { value: new THREE.Vector2() },+ u_thinkingStrength: { value: 0 },+ u_scatterPower: { value: 3 },+ },+ vertexShader,+ fragmentShader,+ transparent: true,+ depthTest: false,+ depthWrite: false,+ });+ }++ get paused() {+ return this._paused;+ }++ set paused(value) {+ if (value) {+ this.resumedAtTime = null;+ this.pausedAtTime = this.lastDrawTime;+ this.lastDrawTime = null;+ }+ this._paused = value;+ }++ initScene() {+ if (this.initialized) return;+ this.initialized = true;+ this.canvasRect = pageRect(this.canvas);+ const size = new THREE.Vector2(this.canvasRect.width, this.canvasRect.height);+ this.renderer.setSize(size.x, size.y, false);+ this.camera.position.set(0, cameraY(size.y), 5000);+ this.sizeCamera(size);+ this.material.uniforms.u_resolution.value = size.clone().multiplyScalar(this.dpr);++ // Invisible plane the pointer ray hits, in the same units as the ring (1 unit = 1 CSS px at zoom 1).+ this.mousePlane = new THREE.Mesh(+ new THREE.PlaneGeometry(size.x, size.y),+ new THREE.MeshBasicMaterial({ color: 0xfff0000, side: THREE.DoubleSide, transparent: true, opacity: 0.1 }),+ );+ this.mousePlane.visible = false;+ this.scene.add(this.mousePlane);++ new THREE.TextureLoader().load(+ SPRITESHEET_URL,+ (texture) => {+ texture.wrapS = THREE.RepeatWrapping;+ texture.wrapT = THREE.RepeatWrapping;+ this.texture = texture;+ this.onLoad();+ },+ undefined,+ () => this.onLoad(),+ );+ }++ createPoints() {+ const count = isTouch() ? POINTS_TOUCH : POINTS_DESKTOP;+ const positions = [];+ const spriteUvs = [];+ for (let i = 0; i < count; i += 1) {+ const angle = Math.random() * Math.PI * 2;+ positions.push(RING_RADIUS * Math.cos(angle), RING_RADIUS * Math.sin(angle), THREE.MathUtils.randFloat(-RING_DEPTH, RING_DEPTH));+ // one of the 4x4 dots in the sprite sheet+ spriteUvs.push(0.25 * THREE.MathUtils.randInt(0, 3), 0.25 * THREE.MathUtils.randInt(0, 3));+ }+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));+ geometry.setAttribute("pointSpriteUv", new THREE.Float32BufferAttribute(spriteUvs, 2));+ return geometry;+ }++ onLoad() {+ this.resolveReady();+ if (!this.texture || this.disposed) return;+ this.material.uniforms.u_pointSpriteSheet.value = this.texture;+ this.points = new THREE.Points(this.createPoints(), this.material);+ this.scene.add(this.points);+ this.addListeners();+ this.loaded = true;+ this.renderLoop = createRenderLoop(this.updateAndRender, FRAME_INTERVAL);+ this.renderLoop.onRenderSuspended = () => this.stopThinking(true);+ this.renderLoop.start();+ if (this.paused) this.render();+ }++ updateAndRender = (now) => {+ if (this.paused || !this.loaded) return;+ if (this.firstDrawTime === null) this.firstDrawTime = now;+ if (this.resumedAtTime === null) {+ this.resumedAtTime = now;+ if (this.pausedAtTime) {+ this.pausedTime += this.resumedAtTime - this.pausedAtTime;+ this.pausedAtTime = null;+ }+ }+ if (this.lastDrawTime === null) this.lastDrawTime = now;+ const dt = now - this.lastDrawTime;+ const time = now - this.firstDrawTime - this.pausedTime;+ this.lastDrawTime = now;++ const towardMouse = this.targetMousePosition.clone().sub(this.currentMousePosition);+ this.currentMousePosition.add(towardMouse.multiplyScalar(MOUSE_LAG * dt));+ this.currentScatterPower += (this.targetScatterPower - this.currentScatterPower) * dt * LAG;+ this.currentMouseStrength += (this.targetMouseStrength - this.currentMouseStrength) * dt * LAG;+ this.currentThinkingStrength += (this.targetThinkingStrength - this.currentThinkingStrength) * dt * LAG;+ this.thinkingVector.rotateAround(new THREE.Vector2(0, 0), THINKING_TURN * dt);++ const u = this.material.uniforms;+ u.u_thinkingVector.value = this.thinkingVector;+ u.u_thinkingStrength.value = this.currentThinkingStrength;+ u.u_mouseStrength.value = this.currentMouseStrength;+ u.u_time.value = time;+ u.u_mousePosition.value = this.currentMousePosition;+ u.u_scatterPower.value = this.currentScatterPower;+ this.render();+ };++ render() {+ this.renderer.clearDepth();+ this.renderer.clearColor();+ this.renderer.render(this.scene, this.camera);+ }++ // After `delay` ms the ring pulls tight and the thinking sweep starts; `duration` ms later it relaxes.+ think(duration, delay) {+ clearTimeout(this.thinkingTimeout);+ this.thinkingTimeout = setTimeout(() => {+ this.targetScatterPower = SCATTER_THINKING;+ this.targetThinkingStrength = 1;+ this.thinkingTimeout = setTimeout(() => this.stopThinking(), duration);+ }, delay);+ }++ stopThinking(immediately = false) {+ clearTimeout(this.thinkingTimeout);+ this.thinkingTimeout = undefined;+ this.targetScatterPower = SCATTER_REST;+ this.targetThinkingStrength = 0;+ if (immediately) {+ this.targetMousePosition = new THREE.Vector3();+ this.targetMouseStrength = 0;+ this.currentScatterPower = this.targetScatterPower;+ this.currentMousePosition = this.targetMousePosition;+ this.currentMouseStrength = this.targetMouseStrength;+ this.currentThinkingStrength = this.targetThinkingStrength;+ }+ }++ sizeCamera(size) {+ this.camera.left = -size.x / 2;+ this.camera.right = size.x / 2;+ this.camera.top = size.y / 2;+ this.camera.bottom = -size.y / 2;+ this.camera.zoom = cameraZoom(size.x);+ this.camera.updateProjectionMatrix();+ }++ resize = () => {+ this.canvasRect = pageRect(this.canvas);+ const size = new THREE.Vector2(this.canvasRect.width, this.canvasRect.height);+ const current = new THREE.Vector2();+ this.renderer.getSize(current);+ if (size.x === current.x && size.y === current.y) return;+ this.renderer.setSize(size.x, size.y, false);+ this.sizeCamera(size);+ this.camera.position.y = cameraY(size.y);+ this.material.uniforms.u_resolution.value = size.clone().multiplyScalar(this.dpr);+ if (this.paused && this.loaded) this.render();+ };++ debouncedResize = debounce(this.resize, 150);++ onMouseMove = (e) => {+ const left = this.canvasRect.left - scrollX;+ const top = this.canvasRect.top - scrollY;+ const ndc = new THREE.Vector2(((e.clientX - left) / this.canvasRect.width) * 2 - 1, (-(e.clientY - top) / this.canvasRect.height) * 2 + 1);+ this.raycaster.setFromCamera(ndc, this.camera);+ if (!this.mousePlane) return;+ const hit = this.raycaster.intersectObject(this.mousePlane);+ if (hit.length > 0) this.targetMousePosition = hit[0].point.clone();+ };++ onMouseOver = () => {+ this.targetMouseStrength = 1;+ };++ onMouseOut = () => {+ this.targetMouseStrength = 0;+ };++ addListeners() {+ this.resizeObserver = new ResizeObserver(this.debouncedResize);+ this.resizeObserver.observe(document.body);+ const root = this.bentoCardRoot;+ if (!root) return;+ root.addEventListener("mousemove", this.onMouseMove);+ root.addEventListener("mouseout", this.onMouseOut);+ root.addEventListener("mouseover", this.onMouseOver);+ }++ removeListeners() {+ this.resizeObserver?.disconnect();+ const root = this.bentoCardRoot;+ if (!root) return;+ root.removeEventListener("mousemove", this.onMouseMove);+ root.removeEventListener("mouseout", this.onMouseOut);+ root.removeEventListener("mouseover", this.onMouseOver);+ }++ dispose() {+ this.disposed = true;+ this.removeListeners();+ this.renderLoop?.stop();+ this.renderLoop = null;+ clearTimeout(this.thinkingTimeout);+ this.texture?.dispose();+ this.scene.remove(...this.scene.children);+ this.renderer.dispose();+ }+}diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce/render-loop.js b/public/examples/stripe-bento/src/widgets/agentic-commerce/render-loop.jsnew file mode 100644index 0000000..360a51a--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce/render-loop.js@@ -0,0 +1,151 @@+// Shared render loop, ported from stripe.com's WebGL helpers.+//+// One requestAnimationFrame drives every registered loop. The first 12 frames only measure the+// display refresh rate; after that each loop renders on every `frameInterval`-th frame and gets+// the time elapsed since the manager (re)started. Every 24 frames the measured frame rate is checked+// against the refresh rate: more than 10 % slower raises a warning level (up to 3), which makes+// loops skip more frames; getting faster again lowers it. Hidden tabs suspend everything.++const REFRESH_RATES = [240, 160, 144, 120, 60, 30, 24];+const ESTIMATE_FRAMES = 12;+const CHECK_FRAMES = 24;++const mean = (values) => values.reduce((a, b) => a + b) / values.length;+const median = (values) => {+ const sorted = [...values].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+};++class RenderLoopManager {+ static #instance = null;++ static get instance() {+ if (!RenderLoopManager.#instance) RenderLoopManager.#instance = new RenderLoopManager();+ return RenderLoopManager.#instance;+ }++ constructor() {+ this.frameTimes = [];+ this.lastFrameTime = 0;+ this.resumedTime = null;+ this.elapsedTime = 0;+ this.loops = new Set();+ this.warningLevel = 0;+ this.suspended = false;+ this.rafId = null;+ this.estimatedRefreshRate = undefined;+ this.estimatedAt = undefined;+ document.addEventListener("visibilitychange", () => {+ if (document.hidden) this.suspend("visibility");+ else this.resume("visibility");+ });+ this.start();+ }++ start() {+ if (this.rafId || this.suspended) return;+ this.lastFrameTime = performance.now();+ this.resumedTime = null;+ this.rafId = requestAnimationFrame(this.update);+ }++ stop() {+ if (this.rafId) cancelAnimationFrame(this.rafId);+ this.rafId = null;+ }++ suspend(reason) {+ for (const loop of this.loops) loop.onRenderSuspended(reason);+ this.stop();+ }++ resume(reason) {+ this.lastFrameTime = performance.now();+ for (const loop of this.loops) loop.onRenderResumed(reason);+ this.start();+ }++ estimateRefreshRate() {+ if (!this.frameTimes.length) return undefined;+ const fps = 1000 / median(this.frameTimes);+ return REFRESH_RATES.reduce((best, rate) => (Math.abs(rate - fps) < Math.abs(best - fps) ? rate : best));+ }++ update = (now) => {+ this.rafId = requestAnimationFrame(this.update);+ this.frameTimes.push(now - this.lastFrameTime);+ this.lastFrameTime = now;++ if (this.frameTimes.length >= ESTIMATE_FRAMES && !this.estimatedRefreshRate) {+ this.estimatedRefreshRate = this.estimateRefreshRate();+ this.estimatedAt = performance.now();+ this.frameTimes = [];+ return;+ }++ // stripe.com holds every loop until the refresh rate is measured. There the manager is started by+ // the hero long before this card mounts; here it starts with the card, so loops also render while+ // it measures, otherwise the ring would appear 12 frames late.+ if (this.resumedTime === null) this.resumedTime = now - this.elapsedTime;+ this.elapsedTime = Math.max(now - this.resumedTime, 0);+ for (const loop of this.loops) {+ loop.frameCount += 1;+ if (loop.frameCount % loop.frameInterval === 0) loop.renderFunction(this.elapsedTime);+ }+ if (!this.estimatedRefreshRate || !this.estimatedAt) return;++ if (this.frameTimes.length >= CHECK_FRAMES) {+ // Average frame time without the two slowest frames.+ const times = [...this.frameTimes].sort((a, b) => a - b);+ times.splice(-2);+ const fps = 1000 / mean(times);+ const shortfall = this.estimatedRefreshRate - fps;+ if (shortfall > 0.1 * this.estimatedRefreshRate) {+ const level = Math.min(this.warningLevel + 1, 3);+ if (level !== this.warningLevel) {+ this.warningLevel = level;+ for (const loop of this.loops) loop.onPerformanceWarning(level);+ }+ } else if (shortfall < 0 && this.warningLevel > 0) {+ this.warningLevel -= 1;+ for (const loop of this.loops) loop.onPerformanceRecovered(this.warningLevel);+ }+ this.frameTimes = [];+ }+ };+}++class RenderLoop {+ constructor(renderFunction, frameInterval = 1) {+ this.renderFunction = renderFunction;+ this.frameCount = 0;+ this.frameInterval = frameInterval;+ this.initialFrameInterval = frameInterval;+ this.onRenderSuspended = () => {};+ this.onRenderResumed = () => {};+ }++ onPerformanceWarning(level) {+ this.frameInterval = Math.max(level + 1, this.frameInterval);+ }++ onPerformanceRecovered(level) {+ this.frameInterval = Math.max(level + 1, this.initialFrameInterval);+ }++ start() {+ RenderLoopManager.instance.loops.add(this);+ }++ stop() {+ RenderLoopManager.instance.loops.delete(this);+ }+}++export const createRenderLoop = (renderFunction, frameInterval = 1) => new RenderLoop(renderFunction, frameInterval);++// On stripe.com the manager is already running (other WebGL graphics started it long before this+// card mounts), so its refresh-rate measurement is done by the time the particles load. Starting it+// when this module is first imported gives the same head start.+export const warmUpRenderLoop = () => RenderLoopManager.instance;diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce/shaders.js b/public/examples/stripe-bento/src/widgets/agentic-commerce/shaders.jsnew file mode 100644index 0000000..44a1a15--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce/shaders.js@@ -0,0 +1,160 @@+// Particle ring shaders, verbatim from stripe.com (AgenticGraphicBackground, three r178 ShaderMaterial).+// GLSL ES 3.00 features (floatBitsToUint, uint literals) work because three compiles ShaderMaterial+// as "#version 300 es" on WebGL2 and maps attribute/varying/texture2D/gl_FragColor for us.++export const vertexShader = /* glsl */ `attribute vec2 pointSpriteUv;+uniform vec2 u_resolution;+uniform vec2 u_mousePosition;+uniform float u_mouseStrength;+uniform float u_scatterPower;+uniform float u_thinkingStrength;+uniform vec2 u_thinkingVector;+uniform float u_pointSize;+uniform float u_pixelRatio;+uniform float u_time;++varying vec2 v_uv;+varying vec2 v_pointSpriteUv;+varying vec2 v_resolution;+varying float v_time;+varying float v_random;+varying float v_alpha;+varying vec2 v_mousePosition;++const float DESIGN_PIXEL_RATIO = 2.0;++// The origin of these popular glsl functions is a mystery, but it seems they+// were likely derived from a paper titled "On generating random numbers, with+// help of y=[(a+x)sin(bx)] mod 1", W.J.J. Rey, 22nd European Meeting of+// Statisticians and the 7th Vilnius Conference on Probability Theory and+// Mathematical Statistics, August 1998.++// https://stackoverflow.com/questions/12964279/whats-the-origin-of-this-glsl-rand-one-liner++#ifndef STRIPE_RANDOM+#define STRIPE_RANDOM+float random(in float x) {+ return fract(sin(x) * 43758.5453);+}+float random(in vec2 st) {+ return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453);+}+float random(in vec3 pos) {+ return fract(sin(dot(pos.xyz, vec3(70.9898, 78.233, 32.4355))) * 43758.5453123);+}+#endif++// Stefan Gustavson's version;+// https://www.shadertoy.com/view/43tBDr+// https://www.researchgate.net/publication/216813608_Simplex_noise_demystified++// https://xxhash.com/+// https://github.com/Cyan4973/xxHash/blob/dev/LICENSE++#ifndef STRIPE_HASH+#define STRIPE_HASH+float xxhash(vec2 x) {+ uvec2 t = floatBitsToUint(x);+ uint h = 0xc2b2ae3du * t.x + 0x165667b9u;+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;+ h += 0xc2b2ae3du * t.y;+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;+ h ^= h >> 15u;+ h *= 0x85ebca77u;+ h ^= h >> 13u;+ h *= 0xc2b2ae3du;+ h ^= h >> 16u;+ return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;+}++vec2 hash(vec2 x) {+ float k = 6.283185307 * xxhash(x);+ return vec2(cos(k), sin(k));+}+#endif+++#ifndef STRIPE_SIMPLEX_NOISE+#define STRIPE_SIMPLEX_NOISE+float simplexNoise(in vec2 p) {+ const float K1 = 0.366025404; // (sqrt(3)-1)/2;+ const float K2 = 0.211324865; // (3-sqrt(3))/6;++ vec2 i = floor(p + (p.x + p.y) * K1);+ vec2 a = p - i + (i.x + i.y) * K2;+ float m = step(a.y, a.x);+ vec2 o = vec2(m, 1.0 - m);+ vec2 b = a - o + K2;+ vec2 c = a - 1.0 + 2.0 * K2;+ vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);+ vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0))); // changed to h^3 [1]++ return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)+}+#endif+++void main() {+ vec3 pos = position;+ vec3 dir = normalize(-pos);++ v_uv = uv;+ v_pointSpriteUv = pointSpriteUv;+ v_random = random(pos.xy);+ v_alpha = random(pos.yz);+ v_time = u_time;+ v_resolution = u_resolution;+ v_mousePosition = u_mousePosition;++ float speedInner = u_time * 0.00004;+ float speedOuter = u_time * 0.00004;+ float noiseInner = simplexNoise(vec2(pos.x * 0.25 + speedInner, pos.y * 0.25 + speedInner));+ float noiseOuter = simplexNoise(vec2(pos.x * 0.07 + speedOuter, pos.y * 0.07 + speedOuter));++ float thinkingAlignment = dot(vec3(u_thinkingVector, 0.0), normalize(vec3(pos.x, pos.y, 0.0)));+ thinkingAlignment = pow(clamp(thinkingAlignment, 0.0, 1.0), 3.0) * u_thinkingStrength;++ vec4 modelPosition = modelMatrix * vec4(pos, 1.0);+ float mouseDistance = distance(u_mousePosition, modelPosition.xy) / u_resolution.x;+ mouseDistance = smoothstep(0.2, 0.0, mouseDistance);++ pos += dir * noiseInner * 100.0 * pow(v_random, u_scatterPower + (u_scatterPower * thinkingAlignment));+ //pos += dir * noiseInner * 20.0 * mouseDistance * u_mouseStrength;+ pos += dir * noiseInner * 20.0 * thinkingAlignment;+ pos += dir * noiseOuter * 5.0 * thinkingAlignment;+ pos = mix(pos, position, mouseDistance * u_mouseStrength + noiseOuter * 0.5);++ vec4 finalModelPosition = modelMatrix * vec4(pos, 1.0);+ vec4 viewPosition = viewMatrix * finalModelPosition;+ vec4 projectedPosition = projectionMatrix * viewPosition;++ gl_PointSize = (1.0 + u_pointSize * v_random) * (u_pixelRatio / DESIGN_PIXEL_RATIO);+ gl_Position = projectedPosition;+}+`;++export const fragmentShader = /* glsl */ `+uniform sampler2D u_pointSpriteSheet;+varying vec2 v_pointSpriteUv;+varying float v_time;+varying float v_random;+varying float v_alpha;+varying vec2 v_resolution;+varying vec2 v_mousePosition;++#define SPRITE_SIZE 1.0 / 4.0++void main() {+ vec2 pixel = 1.0 / v_resolution;+ vec2 st = gl_FragCoord.xy * pixel;+ vec2 spriteCoord = vec2(v_pointSpriteUv.x + gl_PointCoord.x * SPRITE_SIZE, v_pointSpriteUv.y + gl_PointCoord.y * SPRITE_SIZE);+ vec4 color = texture2D(u_pointSpriteSheet, spriteCoord);++ vec3 colorTop = vec3(1.0, 0.25, 0.41);+ vec3 colorBot = vec3(0.52, 0.21, 0.96);+ color.rgb = mix(colorTop, colorBot, 1.0 - st.y);+ color.a *= pow(v_alpha, 2.0);++ gl_FragColor = color;+}+`;diff --git a/public/examples/stripe-bento/src/widgets/agentic-commerce/webgl-support.js b/public/examples/stripe-bento/src/widgets/agentic-commerce/webgl-support.jsnew file mode 100644index 0000000..39f3e12--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/agentic-commerce/webgl-support.js@@ -0,0 +1,93 @@+// WebGL gating, ported from stripe.com: a GPU blocklist decides whether the live particle canvas is+// mounted at all, and the renderer is then checked for the capabilities the graphics rely on.+// Anything that fails shows the static particle image instead.++const BLOCKLIST = [+ "geforce 320m", "geforce 8600", "geforce 8600m gt", "geforce 8800 gs", "geforce 8800 gt", "geforce 9400",+ "geforce 9400m g", "geforce 9400m", "geforce 9600m gt", "geforce 9600m", "geforce fx go5200", "geforce gt 120",+ "geforce gt 130", "geforce gt 330m", "geforce gtx 285", "google swiftshader", "intel g41", "intel g45",+ "intel gma 4500mhd", "intel gma x3100", "intel hd 3000", "intel q45", "legacy", "mali-2", "mali-3", "mali-4",+ "quadro fx 1500", "quadro fx 4", "quadro fx 5", "radeon hd 2400", "radeon hd 2600", "radeon hd 4670",+ "radeon hd 4850", "radeon hd 4870", "radeon hd 5670", "radeon hd 5750", "radeon hd 6290", "radeon hd 6300",+ "radeon hd 6310", "radeon hd 6320", "radeon hd 6490m", "radeon hd 6630m", "radeon hd 6750m", "radeon hd 6770m",+ "radeon hd 6970m", "sgx 543", "sgx543",+];+const LOW_END_APPLE = ["a7", "a8", "a9", "a10"];+const LOW_END_ADRENO = [205, 220, 225, 302, 303, 304, 305, 306, 308, 320, 330, 405, 418, 420, 430, 505, 506];+const LOW_END_MALI = [/mali-[234]/i, /mali-t[67]\d{2}/i, /mali-t8[0-6]\d/i, /mali-g3[01]/i, /mali-g5[01]/i];++const REQUIRED_EXTENSIONS = ["EXT_color_buffer_float", "EXT_texture_filter_anisotropic", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders"];++function device() {+ const { userAgent, platform, maxTouchPoints } = navigator;+ const isIos = /(iphone|ipod|ipad)/i.test(userAgent);+ const isIpad = platform === "iPad" || (platform === "MacIntel" && maxTouchPoints > 0 && !("MSStream" in window));+ return { isMobile: /android/i.test(userAgent) || isIos || isIpad, isSafari12: /Version\/12.+Safari/.test(userAgent) };+}++function rendererName(gl) {+ const info = gl.getExtension("WEBGL_debug_renderer_info");+ let name = (info && gl.getParameter(info.UNMASKED_RENDERER_WEBGL)) || "";+ if (!name) name = gl.getParameter(gl.RENDERER) || "";+ return name+ .toLowerCase()+ .replace(/.*angle ?\((.+)\)(?: on vulkan [0-9.]+)?$/i, "$1")+ .replace(/\s(\d{1,2}gb|direct3d.+$)|\(r\)| \([^)]+\)$/g, "")+ .replace(/(?:vulkan|opengl) \d+\.\d+(?:\.\d+)?(?: \((.*)\))?/, "$1")+ .replace(/angle metal renderer: apple (m\d+(?:\s+(?:pro|max|ultra))?)/i, "apple $1");+}++let cached = null;++// true when the GPU is good enough for the live canvas (stripe.com's `supportsWebGL`).+export function gpuSupportsWebGL() {+ if (cached !== null) return cached;+ const { isMobile, isSafari12 } = device();+ const attrs = { alpha: false, antialias: false, depth: false, failIfMajorPerformanceCaveat: true, stencil: false };+ if (!isSafari12) attrs.powerPreference = "high-performance";+ const canvas = document.createElement("canvas");+ const gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);+ if (!gl) return (cached = false);++ const gpu = rendererName(gl);+ const chip = gpu.match(/apple (a\d+|m\d+(?:\s+(?:pro|max|ultra))?)/i)?.[1]?.toLowerCase();+ const adreno = Number(gpu.match(/adreno[- ]?(\d+)/i)?.[1] ?? 0);+ const blocked =+ BLOCKLIST.some((entry) => gpu.includes(entry)) ||+ (isMobile && chip && LOW_END_APPLE.some((a) => chip.startsWith(a))) ||+ LOW_END_ADRENO.includes(adreno) ||+ LOW_END_MALI.some((re) => re.test(gpu)) ||+ /powervr\s*(sgx|series\s*[456])/i.test(gpu) ||+ /intel.*(gma|g4[15]|q45|hd 3000|hd graphics 3000)/i.test(gpu) ||+ /geforce.*(8\d{3}|9\d{3}|gt\s*[123]\d{2})/i.test(gpu) ||+ /radeon.*(hd\s*[2-5]\d{3})/i.test(gpu);+ return (cached = !blocked);+}++// Creates a WebGLRenderer, first refusing software rendering, then accepting it so the caller can decide.+export function createRenderer(THREE, params) {+ let renderer = null;+ let hasMajorPerformanceCaveat = false;+ try {+ renderer = new THREE.WebGLRenderer({ ...params, failIfMajorPerformanceCaveat: true });+ } catch {+ hasMajorPerformanceCaveat = true;+ }+ if (!renderer) {+ try {+ renderer = new THREE.WebGLRenderer({ ...params, failIfMajorPerformanceCaveat: false });+ } catch {+ // no WebGL at all+ }+ }+ let hasRequiredCapabilities = false;+ if (renderer) {+ const { capabilities: c, extensions } = renderer;+ hasRequiredCapabilities =+ c.isWebGL2 && c.vertexTextures && c.maxTextureSize >= 4096 && c.maxVertexUniforms >= 256 && c.maxFragmentUniforms >= 256 &&+ REQUIRED_EXTENSIONS.every((name) => extensions.get(name) !== null);+ }+ return { renderer, hasMajorPerformanceCaveat, hasRequiredCapabilities };+}++export const webglDisabledByQuery = () => new URLSearchParams(location.search).has("__disableWebGL");diff --git a/public/examples/stripe-bento/src/widgets/crypto.css b/public/examples/stripe-bento/src/widgets/crypto.cssnew file mode 100644index 0000000..010cf7c--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto.css@@ -0,0 +1,102 @@+/* Crypto card globe (stripe.com .globe styles). The canvas bleeds 20px past the card content. */+.globe {+ position: absolute;+ inset: -20px;+ background: transparent;+ display: flex;+ align-items: center;+}+.globe__canvas {+ width: 100%;+ height: 100%;+}+.globe__canvas--draggable {+ cursor: grab;+ touch-action: pan-y;+ -webkit-user-select: none;+ user-select: none;+}+.globe__canvas--dragging {+ cursor: grabbing;+}+.globe__static img {+ display: block;+ width: 100%;+ height: auto;+}++.globe__ui-container {+ position: absolute;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ pointer-events: none;+ overflow: hidden;+}++/* Arc label: positioned by --ui-x/--ui-y (canvas px), scaled and faded by the globe each frame;+ the 150ms transform transition smooths the per-frame position updates. */+.globe__arc-ui {+ --ui-x: 0px;+ --ui-y: 0px;+ --ui-scale: 1;+ --ui-opacity: 0;+ position: absolute;+ top: 0;+ left: 0;+ gap: 10px;+ padding: 4px 12px 4px 4px;+ background: #fff;+ border: 1px solid #f8fafd;+ box-shadow:+ 0 13.5px 27px -12.4px rgba(50, 50, 93, 0.12),+ 0 8.1px 16.2px -8.1px rgba(0, 0, 0, 0.05);+ border-radius: 4px;+ pointer-events: auto;+ cursor: pointer;+ will-change: transform, opacity;+ backface-visibility: hidden;+ transform: translate3d(var(--ui-x), var(--ui-y), 0) translate(-50%, -50%) scale(var(--ui-scale));+ opacity: var(--ui-opacity);+ transition: transform 0.15s ease-out;+ z-index: 1;+}+.globe__arc-ui-content {+ display: flex;+ flex-direction: row;+ align-items: center;+ padding: 0;+ gap: 12px;+}+.globe__arc-ui-icon {+ position: relative;+ width: 24px;+ height: 24px;+ border-radius: 2px;+ flex: none;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+}+.globe__arc-ui-text {+ display: flex;+ flex-direction: row;+ align-items: center;+ padding: 0;+ gap: 4px;+}+.globe__arc-ui-amount,+.globe__arc-ui-currency {+ font-family: "Inter Variable", "SF Pro Display", sans-serif;+ font-weight: 400;+ font-size: 12px;+ line-height: 1.4;+}+.globe__arc-ui-amount {+ color: #061b31;+}+.globe__arc-ui-currency {+ color: #50617a;+}diff --git a/public/examples/stripe-bento/src/widgets/crypto.js b/public/examples/stripe-bento/src/widgets/crypto.jsnew file mode 100644index 0000000..c1d7480--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto.js@@ -0,0 +1,127 @@+// "Access borderless money movement with stablecoins and crypto" card: rotating dotted globe with+// arcs and payment labels (port of stripe.com's <Globe position={{ y: -1 }} />).+//+// mount() builds the same DOM as stripe.com (.globe > canvas.globe__canvas + .globe__ui-container+// with five .globe__arc-ui labels), creates the WebGL globe paused, and resolves once the dots are+// in and the first frame is drawn. The globe then runs while it is on screen (IntersectionObserver,+// 10 % visible with a 100 px margin) and stays paused on that first frame for+// prefers-reduced-motion. Hovering the card boosts the dot corona. Without WebGL (or when the+// capability check fails, as for software renderers on stripe.com) a static image is shown.+import { precomputeDots } from "./crypto/dots-precompute.js";+import { warmUpRenderLoops } from "./crypto/render-loop.js";++const MAP_URL = new URL("../../assets/img/map-dots.png", import.meta.url).href;+const FALLBACK_URL = new URL("../../assets/img/money-movement-fallback_2x.png", import.meta.url).href;+const LABEL_POOL_SIZE = 5;+const RESIZE_DEBOUNCE_MS = 150;++// Start the shared refresh-rate estimate and the dot precompute right away, before three.js is even+// fetched (stripe.com does both long before the card scrolls in).+warmUpRenderLoops();+precomputeDots(MAP_URL);+const globeModule = import("./crypto/globe.js");++function el(tag, className) {+ const node = document.createElement(tag);+ if (className) node.className = className;+ return node;+}++function createLabel() {+ const label = el("div", "globe__arc-ui");+ label.style.display = "none";+ const content = el("div", "globe__arc-ui-content");+ const text = el("div", "globe__arc-ui-text");+ text.append(el("span", "globe__arc-ui-amount"), el("span", "globe__arc-ui-currency"));+ content.append(el("div", "globe__arc-ui-icon"), text);+ label.append(content);+ return label;+}++function hasWebGL() {+ if (new URLSearchParams(window.location.search).has("__disableWebGL")) return false;+ const canvas = document.createElement("canvas");+ const attrs = { alpha: false, antialias: false, depth: false, failIfMajorPerformanceCaveat: true, stencil: false, powerPreference: "high-performance" };+ return !!(canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs));+}++function mountFallback(container) {+ const root = el("div", "globe");+ const wrap = el("div", "globe__static");+ const img = el("img");+ img.src = FALLBACK_URL;+ img.width = 894;+ img.height = 1456;+ img.alt = "";+ wrap.append(img);+ root.append(wrap);+ container.replaceChildren(root);+ return img.decode().catch(() => {});+}++function debounce(fn, ms) {+ let id;+ return (...args) => {+ clearTimeout(id);+ id = setTimeout(() => fn(...args), ms);+ };+}++export async function mount(container, { card }) {+ if (!hasWebGL()) return mountFallback(container);++ const root = el("div", "globe");+ root.setAttribute("aria-hidden", "true");+ const canvas = el("canvas", "globe__canvas");+ canvas.setAttribute("aria-hidden", "true");+ const ui = el("div", "globe__ui-container");+ const labels = Array.from({ length: LABEL_POOL_SIZE }, createLabel);+ ui.append(...labels);+ root.append(canvas, ui);+ container.replaceChildren(root);++ const { Globe } = await globeModule;+ let globe;+ try {+ globe = new Globe(canvas, { imageUrl: MAP_URL, uiPool: labels });+ } catch {+ return mountFallback(container);+ }+ globe.setPosition({ y: -1 });+ globe.paused = true;+ globe.initScene();++ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");+ let onScreen = false;+ const syncPaused = () => {+ globe.paused = onScreen ? reducedMotion.matches : true;+ };+ reducedMotion.addEventListener("change", syncPaused);+ new IntersectionObserver(+ (entries) => {+ onScreen = entries[entries.length - 1].isIntersecting;+ syncPaused();+ },+ { threshold: 0.1, rootMargin: "100px" },+ ).observe(root);++ let lastSize = "";+ new ResizeObserver(+ debounce((entries) => {+ const entry = entries[entries.length - 1];+ const box = entry.borderBoxSize?.[0];+ const width = Math.round(box ? box.inlineSize : entry.contentRect.width);+ const height = Math.round(box ? box.blockSize : entry.contentRect.height);+ if (!width || !height || `${width}x${height}` === lastSize) return;+ lastSize = `${width}x${height}`;+ globe.setSize(width, height);+ }, RESIZE_DEBOUNCE_MS),+ ).observe(root);++ card.addEventListener("mouseenter", () => globe.setHovered(true));+ card.addEventListener("mouseleave", () => globe.setHovered(false));++ // Resolves once the dots are applied and a frame showing them has been rendered (drawn right+ // away while paused, otherwise by the next render-loop frame).+ await new Promise((resolve) => globe.onFirstFrame(resolve));+}diff --git a/public/examples/stripe-bento/src/widgets/crypto/cities.js b/public/examples/stripe-bento/src/widgets/crypto/cities.jsnew file mode 100644index 0000000..3a6af11--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/cities.js@@ -0,0 +1,94 @@+// City anchors for the arcs (ported from stripe.com's globe module): name, lat/lon in degrees,+// unit vector (ux, uy, uz) on the globe and ISO country code.+export const CITIES = [+ { name: "New York City", lat: 40.7128, lon: -74.006, ux: 0.208854, uy: 0.652268, uz: 0.728647, country: "US" },+ { name: "Los Angeles", lat: 34.0522, lon: -118.2437, ux: -0.392078, uy: 0.559948, uz: 0.729886, country: "US" },+ { name: "Mexico City", lat: 19.4326, lon: -99.1332, ux: -0.149688, uy: 0.332698, uz: 0.931078, country: "MX" },+ { name: "Toronto", lat: 43.6532, lon: -79.3832, ux: 0.133303, uy: 0.690292, uz: 0.711145, country: "CA" },+ { name: "Chicago", lat: 41.8781, lon: -87.6298, ux: 0.030792, uy: 0.667548, uz: 0.74393, country: "US" },+ { name: "Miami", lat: 25.7617, lon: -80.1918, ux: 0.153419, uy: 0.434629, uz: 0.887446, country: "US" },+ { name: "Vancouver", lat: 49.2827, lon: -123.1207, ux: -0.356435, uy: 0.757937, uz: 0.546338, country: "CA" },+ { name: "Houston", lat: 29.7604, lon: -95.3698, ux: -0.078251, uy: 0.496481, uz: 0.864467, country: "US" },+ { name: "San Francisco", lat: 37.7749, lon: -122.4194, ux: -0.440285, uy: 0.612231, uz: 0.656953, country: "US" },+ { name: "Seattle", lat: 47.6062, lon: -122.3321, ux: -0.396264, uy: 0.738349, uz: 0.545133, country: "US" },+ { name: "Boston", lat: 42.3601, lon: -71.0589, ux: 0.237618, uy: 0.673879, uz: 0.699487, country: "US" },+ { name: "Atlanta", lat: 33.749, lon: -84.388, ux: 0.076123, uy: 0.555436, uz: 0.828087, country: "US" },+ { name: "Montreal", lat: 45.5017, lon: -73.5673, ux: 0.196539, uy: 0.713171, uz: 0.672597, country: "CA" },+ { name: "Denver", lat: 39.7392, lon: -104.9903, ux: -0.196538, uy: 0.639153, uz: 0.743601, country: "US" },+ { name: "São Paulo", lat: -23.5505, lon: -46.6333, ux: 0.629472, uy: -0.399557, uz: 0.666423, country: "BR" },+ { name: "Buenos Aires", lat: -34.6037, lon: -58.3816, ux: 0.431518, uy: -0.567897, uz: 0.700918, country: "AR" },+ { name: "Santiago", lat: -33.4489, lon: -70.6693, ux: 0.276196, uy: -0.551193, uz: 0.787339, country: "CL" },+ { name: "Lima", lat: -12.0464, lon: -77.0428, ux: 0.219285, uy: -0.208704, uz: 0.953077, country: "PE" },+ { name: "Rio de Janeiro", lat: -22.9068, lon: -43.1729, ux: 0.67178, uy: -0.389233, uz: 0.630246, country: "BR" },+ { name: "Bogotá", lat: 4.711, lon: -74.0721, ux: 0.273651, uy: 0.082151, uz: 0.958354, country: "CO" },+ { name: "Brasília", lat: -15.7975, lon: -47.8919, ux: 0.643556, uy: -0.272307, uz: 0.715204, country: "BR" },+ { name: "London", lat: 51.5074, lon: -0.1278, ux: 0.622412, uy: 0.782689, uz: 0.001388, country: "GB" },+ { name: "Paris", lat: 48.8566, lon: 2.3522, ux: 0.657391, uy: 0.753065, uz: -0.027003, country: "FR" },+ { name: "Berlin", lat: 52.52, lon: 13.405, ux: 0.591907, uy: 0.793566, uz: -0.141067, country: "DE" },+ { name: "Madrid", lat: 40.4168, lon: -3.7038, ux: 0.759758, uy: 0.648343, uz: 0.049182, country: "ES" },+ { name: "Rome", lat: 41.9028, lon: 12.4964, ux: 0.726647, uy: 0.667869, uz: -0.161046, country: "IT" },+ { name: "Frankfurt", lat: 50.1109, lon: 8.6821, ux: 0.633955, uy: 0.767287, uz: -0.096806, country: "DE" },+ { name: "Warsaw", lat: 52.2297, lon: 21.0122, ux: 0.571769, uy: 0.790473, uz: -0.219621, country: "PL" },+ { name: "Amsterdam", lat: 52.3676, lon: 4.9041, ux: 0.608358, uy: 0.791944, uz: -0.052199, country: "NL" },+ { name: "Stockholm", lat: 59.3293, lon: 18.0686, ux: 0.484948, uy: 0.860113, uz: -0.158211, country: "SE" },+ { name: "Munich", lat: 48.1351, lon: 11.582, ux: 0.652312, uy: 0.744769, uz: -0.140312, country: "DE" },+ { name: "Barcelona", lat: 41.3851, lon: 2.1734, ux: 0.746481, uy: 0.661142, uz: -0.0752, country: "ES" },+ { name: "Milan", lat: 45.4642, lon: 9.19, ux: 0.692238, uy: 0.712552, uz: -0.112137, country: "IT" },+ { name: "Vienna", lat: 48.2082, lon: 16.3738, ux: 0.631452, uy: 0.745437, uz: -0.215286, country: "AT" },+ { name: "Dublin", lat: 53.3498, lon: -6.2603, ux: 0.586911, uy: 0.802356, uz: 0.106418, country: "IE" },+ { name: "Brussels", lat: 50.8503, lon: 4.3517, ux: 0.625117, uy: 0.776047, uz: -0.076419, country: "BE" },+ { name: "Lisbon", lat: 38.7223, lon: -9.1393, ux: 0.772119, uy: 0.625547, uz: 0.124091, country: "PT" },+ { name: "Accra", lat: 5.6037, lon: -0.187, ux: 0.995216, uy: 0.097647, uz: 0.003248, country: "GH" },+ { name: "Addis Ababa", lat: 8.9806, lon: 38.7578, ux: 0.77024, uy: 0.1561, uz: -0.618355, country: "ET" },+ { name: "Johannesburg", lat: -26.2041, lon: 28.0473, ux: 0.791856, uy: -0.44157, uz: -0.421876, country: "ZA" },+ { name: "Dakar", lat: 14.6928, lon: -17.4467, ux: 0.9228, uy: 0.253636, uz: 0.290014, country: "SN" },+ { name: "Tunis", lat: 36.8065, lon: 10.1815, ux: 0.788055, uy: 0.599114, uz: -0.141531, country: "TN" },+ { name: "Lomé", lat: 6.1725, lon: 1.2314, ux: 0.993973, uy: 0.107522, uz: -0.021366, country: "TG" },+ { name: "Lagos", lat: 6.5244, lon: 3.3792, ux: 0.990145, uy: 0.113598, uz: -0.082516, country: "NG" },+ { name: "Cairo", lat: 30.0444, lon: 31.2357, ux: 0.740154, uy: 0.500978, uz: -0.449012, country: "EG" },+ { name: "Cape Town", lat: -33.9249, lon: 18.4241, ux: 0.778571, uy: -0.558362, uz: -0.285411, country: "ZA" },+ { name: "Nairobi", lat: -1.2921, lon: 36.8219, ux: 0.79784, uy: -0.022554, uz: -0.602471, country: "KE" },+ { name: "Tokyo", lat: 35.6762, lon: 139.6503, ux: -0.619079, uy: 0.583204, uz: -0.525941, country: "JP" },+ { name: "New Delhi", lat: 28.6139, lon: 77.209, ux: 0.194356, uy: 0.478905, uz: -0.856082, country: "IN" },+ { name: "Seoul", lat: 37.5665, lon: 126.978, ux: -0.476783, uy: 0.609682, uz: -0.633219, country: "KR" },+ { name: "Mumbai", lat: 19.076, lon: 72.8777, ux: 0.278245, uy: 0.326822, uz: -0.903198, country: "IN" },+ { name: "Kuala Lumpur", lat: 3.139, lon: 101.6869, ux: -0.202259, uy: 0.054758, uz: -0.9778, country: "MY" },+ { name: "Taipei", lat: 25.033, lon: 121.5654, ux: -0.474299, uy: 0.42314, uz: -0.772006, country: "TW" },+ { name: "Bangkok", lat: 13.7563, lon: 100.5018, ux: -0.177038, uy: 0.237793, uz: -0.955046, country: "TH" },+ { name: "Singapore", lat: 1.3521, lon: 103.8198, ux: -0.238803, uy: 0.023596, uz: -0.970781, country: "SG" },+ { name: "Dubai", lat: 25.2048, lon: 55.2708, ux: 0.515458, uy: 0.425855, uz: -0.743606, country: "AE" },+ { name: "Beijing", lat: 39.9042, lon: 116.4074, ux: -0.342618, uy: 0.641432, uz: -0.687216, country: "CN" },+ { name: "Shanghai", lat: 31.2304, lon: 121.4737, ux: -0.436321, uy: 0.518516, uz: -0.735112, country: "CN" },+ { name: "Hong Kong", lat: 22.3193, lon: 114.1694, ux: -0.370418, uy: 0.379621, uz: -0.847213, country: "HK" },+ { name: "Osaka", lat: 34.6937, lon: 135.5023, ux: -0.576941, uy: 0.569245, uz: -0.585752, country: "JP" },+ { name: "Bangalore", lat: 12.9716, lon: 77.5946, ux: 0.209124, uy: 0.224491, uz: -0.951786, country: "IN" },+ { name: "Jakarta", lat: -6.2088, lon: 106.8456, ux: -0.285321, uy: -0.108151, uz: -0.952321, country: "ID" },+ { name: "Manila", lat: 14.5995, lon: 120.9842, ux: -0.491218, uy: 0.252105, uz: -0.833512, country: "PH" },+ { name: "Ho Chi Minh City", lat: 10.8231, lon: 106.6297, ux: -0.280954, uy: 0.187828, uz: -0.941215, country: "VN" },+ { name: "Tel Aviv", lat: 32.0853, lon: 34.7818, ux: 0.694283, uy: 0.531063, uz: -0.485618, country: "IL" },+ { name: "Sydney", lat: -33.8688, lon: 151.2093, ux: -0.727676, uy: -0.557293, uz: -0.39989, country: "AU" },+ { name: "Auckland", lat: -36.8509, lon: 174.7645, ux: -0.796861, uy: -0.599735, uz: -0.073018, country: "NZ" },+ { name: "Melbourne", lat: -37.8136, lon: 144.9631, ux: -0.666523, uy: -0.612654, uz: -0.424891, country: "AU" },+ { name: "Brisbane", lat: -27.4698, lon: 153.0251, ux: -0.761432, uy: -0.461152, uz: -0.455311, country: "AU" },+];++// Preferred long-haul pairs used while the Pacific faces the camera.+export const TRANSPACIFIC_PAIRS = [+ { from: "Los Angeles", to: "Tokyo" },+ { from: "Los Angeles", to: "Singapore" },+ { from: "Los Angeles", to: "Sydney" },+ { from: "New York City", to: "Beijing" },+ { from: "New York City", to: "Auckland" },+ { from: "Singapore", to: "Auckland" },+ { from: "Miami", to: "Sydney" },+ { from: "Santiago", to: "Tokyo" },+ { from: "Santiago", to: "Seoul" },+ { from: "Santiago", to: "Kuala Lumpur" },+ { from: "Lima", to: "Tokyo" },+ { from: "Los Angeles", to: "Auckland" },+ { from: "Vancouver", to: "Sydney" },+ { from: "Mexico City", to: "Seoul" },+ { from: "Mexico City", to: "Singapore" },+ { from: "Mexico City", to: "Sydney" },+ { from: "Mexico City", to: "Taipei" },+];diff --git a/public/examples/stripe-bento/src/widgets/crypto/dots-precompute.js b/public/examples/stripe-bento/src/widgets/crypto/dots-precompute.jsnew file mode 100644index 0000000..5a24c70--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/dots-precompute.js@@ -0,0 +1,64 @@+// Loads the land mask and generates the globe dots in a worker, cached per image URL. Kept free of+// three.js so it can start before the (large) three.js module graph has loaded: stripe.com starts+// this as soon as the bento section renders, long before the card scrolls into view.+import { generateDots } from "./dots.js";++const DOT_COUNT_DESKTOP = 60000;+const DOT_COUNT_MOBILE = 30000;+const cache = new Map();++export const isCoarsePointer = () => window.matchMedia("(pointer: coarse)").matches && "ontouchstart" in window;++function loadImageData(url) {+ return new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => {+ const canvas = document.createElement("canvas");+ canvas.width = image.width;+ canvas.height = image.height;+ const ctx = canvas.getContext("2d");+ ctx.drawImage(image, 0, 0);+ resolve(ctx.getImageData(0, 0, image.width, image.height));+ };+ image.onerror = reject;+ image.src = url;+ });+}++export function precomputeDots(imageUrl) {+ const cached = cache.get(imageUrl);+ if (cached) return cached;+ const promise = loadImageData(imageUrl).then(+ (imageData) =>+ new Promise((resolve) => {+ const params = {+ imageWidth: imageData.width,+ imageHeight: imageData.height,+ imageData: imageData.data,+ dotCount: isCoarsePointer() ? DOT_COUNT_MOBILE : DOT_COUNT_DESKTOP,+ radius: 2,+ poissonJitter: 0.75,+ dotSizeVariation: 0.75,+ dotOpacityVariation: 0.3,+ };+ if (typeof Worker !== "undefined") {+ try {+ const worker = new Worker(new URL("./dots-worker.js", import.meta.url), { type: "module" });+ worker.onmessage = (event) => {+ worker.terminate();+ resolve(event.data);+ };+ worker.onerror = () => {+ worker.terminate();+ resolve(generateDots(params));+ };+ worker.postMessage(params);+ return;+ } catch {}+ }+ resolve(generateDots(params));+ }),+ );+ cache.set(imageUrl, promise);+ return promise;+}diff --git a/public/examples/stripe-bento/src/widgets/crypto/dots-worker.js b/public/examples/stripe-bento/src/widgets/crypto/dots-worker.jsnew file mode 100644index 0000000..c7a6de3--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/dots-worker.js@@ -0,0 +1,7 @@+// Generates the globe dots off the main thread, like stripe.com does.+import { generateDots, transferables } from "./dots.js";++self.onmessage = (event) => {+ const dots = generateDots(event.data);+ self.postMessage(dots, transferables(dots));+};diff --git a/public/examples/stripe-bento/src/widgets/crypto/dots.js b/public/examples/stripe-bento/src/widgets/crypto/dots.jsnew file mode 100644index 0000000..7f7ed26--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/dots.js@@ -0,0 +1,99 @@+// Dot layout for the globe (port of stripe.com's dot generator). Points are laid on a+// Fibonacci-style spiral, nudged by a deterministic hash ("poisson jitter"), and kept only where+// the land mask (map-dots.png alpha) is set. Positions and opacity are deterministic; size and+// the corona seeds derive from Math.random(), so they differ per page load, as on stripe.com.++const hash3 = (x, y, z) => {+ const v = 43758.5453 * Math.sin(12.9898 * x + 78.233 * y + 37.719 * z);+ return v - Math.floor(v);+};+const hash1 = (x) => {+ const v = 43758.5453 * Math.sin(x);+ return v - Math.floor(v);+};+const normalize = (v) => {+ const len = Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);+ return len === 0 ? { x: 0, y: 0, z: 0 } : { x: v.x / len, y: v.y / len, z: v.z / len };+};++/** Equirectangular uv of the direction from `from` towards `to` (here: from the dot to the centre). */+const directionUv = (from, to) => {+ const dx = to.x - from.x;+ const dy = to.y - from.y;+ const dz = to.z - from.z;+ const len = Math.sqrt(dx * dx + dy * dy + dz * dz);+ return {+ u: 1 - (0.5 + Math.atan2(dz / len, dx / len) / (2 * Math.PI)),+ v: 0.5 + Math.asin(dy / len) / Math.PI,+ };+};++export function generateDots({+ imageWidth,+ imageHeight,+ imageData,+ dotCount,+ radius,+ poissonJitter,+ dotSizeVariation,+ dotOpacityVariation,+}) {+ const positions = [];+ const rndIds = [];+ const sizeVariations = [];+ const opacityVariations = [];+ const coronaSeeds = [];+ const varianceRates = [];+ const varianceMotions = [];+ const coronaCanParticipate = [];+ const centre = { x: 0, y: 0, z: 0 };++ for (let i = dotCount - 1; i >= 0; i -= 1) {+ const phi = Math.acos(-1 + (2 * i) / dotCount);+ const theta = Math.sqrt(dotCount * Math.PI) * phi;+ const ring = Math.sin(phi) * radius;+ let p = { x: ring * Math.sin(theta), y: Math.cos(phi) * radius, z: ring * Math.cos(theta) };++ if (poissonJitter > 0) {+ const amount = 0.15 * poissonJitter;+ let offset = {+ x: (hash3(p.x, p.y, p.z) - 0.5) * 2,+ y: (hash3(p.y, p.z, p.x) - 0.5) * 2,+ z: (hash3(p.z, p.x, p.y) - 0.5) * 2,+ };+ const n = normalize(p);+ const d = offset.x * n.x + offset.y * n.y + offset.z * n.z;+ offset = normalize({ x: offset.x - n.x * d, y: offset.y - n.y * d, z: offset.z - n.z * d }); // tangent only+ const moved = normalize({ x: p.x + offset.x * amount, y: p.y + offset.y * amount, z: p.z + offset.z * amount });+ p = { x: moved.x * radius, y: moved.y * radius, z: moved.z * radius };+ }++ const { u, v } = directionUv(p, centre);+ const alpha = imageData[4 * Math.floor(u * imageWidth) + 4 * imageWidth * Math.floor(v * imageHeight) + 3];+ if (!(alpha > 0)) continue;++ positions.push(p.x, p.y, p.z);+ const rnd = Math.random();+ rndIds.push(rnd);+ sizeVariations.push(1 + (rnd - 0.5) * dotSizeVariation);+ opacityVariations.push(1 - hash3(100 * p.x, 100 * p.y, 100 * p.z) * dotOpacityVariation);+ const seed = hash1(173.17 * rnd);+ coronaSeeds.push(seed);+ varianceRates.push(hash1((rnd + 0.31) * 97.13));+ varianceMotions.push(hash1((rnd + 0.73) * 57.77));+ coronaCanParticipate.push(seed < 0.25 ? 1 : 0);+ }++ return {+ positions: new Float32Array(positions),+ rndIds: new Float32Array(rndIds),+ sizeVariations: new Float32Array(sizeVariations),+ opacityVariations: new Float32Array(opacityVariations),+ coronaSeeds: new Float32Array(coronaSeeds),+ varianceRates: new Float32Array(varianceRates),+ varianceMotions: new Float32Array(varianceMotions),+ coronaCanParticipate: new Float32Array(coronaCanParticipate),+ };+}++export const transferables = (dots) => Object.values(dots).map((array) => array.buffer);diff --git a/public/examples/stripe-bento/src/widgets/crypto/drag.js b/public/examples/stripe-bento/src/widgets/crypto/drag.jsnew file mode 100644index 0000000..9535fb4--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/drag.js@@ -0,0 +1,244 @@+// Pointer-drag rotation for the globe (port of stripe.com's controller). Horizontal drag spins+// the globe (rotation.y), vertical drag tilts it (rotation.x) with a soft limit: past 60° the tilt+// is damped quadratically up to a hard stop at 90°. On release the last 80 ms of pointer samples+// give a fling speed, and a spring returns the tilt home ("snap" to ±60° first when beyond it).+//+// stripe.com's bento card creates the globe without `dragRotate`, so this controller binds no+// listeners there; it is used only when an axis ("x", "y" or "both") is passed.+import * as THREE from "three";++const SOFT_TILT = THREE.MathUtils.degToRad(60);+const TILT_OVERSHOOT = THREE.MathUtils.degToRad(30);+const MAX_TILT = SOFT_TILT + TILT_OVERSHOOT;+const SAMPLE_WINDOW_MS = 80;++function dampedTilt(angle, delta) {+ const over = Math.min(Math.max(Math.abs(angle) - SOFT_TILT, 0) / TILT_OVERSHOOT, 1);+ return THREE.MathUtils.clamp(angle + (1 - over) * (1 - over) * delta, -MAX_TILT, MAX_TILT);+}++function applyTiltDelta(angle, delta) {+ if (delta === 0) return angle;+ const next = angle + delta;+ if (!(Math.abs(next) > Math.abs(angle))) return THREE.MathUtils.clamp(next, -MAX_TILT, MAX_TILT);+ if (Math.abs(angle) < SOFT_TILT) {+ if (Math.abs(next) <= SOFT_TILT) return next;+ const sign = Math.sign(next);+ const free = sign * SOFT_TILT - angle;+ return dampedTilt(sign * SOFT_TILT, delta - free);+ }+ return dampedTilt(angle, delta);+}++export class DragController {+ constructor(canvas, target, { axis, homeTiltX, onRelease }) {+ this.canvas = canvas;+ this.target = target;+ this.homeTiltX = homeTiltX;+ this.onRelease = onRelease;+ this.axis = undefined;+ this.dragging = false;+ this.listenersBound = false;+ this.lastPointerX = 0;+ this.lastPointerY = 0;+ this.activePointerId = null;+ this.dragSamples = [];+ this.tiltSpringing = false;+ this.tiltReturnPhase = null; // "snap" | "home" | null+ this.tiltSpringVelocity = 0;+ this.tiltSpringTarget = 0;+ this.setAxis(axis);+ }++ get isDragging() {+ return this.dragging;+ }++ get isSettling() {+ return this.tiltSpringing;+ }++ setAxis(axis) {+ if (this.axis === axis && (axis ? this.listenersBound : !this.listenersBound)) return;+ this.axis = axis;+ if (axis) {+ this.bindListeners();+ } else {+ this.endDrag({ skipSpring: true });+ this.tiltSpringing = false;+ this.tiltReturnPhase = null;+ this.unbindListeners();+ }+ }++ update(dt) {+ this.updateTiltSpring(dt);+ }++ dispose() {+ this.endDrag({ skipSpring: true });+ this.tiltSpringing = false;+ this.tiltReturnPhase = null;+ this.unbindListeners();+ }++ onPointerDown = (event) => {+ if (!this.axis || event.button !== 0) return;+ this.dragging = true;+ this.tiltSpringing = false;+ this.tiltReturnPhase = null;+ this.tiltSpringVelocity = 0;+ this.dragSamples = [];+ this.lastPointerX = event.clientX;+ this.lastPointerY = event.clientY;+ this.activePointerId = event.pointerId;+ this.recordDragSample(event.clientX, event.clientY, performance.now());+ this.canvas.setPointerCapture(event.pointerId);+ this.canvas.classList.add("globe__canvas--dragging");+ event.preventDefault();+ };++ onPointerMove = (event) => {+ if (!this.dragging || event.pointerId !== this.activePointerId || !this.axis) return;+ const dx = event.clientX - this.lastPointerX;+ const dy = event.clientY - this.lastPointerY;+ this.lastPointerX = event.clientX;+ this.lastPointerY = event.clientY;+ this.recordDragSample(event.clientX, event.clientY, performance.now());+ const width = this.canvas.clientWidth || 1;+ const height = this.canvas.clientHeight || 1;+ if (this.axis === "y" || this.axis === "both") this.target.rotation.y += (dx / width) * Math.PI * 2;+ if (this.axis === "x" || this.axis === "both") {+ this.target.rotation.x = applyTiltDelta(this.target.rotation.x, (dy / height) * Math.PI);+ }+ event.preventDefault();+ };++ onPointerUp = (event) => {+ if (event.pointerId === this.activePointerId) this.endDrag();+ };++ bindListeners() {+ if (this.listenersBound) return;+ this.canvas.addEventListener("pointerdown", this.onPointerDown, { passive: false });+ this.canvas.addEventListener("pointermove", this.onPointerMove, { passive: false });+ this.canvas.addEventListener("pointerup", this.onPointerUp);+ this.canvas.addEventListener("pointercancel", this.onPointerUp);+ this.listenersBound = true;+ }++ unbindListeners() {+ if (!this.listenersBound) return;+ this.canvas.removeEventListener("pointerdown", this.onPointerDown);+ this.canvas.removeEventListener("pointermove", this.onPointerMove);+ this.canvas.removeEventListener("pointerup", this.onPointerUp);+ this.canvas.removeEventListener("pointercancel", this.onPointerUp);+ this.listenersBound = false;+ }++ recordDragSample(x, y, t) {+ this.dragSamples.push({ t, x, y });+ const cutoff = t - SAMPLE_WINDOW_MS;+ while (this.dragSamples.length > 0 && this.dragSamples[0].t < cutoff) this.dragSamples.shift();+ }++ /** Fling speed in radians per 60 Hz frame, from the samples of the last 80 ms. */+ computeReleaseSpeeds() {+ const samples = this.dragSamples;+ if (samples.length < 2) return { speedX: 0, speedY: 0 };+ const last = samples[samples.length - 1];+ if (performance.now() - last.t > 50) return { speedX: 0, speedY: 0 };+ const first = samples[0];+ const seconds = (last.t - first.t) / 1000;+ if (seconds < 0.008) return { speedX: 0, speedY: 0 };+ const width = this.canvas.clientWidth || 1;+ const height = this.canvas.clientHeight || 1;+ const spin = ((last.x - first.x) / width) * Math.PI * 2;+ return {+ speedX: (((last.y - first.y) / height) * Math.PI) / (60 * seconds),+ speedY: spin / (60 * seconds),+ };+ }++ endDrag(options) {+ if (!this.dragging) return;+ this.dragging = false;+ if (this.activePointerId !== null && this.canvas.hasPointerCapture(this.activePointerId)) {+ this.canvas.releasePointerCapture(this.activePointerId);+ }+ this.activePointerId = null;+ this.canvas.classList.remove("globe__canvas--dragging");+ const speeds = this.computeReleaseSpeeds();+ this.dragSamples = [];+ if (options?.skipSpring) {+ this.tiltSpringing = false;+ this.tiltReturnPhase = null;+ } else {+ this.onRelease(speeds);+ this.startTiltReturn(speeds.speedX);+ }+ }++ getHomeReturnSpeed(angle) {+ return (5 / 6) * Math.abs(angle - this.homeTiltX);+ }++ startTiltReturn(speedX) {+ if (this.axis !== "x" && this.axis !== "both") return;+ const velocity = Math.abs(speedX) > 5e-5 ? speedX : 0;+ const tilt = this.target.rotation.x;+ if (Math.abs(tilt) > SOFT_TILT) {+ this.beginTiltPhase("snap", Math.sign(tilt) * SOFT_TILT, velocity);+ return;+ }+ if (Math.abs(tilt - this.homeTiltX) < 4e-4 && Math.abs(velocity) < 5e-5) {+ this.target.rotation.x = this.homeTiltX;+ return;+ }+ this.beginTiltPhase("home", this.homeTiltX, velocity);+ }++ beginTiltPhase(phase, target, velocity, options) {+ this.tiltReturnPhase = phase;+ this.tiltSpringing = true;+ this.tiltSpringTarget = target;+ if (!options?.keepVelocity) this.tiltSpringVelocity = 60 * velocity;+ }++ /** Semi-implicit spring on rotation.x: stiffness 90 while snapping back under 60°, 10 towards home, damping 12. */+ updateTiltSpring(dt) {+ if (!this.tiltSpringing || !this.tiltReturnPhase) return;+ const tilt = this.target.rotation.x;+ const homeSpeed = this.getHomeReturnSpeed(tilt);+ if (this.tiltReturnPhase === "home" && Math.abs(tilt) > SOFT_TILT && Math.abs(this.tiltSpringVelocity) > homeSpeed) {+ this.beginTiltPhase("snap", Math.sign(tilt) * SOFT_TILT, 0, { keepVelocity: true });+ }+ const stiffness = this.tiltReturnPhase === "snap" ? 90 : 10;+ const damping = 12;+ const accel = -stiffness * (tilt - this.tiltSpringTarget) - damping * this.tiltSpringVelocity;+ this.tiltSpringVelocity += accel * dt;+ let next = tilt + this.tiltSpringVelocity * dt;+ if (next > MAX_TILT) {+ next = MAX_TILT;+ this.tiltSpringVelocity = Math.min(this.tiltSpringVelocity, 0);+ } else if (next < -MAX_TILT) {+ next = -MAX_TILT;+ this.tiltSpringVelocity = Math.max(this.tiltSpringVelocity, 0);+ }+ this.target.rotation.x = next;+ if (this.tiltReturnPhase === "snap" && Math.abs(this.tiltSpringVelocity) <= this.getHomeReturnSpeed(next)) {+ this.beginTiltPhase("home", this.homeTiltX, 0, { keepVelocity: true });+ return;+ }+ if (+ this.tiltReturnPhase === "home" &&+ Math.abs(next - this.tiltSpringTarget) < 4e-4 &&+ Math.abs(this.tiltSpringVelocity) < 4e-4+ ) {+ this.target.rotation.x = this.tiltSpringTarget;+ this.tiltReturnPhase = null;+ this.tiltSpringing = false;+ this.tiltSpringVelocity = 0;+ }+ }+}diff --git a/public/examples/stripe-bento/src/widgets/crypto/easing.js b/public/examples/stripe-bento/src/widgets/crypto/easing.jsnew file mode 100644index 0000000..e63e429--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/easing.js@@ -0,0 +1,21 @@+// Named easings used by the globe's arc timeline (same table as stripe.com).+const easeOutCubic = (t) => 1 - (1 - t) ** 3;++const EASINGS = {+ linear: (t) => t,+ easeOutCubic,+ easeInCubic: (t) => t * t * t,+ easeInOutCubic: (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2),+ easeOutQuad: (t) => 1 - (1 - t) * (1 - t),+ easeInQuad: (t) => t * t,+ easeInOutQuad: (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2),+ easeOutExpo: (t) => (t === 1 ? 1 : 1 - 2 ** (-10 * t)),+ easeInExpo: (t) => (t === 0 ? 0 : 2 ** (10 * t - 10)),+ easeOutBack: (t) => 1 + 2.70158 * (t - 1) ** 3 + 1.70158 * (t - 1) ** 2,+ easeInBack: (t) => 2.70158 * t * t * t - 1.70158 * t * t,+};++/** Applies the named easing to t, clamping t to [0, 1]. Unknown names fall back to easeOutCubic. */+export function ease(t, name) {+ return (EASINGS[name] ?? easeOutCubic)(Math.max(0, Math.min(1, t)));+}diff --git a/public/examples/stripe-bento/src/widgets/crypto/globe.js b/public/examples/stripe-bento/src/widgets/crypto/globe.jsnew file mode 100644index 0000000..25f4334--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/globe.js@@ -0,0 +1,1728 @@+// Dotted globe with flying arcs and payment labels: port of stripe.com's "GradientNoiseGlobe"+// (three.js r178), default variant as used by the homepage crypto bento card.+//+// Scene: a depth-only sphere hides arcs behind the globe, a translucent gradient sphere gives the+// white-to-blue body, ~18k land dots are point sprites coloured by a screen-space orange → pink →+// blue gradient and faded towards the back, and a faint purple halo sits behind it all. The globe+// is tilted (x -2°, z 8°), starts at 70° yaw and auto-rotates 0.00115 rad per 60 Hz frame+// (1.25x while the Pacific faces the camera). Rendering runs on every 2nd frame of the shared+// render loop, more frames are skipped under performance warnings, and dt is capped at 50 ms.+//+// Arcs: up to 4 "main" arcs between random cities (one end facing the camera), each a gradient+// Line2 that grows after its two ring markers pop in, then a label (wallet icon, amount,+// stablecoin) rides along it, fades out, and the line retreats. Up to 3 thin "simple" arcs with a+// shorter timeline run in parallel. All timings use performance.now(), not frame counts.+import * as THREE from "three";+import { Line2 } from "three/addons/lines/Line2.js";+import { LineGeometry } from "three/addons/lines/LineGeometry.js";+import { LineMaterial } from "three/addons/lines/LineMaterial.js";+import { CITIES, TRANSPACIFIC_PAIRS } from "./cities.js";+import { DragController } from "./drag.js";+import { ease } from "./easing.js";+import { isCoarsePointer, precomputeDots } from "./dots-precompute.js";+import { RenderLoop } from "./render-loop.js";+import * as SHADERS from "./shaders.js";+import { STABLECOINS, WALLETS } from "./wallets.js";++const { clamp, lerp, degToRad, randInt, smoothstep } = THREE.MathUtils;++const GLOBE = {+ DOT_COUNT_MAX_DESKTOP: 60000,+ DOT_COUNT_MAX_MOBILE: 30000,+ DOT_SIZE_DESKTOP: 12,+ DOT_SIZE_MOBILE: 14,+ CAMERA_Z_DESKTOP: 11.7,+ CAMERA_Z_MOBILE: 11.3,+ DOT_GRADIENT_STOP_COUNT: 3,+ ARC_UI_MIN_OFFSET: 0.01,+ ARC_UI_MAX_OFFSET: 0.25,+ ARC_UI_HIDE_DOT_THRESHOLD: -0.5,+ ARC_UI_MIN_SCALE: 0.75,+ ARC_UI_MAX_SCALE: 1,+ MARKER_TANGENT_OFFSET: 0.02,+};++/** Main arc timeline (ms). Line duration scales with distance; label travel too. */+const ARC_TIMING = {+ markerA: { durationMs: 600, easing: "easeOutCubic" },+ markerB: { durationMs: 550, easing: "easeOutCubic" },+ line: { durationMs: 2800, easing: "easeOutCubic" },+ uiIntro: { durationMs: 800, easing: "easeOutCubic" },+ uiTravel: { durationMs: 5000, easing: "easeInOutCubic", distanceScale: { factor: 0.12, min: 0.6, max: 1.2 } },+ uiOutro: { durationMs: 600, easing: "easeInCubic" },+ lineRetreat: { durationMs: 2200, easing: "easeInOutCubic" },+ markerFade: { durationMs: 600, easing: "easeOutCubic" },+ lineDistanceScale: { baseDurationMs: 2800, referenceKm: 8000, min: 1800, max: 4500 },+};++/** Simple (label-less) arc timeline (ms). */+const SIMPLE_ARC_TIMING = {+ markerA: { durationMs: 300, easing: "easeOutCubic" },+ markerB: { durationMs: 250, easing: "easeOutCubic" },+ line: { durationMs: 1200, easing: "easeOutCubic" },+ lineRetreat: { durationMs: 800, easing: "easeInOutCubic" },+ markerFade: { durationMs: 400, easing: "easeOutCubic" },+};++const ARC_SPAWN = {+ ENABLED: true,+ MAX_ACTIVE_ARCS: 4,+ MIN_SPAWN_INTERVAL_MS: 1500,+ MAX_SPAWN_INTERVAL_MS: 4000,+ CITY_MIN_DISTANCE_KM: 2000,+ MIN_UI_SCREEN_DISTANCE: 80,+ MAX_SPAWN_DISTANCE_ATTEMPTS: 5,+};++// ---------------------------------------------------------------------------------------------+// Renderer with stripe.com's capability gate: WebGL2 with vertex textures, 4096 textures, 256+// uniforms and a few extensions, and no "major performance caveat" (software rendering).+const REQUIRED_EXTENSIONS = [+ "EXT_color_buffer_float",+ "EXT_texture_filter_anisotropic",+ "WEBGL_debug_renderer_info",+ "WEBGL_debug_shaders",+];++export function createRenderer(params) {+ let renderer;+ let hasMajorPerformanceCaveat = false;+ try {+ renderer = new THREE.WebGLRenderer({ ...params, failIfMajorPerformanceCaveat: true });+ } catch {+ hasMajorPerformanceCaveat = true;+ }+ if (!renderer) {+ try {+ renderer = new THREE.WebGLRenderer({ ...params, failIfMajorPerformanceCaveat: false });+ } catch {}+ }+ let hasRequiredCapabilities = false;+ if (renderer) {+ const { capabilities, extensions } = renderer;+ hasRequiredCapabilities =+ capabilities.isWebGL2 &&+ capabilities.vertexTextures &&+ capabilities.maxTextureSize >= 4096 &&+ capabilities.maxVertexUniforms >= 256 &&+ capabilities.maxFragmentUniforms >= 256 &&+ REQUIRED_EXTENSIONS.every((name) => extensions.get(name) !== null);+ }+ return { renderer, hasMajorPerformanceCaveat, hasRequiredCapabilities };+}++// ---------------------------------------------------------------------------------------------+// Arc lines are LineSegments2 with one instance per segment; this clips them to a progress range+// [start, end] in the fragment shader so they can grow and retreat without new geometry.+function addVisibleRangeClip(material) {+ material.userData.visibleRange = new THREE.Vector2(0, 0);+ material.userData.totalSegments = 1;+ material.onBeforeCompile = (shader) => {+ const range = material.userData.visibleRange || new THREE.Vector2(0, 1);+ const total = material.userData.totalSegments || 1;+ shader.uniforms.u_visibleRange = { value: range };+ shader.uniforms.u_totalSegments = { value: total };+ material.userData.shader = shader;+ material.userData.u_totalSegmentsUniform = shader.uniforms.u_totalSegments;+ shader.vertexShader = `+ uniform vec2 u_visibleRange;+ uniform float u_totalSegments;+ varying float v_instanceProgress;+ ${shader.vertexShader}+ `;+ const main = "void main() {";+ shader.vertexShader = shader.vertexShader.replace(+ main,+ `+ ${main}+ float instanceProg = float(gl_InstanceID) / max(u_totalSegments, 1.0);+ v_instanceProgress = instanceProg;+ `,+ );+ shader.fragmentShader = `+ varying float v_instanceProgress;+ uniform vec2 u_visibleRange;+ ${shader.fragmentShader}+ `;+ shader.fragmentShader = shader.fragmentShader.replace(+ main,+ `+ ${main}+ if (v_instanceProgress < u_visibleRange.x || v_instanceProgress > u_visibleRange.y) {+ discard;+ }+ `,+ );+ };+}++function setTotalSegments(material, count) {+ material.userData.totalSegments = count;+ if (material.userData.u_totalSegmentsUniform) material.userData.u_totalSegmentsUniform.value = count;+ if (material.userData.shader?.uniforms?.u_totalSegments) material.userData.shader.uniforms.u_totalSegments.value = count;+}++/** Ring marker: 25 % halo disc, solid ring, white centre. */+function createMarkerTexture(color) {+ const scale = Math.min(Math.ceil(window.devicePixelRatio || 1), 2);+ const c = new THREE.Color(color);+ const rgba = (alpha) => `rgba(${Math.floor(255 * c.r)},${Math.floor(255 * c.g)},${Math.floor(255 * c.b)},${alpha})`;+ const canvas = document.createElement("canvas");+ canvas.width = 128 * scale;+ canvas.height = 128 * scale;+ const ctx = canvas.getContext("2d");+ ctx.setTransform(scale, 0, 0, scale, 0, 0);+ ctx.clearRect(0, 0, 128, 128);+ ctx.fillStyle = rgba(0.25);+ ctx.beginPath();+ ctx.arc(64, 64, 64, 0, 2 * Math.PI);+ ctx.fill();+ ctx.fillStyle = rgba(1);+ ctx.beginPath();+ ctx.arc(64, 64, 38.4, 0, 2 * Math.PI);+ ctx.arc(64, 64, 25.6, 0, 2 * Math.PI, true);+ ctx.closePath();+ ctx.fill();+ ctx.fillStyle = "rgba(255,255,255,1.0)";+ ctx.beginPath();+ ctx.arc(64, 64, 25.6, 0, 2 * Math.PI);+ ctx.fill();+ const texture = new THREE.CanvasTexture(canvas);+ texture.needsUpdate = true;+ texture.generateMipmaps = true;+ texture.minFilter = THREE.LinearMipmapLinearFilter;+ texture.magFilter = THREE.LinearFilter;+ return texture;+}++function cityDistanceKm(a, b) {+ const lat1 = degToRad(a.lat);+ const lon1 = degToRad(a.lon);+ const lat2 = degToRad(b.lat);+ const lon2 = degToRad(b.lon);+ const dLat = lat2 - lat1;+ const dLon = lon2 - lon1;+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;+ return 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h)) * 6371;+}++const findCity = (name) => CITIES.find((c) => c.name.toLowerCase() === name.toLowerCase()) ?? null;++let svgIdCounter = 0;++// ---------------------------------------------------------------------------------------------+export class Globe {+ constructor(canvas, { imageUrl, uiPool, dragRotate, autoRotate, hoverBoost }) {+ this.radius = 2;+ this.globePosition = new THREE.Vector3(0, 0, 0);+ this.globeRotationMatrix = new THREE.Matrix3();+ this.dotsStartTime = 0;+ this.activeArcs = [];+ this.activeSimpleArcs = [];++ // Main arcs: orange → pink, purple → pink, orange → purple.+ this.arcColorPalettes = [+ { start: 0xff8c57, end: 0xfd3ae6 },+ { start: 0x705bff, end: 0xfd3ae6 },+ { start: 0xff8c57, end: 0x705bff },+ ];+ // Simple arcs: light blue, light orange, light purple.+ this.simpleArcColorPalettes = [+ { start: 0x80d4ff, end: 0x4da6ff },+ { start: 0xffd480, end: 0xffa64d },+ { start: 0xd4a6ff, end: 0xa64dff },+ ];+ this.arcControllerEnabled = ARC_SPAWN.ENABLED;+ this.arcControllerMaxActive = ARC_SPAWN.MAX_ACTIVE_ARCS;+ this.arcPeakMinHeight = 0.1;+ this.arcPeakMaxHeight = 0.275;+ this.arcPeakAnglePower = 1.2;+ this.arcSpawnIntervalMin = ARC_SPAWN.MIN_SPAWN_INTERVAL_MS;+ this.arcSpawnIntervalMax = ARC_SPAWN.MAX_SPAWN_INTERVAL_MS;+ this.arcCityMinDistanceKm = ARC_SPAWN.CITY_MIN_DISTANCE_KM;+ this.arcMinUIScreenDistance = ARC_SPAWN.MIN_UI_SCREEN_DISTANCE;+ this.arcMaxSpawnDistanceAttempts = ARC_SPAWN.MAX_SPAWN_DISTANCE_ATTEMPTS;+ this.arcVisibleCityDotThreshold = 0.25;+ this.arcRightEdgeExclusionRatio = 0.3;+ this.arcPreferTranspacific = true;+ this.arcPacificWestBoundary = -170;+ this.arcPacificEastBoundary = 55;+ this.arcPacificSpeedWestBoundary = -165;+ this.arcPacificSpeedEastBoundary = 50;+ this.arcPacificSpeedMultiplier = 1.25;+ this.arcControllerNextSpawnTime = 0;+ this.lastArcPairKey = null;++ this.simpleArcControllerEnabled = true;+ this.simpleArcMaxActive = 3;+ this.simpleArcSpawnIntervalMin = 800;+ this.simpleArcSpawnIntervalMax = 2000;+ this.simpleArcMaxDistanceKm = 8000;+ this.simpleArcMinDistanceKm = 500;+ this.simpleArcControllerNextSpawnTime = 0;+ this.lastSimpleArcPairKey = null;++ // Dots: gradient #ff7c3f (top) → #fd3ae6 → #533afd (bottom) at 225°.+ this.dotSize = 12;+ this.dotColorTop = new THREE.Color(0xff7c3f);+ this.dotColorMid = new THREE.Color(0xfd3ae6);+ this.dotColorBottom = new THREE.Color(0x533afd);+ this.dotGradientStopTop = 0.024;+ this.dotGradientStopMid = 0.3794;+ this.dotGradientStopBottom = 0.7941;+ this.dotGradientAngle = 225;+ this.dotGradientWidth = 1;+ this.dotGradientHeight = 1;+ this.dotOpacity = 0.6;+ this.dotDepthFadeEnabled = true;+ this.dotDepthFadeFront = 0.25;+ this.dotDepthFadeBack = -0.1;+ this.dotDepthFadeMinOpacity = 0.15;+ this.dotDepthFadeCurve = 2;++ // Globe body: white → #005eff gradient at 20 % opacity, lilac fresnel rim.+ this.globeGradientColorA = new THREE.Color(0xffffff);+ this.globeGradientColorB = new THREE.Color(0x005eff);+ this.globeGradientClockAngle = 215;+ this.globeGradientDepth = -0.1;+ this.globeGradientContrast = 2;+ this.globeGradientOffset = -0.4;+ this.globeOpacity = 0.2;+ this.globeFresnelColor = new THREE.Color(0xc7b6ea);+ this.globeFresnelStrength = 0.1;+ this.globeFresnelPower = 0.3;++ this.atmosphereColor = new THREE.Color("#a953ff");+ this.atmosphereIntensity = 0.08;+ this.atmosphereOpacity = 0.35;+ this.atmosphereFalloff = 0.4;+ this.atmosphereRadius = 1.02;++ // Corona: a share of dots periodically lifts off; hover multiplies share and distance by 1.33.+ this.dotCoronaParticipation = 0.2;+ this.dotCoronaDistance = 0.6;+ this.dotCoronaLaunchRate = 0.15;+ this.dotCoronaTravelSpeed = 0.35;+ this.dotCoronaOpacityDrop = 0.5;+ this.dotCoronaNoiseStrength = 0.42;+ this.dotCoronaNoiseScale = 0.75;+ this.isHovered = false;+ this.hoverMultiplier = 1;+ this.hoverBoostAmount = hoverBoost ?? 1.33;+ this.hoverAttackSpeed = 0.1;+ this.hoverDecaySpeed = 0.04;++ this.renderLoop = null;+ this._paused = false;+ this.pauseStartTime = null;+ this.initialized = false;+ this.loaded = false;+ this.onLoadCallback = null;+ this.firstFrameCallbacks = [];+ this.precomputedDots = null;+ this.lastRender = null;++ this.autoRotate = autoRotate !== false;+ this.rotationSpeedX = 0;+ this.rotationSpeedY = 0.00115;+ this.currentRotationSpeedX = 0;+ this.currentRotationSpeedY = this.autoRotate ? 0.00115 : 0;+ this.rotationSpeedZ = 0;+ this.isCoasting = false;+ this.globeAxisTiltX = -2;+ this.globeAxisTiltZ = 8;+ this.globeInitialRotationY = 70;+ this.dragRotate = dragRotate;++ this.markerTextureCache = {};+ this.markerGeometry = new THREE.PlaneGeometry(0.4, 0.4);+ this.cachedWidth = 0;+ this.cachedHeight = 0;+ this.ARC_LINE_POOL_SIZE = 10;+ this.ARC_MAX_SEGMENTS = 256;+ this.SIMPLE_ARC_LINE_POOL_SIZE = 6;+ this.SIMPLE_ARC_MAX_SEGMENTS = 64;+ this.MARKER_POOL_SIZE = 20;+ this.arcLinePool = [];+ this.simpleArcLinePool = [];+ this.markerPool = [];+ this.arcPointsPool = [];+ this.simpleArcPointsPool = [];+ this.candidateCityIndices = CITIES.map((_, i) => i);+ this.cityVectors = [];++ if (new URLSearchParams(window.location.search).has("__disableWebGL")) {+ throw new Error("WebGL disabled by query param");+ }+ const { renderer, hasMajorPerformanceCaveat, hasRequiredCapabilities } = createRenderer({+ canvas,+ antialias: true,+ alpha: false,+ powerPreference: "high-performance",+ });+ if (!renderer || !hasRequiredCapabilities || hasMajorPerformanceCaveat) {+ renderer?.dispose();+ throw new Error("WebGL disabled based on capabilities check");+ }+ this.dpr = Math.min(window.devicePixelRatio, 2);+ this.renderer = renderer;+ this.renderer.setClearColor(0xffffff, 1);+ this.renderer.setPixelRatio(this.dpr);+ this.canvas = canvas;+ this.uiPool = [...uiPool];+ this.dotSize = isCoarsePointer() ? GLOBE.DOT_SIZE_MOBILE : GLOBE.DOT_SIZE_DESKTOP;+ this.scene = new THREE.Scene();+ this.camera = new THREE.PerspectiveCamera(25, 1, 0.1, 1000);+ this.dotsPrecomputePromise = precomputeDots(imageUrl).then((dots) => (this.precomputedDots = dots));+ }++ get isDragging() {+ return this.drag?.isDragging ?? false;+ }++ // -------------------------------------------------------------------------------- scene setup+ initScene() {+ if (this.initialized) return;+ this.initialized = true;+ const width = this.cachedWidth || this.canvas.clientWidth;+ const height = this.cachedHeight || this.canvas.clientHeight;+ this.renderer.setSize(width, height, false);+ this.camera.aspect = width / height || 1;+ this.camera.updateProjectionMatrix();+ this.camera.position.set(0, 0, isCoarsePointer() ? GLOBE.CAMERA_Z_MOBILE : GLOBE.CAMERA_Z_DESKTOP);+ this.camera.lookAt(0, 0, 0);+ this.createGlobe();++ // Render every `skip`-th loop frame (2 by default, more under performance warnings);+ // the arc/label state machine runs every frame.+ let frame = 0;+ let skip = 2;+ this.renderLoop = new RenderLoop(() => {+ if (frame % skip === 0) this.animate();+ this.updateUI();+ frame += 1;+ });+ this.renderLoop.onPerformanceWarning = (level) => {+ skip = Math.max(level + 1, skip);+ };+ this.renderLoop.onPerformanceRecovered = (level) => {+ skip = Math.max(level + 1, 2);+ };+ this.renderLoop.start();+ }++ createGlobe() {+ this.globeGroup = new THREE.Group();+ this.globeGroup.position.copy(this.globePosition);+ this.globeGroup.rotation.x = degToRad(this.globeAxisTiltX);+ this.globeGroup.rotation.y = degToRad(this.globeInitialRotationY);+ this.globeGroup.rotation.z = degToRad(this.globeAxisTiltZ);+ this.drag = new DragController(this.canvas, this.globeGroup, {+ axis: this.dragRotate,+ homeTiltX: degToRad(this.globeAxisTiltX),+ onRelease: (speeds) => this.applyDragRelease(speeds),+ });+ this.scene.add(this.globeGroup);++ // Depth-only occluder so arcs and markers behind the globe are hidden.+ this.backgroundSphere = new THREE.Mesh(+ new THREE.SphereGeometry(0.993 * this.radius, 64, 64),+ new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, side: THREE.FrontSide, depthWrite: true, colorWrite: false }),+ );+ this.backgroundSphere.renderOrder = -1;+ this.globeGroup.add(this.backgroundSphere);++ const haloSize = 6 * this.radius;+ this.atmosphereMaterial = new THREE.ShaderMaterial({+ uniforms: {+ u_color: { value: this.atmosphereColor.clone() },+ u_intensity: { value: this.atmosphereIntensity },+ u_opacity: { value: this.atmosphereOpacity },+ u_innerRadius: { value: this.radius },+ u_outerRadius: { value: this.radius * this.atmosphereRadius },+ u_outerFade: { value: Math.max(0.01, this.atmosphereFalloff) * this.radius },+ },+ vertexShader: SHADERS.ATMOSPHERE_VERTEX,+ fragmentShader: SHADERS.ATMOSPHERE_FRAGMENT,+ blending: THREE.NormalBlending,+ transparent: true,+ depthWrite: false,+ depthTest: false,+ side: THREE.DoubleSide,+ });+ this.atmosphereMesh = new THREE.Mesh(new THREE.PlaneGeometry(haloSize, haloSize, 1, 1), this.atmosphereMaterial);+ this.atmosphereMesh.frustumCulled = false;+ this.atmosphereMesh.renderOrder = -4;+ this.scene.add(this.atmosphereMesh);++ this.globeSurfaceMaterial = new THREE.ShaderMaterial({+ uniforms: {+ u_colorA: { value: this.globeGradientColorA.clone() },+ u_colorB: { value: this.globeGradientColorB.clone() },+ u_fresnelColor: { value: this.globeFresnelColor.clone() },+ u_fresnelStrength: { value: this.globeFresnelStrength },+ u_fresnelPower: { value: this.globeFresnelPower },+ u_opacity: { value: this.globeOpacity },+ u_gradientDir: { value: new THREE.Vector3(1, 0, 0) },+ u_gradientContrast: { value: this.globeGradientContrast },+ u_gradientOffset: { value: this.globeGradientOffset },+ u_cameraPosition: { value: this.camera.position.clone() },+ u_cameraRight: { value: new THREE.Vector3(1, 0, 0) },+ u_cameraUp: { value: new THREE.Vector3(0, 1, 0) },+ u_cameraForward: { value: new THREE.Vector3(0, 0, -1) },+ },+ vertexShader: SHADERS.SURFACE_VERTEX,+ fragmentShader: SHADERS.SURFACE_FRAGMENT,+ transparent: true,+ depthWrite: true,+ depthTest: true,+ });+ this.globeSurface = new THREE.Mesh(new THREE.SphereGeometry(0.9995 * this.radius, 128, 128), this.globeSurfaceMaterial);+ this.globeSurface.renderOrder = -0.5;+ this.globeGroup.add(this.globeSurface);+ this.updateGlobeSurfaceUniforms();+ this.updateCameraBasisUniforms();+ this.updateAtmosphereMaterial();++ // Arcs and dots live in a group turned 180° about Y relative to the globe body.+ this.arcsGroup = new THREE.Group();+ this.arcsGroup.rotation.x = -Math.PI;+ this.arcsGroup.rotation.z = -Math.PI;+ this.globeGroup.add(this.arcsGroup);+ this.dotsGroup = new THREE.Group();+ this.dotsGroup.rotation.x = -Math.PI;+ this.dotsGroup.rotation.z = -Math.PI;+ this.globeGroup.add(this.dotsGroup);++ this.loadDots();+ this.cityVectors = CITIES.map((c) => new THREE.Vector3(c.ux, c.uy, c.uz).multiplyScalar(this.radius));+ this.globeGroup.updateMatrixWorld(true);+ this.globeRotationMatrix.setFromMatrix4(this.globeGroup.matrixWorld).transpose();+ }++ loadDots() {+ const apply = (dots) => {+ this.applyDotsToScene(dots);+ this.loaded = true;+ if (this.onLoadCallback) {+ this.onLoadCallback();+ this.onLoadCallback = null;+ }+ // Draw the first frame right away. stripe.com does this because the globe is still paused when+ // its (pre-computed) dots arrive; here the dots can arrive after the globe is unpaused.+ if (this.paused || !this.lastFrameRendered) this.updateAndRender(0);+ };+ if (this.precomputedDots) apply(this.precomputedDots);+ else this.dotsPrecomputePromise.then(apply);+ }++ applyDotsToScene(dots) {+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute("position", new THREE.BufferAttribute(dots.positions, 3));+ geometry.setAttribute("rndId", new THREE.BufferAttribute(dots.rndIds, 1));+ geometry.setAttribute("sizeVariation", new THREE.BufferAttribute(dots.sizeVariations, 1));+ geometry.setAttribute("opacityVariation", new THREE.BufferAttribute(dots.opacityVariations, 1));+ geometry.setAttribute("coronaSeed", new THREE.BufferAttribute(dots.coronaSeeds, 1));+ geometry.setAttribute("varianceRate", new THREE.BufferAttribute(dots.varianceRates, 1));+ geometry.setAttribute("varianceMotion", new THREE.BufferAttribute(dots.varianceMotions, 1));+ geometry.setAttribute("coronaCanParticipate", new THREE.BufferAttribute(dots.coronaCanParticipate, 1));++ const travelSpeed = Math.max(0.1, this.dotCoronaTravelSpeed);+ const launchInterval = Math.max(0.45, 1 / Math.max(this.dotCoronaLaunchRate, 0.001));+ this.dotsMaterial = new THREE.ShaderMaterial({+ transparent: true,+ depthTest: false,+ depthWrite: false,+ uniforms: {+ u_timeSec: { value: 0 },+ u_radius: { value: this.radius },+ u_dotSize: { value: 0.01 * this.dotSize },+ u_opacity_factor: { value: this.dotOpacity },+ u_coronaBurstDistance: { value: this.dotCoronaDistance },+ u_coronaParticipation: { value: this.dotCoronaParticipation },+ u_coronaOpacityDrop: { value: this.dotCoronaOpacityDrop },+ u_coronaNoiseStrength: { value: this.dotCoronaNoiseStrength },+ u_coronaNoiseScale: { value: this.dotCoronaNoiseScale },+ u_coronaBaseFlightDur: { value: Math.min(20, Math.max(0.3, 3.1 / travelSpeed)) },+ u_coronaBaseFadeDur: { value: Math.min(20, Math.max(0.05, 0.6 / travelSpeed)) },+ u_coronaLaunchInterval: { value: launchInterval },+ u_canvasHeight: { value: this.cachedHeight || this.canvas.clientHeight },+ u_pixelRatio: { value: this.dpr },+ u_depthFadeEnabled: { value: this.dotDepthFadeEnabled ? 1 : 0 },+ u_depthFadeFront: { value: this.dotDepthFadeFront },+ u_depthFadeBack: { value: this.dotDepthFadeBack },+ u_depthFadeMin: { value: this.dotDepthFadeMinOpacity },+ u_depthFadeCurve: { value: this.dotDepthFadeCurve },+ u_gradientAngle: { value: this.dotGradientAngle },+ u_gradientScale: {+ value: new THREE.Vector2(Math.max(0.05, this.dotGradientWidth), Math.max(0.05, this.dotGradientHeight)),+ },+ u_cameraRight: { value: new THREE.Vector3(1, 0, 0) },+ u_cameraUp: { value: new THREE.Vector3(0, 1, 0) },+ u_cameraForward: { value: new THREE.Vector3(0, 0, -1) },+ u_cameraPosition: { value: new THREE.Vector3() },+ u_gradientStops: { value: new Float32Array(GLOBE.DOT_GRADIENT_STOP_COUNT) },+ u_gradientColors: {+ value: Array.from({ length: GLOBE.DOT_GRADIENT_STOP_COUNT }, () => new THREE.Color(0xffffff)),+ },+ },+ vertexShader: SHADERS.DOTS_VERTEX,+ fragmentShader: SHADERS.DOTS_FRAGMENT,+ });+ this.updateDotGradientUniforms();+ this.updateDotDepthFadeUniforms();+ this.dotsGroup.add(new THREE.Points(geometry, this.dotsMaterial));+ this.dotsStartTime = performance.now();+ }++ updateGlobeSurfaceUniforms() {+ const u = this.globeSurfaceMaterial.uniforms;+ u.u_colorA.value.copy(this.globeGradientColorA);+ u.u_colorB.value.copy(this.globeGradientColorB);+ u.u_fresnelColor.value.copy(this.globeFresnelColor);+ u.u_fresnelStrength.value = this.globeFresnelStrength;+ u.u_fresnelPower.value = this.globeFresnelPower;+ u.u_opacity.value = this.globeOpacity;+ u.u_gradientContrast.value = this.globeGradientContrast;+ u.u_gradientOffset.value = this.globeGradientOffset;+ u.u_cameraPosition.value.copy(this.camera.position);+ u.u_gradientDir.value.copy(this.getGradientDirectionCamera());+ this.globeSurfaceMaterial.needsUpdate = true;+ }++ /** Gradient direction in camera space: a clock angle in the screen plane, pushed towards the viewer. */+ getGradientDirectionCamera() {+ const angle = degToRad(this.globeGradientClockAngle);+ const depth = clamp(this.globeGradientDepth, -1, 1);+ return new THREE.Vector3(Math.sin(angle), Math.cos(angle), 0)+ .multiplyScalar(1 - Math.abs(depth))+ .add(new THREE.Vector3(0, 0, -depth))+ .normalize();+ }++ updateAtmosphereMaterial() {+ const u = this.atmosphereMaterial.uniforms;+ u.u_color.value.copy(this.atmosphereColor);+ u.u_intensity.value = this.atmosphereIntensity;+ u.u_opacity.value = this.atmosphereOpacity;+ u.u_innerRadius.value = this.radius;+ u.u_outerRadius.value = this.radius * this.atmosphereRadius;+ u.u_outerFade.value = Math.max(0.01, this.atmosphereFalloff) * this.radius;+ this.atmosphereMesh.position.copy(this.globeGroup.position);+ this.atmosphereMaterial.needsUpdate = true;+ }++ updateDotDepthFadeUniforms() {+ const u = this.dotsMaterial.uniforms;+ u.u_depthFadeEnabled.value = this.dotDepthFadeEnabled ? 1 : 0;+ u.u_depthFadeFront.value = this.dotDepthFadeFront;+ u.u_depthFadeBack.value = this.dotDepthFadeBack;+ u.u_depthFadeMin.value = this.dotDepthFadeMinOpacity;+ u.u_depthFadeCurve.value = Math.max(0.01, this.dotDepthFadeCurve);+ }++ updateDotGradientUniforms() {+ const u = this.dotsMaterial.uniforms;+ u.u_gradientStops.value[0] = clamp(this.dotGradientStopTop, 0, 1);+ u.u_gradientStops.value[1] = clamp(this.dotGradientStopMid, 0, 1);+ u.u_gradientStops.value[2] = clamp(this.dotGradientStopBottom, 0, 1);+ u.u_gradientColors.value[0].copy(this.dotColorTop);+ u.u_gradientColors.value[1].copy(this.dotColorMid);+ u.u_gradientColors.value[2].copy(this.dotColorBottom);+ u.u_gradientAngle.value = this.dotGradientAngle;+ u.u_gradientScale.value.set(Math.max(0.05, this.dotGradientWidth), Math.max(0.05, this.dotGradientHeight));+ }++ updateCameraBasisUniforms() {+ const right = new THREE.Vector3();+ const up = new THREE.Vector3();+ const forward = new THREE.Vector3();+ this.camera.matrixWorld.extractBasis(right, up, forward);+ forward.negate();+ if (this.dotsMaterial) {+ this.dotsMaterial.uniforms.u_cameraRight.value.copy(right);+ this.dotsMaterial.uniforms.u_cameraUp.value.copy(up);+ this.dotsMaterial.uniforms.u_cameraForward.value.copy(forward);+ }+ const u = this.globeSurfaceMaterial.uniforms;+ u.u_cameraRight.value.copy(right);+ u.u_cameraUp.value.copy(up);+ u.u_cameraForward.value.copy(forward);+ }++ // -------------------------------------------------------------------------------- frame loop+ animate() {+ if (this._paused || !this.loaded) return;+ const now = performance.now();+ if (this.lastRender === null) this.lastRender = now;+ const dt = Math.min((now - this.lastRender) / 1000, 0.05);+ this.lastRender = now;+ this.updateAndRender(dt);+ }++ updateUI() {+ if (this._paused || !this.loaded) return;+ const now = performance.now();+ this.updateArcsConsolidated(now);+ this.updateSimpleArcsConsolidated(now);+ this.updateArcController(now);+ this.updateSimpleArcController(now);+ }++ updateAndRender(dt) {+ this.updateCameraBasisUniforms();+ this.globeSurfaceMaterial.uniforms.u_cameraPosition.value.copy(this.camera.position);+ this.globeSurfaceMaterial.uniforms.u_gradientDir.value.copy(this.getGradientDirectionCamera());+ this.atmosphereMesh.quaternion.copy(this.camera.quaternion);+ this.atmosphereMesh.position.copy(this.globeGroup.position);++ // Hover (or drag) eases the corona boost in at 10 % per rendered frame and out at 4 %.+ const boosted = this.isHovered || this.isDragging;+ const targetMultiplier = boosted ? this.hoverBoostAmount : 1;+ if (Math.abs(this.hoverMultiplier - targetMultiplier) >= 0.001) {+ const rate = boosted ? this.hoverAttackSpeed : this.hoverDecaySpeed;+ this.hoverMultiplier = clamp(lerp(this.hoverMultiplier, targetMultiplier, rate), 1, this.hoverBoostAmount);+ if (this.dotsMaterial) {+ const u = this.dotsMaterial.uniforms;+ u.u_coronaBurstDistance.value = this.dotCoronaDistance * this.hoverMultiplier;+ u.u_coronaParticipation.value = Math.min(1, this.dotCoronaParticipation * this.hoverMultiplier);+ }+ }++ const seconds = (performance.now() - this.dotsStartTime) * 0.001;+ if (this.dotsMaterial) {+ this.dotsMaterial.uniforms.u_timeSec.value = seconds + 100;+ this.dotsMaterial.uniforms.u_cameraPosition.value.copy(this.camera.position);+ }++ if (!this.isDragging && this.globeGroup) {+ if (this.dragRotate) {+ const targetY = this.getAutoRotateTargetY();+ const k = 1 - Math.exp(-10 * dt);+ this.currentRotationSpeedY = lerp(this.currentRotationSpeedY, targetY, k);+ this.currentRotationSpeedX = lerp(this.currentRotationSpeedX, this.rotationSpeedX, k);+ if (!this.drag?.isSettling) this.globeGroup.rotation.x += this.currentRotationSpeedX * dt * 60;+ this.globeGroup.rotation.y += this.currentRotationSpeedY * dt * 60;+ this.globeGroup.rotation.z += this.rotationSpeedZ * dt * 60;+ if (+ this.isCoasting &&+ !this.drag?.isSettling &&+ Math.abs(this.currentRotationSpeedX - this.rotationSpeedX) < 5e-5 &&+ Math.abs(this.currentRotationSpeedY - targetY) < 5e-5+ ) {+ this.currentRotationSpeedX = this.rotationSpeedX;+ this.currentRotationSpeedY = targetY;+ this.isCoasting = false;+ }+ } else if (this.autoRotate) {+ const targetY = this.isPacificForSpeedAcceleration()+ ? this.rotationSpeedY * this.arcPacificSpeedMultiplier+ : this.rotationSpeedY;+ this.currentRotationSpeedY = lerp(this.currentRotationSpeedY, targetY, 0.01);+ this.globeGroup.rotation.x += this.rotationSpeedX * dt * 60;+ this.globeGroup.rotation.y += this.currentRotationSpeedY * dt * 60;+ this.globeGroup.rotation.z += this.rotationSpeedZ * dt * 60;+ }+ }++ this.drag?.update(dt);+ this.globeGroup.updateMatrixWorld(true);+ this.arcsGroup.updateMatrixWorld(true);+ this.globeRotationMatrix.setFromMatrix4(this.globeGroup.matrixWorld).transpose();+ this.renderer.render(this.scene, this.camera);+ if (this.loaded) this.lastFrameRendered = true;+ if (this.loaded && this.firstFrameCallbacks.length) {+ const callbacks = this.firstFrameCallbacks;+ this.firstFrameCallbacks = [];+ callbacks.forEach((cb) => cb());+ }+ }++ // -------------------------------------------------------------------------------- pause / API+ shiftTimestamps(ms) {+ this.dotsStartTime += ms;+ for (const arc of this.activeArcs) {+ arc.animation.startTime += ms;+ arc.uiStartTime += ms;+ arc.finalizeStartTime += ms;+ }+ for (const arc of this.activeSimpleArcs) {+ arc.animation.startTime += ms;+ arc.finalizeStartTime += ms;+ }+ if (this.arcControllerNextSpawnTime > 0) this.arcControllerNextSpawnTime += ms;+ if (this.simpleArcControllerNextSpawnTime > 0) this.simpleArcControllerNextSpawnTime += ms;+ }++ get paused() {+ return this._paused;+ }++ /** Pausing freezes every timeline; resuming shifts them by the paused time. */+ set paused(value) {+ if (value === this._paused) return;+ if (value) {+ this.pauseStartTime = performance.now();+ this.lastRender = null;+ } else if (this.pauseStartTime !== null) {+ this.shiftTimestamps(performance.now() - this.pauseStartTime);+ this.pauseStartTime = null;+ }+ this._paused = value;+ }++ setHovered(value) {+ this.isHovered = value;+ }++ setDragRotate(axis) {+ this.dragRotate = axis;+ this.drag?.setAxis(axis);+ }++ setPosition({ x, y, z }) {+ if (x !== undefined) this.globePosition.x = x;+ if (y !== undefined) this.globePosition.y = y;+ if (z !== undefined) this.globePosition.z = z;+ if (this.globeGroup) {+ this.globeGroup.position.copy(this.globePosition);+ this.atmosphereMesh?.position.copy(this.globeGroup.position);+ }+ }++ applyDragRelease({ speedX, speedY }) {+ const tilts = this.dragRotate === "x" || this.dragRotate === "both";+ if (this.dragRotate === "y" || this.dragRotate === "both") {+ this.currentRotationSpeedY = Math.abs(speedY) > 5e-5 ? speedY : this.getAutoRotateTargetY();+ }+ if (tilts) this.currentRotationSpeedX = this.rotationSpeedX;+ this.isCoasting =+ Math.abs(this.currentRotationSpeedX - this.rotationSpeedX) > 5e-5 ||+ Math.abs(this.currentRotationSpeedY - this.getAutoRotateTargetY()) > 5e-5;+ }++ getAutoRotateTargetY() {+ if (!this.autoRotate) return 0;+ return this.isPacificForSpeedAcceleration() ? this.rotationSpeedY * this.arcPacificSpeedMultiplier : this.rotationSpeedY;+ }++ onLoad(callback) {+ if (this.loaded) callback();+ else this.onLoadCallback = callback;+ }++ /** Called once the dots are in and a frame with them has been rendered. */+ onFirstFrame(callback) {+ if (this.loaded && this.lastFrameRendered) callback();+ else this.firstFrameCallbacks.push(callback);+ }++ setSize(width, height) {+ this.cachedWidth = width;+ this.cachedHeight = height;+ this.resize();+ }++ resize() {+ const width = this.cachedWidth;+ const height = this.cachedHeight;+ if (!width || !height) return;+ this.dpr = Math.min(window.devicePixelRatio, 2);+ this.renderer.setSize(width, height, false);+ this.renderer.setPixelRatio(this.dpr);+ this.camera.aspect = width / height;+ this.camera.updateProjectionMatrix();+ if (this.dotsMaterial) {+ this.dotsMaterial.uniforms.u_canvasHeight.value = height;+ this.dotsMaterial.uniforms.u_pixelRatio.value = this.dpr;+ }+ this.arcsGroup?.children.forEach((child) => {+ const material = child.material;+ if (material?.isLineMaterial && material.resolution) material.resolution.set(width, height);+ });+ }++ dispose() {+ this.drag?.dispose();+ this.renderLoop?.stop();+ this.renderLoop = null;+ for (const arc of [...this.activeArcs, ...this.activeSimpleArcs]) this.disposeArcResources(arc);+ this.activeArcs = [];+ this.activeSimpleArcs = [];+ this.scene.traverse((object) => {+ object.geometry?.dispose?.();+ object.material?.dispose?.();+ });+ Object.values(this.markerTextureCache).forEach((texture) => texture.dispose());+ this.markerTextureCache = {};+ this.markerGeometry.dispose();+ this.renderer.dispose();+ }++ // -------------------------------------------------------------------------------- pools+ createArcLinePool(size, maxSegments, linewidth) {+ const pool = [];+ for (let i = 0; i < size; i += 1) {+ const geometry = new LineGeometry();+ const vertexCount = maxSegments + 1;+ geometry.setPositions(new Float32Array(3 * vertexCount));+ geometry.setColors(new Float32Array(3 * vertexCount));+ const material = new LineMaterial({ transparent: true, depthTest: true, depthWrite: true, linewidth, vertexColors: true });+ material.resolution.set(this.cachedWidth || this.canvas.clientWidth, this.cachedHeight || this.canvas.clientHeight);+ material.worldUnits = true;+ material.opacity = 0;+ addVisibleRangeClip(material);+ const line = new Line2(geometry, material);+ line.computeLineDistances();+ line.renderOrder = 10;+ line.visible = false;+ geometry.instanceCount = 0;+ pool.push({ line, geometry, material, inUse: false });+ }+ return pool;+ }++ acquireLine(isSimple) {+ if (isSimple && !this.simpleArcLinePool.length) {+ this.simpleArcLinePool = this.createArcLinePool(this.SIMPLE_ARC_LINE_POOL_SIZE, this.SIMPLE_ARC_MAX_SEGMENTS, 0.004);+ }+ if (!isSimple && !this.arcLinePool.length) {+ this.arcLinePool = this.createArcLinePool(this.ARC_LINE_POOL_SIZE, this.ARC_MAX_SEGMENTS, 0.007);+ }+ const item = (isSimple ? this.simpleArcLinePool : this.arcLinePool).find((it) => !it.inUse);+ if (!item) return null;+ item.inUse = true;+ if (!item.line.parent) this.arcsGroup.add(item.line);+ return item;+ }++ releaseLine(item) {+ item.inUse = false;+ item.line.visible = false;+ item.material.opacity = 0;+ item.geometry.instanceCount = 0;+ item.material.userData.visibleRange.set(0, 0);+ setTotalSegments(item.material, 1);+ }++ acquireMarker(color) {+ if (!this.markerPool.length) {+ for (let i = 0; i < this.MARKER_POOL_SIZE; i += 1) {+ const material = new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, depthTest: true });+ const mesh = new THREE.Mesh(this.markerGeometry, material);+ mesh.visible = false;+ this.markerPool.push({ mesh, inUse: false });+ }+ }+ const item = this.markerPool.find((it) => !it.inUse);+ if (!item) return null;+ item.inUse = true;+ this.markerTextureCache[color] ??= createMarkerTexture(color);+ item.mesh.material.map = this.markerTextureCache[color];+ item.mesh.material.needsUpdate = true;+ if (!item.mesh.parent) this.arcsGroup.add(item.mesh);+ return item.mesh;+ }++ releaseMarker(mesh) {+ const item = this.markerPool.find((it) => it.mesh === mesh);+ if (!item) return;+ item.inUse = false;+ item.mesh.visible = false;+ }++ acquirePoints(isSimple) {+ const pool = isSimple ? this.simpleArcPointsPool : this.arcPointsPool;+ if (!pool.length) {+ const size = isSimple ? this.SIMPLE_ARC_LINE_POOL_SIZE : this.ARC_LINE_POOL_SIZE;+ const count = (isSimple ? this.SIMPLE_ARC_MAX_SEGMENTS : this.ARC_MAX_SEGMENTS) + 1;+ for (let i = 0; i < size; i += 1) pool.push({ points: Array.from({ length: count }, () => new THREE.Vector3()), inUse: false });+ }+ const item = pool.find((it) => !it.inUse);+ if (!item) return null;+ item.inUse = true;+ return item;+ }++ // -------------------------------------------------------------------------------- geometry helpers+ cityToVector(city, target, radius = this.radius) {+ return target.set(city.ux * radius, city.uy * radius, city.uz * radius);+ }++ /** Cities facing the camera (dot ≥ 0.25) and left of the right 30 % band of the globe. */+ getVisibleCityIndices(threshold = this.arcVisibleCityDotThreshold) {+ const visible = [];+ const minDot = clamp(threshold, -1, 1);+ const centre = new THREE.Vector3();+ this.globeGroup.getWorldPosition(centre);+ const toCamera = this.camera.position.clone().sub(centre).normalize();+ const matrix = this.arcsGroup.matrixWorld;+ const maxNdcX = centre.clone().project(this.camera).x + 1 - 2 * this.arcRightEdgeExclusionRatio;+ const p = new THREE.Vector3();+ const dir = new THREE.Vector3();+ for (let i = 0; i < this.cityVectors.length; i += 1) {+ p.copy(this.cityVectors[i]).applyMatrix4(matrix);+ dir.copy(p).sub(centre);+ if (dir.lengthSq() <= 1e-6) continue;+ dir.normalize();+ if (dir.dot(toCamera) >= minDot && p.clone().project(this.camera).x < maxNdcX) visible.push(i);+ }+ return visible;+ }++ /** Screen position (canvas px) of a world point, plus whether it is off-screen or behind the globe. */+ computeProjection(worldPoint, centre, toCamera, width, height) {+ const ndc = worldPoint.clone().project(this.camera);+ const facing = worldPoint.clone().sub(centre).normalize().dot(toCamera);+ return {+ x: (0.5 * ndc.x + 0.5) * width,+ y: (-0.5 * ndc.y + 0.5) * height,+ isOffscreen: ndc.x < -1.1 || ndc.x > 1.1 || ndc.y < -1.1 || ndc.y > 1.1,+ isBehindGlobe: facing < GLOBE.ARC_UI_HIDE_DOT_THRESHOLD,+ depthFade: facing <= -0.1 ? smoothstep(facing, -0.35, -0.1) : 1,+ };+ }++ getPointOnArc(arc, t, target) {+ if (!arc.points.length) return target.set(0, 0, 0);+ if (!arc.totalLineLength || arc.totalLineLength <= 0) return target.copy(arc.points[arc.points.length - 1]);+ const distances = arc.pointDistances;+ const d = clamp(t, 0, 1) * arc.totalLineLength;+ for (let i = 1; i < distances.length; i += 1) {+ if (d <= distances[i]) {+ const span = distances[i] - distances[i - 1];+ const f = span <= 1e-5 ? 0 : (d - distances[i - 1]) / span;+ return target.copy(arc.points[i - 1]).lerp(arc.points[i], f);+ }+ }+ return target.copy(arc.points[arc.points.length - 1]);+ }++ // -------------------------------------------------------------------------------- arc geometry+ /**+ * Great-circle arc between two cities, lifted by sin(πt)·peak. Endpoints are nudged 0.02 along+ * the chord so the line starts just outside the markers. Returns the points, cumulative lengths+ * and per-vertex colours (start → end colour).+ */+ buildArcPoints(from, to, segments, peakFor, pointsItem, colorStart, colorEnd) {+ const p0 = this.cityToVector(from, new THREE.Vector3());+ const p3 = this.cityToVector(to, new THREE.Vector3());+ const n0 = p0.clone().normalize();+ const n3 = p3.clone().normalize();+ const chord = p3.clone().sub(p0);+ const tangentStart = chord.clone().addScaledVector(n0, -chord.dot(n0)).normalize();+ const tangentEnd = chord.clone().addScaledVector(n3, -chord.dot(n3)).normalize();+ const start = p0.clone().addScaledVector(tangentStart, GLOBE.MARKER_TANGENT_OFFSET).normalize().multiplyScalar(this.radius);+ const end = p3.clone().addScaledVector(tangentEnd, -GLOBE.MARKER_TANGENT_OFFSET).normalize().multiplyScalar(this.radius);+ const u0 = start.clone().normalize();+ const u3 = end.clone().normalize();+ const angle = Math.acos(clamp(u0.dot(u3), -1, 1));+ const peak = peakFor(angle);+ const sinAngle = Math.sin(angle);+ const points = pointsItem.points;+ const dir = new THREE.Vector3();+ for (let i = 0; i <= segments; i += 1) {+ const t = i / segments;+ if (sinAngle > 1e-6) {+ dir.copy(u0).multiplyScalar(Math.sin((1 - t) * angle) / sinAngle).addScaledVector(u3, Math.sin(t * angle) / sinAngle).normalize();+ } else {+ dir.copy(u0).lerp(u3, t).normalize();+ }+ const lift = Math.sin(Math.PI * t) * peak;+ points[i].set(dir.x * (this.radius + lift), dir.y * (this.radius + lift), dir.z * (this.radius + lift));+ }+ const distances = [0];+ let total = 0;+ for (let i = 1; i < points.length; i += 1) {+ total += points[i].distanceTo(points[i - 1]);+ distances.push(total);+ }+ const positions = [];+ const colors = [];+ const a = new THREE.Color().setHex(colorStart);+ const b = new THREE.Color().setHex(colorEnd);+ const c = new THREE.Color();+ for (let i = 0; i < points.length; i += 1) {+ positions.push(points[i].x, points[i].y, points[i].z);+ c.copy(a).lerp(b, i / Math.max(1, points.length - 1));+ colors.push(c.r, c.g, c.b);+ }+ return { p0, p3, points, distances, total, positions, colors };+ }++ setupArcLine(lineItem, positions, colors, vertexCount) {+ const { line, geometry, material } = lineItem;+ geometry.setPositions(positions);+ geometry.setColors(colors);+ material.resolution.set(this.cachedWidth || this.canvas.clientWidth, this.cachedHeight || this.canvas.clientHeight);+ material.opacity = 0;+ line.computeLineDistances();+ const segments = Math.max(1, vertexCount - 1);+ geometry.instanceCount = segments;+ line.visible = false;+ material.userData.visibleRange.set(0, 0);+ setTotalSegments(material, segments);+ return segments;+ }++ /** Places a ring marker on the surface at `position`, facing outwards, hidden until animated. */+ placeMarker(marker, position, initialScale) {+ marker.position.copy(position);+ marker.scale.setScalar(initialScale);+ marker.visible = true;+ marker.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), position.clone().normalize());+ marker.material.opacity = 0;+ marker.material.transparent = true;+ }++ drawArc({ from, to, colorStart = 0xff5fa2, colorEnd = 0x7ab8ff, currentTime }) {+ const pointsItem = this.acquirePoints(false);+ if (!pointsItem) return null;+ const minPeak = Math.max(0.01, this.arcPeakMinHeight);+ const maxPeak = Math.max(minPeak, this.arcPeakMaxHeight);+ const arcData = this.buildArcPoints(+ from,+ to,+ this.ARC_MAX_SEGMENTS,+ (angle) => lerp(minPeak, maxPeak, clamp(angle / Math.PI, 0, 1) ** clamp(this.arcPeakAnglePower, 0.01, 5)) * this.radius,+ pointsItem,+ colorStart,+ colorEnd,+ );+ const lineItem = this.acquireLine(false);+ if (!lineItem) {+ pointsItem.inUse = false;+ return null;+ }+ const segments = this.setupArcLine(lineItem, arcData.positions, arcData.colors, arcData.points.length);+ const startMarker = this.acquireMarker(colorStart);+ const endMarker = this.acquireMarker(colorEnd);+ if (!startMarker || !endMarker) {+ this.releaseLine(lineItem);+ pointsItem.inUse = false;+ if (startMarker) this.releaseMarker(startMarker);+ if (endMarker) this.releaseMarker(endMarker);+ return null;+ }+ this.placeMarker(startMarker, arcData.p0, 0.02);+ this.placeMarker(endMarker, arcData.p3, 0.02);++ // Take a free label from the pool (one not shown by another arc).+ const uiData = this.getRandomUIData();+ const busy = new Set(this.activeArcs.filter((a) => a.uiState !== "done" && a.uiElement).map((a) => a.uiElement));+ const uiElement = this.uiPool.find((el) => !busy.has(el)) ?? null;+ if (uiElement) {+ for (const other of this.activeArcs) {+ if (other.uiElement === uiElement) {+ uiElement.style.display = "none";+ other.uiElement = null;+ other.uiState = "done";+ other.uiOpacity = 0;+ }+ }+ this.updateUIElementContent(uiElement, uiData.walletIndex, uiData.amount, uiData.currencyLabel);+ uiElement.style.setProperty("--ui-opacity", "0");+ uiElement.style.setProperty("--ui-scale", "0");+ uiElement.style.setProperty("--ui-x", "0px");+ uiElement.style.setProperty("--ui-y", "0px");+ uiElement.style.display = "block";+ }++ const km = cityDistanceKm(from, to);+ const startTime = currentTime ?? performance.now();+ const { uiTravel, lineDistanceScale } = ARC_TIMING;+ const travelScale = clamp((km / 10000) * uiTravel.distanceScale.factor + 1, uiTravel.distanceScale.min, uiTravel.distanceScale.max);+ const lineDuration = clamp(+ lineDistanceScale.baseDurationMs * (km / lineDistanceScale.referenceKm),+ lineDistanceScale.min,+ lineDistanceScale.max,+ );+ const arc = {+ mesh: lineItem.line,+ points: arcData.points,+ startMarker,+ endMarker,+ uiElement,+ markerScale: 0.2,+ animation: {+ startTime,+ markerA: ARC_TIMING.markerA.durationMs,+ markerB: ARC_TIMING.markerB.durationMs,+ line: lineDuration,+ markerAEasing: ARC_TIMING.markerA.easing,+ markerBEasing: ARC_TIMING.markerB.easing,+ lineEasing: ARC_TIMING.line.easing,+ },+ lineSegmentCount: segments,+ lineProgress: 0,+ pointDistances: arcData.distances,+ totalLineLength: arcData.total,+ arcDistanceKm: km,+ uiState: "idle", // idle → intro → travel → outro → done+ uiStartTime: 0,+ uiIntroDuration: ARC_TIMING.uiIntro.durationMs,+ uiTravelDuration: uiTravel.durationMs * travelScale,+ uiOutroDuration: ARC_TIMING.uiOutro.durationMs,+ uiIntroEasing: ARC_TIMING.uiIntro.easing,+ uiTravelEasing: uiTravel.easing,+ uiOutroEasing: ARC_TIMING.uiOutro.easing,+ uiOpacity: 0,+ uiScaleValue: 0,+ uiTravelProgress: 0.05,+ uiTravelStartT: 0.05,+ uiTravelEndT: 0.95,+ uiCurrentScale: 0,+ uiOutroStartScale: 0,+ uiHideFade: 0,+ finalizeState: "idle", // idle → active (line retreat + marker fade) → done+ finalizeStartTime: 0,+ lineRetreatDuration: ARC_TIMING.lineRetreat.durationMs,+ markerFadeDuration: ARC_TIMING.markerFade.durationMs,+ lineRetreatEasing: ARC_TIMING.lineRetreat.easing,+ markerFadeEasing: ARC_TIMING.markerFade.easing,+ linePoolItem: lineItem,+ pointsPoolItem: pointsItem,+ isSimpleArc: false,+ fromCityName: from.name ?? "",+ toCityName: to.name ?? "",+ };+ this.activeArcs.push(arc);+ return arc;+ }++ drawSimpleArc({ from, to, colorStart = 0x80d4ff, colorEnd = 0x4da6ff, currentTime }) {+ const pointsItem = this.acquirePoints(true);+ if (!pointsItem) return null;+ const arcData = this.buildArcPoints(+ from,+ to,+ this.SIMPLE_ARC_MAX_SEGMENTS,+ (angle) => lerp(0.06, 0.18, clamp(angle / Math.PI, 0, 1)) * this.radius,+ pointsItem,+ colorStart,+ colorEnd,+ );+ const lineItem = this.acquireLine(true);+ if (!lineItem) {+ pointsItem.inUse = false;+ return null;+ }+ const segments = this.setupArcLine(lineItem, arcData.positions, arcData.colors, arcData.points.length);+ const startMarker = this.acquireMarker(colorStart);+ const endMarker = this.acquireMarker(colorEnd);+ if (!startMarker || !endMarker) {+ this.releaseLine(lineItem);+ pointsItem.inUse = false;+ if (startMarker) this.releaseMarker(startMarker);+ if (endMarker) this.releaseMarker(endMarker);+ return null;+ }+ this.placeMarker(startMarker, arcData.p0, 0.01);+ this.placeMarker(endMarker, arcData.p3, 0.01);+ const startTime = currentTime ?? performance.now();+ return {+ mesh: lineItem.line,+ points: arcData.points,+ startMarker,+ endMarker,+ uiElement: null,+ markerScale: 0.12,+ animation: {+ startTime,+ markerA: SIMPLE_ARC_TIMING.markerA.durationMs,+ markerB: SIMPLE_ARC_TIMING.markerB.durationMs,+ line: SIMPLE_ARC_TIMING.line.durationMs,+ markerAEasing: SIMPLE_ARC_TIMING.markerA.easing,+ markerBEasing: SIMPLE_ARC_TIMING.markerB.easing,+ lineEasing: SIMPLE_ARC_TIMING.line.easing,+ },+ lineSegmentCount: segments,+ lineProgress: 0,+ pointDistances: arcData.distances,+ totalLineLength: arcData.total,+ uiState: "done",+ uiStartTime: 0,+ uiOpacity: 0,+ uiScaleValue: 0,+ finalizeState: "idle",+ finalizeStartTime: 0,+ lineRetreatDuration: SIMPLE_ARC_TIMING.lineRetreat.durationMs,+ markerFadeDuration: SIMPLE_ARC_TIMING.markerFade.durationMs,+ lineRetreatEasing: SIMPLE_ARC_TIMING.lineRetreat.easing,+ markerFadeEasing: SIMPLE_ARC_TIMING.markerFade.easing,+ linePoolItem: lineItem,+ pointsPoolItem: pointsItem,+ isSimpleArc: true,+ fromCityName: from.name ?? "",+ toCityName: to.name ?? "",+ };+ }++ disposeArcResources(arc) {+ if (arc.linePoolItem) this.releaseLine(arc.linePoolItem);+ if (arc.pointsPoolItem) arc.pointsPoolItem.inUse = false;+ if (arc.startMarker) this.releaseMarker(arc.startMarker);+ if (arc.endMarker) this.releaseMarker(arc.endMarker);+ if (arc.uiElement) arc.uiElement.style.display = "none";+ }++ // -------------------------------------------------------------------------------- arc labels+ getRandomUIData() {+ const walletIndex = Math.floor(Math.random() * WALLETS.length);+ const isPhantom = WALLETS[walletIndex].name === "Phantom";+ return {+ walletIndex,+ amount: Math.floor(999 * Math.random()) + 1,+ currencyLabel: isPhantom ? "CASH" : STABLECOINS[Math.floor(Math.random() * STABLECOINS.length)],+ };+ }++ updateUIElementContent(element, walletIndex, amount, currency) {+ const icon = element.querySelector(".globe__arc-ui-icon");+ const amountEl = element.querySelector(".globe__arc-ui-amount");+ const currencyEl = element.querySelector(".globe__arc-ui-currency");+ if (icon) {+ icon.style.display = "";+ svgIdCounter += 1;+ const svg = WALLETS[walletIndex % WALLETS.length].svg+ .replace(/id="([^"]+)"/g, `id="$1-${svgIdCounter}"`)+ .replace(/url\(#([^)]+)\)/g, `url(#$1-${svgIdCounter})`);+ icon.replaceChildren(new DOMParser().parseFromString(svg, "image/svg+xml").documentElement);+ }+ if (amountEl) {+ amountEl.style.display = "";+ amountEl.textContent = `$${amount}`;+ }+ if (currencyEl) currencyEl.textContent = currency;+ }++ // -------------------------------------------------------------------------------- per-frame arc update+ updateArcsConsolidated(now) {+ const centre = new THREE.Vector3();+ this.globeGroup.getWorldPosition(centre);+ const toCamera = this.camera.position.clone().sub(centre).normalize();+ const width = this.cachedWidth;+ const height = this.cachedHeight;+ const hasSize = width > 0 && height > 0;+ for (let i = this.activeArcs.length - 1; i >= 0; i -= 1) {+ const arc = this.activeArcs[i];+ this.updateSingleArcAnimation(arc, now);+ if (hasSize && arc.uiElement) this.updateSingleArcUIPosition(arc, centre, toCamera, width, height);+ if (arc.finalizeState === "done" && arc.uiState === "done") {+ this.disposeArcResources(arc);+ this.activeArcs.splice(i, 1);+ }+ }+ }++ updateSimpleArcsConsolidated(now) {+ for (let i = this.activeSimpleArcs.length - 1; i >= 0; i -= 1) {+ const arc = this.activeSimpleArcs[i];+ this.updateSingleArcAnimation(arc, now);+ if (arc.lineProgress >= 0.999 && arc.finalizeState === "idle") this.startArcFinalization(arc, now);+ if (arc.finalizeState === "done") {+ this.disposeArcResources(arc);+ this.activeSimpleArcs.splice(i, 1);+ }+ }+ }++ /** Marker A pops in, then marker B, then the line grows (opacity follows its eased progress). */+ updateSingleArcAnimation(arc, now) {+ const { markerA, markerB, line, startTime, markerAEasing, markerBEasing, lineEasing } = arc.animation;+ const elapsed = Math.max(0, now - startTime);+ const { markerAlpha, retreat } = this.getArcFinalizationFactors(arc, now);+ const lineT = line <= 0 ? 1 : clamp(Math.max(0, elapsed - markerA - markerB) / line, 0, 1);++ const a = ease(markerA <= 0 ? 1 : Math.min(1, elapsed / markerA), markerAEasing);+ arc.startMarker.material.opacity = a * markerAlpha;+ arc.startMarker.scale.setScalar(Math.max(1e-4, arc.markerScale * a * markerAlpha));++ const b = elapsed >= markerA ? ease(markerB <= 0 ? 1 : Math.min(1, Math.max(0, elapsed - markerA) / markerB), markerBEasing) : 0;+ arc.endMarker.material.opacity = b * markerAlpha;+ arc.endMarker.scale.setScalar(Math.max(1e-4, arc.markerScale * b * markerAlpha));++ const material = arc.mesh.material;+ const head = ease(lineT, lineEasing);+ const tail = arc.finalizeState !== "idle" ? retreat : 0;+ material.userData.visibleRange.set(tail, head);+ setTotalSegments(material, arc.lineSegmentCount);+ if (arc.linePoolItem && arc.linePoolItem.geometry.instanceCount !== arc.lineSegmentCount) {+ arc.linePoolItem.geometry.instanceCount = arc.lineSegmentCount;+ }+ if (retreat > 1e-4 && arc.lineProgress >= 0.999 && arc.finalizeState !== "idle") {+ const opacity = Math.max(0, 1 - retreat);+ if (tail >= head || opacity <= 0.001) {+ arc.mesh.visible = false;+ material.opacity = 0;+ } else {+ arc.mesh.visible = true;+ material.opacity = opacity;+ }+ } else if (lineT <= 0) {+ arc.mesh.visible = false;+ material.opacity = 0;+ } else {+ arc.mesh.visible = true;+ material.opacity = head;+ }+ arc.lineProgress = lineT;+ this.updateArcUIState(arc, now);+ }++ startArcFinalization(arc, now) {+ if (arc.finalizeState !== "idle") return;+ arc.finalizeState = "active";+ arc.finalizeStartTime = now;+ }++ /** Line retreat (tail catches the head) and, from 80 % of it, the marker fade. */+ getArcFinalizationFactors(arc, now) {+ if (arc.finalizeState === "done") return { markerAlpha: 0, retreat: 1 };+ if (arc.finalizeState !== "active") return { markerAlpha: 1, retreat: 0 };+ const elapsed = Math.max(0, now - arc.finalizeStartTime);+ const retreatDuration = Math.max(100, arc.lineRetreatDuration);+ const retreat = ease(clamp(elapsed / retreatDuration, 0, 1), arc.lineRetreatEasing);+ const fadeDuration = Math.max(50, arc.markerFadeDuration);+ const fade = ease(clamp(Math.max(0, elapsed - 0.8 * retreatDuration) / fadeDuration, 0, 1), arc.markerFadeEasing);+ if (retreat >= 1 && fade >= 1) arc.finalizeState = "done";+ return { markerAlpha: Math.max(0, 1 - fade), retreat: clamp(retreat, 0, 1) };+ }++ /** Label: waits for the line, scales/fades in (800 ms), travels 5 → 95 % of the arc, shrinks out (600 ms). */+ updateArcUIState(arc, now) {+ if (arc.uiState === "done") {+ arc.uiOpacity = 0;+ arc.uiScaleValue = 0;+ return;+ }+ if (arc.uiState === "idle") {+ arc.uiOpacity = 0;+ arc.uiScaleValue = 0;+ arc.uiTravelProgress = arc.uiTravelStartT;+ if (arc.lineProgress >= 1) {+ arc.uiState = "intro";+ arc.uiStartTime = now;+ arc.uiScaleValue = 0;+ }+ return;+ }+ if (arc.uiState === "intro") {+ const t = (now - arc.uiStartTime) / Math.max(1, arc.uiIntroDuration);+ const e = ease(t, arc.uiIntroEasing);+ arc.uiOpacity = e;+ arc.uiScaleValue = e;+ arc.uiTravelProgress = arc.uiTravelStartT;+ if (t >= 1) {+ arc.uiState = "travel";+ arc.uiStartTime = now;+ arc.uiScaleValue = 0;+ }+ return;+ }+ if (arc.uiState === "travel") {+ const t = clamp((now - arc.uiStartTime) / Math.max(1, arc.uiTravelDuration), 0, 1);+ const e = ease(t, arc.uiTravelEasing);+ arc.uiOpacity = 1;+ arc.uiScaleValue = e;+ arc.uiTravelProgress = lerp(arc.uiTravelStartT, arc.uiTravelEndT, e);+ if (t >= 1) {+ arc.uiState = "outro";+ arc.uiStartTime = now;+ arc.uiScaleValue = 0;+ this.startArcFinalization(arc, now);+ arc.uiOutroStartScale = arc.uiCurrentScale ?? 0;+ }+ return;+ }+ if (arc.uiState === "outro") {+ const t = (now - arc.uiStartTime) / Math.max(1, arc.uiOutroDuration);+ const e = ease(t, arc.uiOutroEasing);+ arc.uiOpacity = Math.max(0, 1 - e);+ arc.uiScaleValue = e;+ arc.uiTravelProgress = arc.uiTravelEndT;+ if (t >= 1) {+ arc.uiState = "done";+ arc.uiOpacity = 0;+ arc.uiScaleValue = 0;+ }+ }+ }++ /** Positions the label just above the arc point it rides on; scale 0.75..1 grows with arc height. */+ updateSingleArcUIPosition(arc, centre, toCamera, width, height) {+ const point = this.getPointOnArc(arc, clamp(arc.uiTravelProgress ?? 0.5, 0, 1), new THREE.Vector3());+ const normal = point.clone().normalize();+ const lift = Math.max(0, point.length() - this.radius);+ const heightRatio = clamp(lift / (0.75 * this.radius), 0, 1);+ const offset = lerp(GLOBE.ARC_UI_MIN_OFFSET, GLOBE.ARC_UI_MAX_OFFSET, heightRatio);+ const anchor = point.clone().add(normal.multiplyScalar(offset)).applyMatrix4(this.arcsGroup.matrixWorld);+ const { x, y, isOffscreen, isBehindGlobe, depthFade } = this.computeProjection(anchor, centre, toCamera, width, height);+ const hidden = isBehindGlobe || isOffscreen;+ arc.uiHideFade = lerp(arc.uiHideFade, hidden ? 1 : 0, hidden ? 0.25 : 0.15);+ const opacity = clamp(arc.uiOpacity ?? 0, 0, 1) * depthFade * (1 - arc.uiHideFade);+ if (!(opacity > 0.001)) {+ arc.uiElement.style.display = "none";+ return;+ }+ const fullScale = lerp(GLOBE.ARC_UI_MIN_SCALE, GLOBE.ARC_UI_MAX_SCALE, heightRatio);+ const progress = clamp(arc.uiScaleValue ?? 0, 0, 1);+ let scale = 0;+ if (arc.uiState === "intro") scale = lerp(0, fullScale, progress);+ else if (arc.uiState === "travel") scale = fullScale;+ else if (arc.uiState === "outro") scale = lerp(arc.uiOutroStartScale > 0 ? arc.uiOutroStartScale : fullScale, 0, progress);++ const style = arc.uiElement.style;+ const px = Math.round(x);+ const py = Math.round(y);+ if (arc.uiLastX === undefined || arc.uiLastY === undefined || Math.abs(px - arc.uiLastX) >= 1 || Math.abs(py - arc.uiLastY) >= 1) {+ style.setProperty("--ui-x", `${px}px`);+ style.setProperty("--ui-y", `${py}px`);+ arc.uiLastX = px;+ arc.uiLastY = py;+ }+ if (arc.uiCurrentScale !== scale) style.setProperty("--ui-scale", scale.toFixed(3));+ style.setProperty("--ui-opacity", opacity.toFixed(3));+ if (style.display === "none") style.display = "block";+ arc.uiCurrentScale = scale;+ }++ // -------------------------------------------------------------------------------- spawning+ updateArcController(now) {+ if (!this.arcControllerEnabled || CITIES.length < 2) return;+ if (this.arcControllerNextSpawnTime === 0) this.arcControllerNextSpawnTime = now;+ if (now < this.arcControllerNextSpawnTime) return;+ if (this.activeArcs.length >= this.arcControllerMaxActive) {+ this.arcControllerNextSpawnTime = now + 250;+ return;+ }+ let spawned = false;+ for (let attempt = 0; attempt < 2 && !spawned; attempt += 1) spawned = this.spawnRandomCityArc(now);+ if (spawned) {+ const min = Math.max(0, Math.floor(this.arcSpawnIntervalMin));+ const max = Math.max(min, Math.floor(this.arcSpawnIntervalMax));+ this.arcControllerNextSpawnTime = now + Math.max(100, min === max ? min : randInt(min, max));+ } else {+ this.arcControllerNextSpawnTime = now + 200;+ }+ }++ spawnRandomCityArc(now) {+ const pair = this.pickRandomCityPair();+ if (!pair) return false;+ const palette = this.arcColorPalettes[Math.floor(Math.random() * this.arcColorPalettes.length)];+ const arc = this.drawArc({ from: pair.from, to: pair.to, colorStart: palette.start, colorEnd: palette.end, currentTime: now });+ if (arc) this.updateSingleArcAnimation(arc, now);+ return !!arc;+ }++ updateSimpleArcController(now) {+ if (!this.simpleArcControllerEnabled || CITIES.length < 2) return;+ if (this.simpleArcControllerNextSpawnTime === 0) this.simpleArcControllerNextSpawnTime = now;+ if (now < this.simpleArcControllerNextSpawnTime) return;+ const running = this.activeSimpleArcs.filter((arc) => arc.finalizeState !== "done").length;+ if (running >= this.simpleArcMaxActive) {+ this.simpleArcControllerNextSpawnTime = now + 150;+ return;+ }+ let spawned = false;+ for (let attempt = 0; attempt < 2 && !spawned; attempt += 1) spawned = this.spawnSimpleArc(now);+ if (spawned) {+ const min = Math.max(0, Math.floor(this.simpleArcSpawnIntervalMin));+ const max = Math.max(min, Math.floor(this.simpleArcSpawnIntervalMax));+ this.simpleArcControllerNextSpawnTime = now + Math.max(50, min === max ? min : randInt(min, max));+ } else {+ this.simpleArcControllerNextSpawnTime = now + 150;+ }+ }++ spawnSimpleArc(now) {+ const pair = this.pickSimpleArcCityPair();+ if (!pair) return false;+ const palette = this.simpleArcColorPalettes[Math.floor(Math.random() * this.simpleArcColorPalettes.length)];+ const arc = this.drawSimpleArc({ from: pair.from, to: pair.to, colorStart: palette.start, colorEnd: palette.end, currentTime: now });+ if (!arc) return false;+ this.activeSimpleArcs.push(arc);+ this.updateSingleArcAnimation(arc, now);+ return true;+ }++ /** Cities used by labelled arcs are off-limits for simple arcs, so labels stay readable. */+ pickSimpleArcCityPair() {+ const candidates = this.candidateCityIndices;+ const count = candidates.length;+ if (count < 2) return null;+ const busy = new Set();+ for (const arc of this.activeArcs) {+ if (!arc.uiElement) continue;+ if (arc.fromCityName) busy.add(arc.fromCityName);+ if (arc.toCityName) busy.add(arc.toCityName);+ }+ for (let attempt = 0; attempt < 30; attempt += 1) {+ const a = candidates[Math.floor(Math.random() * count)];+ let b = candidates[Math.floor(Math.random() * count)];+ for (let retry = 0; b === a && retry < 10; retry += 1) b = candidates[Math.floor(Math.random() * count)];+ if (b === a) continue;+ const from = CITIES[a];+ const to = CITIES[b];+ if (!from || !to || busy.has(from.name) || busy.has(to.name)) continue;+ const key = `${from.name}-${to.name}`;+ if (key === this.lastSimpleArcPairKey) continue;+ const km = cityDistanceKm(from, to);+ if (km >= this.simpleArcMinDistanceKm && km <= this.simpleArcMaxDistanceKm) {+ this.lastSimpleArcPairKey = key;+ return { from, to };+ }+ }+ return null;+ }++ /** Keeps a new label ≥ 80 px from live labels and ≥ 56 px from their markers (screen space). */+ checkArcSpawnDistance(from, to) {+ if (this.activeArcs.length === 0) return true;+ const minDistance = this.arcMinUIScreenDistance;+ if (minDistance <= 0) return true;+ const a = this.cityToVector(from, new THREE.Vector3());+ const b = this.cityToVector(to, new THREE.Vector3());+ const mid = a.lerp(b, 0.5).normalize().multiplyScalar(1.1 * this.radius).applyMatrix4(this.arcsGroup.matrixWorld);+ const ndc = mid.clone().project(this.camera);+ const width = this.cachedWidth;+ const height = this.cachedHeight;+ if (width === 0 || height === 0) return true;+ const x = (0.5 * ndc.x + 0.5) * width;+ const y = (-0.5 * ndc.y + 0.5) * height;+ if (ndc.z > 1 || ndc.x < -1.2 || ndc.x > 1.2 || ndc.y < -1.2 || ndc.y > 1.2) return true;+ const toScreen = (marker) => {+ const p = marker.position.clone().applyMatrix4(this.arcsGroup.matrixWorld).project(this.camera);+ return { x: (0.5 * p.x + 0.5) * width, y: (-0.5 * p.y + 0.5) * height };+ };+ for (const arc of this.activeArcs) {+ if (arc.uiState === "done" || arc.uiState === "outro") continue;+ if (arc.uiLastX !== undefined && arc.uiLastY !== undefined && Math.hypot(x - arc.uiLastX, y - arc.uiLastY) < minDistance) {+ return false;+ }+ const s = toScreen(arc.startMarker);+ const e = toScreen(arc.endMarker);+ const markerDistance = 0.7 * minDistance;+ if (Math.hypot(x - s.x, y - s.y) < markerDistance) return false;+ if (Math.hypot(x - e.x, y - e.y) < markerDistance) return false;+ }+ return true;+ }++ getViewedLongitude() {+ let yaw = this.globeGroup.rotation.y % (2 * Math.PI);+ if (yaw > Math.PI) yaw -= 2 * Math.PI;+ if (yaw < -Math.PI) yaw += 2 * Math.PI;+ return -((180 / Math.PI) * yaw);+ }++ isPacificOceanVisible() {+ const lon = this.getViewedLongitude();+ return lon <= this.arcPacificWestBoundary || lon >= this.arcPacificEastBoundary;+ }++ isPacificForSpeedAcceleration() {+ const lon = this.getViewedLongitude();+ return lon <= this.arcPacificSpeedWestBoundary || lon >= this.arcPacificSpeedEastBoundary;+ }++ hasActiveTranspacificArc() {+ for (const arc of this.activeArcs) {+ const a = arc.startMarker.position;+ const b = arc.endMarker.position;+ const lonA = Math.atan2(a.x, a.z) * (180 / Math.PI);+ const lonB = Math.atan2(b.x, b.z) * (180 / Math.PI);+ if ((lonA < -100 && lonB > 100) || (lonA > 100 && lonB < -100)) return true;+ }+ return false;+ }++ pickTranspacificPair() {+ for (const pair of [...TRANSPACIFIC_PAIRS].sort(() => Math.random() - 0.5)) {+ let from = findCity(pair.from);+ let to = findCity(pair.to);+ if (!from || !to) continue;+ if (Math.random() < 0.5) [from, to] = [to, from];+ const key = `${from.name}-${to.name}`;+ const reverse = `${to.name}-${from.name}`;+ if (key !== this.lastArcPairKey && reverse !== this.lastArcPairKey && this.checkArcSpawnDistance(from, to)) {+ return { from, to };+ }+ }+ return null;+ }++ /**+ * One end must face the camera (randomly the start or the end); prefers pairs ≥ 2000 km apart+ * that keep labels apart, falling back to the farthest pair found in up to 276 attempts.+ */+ pickRandomCityPair() {+ const candidates = this.candidateCityIndices;+ const count = candidates.length;+ if (count < 2) return null;+ if (this.arcPreferTranspacific && this.isPacificOceanVisible() && !this.hasActiveTranspacificArc()) {+ const pair = this.pickTranspacificPair();+ if (pair) {+ this.lastArcPairKey = `${pair.from.name}-${pair.to.name}`;+ return pair;+ }+ }+ const minKm = Math.max(0, this.arcCityMinDistanceKm);+ const attempts = Math.max(20, 4 * count);+ const maxBlocked = this.arcMaxSpawnDistanceAttempts;+ let best = null;+ let bestKm = -Infinity;+ let bestIsSpaced = false;+ let fromPool = candidates;+ let toPool = candidates;+ const visible = this.getVisibleCityIndices();+ if (visible.length > 0) {+ const visibleSet = new Set(visible);+ const visibleCandidates = candidates.length < CITIES.length ? visible.filter((i) => visibleSet.has(i)) : visible;+ if (visibleCandidates.length > 0) {+ if (Math.random() < 0.5) fromPool = visibleCandidates;+ else toPool = visibleCandidates;+ }+ }+ let blocked = 0;+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ const a = fromPool[Math.floor(Math.random() * fromPool.length)];+ let b = toPool[Math.floor(Math.random() * toPool.length)];+ for (let retry = 0; b === a && retry < toPool.length + 5; retry += 1) b = toPool[Math.floor(Math.random() * toPool.length)];+ if (b === a) continue;+ const from = CITIES[a];+ const to = CITIES[b];+ if (!from || !to || from === to) continue;+ const key = `${from.name}-${to.name}`;+ if (key === this.lastArcPairKey && count > 2) continue;+ const km = cityDistanceKm(from, to);+ if (this.checkArcSpawnDistance(from, to)) {+ if (km > bestKm || !bestIsSpaced) {+ bestKm = km;+ best = { from, to };+ bestIsSpaced = true;+ }+ if (km >= minKm) {+ this.lastArcPairKey = key;+ return { from, to };+ }+ } else {+ blocked += 1;+ if (!bestIsSpaced && km > bestKm) {+ bestKm = km;+ best = { from, to };+ }+ }+ if (blocked >= maxBlocked && !bestIsSpaced && best && km >= minKm) {+ this.lastArcPairKey = key;+ return { from, to };+ }+ }+ if (best) {+ this.lastArcPairKey = `${best.from.name}-${best.to.name}`;+ return best;+ }+ return null;+ }+}diff --git a/public/examples/stripe-bento/src/widgets/crypto/render-loop.js b/public/examples/stripe-bento/src/widgets/crypto/render-loop.jsnew file mode 100644index 0000000..75f43e0--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/render-loop.js@@ -0,0 +1,141 @@+// requestAnimationFrame driver shared by every WebGL graphic on the page (port of stripe.com's+// render-loop manager). It measures the display refresh rate over the first 12 frames, and calls+// each registered loop every frame. Every 24 frames it compares the+// achieved frame rate with the estimate: more than 10 % slower raises a warning level (1..3),+// faster than the estimate lowers it again. Loops use the level to skip frames.++const REFRESH_RATES = [240, 160, 144, 120, 60, 30, 24];+const ESTIMATE_FRAMES = 12;+const CHECK_FRAMES = 24;+const MAX_WARNING_LEVEL = 3;++const median = (values) => {+ if (!values.length) return undefined;+ const sorted = [...values].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+};+const mean = (values) => (values.length ? values.reduce((a, b) => a + b) / values.length : undefined);++class RenderLoopManager {+ static get instance() {+ // One manager per page, like stripe.com's singleton, so every graphic shares the estimate.+ if (!window.__bentoRenderLoopManager) window.__bentoRenderLoopManager = new RenderLoopManager();+ return window.__bentoRenderLoopManager;+ }++ constructor() {+ this.frameTimes = [];+ this.lastFrameTime = 0;+ this.resumedTime = null;+ this.elapsedTime = 0;+ this.loops = new Set();+ this.warningLevel = 0;+ this.estimatedRefreshRate = undefined;+ this.rafId = null;+ document.addEventListener("visibilitychange", () => {+ if (document.hidden) this.suspend();+ else this.resume();+ });+ this.start();+ }++ start() {+ if (this.rafId) return;+ this.lastFrameTime = performance.now();+ this.resumedTime = null;+ this.rafId = requestAnimationFrame(this.update);+ }++ stop() {+ if (this.rafId) cancelAnimationFrame(this.rafId);+ this.rafId = null;+ }++ suspend() {+ this.stop();+ }++ resume() {+ this.lastFrameTime = performance.now();+ this.start();+ }++ update = (time) => {+ this.rafId = requestAnimationFrame(this.update);+ const frameTime = time - this.lastFrameTime;+ this.lastFrameTime = time;+ this.frameTimes.push(frameTime);++ if (!this.estimatedRefreshRate) {+ if (this.frameTimes.length >= ESTIMATE_FRAMES) {+ const fps = 1000 / median(this.frameTimes);+ this.estimatedRefreshRate = REFRESH_RATES.reduce((best, rate) =>+ Math.abs(rate - fps) < Math.abs(best - fps) ? rate : best,+ );+ this.frameTimes = [];+ }+ // On stripe.com the hero gradient starts this singleton at page load, so the estimate is+ // long done when the bento graphics mount. Here the manager starts with the lazily loaded+ // widget, so loops run during the estimate too, rather than waiting 12 frames.+ this.runLoops(time);+ return;+ }++ this.runLoops(time);++ if (this.frameTimes.length >= CHECK_FRAMES) {+ const sorted = this.frameTimes.slice().sort((a, b) => a - b);+ sorted.splice(-2); // ignore the two slowest frames+ const deficit = this.estimatedRefreshRate - 1000 / mean(sorted);+ if (deficit > 0.1 * this.estimatedRefreshRate) {+ const level = Math.min(this.warningLevel + 1, MAX_WARNING_LEVEL);+ if (level !== this.warningLevel) {+ this.warningLevel = level;+ for (const loop of this.loops) loop.onPerformanceWarning(level);+ }+ } else if (deficit < 0 && this.warningLevel > 0) {+ this.warningLevel -= 1;+ for (const loop of this.loops) loop.onPerformanceRecovered?.(this.warningLevel);+ }+ this.frameTimes = [];+ }+ };++ runLoops(time) {+ if (this.resumedTime === null) this.resumedTime = time - this.elapsedTime;+ this.elapsedTime = Math.max(time - this.resumedTime, 0);+ for (const loop of this.loops) {+ loop.frameCount += 1;+ if (loop.frameCount % loop.frameInterval === 0) loop.renderFunction(this.elapsedTime);+ }+ }+}++export class RenderLoop {+ constructor(renderFunction, frameInterval = 1) {+ this.frameCount = 0;+ this.frameInterval = frameInterval;+ this.initialFrameInterval = frameInterval;+ this.renderFunction = renderFunction;+ this.onPerformanceWarning = (level) => {+ this.frameInterval = Math.max(level + 1, this.frameInterval);+ };+ this.onPerformanceRecovered = (level) => {+ this.frameInterval = Math.max(level + 1, this.initialFrameInterval);+ };+ }++ start() {+ RenderLoopManager.instance.loops.add(this);+ }++ stop() {+ RenderLoopManager.instance.loops.delete(this);+ }+}++/** Starts measuring the refresh rate early, so loops created a bit later can run from their first frame. */+export function warmUpRenderLoops() {+ return RenderLoopManager.instance;+}diff --git a/public/examples/stripe-bento/src/widgets/crypto/shaders.js b/public/examples/stripe-bento/src/widgets/crypto/shaders.jsnew file mode 100644index 0000000..17c1779--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/shaders.js@@ -0,0 +1,259 @@+// GLSL copied from stripe.com's globe module (three.js r178 ShaderMaterial built-ins).++// Atmosphere halo: a camera-facing plane around the globe.+export const ATMOSPHERE_VERTEX = /* glsl */ `+varying vec2 vPlanePosition;++void main() {+ vPlanePosition = position.xy;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+}+`;+export const ATMOSPHERE_FRAGMENT = /* glsl */ `+uniform vec3 u_color;+uniform float u_intensity;+uniform float u_opacity;+uniform float u_innerRadius;+uniform float u_outerRadius;+uniform float u_outerFade;++varying vec2 vPlanePosition;++void main() {+ float dist = length(vPlanePosition);+ float inner = u_innerRadius;+ float outer = max(inner + 0.001, u_outerRadius);+ float fadeEnd = outer + max(0.001, u_outerFade);++ float grow = smoothstep(inner, outer, dist);+ float fade = 1.0 - smoothstep(outer, fadeEnd, dist);+ float halo = clamp(grow * fade, 0.0, 1.0);++ vec3 color = u_color;+ float alpha = halo * u_intensity * u_opacity;+ if (alpha <= 0.001) discard;+ gl_FragColor = vec4(color, alpha);+}+`;++// Globe surface: white-to-blue gradient in camera space plus a faint fresnel rim.+export const SURFACE_VERTEX = /* glsl */ `+varying float vGradient;+varying float vFresnel;+uniform vec3 u_gradientDir;+uniform vec3 u_cameraPosition;+uniform vec3 u_cameraRight;+uniform vec3 u_cameraUp;+uniform vec3 u_cameraForward;++void main() {+ vec4 worldPosition = modelMatrix * vec4(position, 1.0);+ vec3 worldNormal = normalize(mat3(modelMatrix) * normal);+ vec3 surfaceDir = normalize(worldPosition.xyz);+ vec3 surfaceCamera;+ surfaceCamera.x = dot(surfaceDir, u_cameraRight);+ surfaceCamera.y = dot(surfaceDir, u_cameraUp);+ surfaceCamera.z = dot(surfaceDir, u_cameraForward);+ vGradient = dot(surfaceCamera, normalize(u_gradientDir)) * 0.5 + 0.5;+ vec3 viewDir = normalize(u_cameraPosition - worldPosition.xyz);+ float fresnel = clamp(1.0 - max(dot(viewDir, worldNormal), 0.0), 0.0, 1.0);+ vFresnel = fresnel;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+}+`;+export const SURFACE_FRAGMENT = /* glsl */ `+uniform vec3 u_colorA;+uniform vec3 u_colorB;+uniform vec3 u_fresnelColor;+uniform float u_fresnelStrength;+uniform float u_fresnelPower;+uniform float u_opacity;+uniform float u_gradientContrast;+uniform float u_gradientOffset;++varying float vGradient;+varying float vFresnel;++void main() {+ float gradient = clamp(vGradient + u_gradientOffset, 0.0, 1.0);+ gradient = clamp(+ 0.5 + (gradient - 0.5) * u_gradientContrast,+ 0.0,+ 1.0+ );+ vec3 baseColor = mix(u_colorA, u_colorB, gradient);+ float fresnelBase = pow(clamp(vFresnel, 0.0, 1.0), u_fresnelPower);+ float rimFactor = clamp(fresnelBase * u_fresnelStrength, 0.0, 1.0);+ vec3 color = mix(baseColor, u_fresnelColor, rimFactor);+ float alpha = clamp(u_opacity, 0.0, 1.0);+ gl_FragColor = vec4(color, alpha);+}+`;++// Land dots: point sprites on the sphere. A share of them periodically lifts off the surface+// ("corona"); hovering the card raises the share and the distance.+export const DOTS_VERTEX = /* glsl */ `+uniform float u_timeSec;+uniform float u_radius;+uniform float u_dotSize;+uniform float u_coronaBurstDistance;+uniform float u_coronaParticipation;+uniform float u_coronaNoiseStrength;+uniform float u_coronaNoiseScale;+uniform float u_gradientAngle;+uniform vec2 u_gradientScale;+uniform vec3 u_cameraRight;+uniform vec3 u_cameraUp;+uniform vec3 u_cameraForward;+uniform vec3 u_cameraPosition;+uniform float u_coronaBaseFlightDur;+uniform float u_coronaBaseFadeDur;+uniform float u_coronaLaunchInterval;+uniform float u_canvasHeight;+uniform float u_pixelRatio;++attribute float rndId;+attribute float sizeVariation;+attribute float opacityVariation;+attribute float coronaSeed;+attribute float varianceRate;+attribute float varianceMotion;+attribute float coronaCanParticipate;++varying float vGradientCoord;+varying float vOpacityVariation;+varying float vCoronaProgress;+varying float vCoronaVisibility;+varying float vDepthFacing;++const float DESIGN_PIXEL_RATIO = 2.0;++void main() {+ vec3 baseNormal = normalize(position);+ vec3 pos = baseNormal * u_radius;+ float coronaEase = 0.0;++ if (u_coronaParticipation > 0.001 && coronaCanParticipate > 0.5) {+ float varianceScale = mix(0.667, 1.5, varianceMotion);+ float flightDuration = u_coronaBaseFlightDur * varianceScale;+ float fadeDuration = u_coronaBaseFadeDur * varianceScale;+ float desiredInterval = u_coronaLaunchInterval * mix(0.7, 1.7, varianceRate);+ float cycleLength = flightDuration + fadeDuration + max(desiredInterval - (flightDuration + fadeDuration), 0.0);++ float phase = mod(u_timeSec + coronaSeed * cycleLength, cycleLength);+ float launchIndex = mod(floor((u_timeSec + coronaSeed * cycleLength) / cycleLength), 100.0);++ float h = fract((coronaSeed * 127.1 + launchIndex * 311.7) * 0.00001 + coronaSeed);+ float coronaActive = step(h, u_coronaParticipation);++ float inFlight = step(phase, flightDuration);+ float travelPhase = phase / flightDuration;+ coronaEase = coronaActive * inFlight * smoothstep(0.0, 1.0, travelPhase);++ float fadeOut = smoothstep(0.65, 1.0, travelPhase);+ float fadePhase = clamp((phase - flightDuration) / fadeDuration, 0.0, 1.0);+ float fadeVisibility = mix(1.0 - fadeOut, 1.0, fadePhase);+ float idlePhase = step(flightDuration + fadeDuration, phase);+ float atSurface = 1.0 - coronaActive + (1.0 - inFlight);++ vCoronaProgress = coronaEase;+ vCoronaVisibility = mix(mix(fadeVisibility, 1.0, idlePhase), 1.0, idlePhase * atSurface);++ if (coronaEase > 0.001) {+ vec3 tangent = normalize(cross(baseNormal, vec3(0.0, 1.0, 0.0)));+ if (dot(tangent, tangent) < 0.01) tangent = normalize(cross(baseNormal, vec3(1.0, 0.0, 0.0)));+ vec3 bitangent = cross(baseNormal, tangent);++ float motionRate = 1.0 / varianceScale;+ float pathPhase = (launchIndex + mod(u_timeSec * motionRate, 6.283)) * u_coronaNoiseScale + rndId * 12.37;+ vec3 flow = tangent * sin(pathPhase) + bitangent * cos(pathPhase * 0.8);+ vec3 pathOffset = flow * (0.6 * u_coronaNoiseStrength * coronaEase);++ pos = baseNormal * (u_radius + u_coronaBurstDistance * coronaEase) + pathOffset;+ }+ } else {+ vCoronaProgress = 0.0;+ vCoronaVisibility = 1.0;+ }++ vec3 worldPosition = (modelMatrix * vec4(pos, 1.0)).xyz;+ vec3 worldNormal = normalize(mat3(modelMatrix) * baseNormal);++ vec3 viewDir = normalize(u_cameraPosition - worldPosition);+ vDepthFacing = dot(viewDir, worldNormal);++ vec3 worldDir = normalize(worldPosition);+ vec2 planar = vec2(dot(worldDir, u_cameraRight), dot(worldDir, u_cameraUp)) / max(u_gradientScale, vec2(0.001));+ float angleRad = radians(u_gradientAngle);+ vGradientCoord = dot(planar, vec2(cos(angleRad), sin(angleRad))) * 0.5 + 0.5;++ vOpacityVariation = opacityVariation;++ vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);+ gl_Position = projectionMatrix * mvPosition;++ float coronaScale = mix(1.0, 0.35, smoothstep(0.15, 0.85, coronaEase));++ float refHeight = 800.0;+ float heightScale = u_canvasHeight / refHeight;+ float perspective = 300.0 / -mvPosition.z;+ float scaledDotSize = u_dotSize * (u_pixelRatio / DESIGN_PIXEL_RATIO);++ gl_PointSize = scaledDotSize * sizeVariation * coronaScale * heightScale * perspective;+}+`;+export const DOTS_FRAGMENT = /* glsl */ `+precision mediump float;++uniform float u_opacity_factor;+uniform float u_coronaOpacityDrop;+uniform float u_depthFadeEnabled;+uniform float u_depthFadeFront;+uniform float u_depthFadeBack;+uniform float u_depthFadeMin;+uniform float u_depthFadeCurve;+uniform float u_gradientStops[3];+uniform vec3 u_gradientColors[3];++varying float vGradientCoord;+varying float vOpacityVariation;+varying float vCoronaProgress;+varying float vCoronaVisibility;+varying float vDepthFacing;++vec3 sampleGradient(float t) {+ float clamped = clamp(t, 0.0, 1.0);+ float s0 = u_gradientStops[0];+ float s1 = u_gradientStops[1];++ float t01 = clamp((clamped - s0) / max(1e-5, s1 - s0), 0.0, 1.0);+ float t12 = clamp((clamped - s1) / max(1e-5, u_gradientStops[2] - s1), 0.0, 1.0);++ vec3 c = mix(u_gradientColors[0], u_gradientColors[1], t01);+ c = mix(c, u_gradientColors[2], t12 * step(s1, clamped));+ return c;+}++void main() {+ vec2 center = gl_PointCoord - vec2(0.5);+ float dist = length(center);+ if (dist > 0.5) discard;++ float alpha = smoothstep(0.5, 0.4, dist);+ vec3 color = sampleGradient(vGradientCoord);++ alpha *= u_opacity_factor * vOpacityVariation;+ alpha *= mix(1.0, max(0.0, 1.0 - u_coronaOpacityDrop), vCoronaProgress) * vCoronaVisibility;++ if (u_depthFadeEnabled > 0.5) {+ float range = max(0.0001, u_depthFadeFront - u_depthFadeBack);+ float mapped = clamp((vDepthFacing - u_depthFadeBack) / range, 0.0, 1.0);+ float fadeFactor = pow(mapped, max(0.01, u_depthFadeCurve));+ alpha *= mix(clamp(u_depthFadeMin, 0.0, 1.0), 1.0, fadeFactor);+ }++ color = mix(color, vec3(1.0), vCoronaProgress * 0.45);++ gl_FragColor = vec4(color, alpha);+}+`;diff --git a/public/examples/stripe-bento/src/widgets/crypto/wallets.js b/public/examples/stripe-bento/src/widgets/crypto/wallets.jsnew file mode 100644index 0000000..a38c68f--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/crypto/wallets.js@@ -0,0 +1,31 @@+// Wallet icons shown in the arc labels (24x24 SVGs copied from stripe.com). Gradient ids get a+// per-use suffix when rendered so several labels can show the same icon.+export const WALLETS = [+ {+ name: "Phantom",+ svg: "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M24 0H0v24h24z\" fill=\"#000\"/><path d=\"M24 0H0v24h24z\" fill=\"#ab9ff2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M10.4444 15.2962c-.94238 1.4439-2.52146 3.2713-4.62262 3.2713-.99328 0-1.94836-.409-1.94836-2.1852 0-4.5236 6.17618-11.52615 11.90668-11.52615 3.26 0 4.5589 2.2618 4.5589 4.83026 0 3.29689-2.1394 7.06649-4.2661 7.06649-.6749 0-1.006-.3706-1.006-.9584 0-.1533.0255-.3194.0764-.4983-.7258 1.2395-2.1266 2.3895-3.4382 2.3895-.9551 0-1.439-.6006-1.439-1.4439 0-.3067.0636-.6262.1783-.9456m4.9363-5.69895c0 .74845-.4416 1.12265-.9355 1.12265-.5015 0-.9356-.3742-.9356-1.12265 0-.74842.4341-1.12264.9356-1.12264.4939 0 .9355.37422.9355 1.12264m2.8066.00002c0 .74843-.4415 1.12263-.9355 1.12263-.5015 0-.9355-.3742-.9355-1.12263 0-.74844.434-1.12266.9355-1.12266.494 0 .9355.37422.9355 1.12266\" fill=\"#fffdf8\"/></svg>",+ },+ {+ name: "MetaMask",+ svg: "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"24\" height=\"24\" rx=\"2\" fill=\"#ebf1f7\"/><path d=\"m18.8095 5-5.8759 4.36414 1.0866-2.57544z\" fill=\"#e2761b\"/><path d=\"m5.24339 5 5.82881 4.4053-1.0337-2.6166-4.79511-1.78811zM16.6947 15.116l-1.5653 2.3984 3.3487.9214.9625-3.2663-2.7459-.053zm-12.07165.0535.95667 3.2663 3.34866-.9214-1.56525-2.3979z\" fill=\"#e4761b\"/><path d=\"m8.74009 11.0643-.93198 1.4124 3.32459.1476-.1176-3.57269-2.27384 2.01389zm6.57321 0-2.3032-2.05502-.0764 3.61442 3.3187-.147-.9391-1.4118zm-6.38388 6.4498 1.99628-.9743-1.72462-1.3465zm4.19888-.9743 2.0022.9743-.2776-2.3214-1.7246 1.3465z\" fill=\"#e4761b\"/><path d=\"m15.1307 17.5145-2.0021-.9744.1593 1.3054-.0176.5486zm-6.20101 0 1.86041.8796-.0117-.5492.147-1.3053z\" fill=\"#d7c1b3\"/><path d=\"m10.8195 14.3308-1.6652-.4904 1.1748-.5374zm2.4155 0 .4904-1.0278 1.1807.5374z\" fill=\"#233447\"/><path d=\"m8.92951 17.5141.28342-2.3979-1.84867.0529zm5.91759-2.3985.2835 2.3985 1.5652-2.345-1.8487-.0529zm1.4054-2.6395-3.3187.1476.3069 1.7069.4904-1.0278 1.1807.5374zm-7.09837 1.3641 1.18067-.5374.4845 1.0278.3129-1.7069-3.32459-.147 1.34652 1.3641z\" fill=\"#cd6116\"/><path d=\"m7.80762 12.4761 1.39356 2.7165-.04704-1.3524zm7.10418 1.3641-.0588 1.3524 1.3995-2.7165zm-3.7796-1.2165-.3128 1.7069.3898 2.0139.0882-2.6519-.1646-1.0689zm1.8016 0-.1593 1.0631.0705 2.6577.3957-2.0139z\" fill=\"#e4751f\"/><path d=\"m13.2709 18.3936.0176-.5492-.1481-.1294h-2.2262l-.1358.1294.0117.5492-1.86041-.8797.64974.5316 1.31707.9149h2.2615l1.323-.9149.6497-.5316-1.8604.8797z\" fill=\"#c0ad9e\"/><path d=\"m13.1281 16.5399-.2834-.1952h-1.6359l-.2834.1952-.1476 1.3054.1353-.1305h2.2267l.1476.1299-.1587-1.3053z\" fill=\"#161616\"/><path d=\"m19.0577 9.64755.5022-2.40962L18.8096 5l-5.6813 4.21655 2.185 1.84865 3.0888.9032.6856-.7968-.2958-.2128.4728-.431-.3663-.2834.4727-.36047zM4.5 7.23793l.50215 2.40962-.31928.23638.47275.36047-.36044.2834.47275.431-.29577.2128.67973.7968 3.08877-.9032 2.18504-1.84865L5.24441 5z\" fill=\"#763d16\"/><path d=\"m13.2409 14.3312-.3957 2.0139.2834.1952 1.7246-1.3465.0588-1.3524zm-4.0866-.4904.04704 1.3524 1.72456 1.3465.2835-.1946-.3899-2.0139z\" fill=\"#f6851b\"/><path d=\"m18.4011 11.9682-3.0888-.9032.939 1.4112-1.3994 2.7166 1.8428-.0236h2.7459zm-9.66205-.9038-3.08818.9038-1.02782 3.201h2.74008l1.83691.0236-1.39356-2.7166.93257-1.4112zm4.19365 1.5594.1946-3.40747.8979-2.42727h-3.9867l.8861 2.42727.2064 3.40747.0706 1.0749.0059 2.646h1.6364l.0117-2.646.0765-1.0749z\" fill=\"#f6851b\"/></svg>",+ },+ {+ name: "Rainbow",+ svg: "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"24\" height=\"24\" rx=\"2\" fill=\"#ebf1f7\"/><path fill=\"url(#rainbow-bg)\" d=\"M0 0h24v24H0z\"/><path d=\"M4.5 7.87498h1.125c5.799 0 10.5 4.70102 10.5 10.49992v1.125h2.25c.6213 0 1.125-.5037 1.125-1.125C19.5 10.712 13.288 4.5 5.625 4.5c-.62132 0-1.125.50368-1.125 1.12499z\" fill=\"url(#rainbow-outer)\"/><path d=\"M4.5 7.50024h1.125c6.0061 0 10.875 4.86886 10.875 10.87496v1.125h-3.375v-1.125c0-4.1421-3.35786-7.5-7.5-7.5H4.5z\" fill=\"url(#rainbow-mid)\"/><path d=\"M4.5 12.3752c0 .6213.50368 1.125 1.125 1.125 2.69239 0 4.875 2.1826 4.875 4.875 0 .6213.5037 1.125 1.125 1.125H13.5v-1.125c0-4.3492-3.52575-7.875-7.875-7.875H4.5z\" fill=\"url(#rainbow-inner)\"/><defs><radialGradient id=\"rainbow-outer\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"matrix(0 -13.8749 13.875 0 5.625 18.3749)\"><stop offset=\".770277\" stop-color=\"#ff4000\"/><stop offset=\"1\" stop-color=\"#8754c9\"/></radialGradient><radialGradient id=\"rainbow-mid\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"matrix(0 -10.8749 10.875 0 5.625 18.3752)\"><stop offset=\".723929\" stop-color=\"#fff700\"/><stop offset=\"1\" stop-color=\"#ff9901\"/></radialGradient><radialGradient id=\"rainbow-inner\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"matrix(0 -7.87495 7.875 0 5.625 18.3752)\"><stop offset=\".59513\" stop-color=\"#0af\"/><stop offset=\"1\" stop-color=\"#01da40\"/></radialGradient><linearGradient id=\"rainbow-bg\" x1=\"12\" y1=\"0\" x2=\"12\" y2=\"24\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#174299\"/><stop offset=\"1\" stop-color=\"#001e59\"/></linearGradient></defs></svg>",+ },+ {+ name: "Crypto.com",+ svg: "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"24\" height=\"24\" rx=\"2\" fill=\"#ebf1f7\"/><path d=\"M0 0v23.9999h24V0z\" fill=\"url(#crypto-bg)\"/><path d=\"M9.35965 7.55055H14.635l.6356 2.66135H8.74766zM13.157 12.1003l.5629-1.4862h-3.4156l.5754 1.4862-.1755 1.6668h1.302l1.3144-.0059z\" fill=\"#fff\"/><path d=\"m15.283 11.1116-1.5447.9951v1.7686l-1.1809 1.1213v.5268l1.1383 1.0377h.9511l2.3984-4.1369zm-4.9846.9951-1.56314-.9834-1.76812 1.3009 2.41022 4.1486h.96354l1.1383-1.0494v-.5268l-1.1808-1.1214z\" fill=\"#fff\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M5.01771 7.9902 12.0009 4 19 8.00014v7.99916L12.0009 20l-.0178-.0099L5 15.9993V8.00014zm6.98319-3.17404L5.71537 8.40941v7.18299l6.28553 3.5914 6.2855-3.5914V8.40941z\" fill=\"#fff\"/><defs><radialGradient id=\"crypto-bg\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"rotate(90)scale(24 52.3481)\"><stop offset=\".0249942\" stop-color=\"#3c62d1\"/><stop offset=\".286382\" stop-color=\"#1e379d\"/><stop offset=\".553401\" stop-color=\"#041c73\"/><stop offset=\".988775\" stop-color=\"#010348\"/></radialGradient></defs></svg>",+ },+ {+ name: "Base",+ svg: "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"24\" height=\"24\" rx=\"2\" fill=\"#00f\"/><path d=\"M5.84 19Q5 19 5 18.16V5.84Q5 5 5.84 5h12.32q.84 0 .84.84v12.32q0 .84-.84.84z\" fill=\"#fff\"/></svg>",+ },+ {+ name: "Kraken",+ svg: "<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"24\" height=\"24\" rx=\"2\" fill=\"#7132f5\"/><path d=\"M11.9981 6C7.58072 6 4 9.41938 4 13.6373v3.2729C4 17.5123 4.511 18 5.14179 18s1.14553-.4877 1.14553-1.0898v-3.2729c0-.6038.50912-1.0915 1.14178-1.0915.63079 0 1.14178.4877 1.14178 1.0915v3.2729c0 .6021.51102 1.0898 1.1418 1.0898.63262 0 1.14362-.4877 1.14362-1.0898v-3.2729c0-.6038.511-1.0915 1.1418-1.0915.6327 0 1.1455.4877 1.1455 1.0915v3.2729c0 .6021.5111 1.0898 1.1418 1.0898.6308 0 1.1418-.4877 1.1418-1.0898v-3.2729c0-.6038.511-1.0915 1.1456-1.0915.6307 0 1.1417.4877 1.1417 1.0915v3.2729c0 .6021.511 1.0898 1.1437 1.0898C19.489 18 20 17.5123 20 16.9102v-3.2729C20 9.41938 16.4174 6 11.9981 6\" fill=\"#fff\"/></svg>",+ },+];++/** Phantom pays out in "CASH"; every other wallet sends one of these stablecoins. */+export const STABLECOINS = ["USDC", "USDB"];diff --git a/public/examples/stripe-bento/src/widgets/issuing.css b/public/examples/stripe-bento/src/widgets/issuing.cssnew file mode 100644index 0000000..c9757c2--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing.css@@ -0,0 +1,25 @@+/* "Create a card issuing program" background graphic (stripe.com values). The box overhangs the+ (already grown) card inner by 20px on every side: 447x728 at the desktop size. */++.issuing-graphic__background {+ position: absolute;+ inset: -20px;+ background: #fff; /* --hds-color-surface-bg-quiet */+ display: flex;+ align-items: center;+}++.issuing-graphic__background-canvas {+ width: 100%;+ height: 100%;+}++/* Static fallback (no WebGL2 / failed capability check): a 2x render of the same box. */+.issuing-graphic__background-static {+ width: 100%;+}+.issuing-graphic__background-static img {+ display: block;+ width: 100%;+ height: auto;+}diff --git a/public/examples/stripe-bento/src/widgets/issuing.js b/public/examples/stripe-bento/src/widgets/issuing.jsnew file mode 100644index 0000000..f259c9c--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing.js@@ -0,0 +1,85 @@+// "Create a card issuing program" bento background: a three.js card that tilts towards the+// pointer over an iridescent wave (port of stripe.com's IssuingGraphicBackground).+//+// mount(container, { card, slot }) is called once by the shell (src/bento.js) for the+// background slot when the card comes within 800px of the viewport. It resolves after the+// textures are loaded and the first frame is drawn; the shell then fades the container in.+//+// Like stripe.com:+// - the scene only animates while within 100px of the viewport, and never with+// prefers-reduced-motion: reduce (one still frame is drawn instead);+// - without WebGL2 or when the capability check fails, a static card image is shown.++import { TEXTURES } from "./issuing/config.js";+import { IssuingGraphic } from "./issuing/graphic.js";+import { warmUpRenderLoop } from "./issuing/render-loop.js";++warmUpRenderLoop();++function supportsWebGL() {+ try {+ const gl = document.createElement("canvas").getContext("webgl2");+ gl?.getExtension("WEBGL_lose_context")?.loseContext();+ return !!gl;+ } catch {+ return false;+ }+}++function el(tag, className, attrs = {}) {+ const node = document.createElement(tag);+ if (className) node.className = className;+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);+ return node;+}++function mountFallback(container) {+ const background = el("div", "issuing-graphic__background");+ const wrapper = el("div", "issuing-graphic__background-static");+ const img = el("img", null, { src: TEXTURES.placeholder, width: "894", height: "1456", alt: "", decoding: "async" });+ wrapper.append(img);+ background.append(wrapper);+ container.replaceChildren(background);+ return img.decode().catch(() => {});+}++const reducedMotionQuery = window.matchMedia?.("(prefers-reduced-motion: reduce)");+const prefersReducedMotion = () => !reducedMotionQuery || reducedMotionQuery.matches;++export function mount(container, { slot } = {}) {+ if (slot !== "background") return Promise.resolve();+ if (!supportsWebGL()) return mountFallback(container);++ const background = el("div", "issuing-graphic__background");+ const canvas = el("canvas", "issuing-graphic__background-canvas", { "aria-hidden": "true" });+ background.append(canvas);+ container.replaceChildren(background);++ return new Promise((resolve) => {+ let graphic;+ try {+ graphic = new IssuingGraphic(canvas, { onFirstFrame: resolve });+ } catch {+ mountFallback(container).then(resolve);+ return;+ }+ graphic.paused = true;+ graphic.initScene();++ // Animate only while near the viewport and when motion is allowed.+ let intersecting = false;+ const update = () => {+ graphic.paused = !intersecting || prefersReducedMotion();+ };+ new IntersectionObserver(+ (entries) => {+ const entry = entries[0];+ if (!entry) return;+ intersecting = entry.isIntersecting && entry.intersectionRatio >= 0;+ update();+ },+ { threshold: 0, rootMargin: "100px" },+ ).observe(background);+ reducedMotionQuery?.addEventListener("change", update);+ });+}diff --git a/public/examples/stripe-bento/src/widgets/issuing/config.js b/public/examples/stripe-bento/src/widgets/issuing/config.jsnew file mode 100644index 0000000..646b354--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/config.js@@ -0,0 +1,60 @@+// Scene settings of stripe.com's issuing bento graphic (the "issuing" wave preset).++export const ISSUING_CONFIG = {+ theme: "light",+ postProcessing: { blurAmount: 0.02, grainAmount: 1.2 },+ // Orthographic wave camera. Its rotation is overwritten by lookAt(), kept for completeness.+ camera: {+ position: { x: 100.00000000000001, y: 3.06222926004786e-13, z: 5000 },+ rotation: { x: -6.124458520095719e-17, y: 0.019997333973150535, z: 1.2246467991473532e-18, order: "XYZ" },+ lookAt: { x: 0, y: 0, z: 0 },+ zoom: 1,+ },+ wave: {+ speed: 8e-5,+ timeOffset: 2275,+ colorContrast: 1,+ colorSaturation: 1,+ colorHueShift: -0.00159265358979299,+ displaceFrequencyX: 0.005831,+ displaceFrequencyZ: 0.016001,+ displaceAmount: -7.821,+ position: { x: -200.7, y: -65.4, z: -11.0999999999999 },+ rotation: { x: -2.87559265358979, y: 3.09592653589793, z: -2.9259265358979 },+ scale: { x: 3, y: 3, z: 3 },+ twistFrequencyX: 0.0590000000000002,+ twistFrequencyY: 0.32,+ twistFrequencyZ: -0.397,+ twistPowerX: 3.63,+ twistPowerY: 0.44,+ twistPowerZ: 5.99,+ glowAmount: 3.86,+ glowPower: 0.923,+ glowRamp: 1,+ lineThickness: 0,+ lineAmount: 0,+ lineDerivativePower: 0,+ },+};++// Card planes: the textures are 822x1294, i.e. this aspect, and sit slightly below centre.+export const CARD_ASPECT = 685 / 1078;+export const CARD_OFFSET_Y = -0.062;+export const CARD_SCALE = 1.42; // cardGroup scale, same on hover and at rest+export const CARD_CAMERA = { fov: 30, near: 0.1, far: 1000, z: 3 };++// Pointer tilt: target angle = ±0.15π at the canvas edges, approached by+// current += (target - current) * EASE_PER_MS * dt every rendered frame.+export const TILT_MAX = 0.15 * Math.PI;+export const EASE_PER_MS = 0.004;++// The render loop draws every 2nd animation frame.+export const FRAME_INTERVAL = 2;++const IMG = new URL("../../../assets/img/", import.meta.url).href;+export const TEXTURES = {+ palette: IMG + "issuing-palette.webp", // RepeatWrapping+ cardForeground: IMG + "issuing_card_fg.webp", // ClampToEdgeWrapping+ cardWindow: IMG + "issuing_card_bg.webp", // ClampToEdgeWrapping+ placeholder: IMG + "issuing-card-placeholder.webp", // static fallback, 894x1456+};diff --git a/public/examples/stripe-bento/src/widgets/issuing/graphic.js b/public/examples/stripe-bento/src/widgets/issuing/graphic.jsnew file mode 100644index 0000000..0b447b7--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/graphic.js@@ -0,0 +1,461 @@+// Port of stripe.com's IssuingGraphicBackground scene.+//+// Three passes per frame, then a composite to the canvas:+// 1. wave – the folded wave ribbon through an orthographic camera → waveTarget+// 2. card – the card foreground (chip, contactless, VISA, shadow) → cardTarget+// 3. window – the card silhouette (white, rounded) → cardWindowTarget+// 4. composite (postFragment): inside the window the wave zoomed 1.5x; outside it the+// angular-blurred wave mixed 70 % with white (the soft glow); the foreground on top; grain.+// The card planes live in a group that tilts towards the pointer (±0.15π) with a+// frame-time-scaled exponential approach (0.004/ms).++import {+ ClampToEdgeWrapping,+ DoubleSide,+ Group,+ MathUtils,+ Mesh,+ OrthographicCamera,+ PerspectiveCamera,+ PlaneGeometry,+ RepeatWrapping,+ Scene,+ ShaderMaterial,+ Texture,+ TextureLoader,+ Vector2,+ Vector3,+ WebGLRenderTarget,+} from "three";+import {+ CARD_ASPECT,+ CARD_CAMERA,+ CARD_OFFSET_Y,+ CARD_SCALE,+ EASE_PER_MS,+ FRAME_INTERVAL,+ ISSUING_CONFIG,+ TEXTURES,+ TILT_MAX,+} from "./config.js";+import { createRenderLoop, createRenderer, isRenderLoopWarm, renderLoopElapsed } from "./render-loop.js";+import { cardFragment, cardVertex, postFragment, postVertex } from "./shaders.js";+import { WaveMesh, createFoldedWaveGeometry } from "./wave.js";++// Page-space rect (viewport rect for fixed elements), like Stripe's helper.+function pageRect(el) {+ const r = el.getBoundingClientRect();+ if (getComputedStyle(el).position === "fixed") return r;+ return new DOMRect(r.left + window.scrollX, r.top + window.scrollY, r.width, r.height);+}++// Capture aid: ?__issuingFrameInterval=N starts the loop at every N-th frame, to reproduce the+// cadence Stripe's performance governor falls back to on a slow page. Not used otherwise.+function frameIntervalOverride() {+ const n = Number(new URLSearchParams(window.location.search).get("__issuingFrameInterval"));+ return Number.isInteger(n) && n > 0 ? n : 0;+}++function debounce(fn, ms) {+ let id;+ return (...args) => {+ clearTimeout(id);+ id = setTimeout(() => fn(...args), ms);+ };+}++// Textures load together; a failed one still counts, as on stripe.com (the graphic then never becomes ready).+function loadTextures(specs, onDone) {+ const loader = new TextureLoader();+ const textures = {};+ let settled = 0;+ const done = () => {+ settled += 1;+ if (settled === specs.length) onDone(textures);+ };+ for (const { id, url, wrap } of specs) {+ loader.load(+ url,+ (texture) => {+ texture.wrapS = wrap;+ texture.wrapT = wrap;+ textures[id] = texture;+ done();+ },+ undefined,+ done,+ );+ }+ return textures;+}++function cardMaterial() {+ return new ShaderMaterial({+ uniforms: { u_texture: { value: new Texture() } },+ vertexShader: cardVertex,+ fragmentShader: cardFragment,+ side: DoubleSide,+ transparent: true,+ depthWrite: false,+ depthTest: false,+ });+}++function postProcessingMaterial() {+ const empty = new Texture();+ return new ShaderMaterial({+ uniforms: {+ u_wave: { value: null },+ u_resolution: { value: new Vector2(0, 0) },+ u_blurAmount: { value: 0.02 },+ u_blurSamples: { value: 6 },+ u_grainAmount: { value: 1 },+ u_card: { value: empty },+ u_cardWindow: { value: empty },+ },+ vertexShader: postVertex,+ fragmentShader: postFragment,+ side: DoubleSide,+ });+}++// Full-screen quad drawn straight to the canvas.+class ScreenPass {+ constructor(material) {+ this.camera = new OrthographicCamera();+ this.scene = new Scene();+ this.mesh = new Mesh(new PlaneGeometry(2, 2), material);+ this.scene.add(this.mesh);+ }+ render(renderer) {+ renderer.setRenderTarget(null);+ renderer.render(this.scene, this.camera);+ }+ dispose() {+ this.mesh.geometry.dispose();+ }+}++export class IssuingGraphic {+ constructor(canvas, { config = ISSUING_CONFIG, onFirstFrame } = {}) {+ if (new URLSearchParams(window.location.search).has("__disableWebGL")) {+ throw new Error("WebGL disabled by query param");+ }+ this.canvas = canvas;+ this.config = config;+ this.onFirstFrame = onFirstFrame;+ this.scene = new Scene();+ this.bentoCardRoot = canvas.closest("[data-bento-card-root]");++ this.canvasRect = new DOMRect();+ this.resolution = new Vector2();+ this.mouseVector = new Vector2(0, 0);+ this.mouseRotationCurrent = new Vector2(0, 0);+ this.mouseRotationTarget = new Vector2(0, 0);+ this.mouseScaleCurrent = CARD_SCALE;+ this.mouseScaleTarget = CARD_SCALE;++ this.waveMesh = null;+ this.renderLoop = null;+ this.resizeObserver = null;+ this.firstDrawTime = null;+ this.lastDrawTime = null;+ this.resumedAtTime = null;+ this.pausedAtTime = null;+ this.pausedTime = 0;+ this._paused = true;+ this.initialized = false;+ this.loaded = false;+ this.drawn = false;+ this.onLoadCallback = null;+ this.textures = null;+ this.texturesPreloaded = false;+ this.texturePreloadCallback = null;++ const { renderer, hasMajorPerformanceCaveat, hasRequiredCapabilities } = createRenderer({+ canvas,+ antialias: false,+ alpha: false,+ powerPreference: "high-performance",+ });+ if (!renderer || !hasRequiredCapabilities || hasMajorPerformanceCaveat) {+ renderer?.dispose();+ throw new Error("WebGL disabled based on capabilities check");+ }+ this.renderer = renderer;+ renderer.autoClear = false;+ renderer.autoClearColor = false;+ renderer.autoClearDepth = false;+ renderer.setClearColor(0xffffff, 0);+ this.dpr = Math.min(window.devicePixelRatio, 2);+ renderer.setPixelRatio(this.dpr);++ this.cardCamera = new PerspectiveCamera(CARD_CAMERA.fov, 1, CARD_CAMERA.near, CARD_CAMERA.far);+ this.cardCamera.position.set(0, 0, CARD_CAMERA.z);+ this.waveCamera = new OrthographicCamera(0, 0, 0, 0, 1, 10000);+ this.waveCamera.position.set(0, 0, 5000);++ this.debouncedResize = debounce(this.resize, 100);+ this.startTexturePreload();+ }++ startTexturePreload() {+ this.textures = loadTextures(+ [+ { id: "palette", url: TEXTURES.palette, wrap: RepeatWrapping },+ { id: "cardForeground", url: TEXTURES.cardForeground, wrap: ClampToEdgeWrapping },+ { id: "cardWindow", url: TEXTURES.cardWindow, wrap: ClampToEdgeWrapping },+ ],+ () => {+ this.texturesPreloaded = true;+ if (this.texturePreloadCallback) {+ this.texturePreloadCallback();+ this.texturePreloadCallback = null;+ }+ },+ );+ }++ onLoadReady(callback) {+ if (this.loaded) callback();+ else this.onLoadCallback = callback;+ }++ initScene() {+ if (this.initialized) return;+ this.initialized = true;+ this.canvasRect = pageRect(this.canvas);+ const size = new Vector2(this.canvasRect.width, this.canvasRect.height);+ this.renderer.setSize(size.width, size.height, false);+ this.resolution = size.clone().multiplyScalar(this.dpr);++ this.sizeCameras(size);+ const foreground = cardMaterial();+ this.card = new Mesh(new PlaneGeometry(CARD_ASPECT, 1), foreground);+ this.card.position.y = CARD_OFFSET_Y;+ this.cardWindow = new Mesh(new PlaneGeometry(CARD_ASPECT, 1), foreground.clone());+ this.cardWindow.position.y = this.card.position.y;+ this.cardGroup = new Group();+ this.cardGroup.add(this.card);+ this.cardGroup.add(this.cardWindow);+ this.scene.add(this.cardGroup);+ this.applyCardTransform();++ const { width, height } = this.resolution;+ this.waveTarget = new WebGLRenderTarget(width, height);+ this.cardTarget = new WebGLRenderTarget(width, height);+ this.cardWindowTarget = new WebGLRenderTarget(width, height);++ this.postProcessingMaterial = postProcessingMaterial();+ const post = this.postProcessingMaterial.uniforms;+ post.u_blurAmount.value = this.config.postProcessing.blurAmount;+ post.u_grainAmount.value = this.config.postProcessing.grainAmount;+ post.u_resolution.value = this.resolution.clone();+ post.u_wave.value = this.waveTarget.texture;+ post.u_card.value = this.cardTarget.texture;+ post.u_cardWindow.value = this.cardWindowTarget.texture;+ this.postProcessingPass = new ScreenPass(this.postProcessingMaterial);++ if (this.texturesPreloaded) this.onLoad();+ else this.texturePreloadCallback = () => this.onLoad();+ }++ onLoad = async () => {+ const { palette, cardForeground, cardWindow } = this.textures;+ if (!palette || !cardForeground || !cardWindow) return;+ this.card.material.uniforms.u_texture.value = cardForeground;+ this.cardWindow.material.uniforms.u_texture.value = cardWindow;++ const geometry = await createFoldedWaveGeometry(400, 400, 128, 256);+ if (this.disposed) return;+ this.waveMesh = new WaveMesh(palette, geometry);+ this.waveMesh.applyConfig(this.config.wave, new Vector3(1, 1, 1));+ this.waveMesh.resolution = new Vector2(this.canvasRect.width * this.dpr, this.canvasRect.height * this.dpr);+ this.scene.add(this.waveMesh.mesh);++ const cam = this.config.camera;+ this.waveCamera.position.set(cam.position.x, cam.position.y, cam.position.z);+ this.waveCamera.rotation.set(cam.rotation.x, cam.rotation.y, cam.rotation.z, cam.rotation.order);+ this.waveCamera.zoom = cam.zoom;+ this.waveCamera.lookAt(cam.lookAt.x, cam.lookAt.y, cam.lookAt.z);++ this.addListeners();+ this.loaded = true;+ if (this.onLoadCallback) {+ this.onLoadCallback();+ this.onLoadCallback = null;+ }+ this.renderLoop = createRenderLoop((elapsed) => this.updateAndRender(elapsed), frameIntervalOverride() || FRAME_INTERVAL);+ this.renderLoop.onRenderResumed = () => {+ this.mouseRotationCurrent = new Vector2(0, 0);+ this.mouseRotationTarget = new Vector2(0, 0);+ };+ this.renderLoop.start();+ // Paused (off screen or reduced motion): draw one still frame. The wave keeps u_time = 0 here.+ if (this.paused) this.render();+ // On stripe.com the shared loop is already warm (the hero gradient starts it), so the first+ // animated frame follows within two frames. Here the loop may still be estimating the refresh+ // rate (12 frames), so draw that first frame now instead.+ else if (!isRenderLoopWarm()) this.updateAndRender(renderLoopElapsed());+ };++ updateAndRender(now) {+ if (this.paused || !this.loaded) return;+ if (this.firstDrawTime === null) this.firstDrawTime = now;+ if (this.resumedAtTime === null) {+ this.resumedAtTime = now;+ if (this.pausedAtTime) {+ this.pausedTime += this.resumedAtTime - this.pausedAtTime;+ this.pausedAtTime = null;+ }+ }+ if (this.lastDrawTime === null) this.lastDrawTime = now;+ const dt = now - this.lastDrawTime;+ const elapsed = now - this.firstDrawTime - this.pausedTime;+ this.lastDrawTime = now;++ if (this.waveMesh) {+ this.waveMesh.mousePosition = this.mouseVector;+ this.waveMesh.time = elapsed;+ }+ const rotationStep = this.mouseRotationTarget.clone().sub(this.mouseRotationCurrent);+ this.mouseRotationCurrent.add(rotationStep.multiplyScalar(EASE_PER_MS * dt));+ this.mouseScaleCurrent += (this.mouseScaleTarget - this.mouseScaleCurrent) * dt * EASE_PER_MS;+ this.applyCardTransform();+ this.render();+ }++ applyCardTransform() {+ if (!this.cardGroup) return;+ this.cardGroup.rotation.x = this.mouseRotationCurrent.x;+ this.cardGroup.rotation.y = this.mouseRotationCurrent.y;+ this.cardGroup.scale.setScalar(this.mouseScaleCurrent);+ }++ sizeCameras(size) {+ this.cardCamera.aspect = size.width / size.height;+ this.cardCamera.updateProjectionMatrix();+ this.waveCamera.left = -size.width / 2;+ this.waveCamera.right = size.width / 2;+ this.waveCamera.top = size.height / 2;+ this.waveCamera.bottom = -size.height / 2;+ this.waveCamera.updateProjectionMatrix();+ }++ resize = () => {+ this.canvasRect = pageRect(this.canvas);+ const size = new Vector2(this.canvasRect.width, this.canvasRect.height);+ const current = new Vector2();+ this.renderer.getSize(current);+ if (this.canvasRect.width === current.width && this.canvasRect.height === current.height) return;+ this.resolution = size.clone().multiplyScalar(this.dpr);+ this.renderer.setPixelRatio(this.dpr);+ this.renderer.setSize(size.width, size.height, false);+ const { width, height } = this.resolution;+ this.waveTarget?.setSize(width, height);+ this.cardTarget?.setSize(width, height);+ this.cardWindowTarget?.setSize(width, height);+ if (this.postProcessingMaterial) this.postProcessingMaterial.uniforms.u_resolution.value = this.resolution.clone();+ this.sizeCameras(size);+ if (this.paused && this.loaded) this.render();+ };++ // Pointer position over the canvas → target tilt. Up/down tilts around x, left/right around y.+ mousemove = (e) => {+ const left = this.canvasRect.left - window.scrollX;+ const top = this.canvasRect.top - window.scrollY;+ const nx = (e.clientX - left) / this.canvasRect.width;+ const ny = 1 - (e.clientY - top) / this.canvasRect.height;+ this.mouseVector.set(nx, ny);+ const sx = MathUtils.mapLinear(nx, 0, 1, -1, 1);+ const sy = MathUtils.mapLinear(ny, 0, 1, -1, 1);+ this.mouseRotationTarget.set(-TILT_MAX * sy, TILT_MAX * sx);+ };++ // mouseout bubbles, so crossing a child resets the target until the next mousemove, as on stripe.com.+ mouseout = () => {+ this.mouseScaleTarget = CARD_SCALE;+ this.mouseRotationTarget.set(0, 0);+ };++ mouseover = () => {+ this.mouseScaleTarget = CARD_SCALE;+ };++ addListeners() {+ this.resizeObserver = new ResizeObserver(this.debouncedResize);+ this.resizeObserver.observe(document.body);+ if (!this.bentoCardRoot) return;+ this.bentoCardRoot.addEventListener("mouseover", this.mouseover);+ this.bentoCardRoot.addEventListener("mousemove", this.mousemove);+ this.bentoCardRoot.addEventListener("mouseout", this.mouseout);+ }++ removeListeners() {+ this.resizeObserver?.disconnect();+ if (!this.bentoCardRoot) return;+ this.bentoCardRoot.removeEventListener("mouseover", this.mouseover);+ this.bentoCardRoot.removeEventListener("mousemove", this.mousemove);+ this.bentoCardRoot.removeEventListener("mouseout", this.mouseout);+ }++ showElements(wave, card, cardWindow) {+ if (!this.card || !this.cardWindow || !this.waveMesh) return;+ this.waveMesh.mesh.visible = wave;+ this.card.visible = card;+ this.cardWindow.visible = cardWindow;+ }++ renderPass(target, camera) {+ this.renderer.setRenderTarget(target);+ this.renderer.clearDepth();+ this.renderer.clearColor();+ this.renderer.render(this.scene, camera);+ }++ render() {+ if (!this.waveTarget || !this.cardTarget || !this.cardWindowTarget) return;+ this.showElements(true, false, false);+ this.renderPass(this.waveTarget, this.waveCamera);+ this.showElements(false, true, false);+ this.renderPass(this.cardTarget, this.cardCamera);+ this.showElements(false, false, true);+ this.renderPass(this.cardWindowTarget, this.cardCamera);+ this.postProcessingPass.render(this.renderer);+ if (!this.drawn) {+ this.drawn = true;+ this.onFirstFrame?.();+ }+ }++ get paused() {+ return this._paused;+ }++ set paused(value) {+ if (value) {+ this.resumedAtTime = null;+ this.pausedAtTime = this.lastDrawTime;+ this.lastDrawTime = null;+ }+ this._paused = value;+ }++ dispose() {+ this.disposed = true;+ this.removeListeners();+ this.renderLoop?.stop();+ this.renderLoop = null;+ for (const t of Object.values(this.textures ?? {})) t.dispose();+ this.waveMesh?.dispose();+ this.card?.geometry.dispose();+ this.cardWindow?.geometry.dispose();+ this.waveTarget?.dispose();+ this.cardTarget?.dispose();+ this.cardWindowTarget?.dispose();+ this.postProcessingPass?.dispose();+ this.postProcessingMaterial?.dispose();+ this.scene.remove(...this.scene.children);+ this.renderer.dispose();+ }+}diff --git a/public/examples/stripe-bento/src/widgets/issuing/render-loop.js b/public/examples/stripe-bento/src/widgets/issuing/render-loop.jsnew file mode 100644index 0000000..abca59b--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/render-loop.js@@ -0,0 +1,194 @@+// Renderer creation with stripe.com's capability check, and its shared render loop:+// one requestAnimationFrame for every graphic, a refresh-rate estimate from the first+// 12 frames (nothing is drawn until then), per-graphic frame intervals, and a+// performance governor that skips more frames when the page cannot keep up.++import { WebGLRenderer } from "three";++const REFRESH_RATES = [240, 160, 144, 120, 60, 30, 24];+const REQUIRED_EXTENSIONS = [+ "EXT_color_buffer_float",+ "EXT_texture_filter_anisotropic",+ "WEBGL_debug_renderer_info",+ "WEBGL_debug_shaders",+];++const mean = (values) => (values.length ? values.reduce((a, b) => a + b) / values.length : undefined);++function median(values) {+ if (!values.length) return undefined;+ const sorted = [...values].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}++function hasRequiredCapabilities(renderer, extraExtensions = []) {+ const { capabilities, extensions } = renderer;+ return (+ capabilities.isWebGL2 &&+ capabilities.vertexTextures &&+ capabilities.maxTextureSize >= 4096 &&+ capabilities.maxVertexUniforms >= 256 &&+ capabilities.maxFragmentUniforms >= 256 &&+ [...REQUIRED_EXTENSIONS, ...extraExtensions].every((name) => extensions.get(name) !== null)+ );+}++// First try without a major performance caveat, then accept one but report it.+export function createRenderer(params, extraExtensions = []) {+ let renderer;+ let hasMajorPerformanceCaveat = false;+ try {+ renderer = new WebGLRenderer({ ...params, failIfMajorPerformanceCaveat: true });+ } catch {+ hasMajorPerformanceCaveat = true;+ }+ if (!renderer) {+ try {+ renderer = new WebGLRenderer({ ...params, failIfMajorPerformanceCaveat: false });+ } catch {}+ }+ return {+ renderer,+ hasMajorPerformanceCaveat,+ hasRequiredCapabilities: renderer ? hasRequiredCapabilities(renderer, extraExtensions) : false,+ };+}++export class RenderLoop {+ constructor(renderFunction) {+ this.frameCount = 0;+ this.frameInterval = 1;+ this.initialFrameInterval = 1;+ this.renderFunction = renderFunction;+ this.onRenderSuspended = () => {};+ this.onRenderResumed = () => {};+ }+ onPerformanceWarning(level) {+ this.frameInterval = Math.max(level + 1, this.frameInterval);+ }+ onPerformanceRecovered(level) {+ this.frameInterval = Math.max(level + 1, this.initialFrameInterval);+ }+ start() {+ RenderLoopManager.instance.loops.add(this);+ }+ stop() {+ RenderLoopManager.instance.loops.delete(this);+ }+}++class RenderLoopManager {+ static get instance() {+ if (!RenderLoopManager._instance) RenderLoopManager._instance = new RenderLoopManager();+ return RenderLoopManager._instance;+ }++ constructor() {+ this.loops = new Set();+ this.frameTimes = [];+ this.lastFrameTime = 0;+ this.resumedTime = null;+ this.elapsedTime = 0;+ this.warningLevel = 0; // 0 none … 3 max+ this.estimatedRefreshRate = undefined;+ this.estimatedAt = undefined;+ this.rafId = null;+ document.addEventListener("visibilitychange", () => {+ if (document.hidden) this.suspend();+ else this.resume();+ });+ this.start();+ }++ start() {+ if (this.rafId) return;+ this.lastFrameTime = performance.now();+ this.resumedTime = null;+ this.rafId = requestAnimationFrame(this.update);+ }++ stop() {+ if (this.rafId) cancelAnimationFrame(this.rafId);+ this.rafId = null;+ }++ suspend() {+ this.loops.forEach((loop) => loop.onRenderSuspended("visibility"));+ this.stop();+ }++ resume() {+ this.lastFrameTime = performance.now();+ this.loops.forEach((loop) => loop.onRenderResumed("visibility"));+ this.start();+ }++ update = (now) => {+ this.rafId = requestAnimationFrame(this.update);+ const dt = now - this.lastFrameTime;+ this.lastFrameTime = now;+ this.frameTimes.push(dt);++ if (this.frameTimes.length >= 12 && !this.estimatedRefreshRate) {+ this.estimatedRefreshRate = this.estimateRefreshRate();+ this.estimatedAt = performance.now();+ this.frameTimes = [];+ return;+ }+ if (!this.estimatedRefreshRate || !this.estimatedAt) return;++ if (this.resumedTime === null) this.resumedTime = now - this.elapsedTime;+ this.elapsedTime = Math.max(now - this.resumedTime, 0);+ this.loops.forEach((loop) => {+ loop.frameCount += 1;+ if (loop.frameCount % loop.frameInterval === 0) loop.renderFunction(this.elapsedTime);+ });++ if (this.frameTimes.length < 24) return;+ // Every 24 frames: compare the achieved frame rate (two slowest frames dropped) with the display's.+ const sorted = this.frameTimes.slice().sort((a, b) => a - b);+ sorted.splice(-2);+ const fps = 1000 / mean(sorted);+ const shortfall = this.estimatedRefreshRate - fps;+ if (shortfall > 0.1 * this.estimatedRefreshRate) {+ const level = Math.min(this.warningLevel + 1, 3);+ if (this.warningLevel !== level) {+ this.warningLevel = level;+ this.loops.forEach((loop) => loop.onPerformanceWarning(level));+ }+ } else if (shortfall < 0 && this.warningLevel > 0) {+ this.warningLevel -= 1;+ this.loops.forEach((loop) => loop.onPerformanceRecovered(this.warningLevel));+ }+ this.frameTimes = [];+ };++ estimateRefreshRate() {+ if (!this.frameTimes.length) return undefined;+ const measured = 1000 / median(this.frameTimes);+ return REFRESH_RATES.reduce((best, rate) => (Math.abs(rate - measured) < Math.abs(best - measured) ? rate : best));+ }+}++// On stripe.com the shared loop is already running (the hero gradient starts it), so the+// refresh-rate estimate is done before this graphic loads. Start it as early as possible.+export function warmUpRenderLoop() {+ return RenderLoopManager.instance;+}++// True once the refresh-rate estimate is done and loops are being called.+export function isRenderLoopWarm() {+ return !!RenderLoopManager.instance.estimatedRefreshRate;+}++export function renderLoopElapsed() {+ return RenderLoopManager.instance.elapsedTime;+}++export function createRenderLoop(renderFunction, frameInterval = 1) {+ const loop = new RenderLoop(renderFunction);+ loop.frameInterval = frameInterval;+ loop.initialFrameInterval = frameInterval;+ return loop;+}diff --git a/public/examples/stripe-bento/src/widgets/issuing/shaders.js b/public/examples/stripe-bento/src/widgets/issuing/shaders.jsnew file mode 100644index 0000000..095bdf8--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/shaders.js@@ -0,0 +1,700 @@+// GLSL from stripe.com's issuing bento graphic (three r178 ShaderMaterial, GLSL3 via three's WebGL2 prefix).+// Kept verbatim so the clone renders the same pixels.++// Full-screen quad for the composite pass (positions are already clip space).+export const postVertex = /* glsl */ `varying vec2 v_uv;++void main() {+ v_uv = uv;+ vec4 projectedPosition = vec4(position, 1.0);+ gl_Position = projectedPosition;+}+`;++// Composite: zoomed wave inside the card window, blurred wave mixed 70 % with white outside it, card foreground on top, grain.+export const postFragment = /* glsl */ `uniform sampler2D u_wave;+uniform sampler2D u_cardWindow;+uniform sampler2D u_card;+uniform float u_blurAmount;+uniform int u_blurSamples;+uniform float u_grainAmount;+uniform vec2 u_resolution;+varying vec2 v_uv;++// TODO(weston): glsl-loader.js is looking for paths relative to the shader source.+// We should update it to start from a configurable root location++// The origin of these popular glsl functions is a mystery, but it seems they+// were likely derived from a paper titled "On generating random numbers, with+// help of y=[(a+x)sin(bx)] mod 1", W.J.J. Rey, 22nd European Meeting of+// Statisticians and the 7th Vilnius Conference on Probability Theory and+// Mathematical Statistics, August 1998.++// https://stackoverflow.com/questions/12964279/whats-the-origin-of-this-glsl-rand-one-liner++#ifndef STRIPE_RANDOM+#define STRIPE_RANDOM+float random(in float x) {+ return fract(sin(x) * 43758.5453);+}+float random(in vec2 st) {+ return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453);+}+float random(in vec3 pos) {+ return fract(sin(dot(pos.xyz, vec3(70.9898, 78.233, 32.4355))) * 43758.5453123);+}+#endif+++#ifndef STRIPE_GRAIN+#define STRIPE_GRAIN+vec3 grain(vec3 color, float amount) {+ float grid_position = random(gl_FragCoord.xy * 0.01);+ vec3 dither_shift_RGB = vec3(4.0 / 255.0, 4.0 / 255.0, 4.0 / 255.0);+ dither_shift_RGB = mix(amount * dither_shift_RGB, -amount * dither_shift_RGB, grid_position);+ return color + dither_shift_RGB;+}+#endif++#ifndef STRIPE_BLUR_ANGULAR+#define STRIPE_BLUR_ANGULAR++vec4 blurAngular(sampler2D tex, vec2 uv, float angle, int samples) {+ vec4 total = vec4(0);+ vec2 coord = uv - 0.5;++ float dist = 1.0 / float(samples);+ vec2 dir = vec2(cos(angle * dist), sin(angle * dist));+ mat2 rot = mat2(dir.xy, -dir.y, dir.x);++ for(int i = 0; i < samples; i += 1) {+ vec4 color = texture(tex, coord + 0.5);+ total += color;+ coord *= rot;+ }++ return total * dist;+}++#endif+++void main() {+ vec2 texel = 1.0 / u_resolution;+ vec2 st = gl_FragCoord.xy * texel;++ vec2 center = vec2(0.5, 0.5);+ vec2 offset = v_uv - center;+ vec2 scaledOffset = offset / 1.5;+ vec2 zoomedUv = center + scaledOffset;+ zoomedUv = clamp(zoomedUv, 0.0, 1.0);++ vec4 whiteColor = vec4(1.0);+ vec4 waveColor = texture2D(u_wave, zoomedUv);+ vec4 cardColor = texture2D(u_card, v_uv);+ vec4 cardWindowColor = texture2D(u_cardWindow, v_uv);++ vec4 blurColor = blurAngular(u_wave, v_uv, 0.14, u_blurSamples);+ vec4 zoomedBlurColor = blurAngular(u_wave, zoomedUv, 0.14, u_blurSamples);+ waveColor = mix(waveColor, zoomedBlurColor, 0.25);++ float a = 1.0 - cardWindowColor.a;+ vec4 finalColor = mix(waveColor, mix(blurColor, whiteColor, a * 0.7), a);+ finalColor = mix(finalColor, cardColor, cardColor.a);+ finalColor.rgb = grain(finalColor.rgb, u_grainAmount);++ gl_FragColor = finalColor;+}+`;++// Card planes (foreground and window) through the perspective card camera.+export const cardVertex = /* glsl */ `+varying vec2 v_uv;++void main() {+ v_uv = uv;+ vec4 modelPosition = modelMatrix * vec4(position, 1.0);+ vec4 viewPosition = viewMatrix * modelPosition;+ vec4 projectedPosition = projectionMatrix * viewPosition;+ gl_Position = projectedPosition;+}+`;++// Card planes: straight texture lookup.+export const cardFragment = /* glsl */ `uniform sampler2D u_texture;+uniform vec2 u_resolution;+varying vec2 v_uv;++void main() {+ vec4 color = texture2D(u_texture, v_uv);+ gl_FragColor = color;+}+`;++// Folded wave ribbon: simplex displacement over time plus three twists.+export const waveVertex = /* glsl */ `attribute vec3 tangent;++uniform float u_time;+uniform float u_speed;+uniform vec2 u_resolution;++uniform float u_twistFrequencyX;+uniform float u_twistFrequencyY;+uniform float u_twistFrequencyZ;++uniform float u_twistPowerX;+uniform float u_twistPowerY;+uniform float u_twistPowerZ;++uniform float u_displaceFrequencyX;+uniform float u_displaceFrequencyZ;+uniform float u_displaceAmount;++varying float v_time;+varying float v_speed;+varying vec2 v_uv;+varying vec3 v_position;+varying vec4 v_clipPosition;+varying vec2 v_resolution;++// TODO(weston): glsl-loader.js is looking for paths relative to the shader source.+// We should update it to start from a configurable root location++// Stefan Gustavson's version;+// https://www.shadertoy.com/view/43tBDr+// https://www.researchgate.net/publication/216813608_Simplex_noise_demystified++// https://xxhash.com/+// https://github.com/Cyan4973/xxHash/blob/dev/LICENSE++#ifndef STRIPE_HASH+#define STRIPE_HASH+float xxhash(vec2 x) {+ uvec2 t = floatBitsToUint(x);+ uint h = 0xc2b2ae3du * t.x + 0x165667b9u;+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;+ h += 0xc2b2ae3du * t.y;+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;+ h ^= h >> 15u;+ h *= 0x85ebca77u;+ h ^= h >> 13u;+ h *= 0xc2b2ae3du;+ h ^= h >> 16u;+ return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;+}++vec2 hash(vec2 x) {+ float k = 6.283185307 * xxhash(x);+ return vec2(cos(k), sin(k));+}+#endif+++#ifndef STRIPE_SIMPLEX_NOISE+#define STRIPE_SIMPLEX_NOISE+float simplexNoise(in vec2 p) {+ const float K1 = 0.366025404; // (sqrt(3)-1)/2;+ const float K2 = 0.211324865; // (3-sqrt(3))/6;++ vec2 i = floor(p + (p.x + p.y) * K1);+ vec2 a = p - i + (i.x + i.y) * K2;+ float m = step(a.y, a.x);+ vec2 o = vec2(m, 1.0 - m);+ vec2 b = a - o + K2;+ vec2 c = a - 1.0 + 2.0 * K2;+ vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);+ vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0))); // changed to h^3 [1]++ return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)+}+#endif++// Shaping functions by Inigo Quilez+// https://iquilezles.org/articles/functions/+// https://thebookofshaders.com/05/+++// Taken from glm's math.h++#ifndef STRIPE_CONSTANTS+#define STRIPE_CONSTANTS++#define M_E 2.71828182845904523536028747135266250 /* e */+#define M_LOG2E 1.44269504088896340735992468100189214 /* log 2e */+#define M_LOG10E 0.434294481903251827651128918916605082 /* log 10e */+#define M_LN2 0.693147180559945309417232121458176568 /* log e2 */+#define M_LN10 2.30258509299404568401799145468436421 /* log e10 */+#define M_PI 3.14159265358979323846264338327950288 /* pi */+#define M_PI_2 1.57079632679489661923132169163975144 /* pi/2 */+#define M_PI_4 0.785398163397448309615660845819875721 /* pi/4 */+#define M_1_PI 0.318309886183790671537767526745028724 /* 1/pi */+#define M_2_PI 0.636619772367581343075535053490057448 /* 2/pi */+#define M_2_SQRTPI 1.12837916709551257389615890312154517 /* 2/sqrt(pi) */+#define M_SQRT2 1.41421356237309504880168872420969808 /* sqrt(2) */+#define M_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */++#endif+++#ifndef STRIPE_SHAPING+#define STRIPE_SHAPING++float almostIdentity(float x, float n) {+ return sqrt(x * x + n * n);+}++float integralSmoothstep(float x, float T) {+ if(x > T)+ return x - T / 2.0;+ return x * x * x * (1.0 - x * 0.5 / T) / T / T;+}++// Impulses++float expImpulse(float x, float k) {+ float h = k * x;+ return h * exp(1.0 - h);+}++float quadImpulse(float k, float x) {+ return 2.0 * sqrt(k) * x / (1.0 + k * x * x);+}++float polyImpulse(float k, float n, float x) {+ return (n / (n - 1.0)) *+ pow((n - 1.0) * k, 1.0 / n) *+ x / (1.0 + k * pow(x, n));+}++float expSustainedImpulse(float x, float f, float k) {+ float s = max(x - f, 0.0);+ return min(x * x / (f * f), 1.0 + (2.0 / f) * s * exp(-k * s));+}++float sincImpulse(float x, float k) {+ float a = M_PI * (k * x - 1.0);+ return sin(a) / a;+}++// Falloff++float quadFallof(float x, float m) {+ x /= m;+ return (x - 2.0) * x + 1.0;+}++// Unitary++float almostUnitIdentity(float x) {+ return x * x * (2.0 - x);+}++float gain(float x, float k) {+ float a = 0.5 * pow(2.0 * ((x < 0.5) ? x : 1.0 - x), k);+ return (x < 0.5) ? a : 1.0 - a;+}++float parabola(float x, float k) {+ return pow(4.0 * x * (1.0 - x), k);+}++float pcurve(float x, float a, float b) {+ float k = pow(a + b, a + b) / (pow(a, a) * pow(b, b));+ return k * pow(x, a) * pow(1.0 - x, b);+}++float tone(float x, float k) {+ return (k + 1.0) / (1.0 + k * x);+}++// Pulse++float cubicPulse(float c, float w, float x) {+ x = abs(x - c);+ if(x > w)+ return 0.0;+ x /= w;+ return 1.0 - x * x * (3.0 - 2.0 * x);+}++float rationalBump(float x, float k) {+ return 1.0 / (1.0 + k * x * x);+}++float expStep(float x, float n) {+ return exp2(-exp2(n) * pow(x, n));+}++#endif++#ifndef STRIPE_UTILS+#define STRIPE_UTILS++float mapLinear(float value, float min1, float max1, float min2, float max2) {+ return min2 + (value - min1) * (max2 - min2) / (max1 - min1);+}++mat4 rotationMatrix(vec3 axis, float angle) {+ axis = normalize(axis);+ float s = sin(angle);+ float c = cos(angle);+ float oc = 1.0 - c;+ return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, 0.0, 0.0, 0.0, 1.0);+}++#endif+++vec3 displace(vec2 uv, vec3 position, float time, float frequencyX, float frequencyY, float amount) {+ float noise = simplexNoise(vec2(position.x * frequencyX + time, position.z * frequencyY + time));+ float dist = mapLinear(uv.x, 0.0, 1.0, -1.0, 1.0);+ position.y += amount * noise;+ return position;+}++void main(void) {+ v_time = u_time;+ v_uv = uv;+ v_resolution = u_resolution;++ mat4 rotationA = rotationMatrix(vec3(0.5, 0.0, 0.5), u_twistFrequencyY * expStep(v_uv.x, u_twistPowerY));+ mat4 rotationB = rotationMatrix(vec3(0.0, 0.5, 0.5), u_twistFrequencyX * expStep(v_uv.y, u_twistPowerX));+ mat4 rotationC = rotationMatrix(vec3(0.5, 0.0, 0.5), u_twistFrequencyZ * expStep(v_uv.y, u_twistPowerZ));++ vec3 displacedPosition = displace(uv, position.xyz, u_time * u_speed, u_displaceFrequencyX, u_displaceFrequencyZ, u_displaceAmount);++ v_position = displacedPosition;+ v_position = (vec4(v_position, 1.0) * rotationA).xyz;+ v_position = (vec4(v_position, 1.0) * rotationB).xyz;+ v_position = (vec4(v_position, 1.0) * rotationC).xyz;++ v_clipPosition = projectionMatrix * modelViewMatrix * vec4(v_position, 1.0);+ vec4 clipPosition = projectionMatrix * modelViewMatrix * vec4(v_position, 1.0);+ gl_Position = v_clipPosition;+}+`;++// Wave surface colour: palette lookup, fine noise lines, glow from the uv derivative, contrast/saturation/hue.+export const waveFragment = /* glsl */ `precision highp float;++varying float v_time;+varying vec2 v_uv;+varying vec3 v_position;+varying vec4 v_clipPosition;+varying vec2 v_resolution;++uniform vec2 u_mousePosition;++uniform sampler2D u_paletteTexture;+uniform sampler2D u_lutTexture;+uniform sampler2D u_blueNoiseTexture;++uniform float u_colorSaturation;+uniform float u_colorContrast;+uniform float u_colorHueShift;++uniform float u_lineAmount;+uniform float u_lineThickness;+uniform float u_lineDerivativePower;++uniform float u_glowAmount;+uniform float u_glowPower;+uniform float u_glowRamp;++uniform vec3 u_clearColor;++#ifdef USE_NOISE_BANDS+const int MAX_NOISE_BANDS = 2;+uniform int u_numNoiseBands;+uniform vec4 u_noiseBandBounds[2];+uniform vec4 u_noiseBandParams[2];+uniform float u_noiseBandParabolaPower[2];+#endif++// TODO(weston): glsl-loader.js is looking for paths relative to the shader source.+// We should update it to start from a configurable root location++// Stefan Gustavson's version;+// https://www.shadertoy.com/view/43tBDr+// https://www.researchgate.net/publication/216813608_Simplex_noise_demystified++// https://xxhash.com/+// https://github.com/Cyan4973/xxHash/blob/dev/LICENSE++#ifndef STRIPE_HASH+#define STRIPE_HASH+float xxhash(vec2 x) {+ uvec2 t = floatBitsToUint(x);+ uint h = 0xc2b2ae3du * t.x + 0x165667b9u;+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;+ h += 0xc2b2ae3du * t.y;+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;+ h ^= h >> 15u;+ h *= 0x85ebca77u;+ h ^= h >> 13u;+ h *= 0xc2b2ae3du;+ h ^= h >> 16u;+ return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;+}++vec2 hash(vec2 x) {+ float k = 6.283185307 * xxhash(x);+ return vec2(cos(k), sin(k));+}+#endif+++#ifndef STRIPE_SIMPLEX_NOISE+#define STRIPE_SIMPLEX_NOISE+float simplexNoise(in vec2 p) {+ const float K1 = 0.366025404; // (sqrt(3)-1)/2;+ const float K2 = 0.211324865; // (3-sqrt(3))/6;++ vec2 i = floor(p + (p.x + p.y) * K1);+ vec2 a = p - i + (i.x + i.y) * K2;+ float m = step(a.y, a.x);+ vec2 o = vec2(m, 1.0 - m);+ vec2 b = a - o + K2;+ vec2 c = a - 1.0 + 2.0 * K2;+ vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);+ vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0))); // changed to h^3 [1]++ return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)+}+#endif++// Shaping functions by Inigo Quilez+// https://iquilezles.org/articles/functions/+// https://thebookofshaders.com/05/+++// Taken from glm's math.h++#ifndef STRIPE_CONSTANTS+#define STRIPE_CONSTANTS++#define M_E 2.71828182845904523536028747135266250 /* e */+#define M_LOG2E 1.44269504088896340735992468100189214 /* log 2e */+#define M_LOG10E 0.434294481903251827651128918916605082 /* log 10e */+#define M_LN2 0.693147180559945309417232121458176568 /* log e2 */+#define M_LN10 2.30258509299404568401799145468436421 /* log e10 */+#define M_PI 3.14159265358979323846264338327950288 /* pi */+#define M_PI_2 1.57079632679489661923132169163975144 /* pi/2 */+#define M_PI_4 0.785398163397448309615660845819875721 /* pi/4 */+#define M_1_PI 0.318309886183790671537767526745028724 /* 1/pi */+#define M_2_PI 0.636619772367581343075535053490057448 /* 2/pi */+#define M_2_SQRTPI 1.12837916709551257389615890312154517 /* 2/sqrt(pi) */+#define M_SQRT2 1.41421356237309504880168872420969808 /* sqrt(2) */+#define M_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */++#endif+++#ifndef STRIPE_SHAPING+#define STRIPE_SHAPING++float almostIdentity(float x, float n) {+ return sqrt(x * x + n * n);+}++float integralSmoothstep(float x, float T) {+ if(x > T)+ return x - T / 2.0;+ return x * x * x * (1.0 - x * 0.5 / T) / T / T;+}++// Impulses++float expImpulse(float x, float k) {+ float h = k * x;+ return h * exp(1.0 - h);+}++float quadImpulse(float k, float x) {+ return 2.0 * sqrt(k) * x / (1.0 + k * x * x);+}++float polyImpulse(float k, float n, float x) {+ return (n / (n - 1.0)) *+ pow((n - 1.0) * k, 1.0 / n) *+ x / (1.0 + k * pow(x, n));+}++float expSustainedImpulse(float x, float f, float k) {+ float s = max(x - f, 0.0);+ return min(x * x / (f * f), 1.0 + (2.0 / f) * s * exp(-k * s));+}++float sincImpulse(float x, float k) {+ float a = M_PI * (k * x - 1.0);+ return sin(a) / a;+}++// Falloff++float quadFallof(float x, float m) {+ x /= m;+ return (x - 2.0) * x + 1.0;+}++// Unitary++float almostUnitIdentity(float x) {+ return x * x * (2.0 - x);+}++float gain(float x, float k) {+ float a = 0.5 * pow(2.0 * ((x < 0.5) ? x : 1.0 - x), k);+ return (x < 0.5) ? a : 1.0 - a;+}++float parabola(float x, float k) {+ return pow(4.0 * x * (1.0 - x), k);+}++float pcurve(float x, float a, float b) {+ float k = pow(a + b, a + b) / (pow(a, a) * pow(b, b));+ return k * pow(x, a) * pow(1.0 - x, b);+}++float tone(float x, float k) {+ return (k + 1.0) / (1.0 + k * x);+}++// Pulse++float cubicPulse(float c, float w, float x) {+ x = abs(x - c);+ if(x > w)+ return 0.0;+ x /= w;+ return 1.0 - x * x * (3.0 - 2.0 * x);+}++float rationalBump(float x, float k) {+ return 1.0 / (1.0 + k * x * x);+}++float expStep(float x, float n) {+ return exp2(-exp2(n) * pow(x, n));+}++#endif++#ifndef STRIPE_COLOR+#define STRIPE_COLOR++vec3 contrast(in vec3 v, in float a) {+ return (v - 0.5) * a + 0.5;+}++vec3 desaturate(vec3 color, float factor) {+ // generic, rgb values are arbitrary+ vec3 lum = vec3(0.299, 0.587, 0.114);+ vec3 gray = vec3(dot(lum, color));+ return mix(color, gray, factor);+}++// https://godotshaders.com/shader/hue-shift/+// CC0 license, https://creativecommons.org/publicdomain/zero/1.0/+vec3 hueShift(vec3 color, float shift) {+ vec3 gray = vec3(0.57735);+ vec3 projection = gray * dot(gray, color);+ vec3 U = color - projection;+ vec3 V = cross(gray, U);+ vec3 shifted = U * cos(shift) + V * sin(shift) + projection;+ return shifted;+}++// By Inigo Quilez, under MIT license+// https://www.shadertoy.com/view/ttcyRS+vec3 oklab_mix(vec3 lin1, vec3 lin2, float a) {+ const mat3 kCONEtoLMS = mat3(0.4121656120, 0.2118591070, 0.0883097947, 0.5362752080, 0.6807189584, 0.2818474174, 0.0514575653, 0.1074065790, 0.6302613616);+ const mat3 kLMStoCONE = mat3(4.0767245293, -1.2681437731, -0.0041119885, -3.3072168827, 2.6093323231, -0.7034763098, 0.2307590544, -0.3411344290, 1.7068625689);+ vec3 lms1 = pow(kCONEtoLMS * lin1, vec3(1.0 / 3.0));+ vec3 lms2 = pow(kCONEtoLMS * lin2, vec3(1.0 / 3.0));+ vec3 lms = mix(lms1, lms2, a);+ lms *= 1.0 + 0.2 * a * (1.0 - a);+ return kLMStoCONE * (lms * lms * lms);+}++#endif++#ifndef STRIPE_UTILS+#define STRIPE_UTILS++float mapLinear(float value, float min1, float max1, float min2, float max2) {+ return min2 + (value - min1) * (max2 - min2) / (max1 - min1);+}++mat4 rotationMatrix(vec3 axis, float angle) {+ axis = normalize(axis);+ float s = sin(angle);+ float c = cos(angle);+ float oc = 1.0 - c;+ return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, 0.0, 0.0, 0.0, 1.0);+}++#endif+++vec3 surfaceColor(vec2 uv, vec3 pos, float pdy) {+ vec3 color = texture2D(u_paletteTexture, vec2(uv.x, uv.y)).rgb;++ float strength = 0.2;+ float freq = 600.0;+ float colorAtten = 0.9;+ float paraPow = 3.0;++ #ifdef USE_NOISE_BANDS+ for (int i = 0; i < MAX_NOISE_BANDS; i++) {+ if (i >= u_numNoiseBands) break;+ vec4 bounds = u_noiseBandBounds[i];+ vec4 nbp = u_noiseBandParams[i];+ float feather = nbp.x;+ float left = smoothstep(bounds.x - feather, bounds.x, uv.x);+ float right = 1.0 - smoothstep(bounds.y, bounds.y + feather, uv.x);+ float bottom = smoothstep(bounds.z - feather, bounds.z, uv.y);+ float top = 1.0 - smoothstep(bounds.w, bounds.w + feather, uv.y);+ float blend = left * right * bottom * top;+ strength = mix(strength, nbp.y, blend);+ freq = mix(freq, nbp.z, blend);+ colorAtten = mix(colorAtten, nbp.w, blend);+ paraPow = mix(paraPow, u_noiseBandParabolaPower[i], blend);+ }+ #endif++ float p = 1.0 - parabola(uv.x, paraPow);+ float n0 = simplexNoise(vec2(v_uv.x * 0.1, v_uv.y * 0.5));+ float n1 = simplexNoise(vec2(v_uv.x * (freq + (freq * 0.5 * n0)), v_uv.y * 4.0 * n0));+ n1 = mapLinear(n1, -1.0, 1.0, 0.0, 1.0);++ vec3 textureColor = color;+ textureColor += (n1 * strength * (1.0 - textureColor.b * colorAtten) * pdy * p);++ color = textureColor;+ return color;+}++void main(void) {+ vec2 st = gl_FragCoord.xy / v_resolution.xy;++ vec2 dy = dFdy(v_uv);+ float pdy = dy.y * v_resolution.y * u_glowAmount;+ pdy = mapLinear(pdy, -1.0, 1.0, 0.0, 1.0);+ pdy = clamp(pdy, 0.0, 1.0);+ pdy = pow(pdy, u_glowPower);+ pdy = smoothstep(0.0, u_glowRamp, pdy);+ pdy = clamp(pdy, 0.0, 1.0);++ vec4 color = vec4(surfaceColor(v_uv, v_position, pdy), 1.0);++ color.rgb = contrast(color.rgb, u_colorContrast);+ color.rgb = desaturate(color.rgb, 1.0 - u_colorSaturation);+ color.rgb = hueShift(color.rgb, u_colorHueShift);++ color += (1.0 - pdy) * 0.25;+ gl_FragColor = clamp(color, 0.0, 1.0);+}+`;+diff --git a/public/examples/stripe-bento/src/widgets/issuing/wave-geometry.js b/public/examples/stripe-bento/src/widgets/issuing/wave-geometry.jsnew file mode 100644index 0000000..9163359--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/wave-geometry.js@@ -0,0 +1,102 @@+// Folded wave ribbon as plain typed arrays (no three.js), so it can be built in a worker like on+// stripe.com. A width x height plane with segX x segY segments is folded: left of x=-16 it is+// lifted by d, between -16 and 16 it bends round a half cylinder of radius d, right of 16 it comes+// back mirrored at -d (d = 4 in the middle rows, falling to 2 at the top and bottom edges), then it+// is shifted by width/4 and turned on its side (-90° about x, then -90° about y).++// Rotate point v around a unit axis by angle (quaternion sandwich, as in Stripe's worker).+function rotateAroundAxis(v, axis, angle) {+ const half = angle / 2;+ const s = Math.sin(half);+ const qx = axis.x * s;+ const qy = axis.y * s;+ const qz = axis.z * s;+ const qw = Math.cos(half);+ const ix = qw * v.x + qy * v.z - qz * v.y;+ const iy = qw * v.y + qz * v.x - qx * v.z;+ const iz = qw * v.z + qx * v.y - qy * v.x;+ const iw = -qx * v.x - qy * v.y - qz * v.z;+ return {+ x: ix * qw - iw * qx - iy * qz + iz * qy,+ y: iy * qw - iw * qy - iz * qx + ix * qz,+ z: iz * qw - iw * qz - ix * qy + iy * qx,+ };+}++// Same vertex order, uvs and triangle winding as three's PlaneGeometry.+function planeArrays(width, height, segX, segY) {+ const halfW = width / 2;+ const halfH = height / 2;+ const cols = segX + 1;+ const rows = segY + 1;+ const stepX = width / segX;+ const stepY = height / segY;+ const positions = new Float32Array(cols * rows * 3);+ const uvs = new Float32Array(cols * rows * 2);+ let p = 0;+ let u = 0;+ for (let row = 0; row < rows; row += 1) {+ const y = row * stepY - halfH;+ for (let col = 0; col < cols; col += 1) {+ positions[p] = col * stepX - halfW;+ positions[p + 1] = -y;+ positions[p + 2] = 0;+ p += 3;+ uvs[u] = col / segX;+ uvs[u + 1] = 1 - row / segY;+ u += 2;+ }+ }+ const indices = new Uint32Array(segX * segY * 6);+ let k = 0;+ for (let row = 0; row < segY; row += 1) {+ for (let col = 0; col < segX; col += 1) {+ const a = col + cols * row;+ const b = col + cols * (row + 1);+ const c = col + 1 + cols * (row + 1);+ const d = col + 1 + cols * row;+ indices[k] = a;+ indices[k + 1] = b;+ indices[k + 2] = d;+ indices[k + 3] = b;+ indices[k + 4] = c;+ indices[k + 5] = d;+ k += 6;+ }+ }+ return { positions, uvs, indices };+}++const X_AXIS = { x: 1, y: 0, z: 0 };+const Y_AXIS = { x: 0, y: 1, z: 0 };++export function foldedWaveArrays({ width = 400, height = 400, subdivisionsX = 128, subdivisionsY = 256 } = {}) {+ const { positions, uvs, indices } = planeArrays(width, height, subdivisionsX, subdivisionsY);+ const count = positions.length / 3;+ for (let i = 0; i < count; i += 1) {+ let x = positions[3 * i];+ const y = positions[3 * i + 1];+ let z = positions[3 * i + 2];+ const v = uvs[2 * i + 1];+ const depth = 4 - 2 * (4 * v * (1 - v)) ** 9.5;+ if (x < -16) {+ z += depth;+ } else if (x < 16) {+ z = Math.cos(((x + 16) * Math.PI) / 32) * depth;+ x = Math.cos(-Math.PI / 2 + ((x + 16) * Math.PI) / 32) * depth - 16;+ } else {+ z -= depth;+ x = -x;+ }+ x += width / 4;+ let point = rotateAroundAxis({ x, y, z }, X_AXIS, -Math.PI / 2);+ point = rotateAroundAxis(point, Y_AXIS, -Math.PI / 2);+ positions[3 * i] = point.x;+ positions[3 * i + 1] = point.y;+ positions[3 * i + 2] = point.z;+ }+ // Placeholder normals; the main thread recomputes them from the faces.+ const normals = new Float32Array(count * 3);+ for (let i = 0; i < count; i += 1) normals[3 * i + 2] = 1;+ return { positions, uvs, normals, indices };+}diff --git a/public/examples/stripe-bento/src/widgets/issuing/wave-geometry.worker.js b/public/examples/stripe-bento/src/widgets/issuing/wave-geometry.worker.jsnew file mode 100644index 0000000..2624cb7--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/wave-geometry.worker.js@@ -0,0 +1,7 @@+// Builds the folded wave ribbon off the main thread (module worker), like stripe.com's waveGeometry worker.+import { foldedWaveArrays } from "./wave-geometry.js";++self.onmessage = (event) => {+ const result = foldedWaveArrays(event.data);+ self.postMessage(result, [result.positions.buffer, result.uvs.buffer, result.normals.buffer, result.indices.buffer]);+};diff --git a/public/examples/stripe-bento/src/widgets/issuing/wave.js b/public/examples/stripe-bento/src/widgets/issuing/wave.jsnew file mode 100644index 0000000..7f09021--- /dev/null+++ b/public/examples/stripe-bento/src/widgets/issuing/wave.js@@ -0,0 +1,167 @@+// The iridescent "wave": a 400x400 plane (128x256 segments) folded into a ribbon (wave-geometry.js),+// displaced by simplex noise over time and coloured from the palette texture. Port of stripe.com's+// wave mesh (light theme, no noise bands).++import {+ AddEquation,+ BufferAttribute,+ BufferGeometry,+ CustomBlending,+ DoubleSide,+ Mesh,+ ShaderMaterial,+ SrcColorFactor,+ Texture,+ Vector2,+ Vector3,+ ZeroFactor,+} from "three";+import { waveFragment, waveVertex } from "./shaders.js";+import { foldedWaveArrays } from "./wave-geometry.js";++// Build the ribbon in a worker (fallback: on this thread), once per page, as stripe.com does.+let sharedGeometry = null;+let pendingGeometry = null;++function toBufferGeometry({ positions, uvs, normals, indices }) {+ const geometry = new BufferGeometry();+ geometry.setAttribute("position", new BufferAttribute(positions, 3));+ geometry.setAttribute("uv", new BufferAttribute(uvs, 2));+ geometry.setAttribute("normal", new BufferAttribute(normals, 3));+ geometry.setIndex(Array.from(indices));+ geometry.computeVertexNormals();+ return geometry;+}++export function createFoldedWaveGeometry(width = 400, height = 400, subdivisionsX = 128, subdivisionsY = 256) {+ if (sharedGeometry) return Promise.resolve(sharedGeometry);+ if (pendingGeometry) return pendingGeometry;+ const params = { width, height, subdivisionsX, subdivisionsY };+ pendingGeometry = (async () => {+ let arrays;+ if (typeof Worker !== "undefined") {+ try {+ const worker = new Worker(new URL("./wave-geometry.worker.js", import.meta.url), { type: "module" });+ arrays = await new Promise((resolve) => {+ worker.onmessage = (e) => {+ worker.terminate();+ resolve(e.data);+ };+ worker.onerror = () => {+ worker.terminate();+ resolve(foldedWaveArrays(params));+ };+ worker.postMessage(params);+ });+ } catch {+ arrays = foldedWaveArrays(params);+ }+ } else {+ arrays = foldedWaveArrays(params);+ }+ sharedGeometry = toBufferGeometry(arrays);+ pendingGeometry = null;+ return sharedGeometry;+ })();+ return pendingGeometry;+}++function waveUniforms() {+ const empty = new Texture();+ return {+ u_time: { value: 0 },+ u_speed: { value: 4e-5 },+ u_resolution: { value: new Vector2() },+ u_paletteTexture: { value: empty },+ u_lutTexture: { value: empty },+ u_blueNoiseTexture: { value: empty },+ u_colorContrast: { value: 1 },+ u_colorSaturation: { value: 1 },+ u_colorHueShift: { value: 0 },+ u_displaceFrequencyX: { value: 2.25 },+ u_displaceFrequencyZ: { value: 2.25 },+ u_displaceAmount: { value: 0 },+ u_twistFrequencyY: { value: 0 },+ u_twistFrequencyX: { value: 0 },+ u_twistFrequencyZ: { value: 0 },+ u_twistPowerY: { value: 1 },+ u_twistPowerX: { value: 1 },+ u_twistPowerZ: { value: 1 },+ u_glowAmount: { value: 0.01 },+ u_glowPower: { value: 0.01 },+ u_glowRamp: { value: 1 },+ u_mousePosition: { value: new Vector2(0, 0) },+ u_lineAmount: { value: 450 },+ u_lineThickness: { value: 0.01 },+ u_lineDerivativePower: { value: 0.9 },+ u_maxWidth: { value: 1232 },+ u_clearColor: { value: new Vector3(1, 1, 1) },+ };+}++export class WaveMesh {+ constructor(paletteTexture, geometry) {+ // Light theme: the output is multiplied by itself (src·src + dst·0), which deepens the palette.+ this.material = new ShaderMaterial({+ uniforms: waveUniforms(),+ vertexShader: waveVertex,+ fragmentShader: waveFragment,+ depthWrite: true,+ depthTest: true,+ side: DoubleSide,+ colorWrite: true,+ blending: CustomBlending,+ blendEquation: AddEquation,+ blendSrc: SrcColorFactor,+ blendDst: ZeroFactor,+ });+ this.material.uniforms.u_paletteTexture.value = paletteTexture;+ this.mesh = new Mesh(geometry, this.material);+ this.timeOffset = 0;+ }++ applyConfig(config, clearColor) {+ const u = this.material.uniforms;+ this.timeOffset = config.timeOffset;+ u.u_speed.value = config.speed;+ u.u_colorContrast.value = config.colorContrast;+ u.u_colorSaturation.value = config.colorSaturation;+ u.u_colorHueShift.value = config.colorHueShift;+ u.u_displaceFrequencyX.value = config.displaceFrequencyX;+ u.u_displaceFrequencyZ.value = config.displaceFrequencyZ;+ u.u_displaceAmount.value = config.displaceAmount;+ u.u_twistFrequencyX.value = config.twistFrequencyX;+ u.u_twistFrequencyY.value = config.twistFrequencyY;+ u.u_twistFrequencyZ.value = config.twistFrequencyZ;+ u.u_twistPowerX.value = config.twistPowerX;+ u.u_twistPowerY.value = config.twistPowerY;+ u.u_twistPowerZ.value = config.twistPowerZ;+ u.u_glowAmount.value = config.glowAmount;+ u.u_glowPower.value = config.glowPower;+ u.u_glowRamp.value = config.glowRamp;+ u.u_lineThickness.value = config.lineThickness;+ u.u_lineAmount.value = config.lineAmount;+ u.u_lineDerivativePower.value = config.lineDerivativePower;+ u.u_clearColor.value = clearColor;+ this.mesh.position.set(config.position.x, config.position.y, config.position.z);+ this.mesh.rotation.set(config.rotation.x, config.rotation.y, config.rotation.z);+ this.mesh.scale.set(config.scale.x, config.scale.y, config.scale.z);+ }++ set time(ms) {+ this.material.uniforms.u_time.value = ms + this.timeOffset;+ }++ set resolution(v) {+ this.material.uniforms.u_resolution.value = v;+ }++ set mousePosition(v) {+ this.material.uniforms.u_mousePosition.value = v;+ }++ dispose() {+ this.mesh.geometry.dispose();+ this.material.dispose();+ }+}diff --git a/public/file.svg b/public/file.svgdeleted file mode 100644index 004145c..0000000--- a/public/file.svg+++ /dev/null@@ -1 +0,0 @@-<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/public/globe.svg b/public/globe.svgdeleted file mode 100644index 567f17b..0000000--- a/public/globe.svg+++ /dev/null@@ -1 +0,0 @@-<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>\ No newline at end of filediff --git a/public/media/entrance-clone.mp4 b/public/media/entrance-clone.mp4new file mode 100644index 0000000..7d25aa9Binary files /dev/null and b/public/media/entrance-clone.mp4 differdiff --git a/public/media/entrance-ref.mp4 b/public/media/entrance-ref.mp4new file mode 100644index 0000000..93ba985Binary files /dev/null and b/public/media/entrance-ref.mp4 differdiff --git a/public/media/hover-agentic-commerce-clone.mp4 b/public/media/hover-agentic-commerce-clone.mp4new file mode 100644index 0000000..0e08d96Binary files /dev/null and b/public/media/hover-agentic-commerce-clone.mp4 differdiff --git a/public/media/hover-agentic-commerce-ref.mp4 b/public/media/hover-agentic-commerce-ref.mp4new file mode 100644index 0000000..011c317Binary files /dev/null and b/public/media/hover-agentic-commerce-ref.mp4 differdiff --git a/public/media/hover-crypto-clone.mp4 b/public/media/hover-crypto-clone.mp4new file mode 100644index 0000000..370777bBinary files /dev/null and b/public/media/hover-crypto-clone.mp4 differdiff --git a/public/media/hover-crypto-ref.mp4 b/public/media/hover-crypto-ref.mp4new file mode 100644index 0000000..55a0b27Binary files /dev/null and b/public/media/hover-crypto-ref.mp4 differdiff --git a/public/media/hover-issuing-clone.mp4 b/public/media/hover-issuing-clone.mp4new file mode 100644index 0000000..86e4e55Binary files /dev/null and b/public/media/hover-issuing-clone.mp4 differdiff --git a/public/media/hover-issuing-ref.mp4 b/public/media/hover-issuing-ref.mp4new file mode 100644index 0000000..c6fa6abBinary files /dev/null and b/public/media/hover-issuing-ref.mp4 differdiff --git a/public/media/sheet-issuing-hover.webp b/public/media/sheet-issuing-hover.webpnew file mode 100644index 0000000..31cf0d5Binary files /dev/null and b/public/media/sheet-issuing-hover.webp differdiff --git a/public/next.svg b/public/next.svgdeleted file mode 100644index 5174b28..0000000--- a/public/next.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>\ No newline at end of filediff --git a/public/og.png b/public/og.pngnew file mode 100644index 0000000..6215e73Binary files /dev/null and b/public/og.png differdiff --git a/public/vercel.svg b/public/vercel.svgdeleted file mode 100644index 7705396..0000000--- a/public/vercel.svg+++ /dev/null@@ -1 +0,0 @@-<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>\ No newline at end of filediff --git a/public/window.svg b/public/window.svgdeleted file mode 100644index b2b2a44..0000000--- a/public/window.svg+++ /dev/null@@ -1 +0,0 @@-<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>\ No newline at end of filediff --git a/scripts/vendor-examples.mjs b/scripts/vendor-examples.mjsnew file mode 100644index 0000000..0896216--- /dev/null+++ b/scripts/vendor-examples.mjs@@ -0,0 +1,19 @@+// Copies the runtime files the live examples load (three.js r178 and the Inter font) from+// node_modules into public/examples/*/vendor, so they are served with the static export.+// Runs before `dev` and `build`; the vendor folders are git-ignored.+import { cpSync, mkdirSync, rmSync } from "node:fs";+import { join } from "node:path";++const root = join(import.meta.dirname, "..");+const nm = (...p) => join(root, "node_modules", ...p);+const vendor = join(root, "public", "examples", "stripe-bento", "vendor");++rmSync(vendor, { recursive: true, force: true });+mkdirSync(join(vendor, "three", "addons"), { recursive: true });+mkdirSync(join(vendor, "fonts"), { recursive: true });+for (const f of ["three.module.js", "three.core.js"]) cpSync(nm("three", "build", f), join(vendor, "three", f));+cpSync(nm("three", "examples", "jsm", "lines"), join(vendor, "three", "addons", "lines"), { recursive: true });+cpSync(nm("three", "LICENSE"), join(vendor, "three", "LICENSE"));+cpSync(nm("@fontsource-variable", "inter", "files", "inter-latin-wght-normal.woff2"), join(vendor, "fonts", "inter-latin-wght-normal.woff2"));+cpSync(nm("@fontsource-variable", "inter", "LICENSE"), join(vendor, "fonts", "LICENSE-inter.txt"));+console.log("vendored three.js + Inter into", vendor);diff --git a/src/app/favicon.ico b/src/app/favicon.icodeleted file mode 100644index af98450..0000000Binary files a/src/app/favicon.ico and /dev/null differdiff --git a/src/app/globals.css b/src/app/globals.cssindex a2dc41e..4461c23 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -1,26 +1,182 @@@import "tailwindcss";:root {- --background: #ffffff;- --foreground: #171717;+ --bg: #fafafa;+ --fg: #171717;+ --muted: #737373;+ --faint: #a3a3a3;+ --rule: #e7e7e5;+ --panel: #ffffff;+ --accent: #533afd;+ --col: 560px;+ --side: 220px;+ --nav: 200px;}@theme inline {- --color-background: var(--background);- --color-foreground: var(--foreground);- --font-sans: var(--font-geist-sans);- --font-mono: var(--font-geist-mono);+ --font-sans: var(--font-sans);+ --font-serif: var(--font-serif);+ --font-mono: var(--font-mono);}-@media (prefers-color-scheme: dark) {- :root {- --background: #0a0a0a;- --foreground: #ededed;- }-}+html { scroll-behavior: smooth; scroll-padding-top: 48px; }+@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }body {- background: var(--background);- color: var(--foreground);- font-family: Arial, Helvetica, sans-serif;+ margin: 0;+ background: var(--bg);+ color: var(--fg);+ font-family: var(--font-sans), system-ui, sans-serif;+ font-size: 15px;+ line-height: 1.45;+ -webkit-font-smoothing: antialiased;+ font-feature-settings: "cv11", "ss03";+}++a { color: inherit; text-decoration: underline; text-decoration-color: var(--faint); text-underline-offset: 3px; }+a:hover { text-decoration-color: var(--fg); }+em, .serif { font-family: var(--font-serif), Georgia, serif; font-style: italic; font-size: 1.12em; letter-spacing: -0.005em; }+code, kbd, .mono { font-family: var(--font-mono), ui-monospace, monospace; font-size: 0.86em; }+p code, li code, td code { background: #f0f0ee; padding: 1px 5px; border-radius: 4px; }++/* ---------- page grid: nav | column | sidenotes ---------- */++.page {+ display: grid;+ grid-template-columns: var(--nav) minmax(0, var(--col)) var(--side);+ column-gap: 56px;+ justify-content: center;+ padding: 56px 24px 120px;+}+.main { grid-column: 2; min-width: 0; }++@media (max-width: 1180px) {+ .page { grid-template-columns: minmax(0, var(--col)) var(--side); }+ .main { grid-column: 1; }+ .nav { display: none; }+}+@media (max-width: 900px) {+ .page { grid-template-columns: minmax(0, var(--col)); padding-top: 32px; }}++/* ---------- nav ---------- */++.nav { grid-column: 1; grid-row: 1; }+.nav__inner { position: sticky; top: 56px; display: flex; flex-direction: column; gap: 28px; }+.nav ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }+.nav a { text-decoration: none; color: var(--muted); font-size: 13.5px; transition: color 0.2s; }+.nav a:hover, .nav a[aria-current="true"] { color: var(--fg); }+.nav__brand { display: flex; align-items: center; gap: 10px; color: var(--fg) !important; font-weight: 500; }++/* the mark: a square that moves, with onion-skin frames trailing behind it */+.mark { width: 30px; height: 14px; position: relative; flex: none; }+.mark i { position: absolute; top: 2px; left: 0; width: 10px; height: 10px; border-radius: 2.5px; background: var(--fg); animation: mark 2.4s cubic-bezier(0.16, 1, 0.3, 1) infinite; }+.mark i:nth-child(1) { opacity: 0.15; animation-delay: -0.24s; }+.mark i:nth-child(2) { opacity: 0.35; animation-delay: -0.12s; }+@keyframes mark { 0%, 12% { transform: translateX(0); } 50%, 62% { transform: translateX(20px); } 100% { transform: translateX(0); } }+@media (prefers-reduced-motion: reduce) { .mark i { animation: none; } .mark i:nth-child(1) { transform: translateX(10px); } .mark i:nth-child(3) { transform: translateX(20px); } }++/* ---------- header ---------- */++.masthead { display: flex; justify-content: space-between; align-items: baseline; gap: 16px; }+.masthead h1 { margin: 0; font-size: 15px; font-weight: 600; }+.masthead h1 span { color: var(--muted); font-weight: 400; }+.masthead__links { display: flex; gap: 14px; }+.masthead__links a { color: var(--muted); }+.lede { margin: 26px 0 0; font-size: 15.5px; }+.meta { display: flex; flex-wrap: wrap; gap: 6px 10px; margin: 18px 0 0; padding: 14px 0; border-block: 1px solid var(--rule); color: var(--muted); font-size: 13.5px; }+.meta span + span::before { content: "·"; margin-right: 10px; color: var(--faint); }++/* ---------- prose ---------- */++.main > p, .section > p { margin: 18px 0 0; }+.section__head + p { margin-top: 22px; }+ul.list { margin: 22px 0 0; padding-left: 18px; list-style: disc; }+ul.list li { padding-left: 4px; }+ul.list li::marker { color: var(--faint); }+ul.list li + li { margin-top: 8px; }+.section h3 { margin: 56px 0 0; font-size: 15px; font-weight: 600; }++.section { margin-top: 88px; }+.section__head { display: flex; align-items: center; gap: 16px; }+.section__head h2 { margin: 0; font-size: 15px; font-weight: 600; white-space: nowrap; }+.section__head::after { content: ""; order: 1; flex: 1; height: 1px; background: var(--rule); }+.section__head .num { order: 2; color: var(--muted); }++blockquote.rule { margin: 26px 0 0; padding: 0 0 0 18px; border-left: 2px solid var(--fg); }+blockquote.rule p { margin: 0; font-size: 17px; }+blockquote.rule cite { display: block; margin-top: 6px; color: var(--muted); font-size: 13px; font-style: normal; }++/* key/value table */+.kv { width: 100%; margin-top: 26px; border-collapse: collapse; }+.kv tr { border-top: 1px solid var(--rule); }+.kv tr:last-child { border-bottom: 1px solid var(--rule); }+.kv th, .kv td { text-align: left; vertical-align: top; padding: 11px 0; font-size: 14.5px; }+.kv th { font-weight: 600; width: 148px; padding-right: 18px; }+.kv td { color: #404040; }+.kv td.num { white-space: nowrap; text-align: right; color: var(--fg); padding-left: 16px; }+.kv thead th { font-weight: 500; color: var(--muted); font-size: 13px; }++/* sidenotes: in the right column on wide screens, under the paragraph on narrow ones */+.sn-ref { font-size: 0.7em; vertical-align: super; line-height: 0; color: var(--muted); margin-left: 1px; }+.sidenote { float: right; clear: right; width: var(--side); margin-right: calc(-1 * var(--side) - 56px); margin-top: 4px; font-size: 12.5px; line-height: 1.45; color: var(--muted); position: relative; }+.sidenote::before { content: attr(data-n); position: absolute; left: -14px; top: 0; font-size: 10px; }+@media (max-width: 900px) {+ .sidenote { float: none; display: block; width: auto; margin: 10px 0 0; padding-left: 14px; }+ .sidenote::before { left: 0; }+}++/* ---------- figures ---------- */++.figure { margin: 34px 0 0; }+.figure--wide { margin-right: calc(-1 * var(--side) - 56px); }+@media (max-width: 900px) { .figure--wide { margin-right: 0; } }+.figure__caption { margin-top: 10px; font-size: 12.5px; color: var(--muted); display: flex; justify-content: space-between; gap: 16px; }+.figure__caption button, .figure__caption a { color: var(--muted); font-size: 12.5px; background: none; border: 0; padding: 0; cursor: pointer; text-decoration: underline; text-decoration-color: var(--faint); text-underline-offset: 3px; white-space: nowrap; font-family: inherit; }+.figure__caption button:hover, .figure__caption a:hover { color: var(--fg); }++.live { position: relative; overflow: hidden; background: #fff; border-radius: 10px; box-shadow: 0 0 0 1px var(--rule); }+.live iframe { position: absolute; top: 0; left: 0; border: 0; transform-origin: 0 0; background: #fff; }+.live__badge { position: absolute; left: 12px; bottom: 10px; z-index: 1; font-size: 11px; letter-spacing: 0.02em; color: var(--muted); background: rgba(255,255,255,0.85); padding: 2px 7px; border-radius: 99px; box-shadow: 0 0 0 1px var(--rule); pointer-events: none; }+.live__badge b { display: inline-block; width: 6px; height: 6px; margin-right: 6px; border-radius: 50%; background: #16a34a; vertical-align: 1px; }++.compare { position: relative; overflow: hidden; border-radius: 10px; box-shadow: 0 0 0 1px var(--rule); background: #fff; touch-action: pan-y; cursor: ew-resize; user-select: none; }+.compare video { display: block; width: 100%; height: auto; }+.compare__top { position: absolute; inset: 0; }+.compare__line { position: absolute; top: 0; bottom: 0; width: 2px; margin-left: -1px; background: var(--fg); pointer-events: none; }+.compare__line::after { content: "↔"; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 28px; height: 28px; border-radius: 50%; background: var(--fg); color: #fff; font-size: 13px; display: grid; place-items: center; }+.compare__label { position: absolute; top: 10px; font-size: 11px; padding: 2px 8px; border-radius: 99px; background: rgba(23,23,23,0.82); color: #fff; pointer-events: none; }+.compare__label--left { left: 10px; }+.compare__label--right { right: 10px; }+.compare input[type="range"] { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: ew-resize; margin: 0; }++.sheet { display: block; width: 100%; height: auto; border-radius: 10px; box-shadow: 0 0 0 1px var(--rule); }++/* card sections: live card next to its comparison */+.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; align-items: start; }+@media (max-width: 640px) { .pair { grid-template-columns: 1fr; } }+.pair__label { font-size: 12px; color: var(--muted); margin-bottom: 6px; }++/* ---------- install / commands ---------- */++.cmd { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 18px; padding: 12px 14px; border-radius: 8px; background: #171717; color: #fafafa; font-family: var(--font-mono), monospace; font-size: 13.5px; overflow-x: auto; }+.cmd span::before { content: "$ "; color: #8a8a8a; }+.cmd button { flex: none; background: #2a2a2a; color: #d4d4d4; border: 0; border-radius: 5px; padding: 4px 9px; font: inherit; font-size: 12px; cursor: pointer; }+.cmd button:hover { background: #3a3a3a; color: #fff; }++.prompts { margin-top: 22px; display: flex; flex-direction: column; gap: 14px; }+.prompt__label { font-size: 12.5px; color: var(--muted); margin-bottom: 5px; }+.prompt__text { padding: 11px 14px; border-radius: 8px; background: var(--panel); box-shadow: 0 0 0 1px var(--rule); font-size: 14px; }+.prompt__text .slash { font-family: var(--font-mono), monospace; font-size: 0.9em; color: var(--accent); margin-right: 6px; }+.prompt__text b { font-weight: 600; }++/* FAQ */+.faq { margin-top: 22px; border-top: 1px solid var(--rule); }+.faq details { border-bottom: 1px solid var(--rule); padding: 12px 0; }+.faq summary { cursor: pointer; font-weight: 500; list-style: none; display: flex; justify-content: space-between; gap: 12px; }+.faq summary::-webkit-details-marker { display: none; }+.faq summary::after { content: "+"; color: var(--muted); }+.faq details[open] summary::after { content: "–"; }+.faq details p { margin: 8px 0 0; color: #404040; }++.footer { margin-top: 96px; padding-top: 18px; border-top: 1px solid var(--rule); font-size: 12.5px; color: var(--muted); display: flex; flex-direction: column; gap: 8px; }diff --git a/src/app/icon.svg b/src/app/icon.svgnew file mode 100644index 0000000..a386181--- /dev/null+++ b/src/app/icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#171717"/><rect x="5" y="11" width="10" height="10" rx="2.5" fill="#fff" opacity=".2"/><rect x="11" y="11" width="10" height="10" rx="2.5" fill="#fff" opacity=".45"/><rect x="17" y="11" width="10" height="10" rx="2.5" fill="#fff"/></svg>diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 9852c15..a6db919 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -1,29 +1,41 @@-import type { Metadata } from "next";-import { Geist, Geist_Mono } from "next/font/google";+import type { Metadata, Viewport } from "next";+import { Inter, Instrument_Serif, JetBrains_Mono } from "next/font/google";import "./globals.css";-const geistSans = Geist({- variable: "--font-geist-sans",- subsets: ["latin"],-});+const sans = Inter({ variable: "--font-sans", subsets: ["latin"] });+const serif = Instrument_Serif({ variable: "--font-serif", subsets: ["latin"], weight: "400", style: "italic" });+const mono = JetBrains_Mono({ variable: "--font-mono", subsets: ["latin"] });-const geistMono = Geist_Mono({- variable: "--font-geist-mono",- subsets: ["latin"],-});+// The public URL, for absolute Open Graph and canonical links. Set in .env.production (or the build+// environment) once the Worker has its final domain.+const siteUrl = process.env.SITE_URL || "http://localhost:3000";++const title = "motion-clone · a skill for Claude Code";+const description =+ "Point Claude at any animation, on a live site, in a video or a gif, and it rebuilds it frame by frame in your codebase, then records the copy and compares the two until they move the same.";export const metadata: Metadata = {- title: "Create Next App",- description: "Generated by create next app",+ metadataBase: new URL(siteUrl),+ title,+ description,+ alternates: { canonical: "/" },+ openGraph: {+ title,+ description,+ url: "/",+ siteName: "motion-clone",+ type: "website",+ images: [{ url: "/og.png", width: 1200, height: 630, alt: "Three stripe.com cards rebuilt by motion-clone" }],+ },+ twitter: { card: "summary_large_image", title, description, images: ["/og.png"] },};+export const viewport: Viewport = { themeColor: "#fafafa" };+export default function RootLayout({ children }: LayoutProps<"/">) {return (- <html- lang="en"- className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}- >- <body className="min-h-full flex flex-col">{children}</body>+ <html lang="en" className={`${sans.variable} ${serif.variable} ${mono.variable}`}>+ <body>{children}</body></html>);}diff --git a/src/app/page.tsx b/src/app/page.tsxindex c887311..332a2b4 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -1,68 +1,329 @@-import Image from "next/image";+import { CompareVideo } from "@/components/CompareVideo";+import { CopyCommand } from "@/components/CopyCommand";+import { LiveExample } from "@/components/LiveExample";+import { Nav, type NavItem } from "@/components/Nav";+import { Sidenote } from "@/components/Sidenote";++const REPO = "https://github.com/NiazMorshed2007/motion-clone";+const INSTALL = "npx skills add NiazMorshed2007/motion-clone -g";++const sections: NavItem[] = [+ { id: "measure", label: "Measure, don’t eyeball" },+ { id: "levels", label: "Three levels of done" },+ { id: "numbers", label: "Where the numbers come from" },+ { id: "evidence", label: "Reading the evidence" },+ { id: "cards", label: "Three cards, up close" },+ { id: "prompt", label: "Writing a prompt" },+ { id: "install", label: "Install" },+ { id: "limits", label: "Limits" },+ { id: "questions", label: "Questions" },+];++function Section({ id, n, title, children }: { id: string; n: number; title: string; children: React.ReactNode }) {+ return (+ <section id={id} className="section">+ <div className="section__head">+ <h2>{title}</h2>+ <span className="num serif">{String(n).padStart(2, "0")}</span>+ </div>+ {children}+ </section>+ );+}++function Rows({ rows, head }: { rows: [string, React.ReactNode, React.ReactNode?][]; head?: [string, string, string?] }) {+ return (+ <table className="kv">+ {head && (+ <thead>+ <tr>+ <th>{head[0]}</th>+ <th>{head[1]}</th>+ {head[2] !== undefined && <th className="num">{head[2]}</th>}+ </tr>+ </thead>+ )}+ <tbody>+ {rows.map(([k, v, num]) => (+ <tr key={k}>+ <th scope="row">{k}</th>+ <td>{v}</td>+ {num !== undefined && <td className="num">{num}</td>}+ </tr>+ ))}+ </tbody>+ </table>+ );+}export default function Home() {return (- <div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">- <main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">- <Image- className="dark:invert h-5 w-[100px]"- src="/next.svg"- alt="Next.js logo"- width={100}- height={20}- priority- />- <div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">- <h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">- To get started, edit the{" "}- <code className="rounded bg-black/[.06] px-1.5 py-0.5 font-mono text-[0.9em] dark:bg-white/[.08]">- page.tsx- </code>{" "}- file.+ <div className="page" id="top">+ <Nav items={sections} />++ <main className="main">+ <header className="masthead">+ <h1>+ motion-clone <span>· a skill for Claude Code</span></h1>- <p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">- Looking for a starting point or more instructions? Head over to{" "}- <a- href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"- className="font-medium text-zinc-950 dark:text-zinc-50"- >- Templates- </a>{" "}- or the{" "}- <a- href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"- className="font-medium text-zinc-950 dark:text-zinc-50"- >- Learning- </a>{" "}- center.- </p>- </div>- <div className="flex flex-col gap-4 text-base font-medium sm:flex-row">- <a- className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"- href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"- target="_blank"- rel="noopener noreferrer"- >- <Image- className="dark:invert h-[14px] w-4"- src="/vercel.svg"- alt="Vercel logomark"- width={16}- height={14}- />- Deploy Now- </a>- <a- className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"- href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"- target="_blank"- rel="noopener noreferrer"- >- Documentation- </a>+ <div className="masthead__links">+ <a href={REPO} aria-label="GitHub repository">GitHub</a>+ </div>+ </header>++ <p className="lede">+ Point Claude at an animation, and it rebuilds it <em>frame by frame</em>, then proves the copy moves the same.+ </p>++ <div className="meta">+ <span>/motion-clone</span>+ <span><a href="#cards">3 cards, all live</a></span>+ <span>by <a href="https://github.com/NiazMorshed2007">Niaz</a></span>+ <span>29 October 2026</span>+ <span><a href="#install">Install ↓</a></span></div>++ <p>+ Copying an animation by eye goes the same way every time. The copy looks right in a screenshot and feels wrong in motion. The easing is a little sharper, the second line starts a beat late, the card lifts four pixels instead of six. Nobody can say what is off, so nobody fixes it.+ </p>+ <p>+ motion-clone is a skill for Claude Code that treats an animation as something to <em>measure</em>. It records the reference, whether that is a live site, a screen recording or a gif, reads it frame by frame and writes down every timing and easing. Then it rebuilds the animation in your codebase, records the copy the same way and compares the two until the numbers agree.+ </p>++ <figure className="figure figure--wide">+ <LiveExample title="Three stripe.com cards, rebuilt by motion-clone, running live" />+ <figcaption className="sr-only">Three cards from the stripe.com homepage, rebuilt by motion-clone.</figcaption>+ </figure>++ <p>+ These are three cards from the stripe.com homepage, rebuilt by the skill, one agent per card.+ <Sidenote n={1}>+ The cards here use Inter. stripe.com uses its licensed Söhne, and the clone was verified with the original font before this public build swapped it.+ </Sidenote>{" "}+ What you see above is the clone, running live. Hover a card: it grows six pixels, the title and the button slide out of the way and the border lights up where your pointer is. The Visa card tilts towards you, the particle ring pulls in near your pointer and the globe’s dots brighten.+ </p>++ <figure className="figure figure--wide">+ <CompareVideo reference="/media/entrance-ref.mp4" clone="/media/entrance-clone.mp4" width={1252} height={696} label="Entrance" />+ <figcaption className="figure__caption">+ <span>The entrance, recorded on stripe.com and on the clone with the same command. Drag the line.</span>+ </figcaption>+ </figure>++ <Section id="measure" n={1} title="Measure, don’t eyeball">+ <p>The skill rests on one rule, near the top of its instructions:</p>+ <blockquote className="rule">+ <p>The deliverable is code in the user’s project plus evidence (numbers and side-by-side sheets), never “it looks about right”.</p>+ <cite>SKILL.md</cite>+ </blockquote>+ <p>Every clone runs the same loop, and the loop doesn’t end until the comparison passes.</p>+ <Rows+ rows={[+ ["Capture", "Records the reference in a headless browser at a fixed viewport and frame rate: a video, numbered frames, every CSS and Web Animations API animation it can find, and the position of chosen elements on every frame."],+ ["Spec", "Writes one row per element per property: when it starts, how long it runs, from where to where, with which easing. A row with a question mark means the frames haven’t been read yet."],+ ["Build", "Implements it in your stack, with what the project already uses: CSS, Framer Motion, GSAP, three.js."],+ ["Verify", "Records the clone with the exact command used for the reference, then compares timing, pixels and the easing curve, and builds side-by-side sheets."],+ ["Repeat", "Fixes the smallest thing the evidence points at and records again. Two to five rounds is normal. A row that still fails after five is reported with its numbers and the reason, not hidden."],+ ]}+ />+ <p>+ The capture is the part that makes this work. The reference and the clone are recorded by the same script with the same viewport, crop, trigger, duration and frame rate. When the two differ, the difference is in the clone, not in how it was filmed.+ </p>+ </Section>++ <Section id="levels" n={2} title="Three levels of done">+ <p>The words in your prompt pick how close the copy has to be, and that decides what gets checked.</p>+ <Rows+ rows={[+ ["Motion-faithful", <>The default. Trigger, order, stagger, the timing of every step to within 80 ms, the easing family, and how far things move relative to their size. Copy, colours and fonts can be yours.</>],+ ["Pixel-faithful", <>Say <em>match it exactly</em> or <em>pixel-perfect</em>. Everything above, plus fonts, sizes, colours, spacing and assets, with at most 2 % of pixels differing on average.</>],+ ["Mixed", <>Say <em>clone this and add that</em>. The cloned parts are held to one of the levels above; your additions live in their own components and are checked only for not breaking the motion.</>],+ ]}+ />+ <p>You can also narrow the target: one section, one widget, or a time range of a video, like <em>0:12 to 0:15</em>. It clones exactly that and leaves the rest of the page alone.</p>+ </Section>++ <Section id="numbers" n={3} title="Where the numbers come from">+ <p>Most of an animation’s spec is sitting in the page, if you know where to look. The skill reads its sources in this order and stops at the first one that answers:</p>+ <Rows+ rows={[+ ["Declared", "CSS animations, transitions and Web Animations that ran under the target, with their durations, delays and per-keyframe easings. When these exist they are the spec."],+ ["Tracked", "The position, size, opacity and transform of chosen elements on every animation frame, fitted against a table of named easings. It reports the best fit, the overshoot and whether the motion looks like a spring."],+ ["Read", "For video, gifs and canvas: the first frame where something changes and the last, and where the midpoint lands. Past halfway at a third of the time is an ease-out; a quarter or less is an ease-in."],+ ]}+ />+ <p>+ For WebGL graphics, like the three canvases in these cards, the pixels are the only output, so the skill reads the scripts the page loaded to recover the shaders, constants and timings, and rebuilds the scene from those.+ </p>+ </Section>++ <Section id="evidence" n={4} title="Reading the evidence">+ <p>Each round ends with numbers and a sheet. The numbers say <em>that</em> something is off; the sheet says <em>what</em>.</p>+ <figure className="figure">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img className="sheet" src="/media/sheet-issuing-hover.webp" alt="A comparison sheet: four moments of the card issuing hover, stripe.com on the left, the clone in the middle, and on the right the pixels that differ, in red. Only thin outlines of the card's edge and the title differ." width={816} height={975} loading="lazy" />+ <figcaption className="figure__caption">+ <span>Hovering the card issuing card: stripe.com, the clone, and in red the pixels that differ. 0.91 % differ on average.</span>+ </figcaption>+ </figure>+ <p>For the hover shared by all three cards, the same measurement on both pages:</p>+ <Rows+ head={["", "stripe.com → clone", "difference"]}+ rows={[+ ["Title shift", "ease-out-expo, starts 38 → 34 ms, settles in 643 → 633 ms", "0.13 px"],+ ["Button shift", "same curve, (3.55, −6) px", "0.08 px"],+ ["Icon arrows", "ease-out-expo, settles in 397 → 383 ms", "0.05 px"],+ ["Border glow", "follows the pointer to the card’s edge", "6.6 of 290 px"],+ ["Card growth", "6 px taller, 3.55 px wider, clipped open", "0 px"],+ ]}+ />+ </Section>++ <Section id="cards" n={5} title="Three cards, up close">+ <p>+ Each card was cloned by its own agent running the skill, in parallel, in 28 to 40 minutes.+ <Sidenote n={2}>Measured as the agent’s working time, from the first recording to the final report.</Sidenote>{" "}+ On the left of each card below is the clone, live. On the right, both recordings of the same pointer path: in, hold, across, out.+ </p>++ <h3>Agentic commerce</h3>+ <div className="pair figure figure--wide">+ <div>+ <div className="pair__label">Live clone</div>+ <LiveExample card="agentic-commerce" title="Agentic commerce card, live clone" />+ </div>+ <div>+ <div className="pair__label">Recorded: stripe.com | clone</div>+ <CompareVideo reference="/media/hover-agentic-commerce-ref.mp4" clone="/media/hover-agentic-commerce-clone.mp4" width={420} height={696} label="Agentic commerce hover" />+ </div>+ </div>+ <p>+ A chat plays once when the card comes into view. The question rises in at 0.25 s, the answer’s seventeen words fade in 60 ms apart, and two products rise 20 px into place at 1.4 s. Behind it, ten thousand points pull into a ring with a clockwise sweep and relax again, and the ones near your pointer are pulled back onto it.+ </p>+ <Rows+ rows={[+ ["Chat timing", "every step within Stripe’s own spread between two recordings", "≤ 43 ms"],+ ["Chat layout", "52 of 52 elements in the same place, same styles", "≤ 0.05 px"],+ ["Particle ring", "tightens past half at 1.44 s (Stripe: 1.44–1.48 s), relaxed by 4.24 s", "pass"],+ ["Whole card", "pixel difference, entrance to pointer, vs stripe.com against itself", "0.9–1.2 %"],+ ]}+ />++ <h3>Card issuing</h3>+ <div className="pair figure figure--wide">+ <div>+ <div className="pair__label">Live clone</div>+ <LiveExample card="issuing" title="Card issuing card, live clone" />+ </div>+ <div>+ <div className="pair__label">Recorded: stripe.com | clone</div>+ <CompareVideo reference="/media/hover-issuing-ref.mp4" clone="/media/hover-issuing-clone.mp4" width={420} height={696} label="Card issuing hover" />+ </div>+ </div>+ <p>+ A three.js scene: a folded ribbon of colour drifts behind a Visa card that is drawn separately and combined in a final pass. On hover the card tilts towards the pointer, up to 27°, easing in with no overshoot, and lies flat again when you leave.+ </p>+ <Rows+ rows={[+ ["At rest", "pixels that differ (stripe.com vs itself: 0.10 %)", "0.03–0.05 %"],+ ["Tilt", "settled pose at three pointer positions", "≤ 0.4 px"],+ ["Hover in and out", "tilt curve and pixels, within the noise of two Stripe recordings", "pass"],+ ["Entrance", "fades in earlier than on Stripe’s heavier page", "−210 ms"],+ ]}+ />++ <h3>Stablecoins and crypto</h3>+ <div className="pair figure figure--wide">+ <div>+ <div className="pair__label">Live clone</div>+ <LiveExample card="crypto" title="Stablecoins and crypto card, live clone" />+ </div>+ <div>+ <div className="pair__label">Recorded: stripe.com | clone</div>+ <CompareVideo reference="/media/hover-crypto-ref.mp4" clone="/media/hover-crypto-clone.mp4" width={420} height={696} label="Crypto hover" />+ </div>+ </div>+ <p>+ A dotted globe built from a land map turns slowly, faster over the Pacific. Arcs fly between 69 cities with a label riding each one, a random amount in USDC, USDB or cash. On hover the dots brighten in a corona around the globe’s edge.+ <Sidenote n={3}>+ The arcs, amounts and dot sizes are random on every load, on stripe.com too, so they are compared by their timing, not their pixels.+ </Sidenote>+ </p>+ <Rows+ rows={[+ ["Globe pose", "start angle, tilt, centre and camera", "exact"],+ ["Rotation", "per rendered frame", "0.0016°"],+ ["Arcs and labels", "spawn, line growth, label intro and travel, within Stripe’s spread", "pass"],+ ["Hover glow", "the same value on every rendered frame", "identical"],+ ]}+ />+ </Section>++ <Section id="prompt" n={6} title="Writing a prompt">+ <p>Name the thing, where it is, and where it should go. The skill infers the rest from your request and your repo, and asks only when two readings would lead to different work.</p>+ <div className="prompts">+ {[+ ["From a live site", <>the hero entrance on <b>https://example.com</b>, into <b>components/Hero.tsx</b></>],+ ["From a video", <>this loader, <b>0:03 to 0:05</b> of ~/Downloads/loader.mov</>],+ ["Pixel-exact", <>the card hover in this gif, <b>match it exactly</b></>],+ ["With your own parts", <>the logo marquee from https://example.com, <b>with our logos and pause on hover</b></>],+ ].map(([label, text]) => (+ <div key={label as string}>+ <div className="prompt__label">{label}</div>+ <div className="prompt__text"><span className="slash">/motion-clone</span>{text}</div>+ </div>+ ))}+ </div>+ </Section>++ <Section id="install" n={7} title="Install">+ <CopyCommand command={INSTALL} />+ <p>+ The <a href="https://skills.sh">skills CLI</a> asks which agents to set up; add <code>-a claude-code</code> to skip the question. Then, in Claude Code, type <code>/motion-clone</code> followed by what you want cloned.+ </p>+ <p>+ The scripts run on <a href="https://bun.sh">Bun</a>. The first run downloads Playwright’s Chromium and a static ffmpeg into the skill’s folder, about 250 MB, and nothing after that. No API keys.+ <Sidenote n={4}>The skills CLI can install it for other agents that read SKILL.md, but it has only been tested with Claude Code.</Sidenote>+ </p>+ </Section>++ <Section id="limits" n={8} title="Limits">+ <ul className="list">+ <li>WebGL and canvas are compared as pixels. Random content, like particles, never matches exactly, so it is judged against two recordings of the reference instead.</li>+ <li>Headless browsers draw WebGL in software. Frame pacing in the recordings differs from a real screen, mostly on heavy pages.</li>+ <li>Pages behind a login, YouTube and Loom can’t be recorded directly. Hand it a screen recording.</li>+ <li>Physics springs are fitted from their overshoot and settle time, not read from the source.</li>+ <li>It clones what you point it at. Fonts, images and code from another site still belong to their owners; make sure you may use what you copy.</li>+ </ul>+ </Section>++ <Section id="questions" n={9} title="Questions">+ <div className="faq">+ <details>+ <summary>Does it copy the other site’s code?</summary>+ <p>It reads what the browser receives: CSS, keyframes and, for canvas graphics, the scripts that draw them. It writes its own implementation in your stack. The licences of whatever you copy still apply.</p>+ </details>+ <details>+ <summary>Which frameworks does it write?</summary>+ <p>Whatever your project already uses. It reads package.json and your existing components first, and won’t add GSAP to a project that animates with CSS.</p>+ </details>+ <details>+ <summary>Can it clone scroll-driven animations?</summary>+ <p>Yes. Scroll-linked motion is compared by scroll position instead of time, with the same stepped scroll on both pages.</p>+ </details>+ <details>+ <summary>What if it can’t get a row to pass?</summary>+ <p>After five rounds it stops and reports that row with its last numbers and the reason, such as a missing font or a physics spring it approximated. It never loosens a threshold quietly.</p>+ </details>+ </div>+ </Section>++ <footer className="footer">+ <span>+ <a href={REPO}>GitHub</a> · MIT licence · built with motion-clone+ </span>+ <span>The examples recreate three cards from stripe.com as a study of the technique. Not affiliated with or endorsed by Stripe. Stripe and Visa are trademarks of their respective owners.</span>+ </footer></main></div>);diff --git a/src/components/CompareVideo.tsx b/src/components/CompareVideo.tsxnew file mode 100644index 0000000..f544c8b--- /dev/null+++ b/src/components/CompareVideo.tsx@@ -0,0 +1,56 @@+"use client";++import { useEffect, useRef, useState } from "react";++// Two recordings made with the same capture command, stacked: the reference on the left of the+// line, the clone on the right. Drag (or use the arrow keys) to move the line. Both videos play+// only while on screen and are kept on the same frame.++export function CompareVideo({ reference, clone, width, height, label }: { reference: string; clone: string; width: number; height: number; label: string }) {+ const box = useRef<HTMLDivElement>(null);+ const top = useRef<HTMLVideoElement>(null);+ const bottom = useRef<HTMLVideoElement>(null);+ const [pos, setPos] = useState(50);++ useEffect(() => {+ const el = box.current;+ const a = top.current;+ const b = bottom.current;+ if (!el || !a || !b) return;+ const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;+ let syncId = 0;+ const play = () => {+ if (reduce) return;+ b.currentTime = a.currentTime;+ void a.play().catch(() => {});+ void b.play().catch(() => {});+ syncId = window.setInterval(() => {+ if (Math.abs(a.currentTime - b.currentTime) > 0.04) b.currentTime = a.currentTime;+ }, 400);+ };+ const pause = () => {+ a.pause();+ b.pause();+ clearInterval(syncId);+ };+ const io = new IntersectionObserver(([e]) => (e.isIntersecting ? play() : pause()), { threshold: 0.3 });+ io.observe(el);+ return () => {+ io.disconnect();+ pause();+ };+ }, []);++ return (+ <div ref={box} className="compare" style={{ aspectRatio: `${width} / ${height}` }}>+ <video ref={bottom} src={clone} muted playsInline loop preload="metadata" width={width} height={height} aria-hidden="true" />+ <div className="compare__top" style={{ clipPath: `inset(0 ${100 - pos}% 0 0)` }}>+ <video ref={top} src={reference} muted playsInline loop preload="metadata" width={width} height={height} aria-hidden="true" />+ </div>+ <div className="compare__line" style={{ left: `${pos}%` }} />+ <span className="compare__label compare__label--left">stripe.com</span>+ <span className="compare__label compare__label--right">clone</span>+ <input type="range" min={0} max={100} step={0.5} value={pos} onChange={(e) => setPos(Number(e.target.value))} aria-label={`${label}: drag to compare stripe.com (left) with the clone (right)`} />+ </div>+ );+}diff --git a/src/components/CopyCommand.tsx b/src/components/CopyCommand.tsxnew file mode 100644index 0000000..6605164--- /dev/null+++ b/src/components/CopyCommand.tsx@@ -0,0 +1,22 @@+"use client";++import { useState } from "react";++export function CopyCommand({ command }: { command: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <div className="cmd">+ <span>{command}</span>+ <button+ type="button"+ onClick={async () => {+ await navigator.clipboard.writeText(command);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ }}+ >+ {copied ? "Copied" : "Copy"}+ </button>+ </div>+ );+}diff --git a/src/components/LiveExample.tsx b/src/components/LiveExample.tsxnew file mode 100644index 0000000..3a047b8--- /dev/null+++ b/src/components/LiveExample.tsx@@ -0,0 +1,69 @@+"use client";++import { useEffect, useRef, useState } from "react";++// The clone, running live in an iframe. The cards switch to their desktop layout and hover+// behaviour from a 940px viewport, so the iframe is always laid out at least that wide and+// scaled (row) or cropped (single card) to fit. The iframe loads when it scrolls into view,+// so the entrance plays when the reader gets there.++const ROW = { width: 1300, height: 712 };+const CARD = { width: 960, height: 712, crop: 440 };++type Card = "agentic-commerce" | "issuing" | "crypto";++export function LiveExample({ card, title }: { card?: Card; title: string }) {+ const box = useRef<HTMLDivElement>(null);+ const [scale, setScale] = useState(0);+ const [visible, setVisible] = useState(false);+ const [run, setRun] = useState(0);++ const frameWidth = card ? CARD.crop : ROW.width;+ const src = `/examples/stripe-bento/${card ? `?card=${card}` : ""}`;++ useEffect(() => {+ const el = box.current;+ if (!el) return;+ const ro = new ResizeObserver(([e]) => setScale(Math.min(1, e.contentRect.width / frameWidth)));+ ro.observe(el);+ const io = new IntersectionObserver(+ ([e]) => {+ if (e.isIntersecting) {+ setVisible(true);+ io.disconnect();+ }+ },+ { threshold: 0.35 },+ );+ io.observe(el);+ return () => {+ ro.disconnect();+ io.disconnect();+ };+ }, [frameWidth]);++ const height = (card ? CARD.height : ROW.height) * scale;+ const offsetX = card ? ((CARD.width - CARD.crop) / 2) * scale : 0;++ return (+ <div className="figure-live">+ <div ref={box} className="live" style={{ height: height || undefined, aspectRatio: height ? undefined : `${frameWidth} / ${card ? CARD.height : ROW.height}`, maxWidth: card ? CARD.crop : undefined }}>+ {visible && scale > 0 && (+ <iframe+ key={run}+ src={src}+ title={title}+ width={card ? CARD.width : ROW.width}+ height={card ? CARD.height : ROW.height}+ style={{ transform: `translateX(${-offsetX}px) scale(${scale})` }}+ />+ )}+ <span className="live__badge"><b />live clone</span>+ </div>+ <div className="figure__caption" style={{ maxWidth: card ? CARD.crop : undefined }}>+ <button type="button" onClick={() => setRun((n) => n + 1)}>Replay entrance</button>+ <a href={src} target="_blank" rel="noreferrer">Open full size ↗</a>+ </div>+ </div>+ );+}diff --git a/src/components/Nav.tsx b/src/components/Nav.tsxnew file mode 100644index 0000000..28056e8--- /dev/null+++ b/src/components/Nav.tsx@@ -0,0 +1,41 @@+"use client";++import { useEffect, useState } from "react";++export type NavItem = { id: string; label: string };++// Sticky table of contents; highlights the section currently in view.+export function Nav({ items }: { items: NavItem[] }) {+ const [active, setActive] = useState(items[0]?.id);++ useEffect(() => {+ const sections = items.map((i) => document.getElementById(i.id)).filter((el): el is HTMLElement => !!el);+ const io = new IntersectionObserver(+ (entries) => {+ const hit = entries.filter((e) => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];+ if (hit) setActive(hit.target.id);+ },+ { rootMargin: "-20% 0px -70% 0px" },+ );+ sections.forEach((s) => io.observe(s));+ return () => io.disconnect();+ }, [items]);++ return (+ <nav className="nav" aria-label="On this page">+ <div className="nav__inner">+ <a href="#top" className="nav__brand">+ <span className="mark" aria-hidden="true"><i /><i /><i /></span>+ motion-clone+ </a>+ <ul>+ {items.map((i) => (+ <li key={i.id}>+ <a href={`#${i.id}`} aria-current={active === i.id ? "true" : undefined}>{i.label}</a>+ </li>+ ))}+ </ul>+ </div>+ </nav>+ );+}diff --git a/src/components/Sidenote.tsx b/src/components/Sidenote.tsxnew file mode 100644index 0000000..76f92ea--- /dev/null+++ b/src/components/Sidenote.tsx@@ -0,0 +1,13 @@+import type { ReactNode } from "react";++// Numbered margin note: sits in the right-hand column on wide screens, under the text on narrow ones.+export function Sidenote({ n, children }: { n: number; children: ReactNode }) {+ return (+ <>+ <sup className="sn-ref">{n}</sup>+ <span className="sidenote" data-n={n} role="note">+ {children}+ </span>+ </>+ );+}diff --git a/wrangler.jsonc b/wrangler.jsoncnew file mode 100644index 0000000..97c2a17--- /dev/null+++ b/wrangler.jsonc@@ -0,0 +1,10 @@+{+ // Static-assets-only Worker: serves the Next.js static export in ./out.+ "$schema": "node_modules/wrangler/config-schema.json",+ "name": "motion-clone",+ "compatibility_date": "2026-10-29",+ "assets": {+ "directory": "./out",+ "not_found_handling": "404-page"+ }+}