176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
fix: GPGPU Particle System (06.13) and Cloth Simulation (06.15) mark their phone default data-hb-phone and start from it, so a home page card's Copy prompt copies the phone value on phones too
matin735bd1a3ae5a
diff --git a/animations/06-3d-advanced/cloth-simulation/index.html b/animations/06-3d-advanced/cloth-simulation/index.htmlindex 4faae117..c7a6a418 100644--- a/animations/06-3d-advanced/cloth-simulation/index.html+++ b/animations/06-3d-advanced/cloth-simulation/index.html@@ -105,7 +105,7 @@<div class="hb-setting"><p class="hb-setting-name" id="detail-lbl">Detail</p><div class="seg" id="detail-seg" role="group" aria-labelledby="detail-lbl">- <button type="button" data-cols="16" aria-pressed="false">Low</button>+ <button type="button" data-cols="16" data-hb-phone aria-pressed="false">Low</button><button type="button" data-cols="24" class="on" aria-pressed="true">Medium</button><button type="button" data-cols="40" aria-pressed="false">High</button></div>@@ -166,9 +166,10 @@ let pts=[],prev=[],pinned=[],constraints=[];let dragIdx=-1,dragMouse={x:0,y:0};// Phones are screens up to 600px wide, or up to 500px tall when held sideways. They start at Low detail (16 × 12 points),-// a coarser grid that means far fewer constraint solves per frame; the visitor can still pick more.+// a coarser grid that means far fewer constraint solves per frame; the visitor can still pick more. Low is the Detail choice+// marked data-hb-phone, which the home page's Copy prompt reads on phones too.const PHONE=matchMedia('(max-width:600px),(max-height:500px)');-if(PHONE.matches){COLS=16;ROWS=12;}+if(PHONE.matches){COLS=+document.querySelector('#detail-seg [data-hb-phone]').dataset.cols;ROWS=Math.round(COLS*.75);}// The pressed Detail choice follows the start (this runs before the shared script reads the settings for "Your settings")document.querySelectorAll('#detail-seg button').forEach(b=>{const on=+b.dataset.cols===COLS;diff --git a/animations/06-3d-advanced/gpgpu-particle-system/index.html b/animations/06-3d-advanced/gpgpu-particle-system/index.htmlindex 2037e239..98c40869 100644--- a/animations/06-3d-advanced/gpgpu-particle-system/index.html+++ b/animations/06-3d-advanced/gpgpu-particle-system/index.html@@ -76,7 +76,7 @@<div class="hb-setting"><p class="hb-setting-name" id="count-lbl">Number of particles</p><div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">- <button type="button" data-n="128" aria-pressed="false">16,000</button>+ <button type="button" data-n="128" data-hb-phone aria-pressed="false">16,000</button><button type="button" data-n="256" class="on" aria-pressed="true">65,000</button><button type="button" data-n="320" aria-pressed="false">100,000</button></div>@@ -223,11 +223,12 @@ void main(){fragColor=vec4(.024,.039,.063,.12);}`;const stage=document.getElementById('stage'),cvs=document.getElementById('cvs'),noWgl2=document.getElementById('no-wgl2');const slowTog=document.getElementById('slow-tog');const NO_WGL2_MSG='This demo needs WebGL 2, which this browser does not offer. Try a recent Chrome, Firefox or Safari.';-// Phones are screens up to 600px wide, or up to 500px tall when held sideways. They start with the 16k texture:-// 65k points is too much fill for a phone, and the visitor can still pick more.-const PHONE=matchMedia('(max-width:600px),(max-height:500px)');+// Phones are screens up to 600px wide, or up to 500px tall when held sideways. They start with the 16k texture: 65k points+// is too much fill for a phone, and the visitor can still pick more. 16k is the count marked data-hb-phone, which the home+// page's Copy prompt reads on phones too.+const PHONE=matchMedia('(max-width:600px),(max-height:500px)'),PHONE_N=+document.querySelector('#count-seg [data-hb-phone]').dataset.n;let W=0,H=0,DPR=1,gl,physicsProg,renderProg,fadeProg,qBuf,fbo0,fbo1,tex0,tex1,raf=null;-let paused=false,last=null,simT=0,TEX_N=PHONE.matches?128:256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;+let paused=false,last=null,simT=0,TEX_N=PHONE.matches?PHONE_N:256,BEHAVIOR=0,SPD=0.6,COLOR_MODE=0,TRAILS=false;let idxBuf=null,particleCount=0,PT=1.5,shaderErr='';// The pressed count follows the start (this runs before the shared script reads the settings for "Your settings")diff --git a/assets/js/demo-page.js b/assets/js/demo-page.jsindex b4734a20..06b7885a 100644--- a/assets/js/demo-page.js+++ b/assets/js/demo-page.js@@ -157,7 +157,9 @@return setting ? text(setting.querySelector('.hb-setting-name')) : '';}- function valueFor(control) {+ // The value a control gives. A choice group gives its pressed choice or, with phone (see phoneDefaults), the choice it marks+ // data-hb-phone where it marks one.+ function valueFor(control, phone) {if (control.matches('input[type=range]')) {var setting = control.closest('.hb-setting');var shown = setting && setting.querySelector('.hb-value');@@ -166,10 +168,24 @@if (control.matches('input[type=text], textarea')) return quoteText(control.value, 40);if (control.matches('input[type=checkbox]')) return control.checked ? 'on' : 'off';if (control.matches('select')) return control.selectedOptions[0] ? text(control.selectedOptions[0]) : control.value;- var active = control.querySelector('.on, [aria-pressed="true"]');+ var active = (phone && control.querySelector('[data-hb-phone]')) || control.querySelector('.on, [aria-pressed="true"]');return active ? (active.getAttribute('aria-label') || text(active)) : '';}+ // Phones, as the pages that start a setting lower there see them: up to 600px wide, or up to 500px tall (held sideways).+ var PHONE = '(max-width:600px),(max-height:500px)';++ // Whether the phone defaults count. A page that starts a setting lower on phones marks that choice data-hb-phone, and its own+ // script presses it there. A page the home page has fetched and parsed (any document but the window's own) ran no script, so+ // on a phone its marked choices count in place of the pressed ones: the home page then copies what the page itself copies on+ // the same screen. The home page's stand-in window only answers getComputedStyle; the window this script runs in then answers+ // the media query.+ function phoneDefaults(doc, win) {+ if (doc === win.document) return false;+ var query = typeof win.matchMedia === 'function' ? win.matchMedia(PHONE) : typeof matchMedia === 'function' ? matchMedia(PHONE) : null;+ return !!(query && query.matches);+ }+// A control counts unless it, or anything between it and the scope, is hidden, skipped or// display:none. Controls inside a closed More options still count: <details> hides them another way.function isShown(control, scope, win) {@@ -182,15 +198,16 @@// The demo's current settings in page order, as [{ label, value }].function readSettings(doc, scope, win) {+ var phone = phoneDefaults(doc, win);return Array.prototype.filter.call(scope.querySelectorAll(CONTROLS), function (control) {return isShown(control, scope, win);}).map(function (control) {- return { label: labelFor(doc, control), value: valueFor(control), control: control };+ return { label: labelFor(doc, control), value: valueFor(control, phone), control: control };});}// What Copy prompt copies on a page, with its settings as they are now. The home page runs it on a page it has- // fetched and parsed, where every setting is at its default.+ // fetched and parsed, where every setting is at its default: on a phone, the phone default where the page marks one.function pageCopyText(doc, win) {var page = doc.querySelector('.hb-page');var promptEl = page && page.querySelector('.hb-prompt');diff --git a/tests/demo-page.test.js b/tests/demo-page.test.jsindex bd488f96..5495d20f 100644--- a/tests/demo-page.test.js+++ b/tests/demo-page.test.js@@ -157,6 +157,7 @@ function standInPage(kind, reduced, bodyAttributes, copy, links) {const doc = { body, querySelector: selector => (selector === '.hb-page' ? page : null), createElement: node, dispatchEvent: event => sent.push(event),querySelectorAll: selector => (selector === 'a[href]' ? anchors : []) };const win = {+ document: doc, // the page's own document, as in a browsermatchMedia: () => ({ matches: !!reduced, addEventListener() {} }),setTimeout: (fn, ms) => timers.push({ fn, ms }),clearTimeout() {}, location: { protocol: (links && links.protocol) || 'http:' }, console,@@ -294,6 +295,75 @@ test('pageCopyText reads the prompt and the Try it settings of a page', () => {assert.equal(DP.pageCopyText({ querySelector: () => null }, win), '');});+// A choice group labelled `label`, of choices [{ text, pressed, phone }], as the shared script reads one: it asks for the choice+// marked data-hb-phone and for the pressed one.+function choiceGroup(label, choices) {+ const button = choice => ({ textContent: choice.text, getAttribute: () => null });+ return { hidden: false, parentElement: null, hasAttribute: () => false, matches: () => false,+ getAttribute: name => (name === 'data-hb-label' ? label : null),+ querySelector: selector => {+ const found = choices.find(choice => (selector === '[data-hb-phone]' ? choice.phone : choice.pressed));+ return found ? button(found) : null;+ } };+}+// A page as the home page has it once fetched and parsed: its prompt, and a Try it step holding `controls`.+function parsedPage(prompt, controls) {+ const page = { querySelector: s => ({ '.hb-prompt': { textContent: prompt }, '.hb-try': { querySelectorAll: () => controls } })[s] || null };+ return { querySelector: s => (s === '.hb-page' ? page : null), getElementById: () => null };+}+// A window of width × height whose own document is another one, answering the media queries the script asks (a list of+// max-width and max-height features, as on the pages that start a setting lower on phones).+function windowOf(width, height) {+ return { document: {}, getComputedStyle: () => ({ display: '' }),+ matchMedia: query => ({ matches: query.split(',').some(part => {+ const m = /^\s*\(\s*max-(width|height)\s*:\s*(\d+)px\s*\)\s*$/.exec(part);+ if (!m) throw new Error(`unexpected media query: ${query}`);+ return (m[1] === 'width' ? width : height) <= Number(m[2]);+ }) }) };+}++// GPGPU Particle System and Cloth Simulation start a setting lower on phones: their own script presses the choice marked+// data-hb-phone there. The home page reads a page it fetched, where no script ran, so it must count that mark on a phone.+test('a fetched page read on a phone gives the choices marked data-hb-phone and on larger screens the pressed ones; a page in its own window gives what is pressed', () => {+ const prompt = 'Add a cloth to [the banner].';+ // Detail: Medium is pressed in the markup and Low is the phone default; Wind has no phone default.+ const wind = choiceGroup('Wind', [{ text: 'Light' }, { text: 'Medium', pressed: true }]);+ const fetched = parsedPage(prompt, [choiceGroup('Detail', [{ text: 'Low', phone: true }, { text: 'Medium', pressed: true }, { text: 'High' }]), wind]);+ const phone = prompt + '\n\nSettings from the demo: Detail: Low, Wind: Medium.';+ const larger = prompt + '\n\nSettings from the demo: Detail: Medium, Wind: Medium.';+ for (const [width, height, expected, screen] of [[375, 812, phone, 'a phone'], [320, 640, phone, 'a small phone'],+ [812, 375, phone, 'a phone held sideways'], [1280, 800, larger, 'a desktop'], [1366, 657, larger, 'a laptop'], [768, 1024, larger, 'a tablet']]) {+ assert.equal(DP.pageCopyText(fetched, windowOf(width, height)), expected, screen);+ }+ // The page in its own window ran its script, which pressed what counts there, so the pressed choice is read on any screen.+ const own = parsedPage(prompt, [choiceGroup('Detail', [{ text: 'Low', phone: true }, { text: 'Medium' }, { text: 'High', pressed: true }]), wind]);+ for (const [width, height] of [[375, 812], [1280, 800]]) {+ const win = Object.assign(windowOf(width, height), { document: own });+ assert.equal(DP.pageCopyText(own, win), prompt + '\n\nSettings from the demo: Detail: High, Wind: Medium.', `its own window, ${width}px wide`);+ }+});++// The home page passes a stand-in window that only answers getComputedStyle (NO_STYLE in index.html): the window the script+// runs in answers the media query then.+test("on the home page's stand-in window, the window the script runs in says whether the screen is a phone", () => {+ const prompt = 'Add particles to [the hero].';+ const fetched = parsedPage(prompt, [choiceGroup('Number of particles', [{ text: '16,000', phone: true }, { text: '65,000', pressed: true }])]);+ const NO_STYLE = { getComputedStyle: () => ({ display: '' }) };+ const copied = value => `${prompt}\n\nSettings from the demo: Number of particles: ${value}.`;+ const before = Object.getOwnPropertyDescriptor(globalThis, 'matchMedia');+ try {+ globalThis.matchMedia = windowOf(375, 812).matchMedia;+ assert.equal(DP.pageCopyText(fetched, NO_STYLE), copied('16,000'), 'a phone');+ globalThis.matchMedia = windowOf(1280, 800).matchMedia;+ assert.equal(DP.pageCopyText(fetched, NO_STYLE), copied('65,000'), 'a desktop');+ delete globalThis.matchMedia;+ assert.equal(DP.pageCopyText(fetched, NO_STYLE), copied('65,000'), 'where nothing answers media queries');+ } finally {+ if (before) Object.defineProperty(globalThis, 'matchMedia', before);+ else delete globalThis.matchMedia;+ }+});+// The home page copies a card's prompt with pageCopyText, so the button on the page itself has to copy exactly what that gives.// The clipboard here keeps every text it is asked to write and answers with a promise that is already settled.test("pressing a page's Copy prompt copies what pageCopyText gives", async () => {diff --git a/tests/pages.test.js b/tests/pages.test.jsindex 5564790d..129c8da8 100644--- a/tests/pages.test.js+++ b/tests/pages.test.js@@ -377,6 +377,35 @@ test('every guided-steps page and the home page link the same version of the shaassert.match(HOME, /<script src="assets\/js\/demo-page\.js\?v=\d+" defer><\/script>/, 'the home page links the page script, for Copy prompt');});+// A page that starts a setting lower on phones marks that choice data-hb-phone, and its own script takes the phone default from+// the mark and presses it there. The home page reads the page without running it, and on a phone the shared script counts the+// marked choice instead of the pressed one, so a card's Copy prompt copies what the page copies on the same screen.+test('a setting that starts lower on phones marks that choice data-hb-phone, and the page script starts there from the mark', () => {+ const PHONE_DEFAULTS = { 'gpgpu-particle-system': ['count-seg', '16,000'], 'cloth-simulation': ['detail-seg', 'Low'] };+ for (const slug of Object.keys(PHONE_DEFAULTS)) assert.ok(steps.some(d => d.slug === slug), `${slug} is a guided-steps page`);+ for (const d of steps) {+ const html = pageOf(d), where = `${d.cat}/${d.slug}`;+ const scripts = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)].map(m => m[1]).join('\n');+ const markup = html.replace(/<script\b[\s\S]*?<\/script>/g, '');+ // Every mark is on a choice button of a choice group in Try it, one at most in each group, and never on the pressed choice:+ // the markup presses the default of larger screens.+ const marked = {};+ for (const [, attrs, inner] of tryItOf(markup).matchAll(/<div\b(?=[^>]*\sclass="(?:[^"]*\s)?(?:seg|swatches)(?:\s[^"]*)?")([^>]*)>([\s\S]*?)<\/div>/g)) {+ const id = (attrs.match(/\sid="([^"]+)"/) || [])[1];+ const phone = [...inner.matchAll(/<button\b([^>]*)>([^<]*)<\/button>/g)].filter(([, a]) => /\sdata-hb-phone(?=[\s=]|$)/.test(a));+ assert.ok(phone.length <= 1, `${where}: ${id} marks one phone default at most`);+ for (const [, a, label] of phone) {+ assert.ok(!/aria-pressed="true"/.test(a), `${where}: the phone default of ${id} is not the choice pressed in the markup`);+ marked[id] = decode(label.trim());+ }+ }+ assert.equal(Object.keys(marked).length, count(markup, 'data-hb-phone'), `${where}: every data-hb-phone is on a choice button in Try it`);+ for (const id of Object.keys(marked)) assert.ok(scripts.includes(`#${id} [data-hb-phone]`), `${where}: the page script reads the phone default of ${id} from its mark`);+ const known = PHONE_DEFAULTS[d.slug];+ if (known) assert.deepEqual(marked, { [known[0]]: known[1] }, `${where}: phones start with ${known[1]}`);+ }+});+const sharedRules = cssRules(read(path.join(ROOT, 'assets/css/demo-page.css')));const rulesFor = selector => sharedRules.filter(rule => rule.selector.split(',').some(part => part.trim() === selector));