Skip to content

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.

fix: turn scroll snapping off by a mark during Play and tighten the scroll checks

matind49cb4a75957
diff --git a/assets/css/demo-page.css b/assets/css/demo-page.css
index c31af48d..60c8ea8c 100644
--- a/assets/css/demo-page.css
+++ b/assets/css/demo-page.css
@@ -88,6 +88,11 @@ body.hb [hidden]{display:none!important}
/* data-hb-pause="css": the shared script puts hb-paused on the stage, which holds every CSS animation on it */
.hb-page .stage.hb-paused,.hb-page .stage.hb-paused::before,.hb-page .stage.hb-paused::after,
.hb-page .stage.hb-paused *,.hb-page .stage.hb-paused *::before,.hb-page .stage.hb-paused *::after{animation-play-state:paused!important}
+/* Scroll pages: while Play scrolls a box, the shared script marks it, and CSS scroll snapping is off for it, or every step would
+ snap and the box would jump from one snap point to the next. !important, so that a snap type the page sets on the box itself,
+ inline or in its own style, cannot win, and nothing has to be remembered and written back. When the mark goes the page's own
+ snap type applies again and the browser settles the box on the nearest snap point. */
+[data-hb-autoscrolling]{scroll-snap-type:none!important}
/* Switches: a checkbox drawn as a track and knob (gradients, so no pseudo-elements on the input) */
.hb-switch{appearance:none;-webkit-appearance:none;flex:none;width:32px;height:20px;margin:0;border-radius:999px;cursor:pointer;
diff --git a/assets/js/demo-page.js b/assets/js/demo-page.js
index 207f97e1..50dff802 100644
--- a/assets/js/demo-page.js
+++ b/assets/js/demo-page.js
@@ -361,23 +361,19 @@
}
// Scroll pages: Play scrolls the box from where it is to its end at a steady speed (the whole box in about six
- // seconds), from the top when it is already at the end. The visitor's own wheel, touch, press or key input anywhere
- // in the stage stops it, and so does Back to top, which jumps the box to the top.
+ // seconds), from the top when it is already at the end. The visitor's own wheel, touch, press, key or click input
+ // anywhere in the stage stops it, and so does Back to top, which jumps the box to the top.
var FULL_SCROLL_MS = 6000;
var scrollFrame = 0;
- var snapKept = null;
- // While the scroll runs, CSS scroll snapping is off on the scroller (its own inline value is kept), or every step
- // would snap and the box would jump from one snap point to the next. It goes back on when the scroll ends, is
- // stopped or Back to top is pressed, and the browser then settles on the nearest snap point by itself.
- function snapOff() {
- if (snapKept !== null || win.getComputedStyle(scroller).scrollSnapType === 'none') return;
- snapKept = scroller.style.scrollSnapType;
- scroller.style.scrollSnapType = 'none';
- }
- function snapOn() {
- if (snapKept === null) return;
- scroller.style.scrollSnapType = snapKept;
- snapKept = null;
+ // While the scroll runs the box carries data-hb-autoscrolling, and the shared stylesheet turns CSS scroll snapping off
+ // for it (or every step would snap and the box would jump from one snap point to the next). The mark goes when the
+ // scroll ends, is stopped or Back to top is pressed, and the page's own snap type applies again: the browser settles
+ // the box on the nearest snap point by itself. Nothing is remembered or written back, so a snap type the page sets
+ // during a run is simply what applies afterwards.
+ function mark(on) {
+ if (scroller.hasAttribute('data-hb-autoscrolling') === on) return;
+ if (on) scroller.setAttribute('data-hb-autoscrolling', '');
+ else scroller.removeAttribute('data-hb-autoscrolling');
}
function cancelFrame() {
if (scrollFrame) win.cancelAnimationFrame(scrollFrame);
@@ -385,14 +381,14 @@
}
function stopScroll() {
cancelFrame();
- snapOn();
+ mark(false);
}
function scrollBox(top) { scroller.scrollTo({ top: top, behavior: 'instant' }); }
function autoscroll() {
- cancelFrame(); // not stopScroll(): pressing Play during a run keeps snapping off, so the box does not snap in between
+ cancelFrame(); // not stopScroll(): the mark stays through a second press of Play, so nothing snaps in between
var end = scroller.scrollHeight - scroller.clientHeight;
- if (end <= 0) { snapOn(); return; }
- snapOff();
+ if (end <= 0) { mark(false); return; }
+ mark(true);
if (scroller.scrollTop >= end - 2) scrollBox(0);
var pos = scroller.scrollTop, last = 0, speed = end / FULL_SCROLL_MS;
function step(now) {
@@ -400,17 +396,21 @@
last = now;
scrollBox(pos);
scrollFrame = pos < end ? win.requestAnimationFrame(step) : 0;
- if (!scrollFrame) snapOn();
+ if (!scrollFrame) mark(false);
}
scrollFrame = win.requestAnimationFrame(step);
}
function setUpScroll() {
scrollCtl.addEventListener('click', autoscroll);
if (topCtl) topCtl.addEventListener('click', function () { stopScroll(); scrollBox(0); });
- // On the stage, not the scroller: a menu or button beside an inner scroller is the visitor's input too.
- var heard = stage || scroller;
- ['wheel', 'touchstart', 'pointerdown', 'keydown'].forEach(function (type) {
- heard.addEventListener(type, function (e) { if (e.isTrusted) stopScroll(); }, { passive: true });
+ // The visitor's own input anywhere in the stage stops a run (a menu or button beside an inner scroller counts), and on
+ // the scroller itself when it is not inside the stage. Capture phase, so a widget that stops the propagation of its
+ // events cannot hide them; click is there for activations that come with no pointer or key event.
+ var heard = stage && stage.contains(scroller) ? [stage] : [stage, scroller].filter(Boolean);
+ heard.forEach(function (el) {
+ ['wheel', 'touchstart', 'pointerdown', 'keydown', 'click'].forEach(function (type) {
+ el.addEventListener(type, function (e) { if (e.isTrusted) stopScroll(); }, { capture: true, passive: true });
+ });
});
}
diff --git a/tests/pages.test.js b/tests/pages.test.js
index 21ee1f91..b60d6d51 100644
--- a/tests/pages.test.js
+++ b/tests/pages.test.js
@@ -73,6 +73,29 @@ function assertShowMeAndReset(kind, html, player) {
if (kind === 'do') assert.ok(bar.includes(SHOW_ME + RESET), 'on a do-it page the Reset button comes right after Show me');
}
+// Play, Back to top and the scroller belong to scroll pages, and only to them: the shared script presses Play before anything
+// else on arrival, so a stray one on another kind of page would quietly replace that page's own arrival. `html` is the whole
+// page, `player` its player bar and `autoplay` whether the body asks for the run on arrival.
+function assertScrollControls(kind, html, player, autoplay) {
+ if (kind !== 'scroll') {
+ for (const marker of ['data-hb-autoscroll', 'data-hb-top', 'data-hb-scroller']) {
+ assert.equal(count(html, marker), 0, `only a scroll page has ${marker}`);
+ }
+ return;
+ }
+ // A scroll page shows itself once on arrival: the shared script presses Play when the body asks for autoplay.
+ assert.ok(autoplay, 'a scroll page scrolls once on arrival (data-hb-autoplay on the body)');
+ assert.equal(count(html, 'data-hb-autoscroll'), 1, 'one Play control');
+ assert.equal(count(html, 'data-hb-top'), 1, 'one Back to top control');
+ assert.ok(player.includes('id="btn-scroll" data-hb-autoscroll') && player.includes('id="btn-top" data-hb-top'),
+ 'Play and Back to top are in the player bar');
+ assert.ok(count(html, 'data-hb-scroller') <= 1, 'at most one scroller');
+ // A scroll page has none of the other player controls; Slow motion is one of them (Play's speed is fixed).
+ for (const other of ['data-hb-replay', 'data-hb-loop', 'data-hb-pause', 'data-hb-demo', 'data-hb-slowmo']) {
+ assert.equal(count(html, other), 0, `a scroll page has no ${other}`);
+ }
+}
+
for (const cat of CONVERTED) {
test(`every ${cat} demo uses the guided-steps page`, () => {
const inCategory = demos.filter(d => d.cat === cat);
@@ -141,16 +164,7 @@ for (const d of steps) {
assert.equal(count(html, other), 0, `a do-it page has no ${other}`);
}
}
- if (kind === 'scroll') {
- assert.equal(count(html, 'data-hb-autoscroll'), 1, 'one Play control');
- assert.equal(count(html, 'data-hb-top'), 1, 'one Back to top control');
- assert.ok(player.includes('id="btn-scroll" data-hb-autoscroll') && player.includes('id="btn-top" data-hb-top'),
- 'Play and Back to top are in the player bar');
- assert.ok(count(html, 'data-hb-scroller') <= 1, 'at most one scroller');
- for (const other of ['data-hb-replay', 'data-hb-loop', 'data-hb-pause', 'data-hb-demo']) {
- assert.equal(count(html, other), 0, `a scroll page has no ${other}`);
- }
- }
+ assertScrollControls(kind, html, player, !!body[2]);
assertShowMeAndReset(kind, html, player);
for (const marker of ['data-hb-loop', 'data-hb-slowmo', 'data-hb-pause', 'data-hb-demo', 'data-hb-reset', 'data-hb-autoscroll', 'data-hb-top']) {
assert.ok(count(html, marker) <= 1, `at most one ${marker}`);
@@ -294,6 +308,45 @@ test('Show me belongs to do-it pages and Reset to do-it and loop pages, each exa
}
});
+// The Play, Back to top and scroller rules run on every page above. These cases run them on made-up pages, so the scroll
+// kind is covered before a scroll page exists.
+test('Play, Back to top and the scroller belong to scroll pages, and a scroll page runs once on arrival with no other player control', () => {
+ const PLAY_BUTTON = '<button class="hb-play" type="button" id="btn-scroll" data-hb-autoscroll>Play</button>';
+ const TOP_BUTTON = '<button class="hb-play" type="button" id="btn-top" data-hb-top>Back to top</button>';
+ const REPLAY = '<button class="hb-play" type="button" id="btn-play" data-hb-replay>Replay</button>';
+ const LOOP = '<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="loop-tog" data-hb-loop autocomplete="off"><span>Loop</span></label>';
+ const SLOW = '<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>';
+ const pageOf = (bar, stage = '') => `<div class="stage">${stage}</div>\n <div class="hb-player">\n ${bar.join('\n ')}\n </div>`;
+ const run = (kind, html, autoplay = true) => assertScrollControls(kind, html, between(html, '<div class="hb-player">', '</div>'), autoplay);
+ const ok = (kind, html) => assert.doesNotThrow(() => run(kind, html), `a ${kind} page passes`);
+ const notOk = (message, kind, html, autoplay) => assert.throws(() => run(kind, html, autoplay), err => err.message.startsWith(message), `${kind}: ${message}`);
+
+ const scrollPage = pageOf([PLAY_BUTTON, TOP_BUTTON]);
+ ok('scroll', scrollPage);
+ ok('scroll', pageOf([PLAY_BUTTON, TOP_BUTTON], '<div data-hb-scroller></div>')); // the stage holds its own scroller
+
+ notOk('a scroll page scrolls once on arrival (data-hb-autoplay on the body)', 'scroll', scrollPage, false);
+ notOk('one Play control', 'scroll', pageOf([TOP_BUTTON]));
+ notOk('one Play control', 'scroll', pageOf([PLAY_BUTTON, PLAY_BUTTON.replace('btn-scroll', 'btn-scroll-2'), TOP_BUTTON]));
+ notOk('one Back to top control', 'scroll', pageOf([PLAY_BUTTON]));
+ notOk('Play and Back to top are in the player bar', 'scroll', `<div class="stage">${PLAY_BUTTON}</div>\n<div class="hb-player">\n${TOP_BUTTON}\n</div>`);
+ notOk('at most one scroller', 'scroll', pageOf([PLAY_BUTTON, TOP_BUTTON], '<div data-hb-scroller></div><div data-hb-scroller></div>'));
+ // A scroll page has none of the other player controls; Slow motion is one of them (Play's speed is fixed).
+ for (const [marker, control] of [['data-hb-replay', REPLAY], ['data-hb-loop', LOOP], ['data-hb-pause', PAUSE.replace('{MODE}', '')],
+ ['data-hb-demo', SHOW_ME], ['data-hb-slowmo', SLOW]]) {
+ notOk(`a scroll page has no ${marker}`, 'scroll', pageOf([PLAY_BUTTON, TOP_BUTTON, control]));
+ }
+
+ // Only scroll pages have these markers: the shared script presses Play before anything else on arrival, so a stray one on
+ // another kind of page would quietly replace that page's own arrival.
+ for (const kind of ['once', 'loop', 'do']) {
+ ok(kind, pageOf([REPLAY]));
+ notOk('only a scroll page has data-hb-autoscroll', kind, pageOf([REPLAY, PLAY_BUTTON]));
+ notOk('only a scroll page has data-hb-top', kind, pageOf([REPLAY, TOP_BUTTON]));
+ notOk('only a scroll page has data-hb-scroller', kind, pageOf([REPLAY], '<div data-hb-scroller></div>'));
+ }
+});
+
test('every guided-steps page links the same version of the shared files', () => {
const versions = new Set(steps.flatMap(d => [...pageOf(d).matchAll(/demo-page\.(?:css|js)\?v=(\d+)/g)].map(m => m[1])));
assert.equal(versions.size, 1, `versions in use: ${[...versions].join(', ')}`);
@@ -312,6 +365,14 @@ test('the shared stylesheet draws the focus ring inward inside the stage, beatin
`${inward} (${specificity(inward)}) must outrank ${site[0].selector} (${specificity(site[0].selector)})`);
});
+test('the shared stylesheet turns CSS scroll snapping off on a box that Play is scrolling', () => {
+ // While Play scrolls a box the shared script marks it data-hb-autoscrolling; with snapping on, every step would snap to the
+ // nearest snap point and the box would jump from card to card. !important, so that a snap type the page sets on the box
+ // itself (inline, or in its own style) does not win, and nothing has to be remembered and written back afterwards.
+ assert.ok(rulesFor('[data-hb-autoscrolling]').some(rule => /(^|;)\s*scroll-snap-type:\s*none\s*!important\s*(;|$)/.test(rule.body)),
+ 'a box marked data-hb-autoscrolling has scroll-snap-type: none !important');
+});
+
test('the shared stylesheet keeps choice buttons at least 44px wide', () => {
assert.ok(rulesFor('.hb-page .seg button').some(rule => /(^|;)\s*min-width:\s*44px\s*(;|$)/.test(rule.body)), 'a choice button is at least 44px wide');
});
diff --git a/tools/check-pages.mjs b/tools/check-pages.mjs
index f370d8ee..e8d931c8 100644
--- a/tools/check-pages.mjs
+++ b/tools/check-pages.mjs
@@ -5,7 +5,7 @@
// e.g. node tools/check-pages.mjs animations/02-entrance-and-exit
// A folder with no index.html of its own stands for the page folders inside it. Each page is loaded at six screen
// setups and prints one line for each (ok or FAIL); problems are printed and screenshots saved, by default into
-// hb-check in the temp folder (emptied at the start of each run). Console warnings count as problems too (the page
+// a folder of its own in the temp folder, whose path is printed. Console warnings count as problems too (the page
// script warns about settings that have no label or value). On plays-once pages the desktop run also checks that
// Replay and a setting change visibly move the stage; on loop pages it checks that the stage moves, that Pause stops
// it and Play starts it again (twice over), and the reduced-motion run checks that the loop starts paused. On do-it
@@ -13,9 +13,14 @@
// it exactly once on arrival and waits for that run to end, the reduced-motion run checks that it pressed it not at
// all; both then check that the stage is at rest, that pressing Show me visibly moves it and that the run brings it
// back to rest. On scroll pages the desktop and reduced-motion runs check that the box scrolls by itself on arrival (not
-// under reduced motion), that Back to top returns it to the top and stops it, that Play scrolls it and that a real
-// wheel turn over the box stops Play. The 320px phone runs the page checks (overflow, small targets, chips, README)
+// under reduced motion), that Play scrolls it, that Back to top, pressed while Play runs, returns it to the top and
+// stops it, that on a scroller with CSS scroll snapping the snapping is off while Play runs and back once the run is
+// stopped, and that a real wheel turn stops Play (over the stage beside an inner scroller, where there is room there,
+// so the stage-wide stop is tried too). The 320px phone runs the page checks (overflow, small targets, chips, README)
// and takes screenshots, and nothing more.
+// Without --out every run writes into a new hb-check-<date>-<time>-<process id> folder (--out picks another one).
+// Nothing is emptied or removed, so runs going on at the same time, in other lanes or terminals, never wipe each
+// other's screenshots.
// Exit code 1 on any problem.
import { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
@@ -36,7 +41,10 @@ function option(name, fallback) {
}
const BASE = option('--base', 'http://127.0.0.1:8731').replace(/\/$/, '');
const givenOut = option('--out', '');
-const OUT = givenOut || join(tmpdir(), 'hb-check');
+// A run without --out gets a folder of its own (start time and process id), so runs going on at the same time never
+// share one.
+const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
+const OUT = givenOut || join(tmpdir(), `hb-check-${stamp}-${process.pid}`);
const isPage = folder => existsSync(join(ROOT, folder, 'index.html'));
// A category folder (no index.html, but page folders inside) is expanded to its pages, so the call works
// in shells that do not expand wildcards, such as PowerShell.
@@ -51,11 +59,8 @@ if (!pages.length) {
console.error('Usage: node tools/check-pages.mjs [--base URL] [--out DIR] <page or category folder>...');
process.exit(2);
}
-if (!givenOut) {
- try { rmSync(OUT, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); }
- catch { console.error(`Could not empty ${OUT}; screenshots from an earlier run may remain.`); }
-}
mkdirSync(OUT, { recursive: true });
+console.log(`Screenshots go to ${OUT}`);
const SETUPS = [
{ name: 'desktop', width: 1280, height: 800, full: true, moves: true },
@@ -304,27 +309,52 @@ async function demoProblems(reduced) {
return problems;
}
-// Scroll pages: the box scrolls by itself on arrival (not under reduced motion); Back to top returns it to the top and
-// stops it; Play scrolls it; a real wheel turn over the box stops Play.
+// Scroll pages: the box scrolls by itself on arrival (not under reduced motion); Play scrolls it; Back to top, pressed
+// while Play runs, returns it to the top and stops it (at 0 half a second later and still at 0 a little over a second
+// later, so both the jump and the stop are seen whatever the arrival did); on a scroller with CSS scroll snapping the
+// snapping is off 300 ms into Play and back once the run has been stopped; a real wheel turn stops Play. The wheel goes
+// to the stage beside an inner scroller where there is room there (the stage-wide stop), else to the box, and the box is
+// read once it has settled: a snapping box glides to its snap point after the turn.
async function scrollProblems(reduced) {
const box = `(document.querySelector('[data-hb-scroller]') || document.querySelector('.hb-page .stage'))`;
const pos = () => evaluate(`${box}.scrollTop`);
+ const snap = () => evaluate(`getComputedStyle(${box}).scrollSnapType`);
+ const press = selector => evaluate(`document.querySelector('${selector}').click()`);
const problems = [];
+ const startSnap = await snap(); // under reduced motion nothing has run yet: this is the page's own snap type
const arrived = await pos();
if (reduced && arrived > 0) problems.push('the box scrolls by itself under reduced motion');
if (!reduced && arrived <= 0) problems.push('the box does not scroll by itself on arrival');
- await evaluate(`document.querySelector('[data-hb-top]').click()`);
- await sleep(500);
- if (await pos() !== 0) problems.push('Back to top does not return the box to the top and stop it');
- await evaluate(`document.querySelector('[data-hb-autoscroll]').click()`);
+ await press('[data-hb-autoscroll]');
await sleep(800);
if (await pos() <= 0) problems.push('Play does not scroll the box');
- const c = await evaluate(`(() => { const b = ${box}.getBoundingClientRect(); return { x: b.left + b.width / 2, y: b.top + Math.min(b.height, innerHeight - b.top) / 2 }; })()`);
- await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: c.x, y: c.y, deltaX: 0, deltaY: 40 });
+ await press('[data-hb-top]');
+ await sleep(500);
+ const atTop = await pos() === 0;
+ await sleep(600);
+ if (!atTop || await pos() !== 0) problems.push('Back to top does not return the box to the top and stop it');
+ // The page's own snap type: read before anything ran (reduced motion), else with the run stopped (a mark left behind
+ // would show as "none" here, but the reduced-motion run sees it)
+ const snaps = reduced ? startSnap : await snap();
+ await press('[data-hb-autoscroll]');
await sleep(300);
- const held = await pos();
+ if (snaps !== 'none' && await snap() !== 'none') problems.push('scroll snapping is not turned off while Play runs');
+ await sleep(500);
+ const spot = await evaluate(`(() => {
+ const b = ${box}, s = document.querySelector('.hb-page .stage');
+ if (b !== s) {
+ const r = s.getBoundingClientRect(), x = r.left + 3, y = r.top + 3, hit = document.elementFromPoint(x, y);
+ if (hit && s.contains(hit) && !b.contains(hit)) return { x, y };
+ }
+ const r = b.getBoundingClientRect();
+ return { x: r.left + r.width / 2, y: r.top + Math.min(r.height, innerHeight - r.top) / 2 };
+ })()`);
+ await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: spot.x, y: spot.y, deltaX: 0, deltaY: 40 });
+ let held = await pos();
+ for (let i = 0; i < 15; i++) { await sleep(100); const next = await pos(); if (next === held) break; held = next; }
await sleep(600);
if (await pos() !== held) problems.push('turning the wheel does not stop Play');
+ else if (snaps !== 'none' && await snap() !== snaps) problems.push('scroll snapping does not come back when the wheel stops Play');
return problems;
}