8000 fix: show focused content before hydration and during the entrance delay by morellodev · Pull Request #335 · awesome-reveal/awesome-reveal · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/rules/core/adapter-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ paths:
- The behavior spec of the adapters is the contract suite in `packages/test-utils` (`contract.ts`, `contract-ssr.ts`). Change a behavior there first, so that all adapters follow. A framework adapter cannot add behavior that core does not have.
- A cascade store reads the children in `play`, at the reveal, and not at `attach`, so children that the framework renders after the attach also animate. Imperative `cascade()` reads them when it is called. The adapter cascade hides the children, not the container: `[data-awesome-reveal="cascade"] > *`. With a hidden container, its background and border appear with no animation. A child with `display: contents`, such as an Astro island or host, gets no visible entrance.
- Each adapter renders the hidden markup itself, with `hiddenAttributes` or `cascadeHiddenAttributes`, and ships its own `reveal.css`. The library writes no inline style, so a strict CSP needs no `'unsafe-inline'`. `data-awesome-reveal`, `data-awesome-reveal-attached` and the `awesome-reveal-hold` keyframes are reserved.
- `reveal.css` hides only on screen and with no reduced motion, so print and reduced motion keep the author opacity. A separate `(scripting: none)` query cancels the hold. Do not put `scripting` in the hiding query: browsers without the feature, such as Safari 16, then never hide. Before the attach, a short CSS hold hides the element, so markup that no script attaches shows again. `attach` sets `data-awesome-reveal-attached` on the element, and a CSS rule holds it after that. The hold after the attach is a CSS marker on the element, not a WAAPI hold, because a WAAPI hold cannot cover cascade children that render after the attach.
- `reveal.css` hides only on screen and with no reduced motion, so print and reduced motion keep the author opacity. A separate `(scripting: none)` query cancels the hold. Focus before the attach sets `animation-duration: 0s` on the hold, so the element shows while it has focus. A change of duration keeps the start time, so after a blur the hold hides the element only until its first 5 s end. Do not use `animation: none` there: a blur then starts a new 5 s hold, also after the first hold ended. Do not put `scripting` in the hiding query: browsers without the feature, such as Safari 16, then never hide. Before the attach, a short CSS hold hides the element, so markup that no script attaches shows again. `attach` sets `data-awesome-reveal-attached` on the element, and a CSS rule holds it after that. The hold after the attach is a CSS marker on the element, not a WAAPI hold, because a WAAPI hold cannot cover cascade children that render after the attach.
- The hold owns the `animation` property of hidden markup with `!important`. CSS cannot add an animation to the author list, and only an animation can end a hide after a time. Without `!important`, the stylesheet order and the specificity decide if the author animation or the hold wins. So an author animation on the same element starts at the reveal, and does not run when no script reveals the element. The READMEs tell users to animate an inner element.
- An attach after the hold ends hides the element again until it reveals. Do not detect the expiry of the hold: it conflicts with `when: false`, and it needs a style flush. The READMEs document the flicker.
2 changes: 1 addition & 1 deletion .claude/rules/core/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ paths:
- Print has no stylesheet in core. `motions()` adds each group to one shared `beforeprint`/`afterprint` listener pair. The listener moves each paused animation to its end time on `beforeprint`, past its backwards fill, and back to 0 on `afterprint`. Only paused animations move, so a playing entrance is not rewound. Every animation also gets `fill: "none"` until `afterprint`, so a running animation in its delay prints at rest and keeps its time. Do not pause it: the animation would lose the print time, and `play()` would see a paused animation. The adapter store plays through `motions()` too. `reveal.css` does not match print, but without the print listener the backwards fill would still hide an element in its delay. A real print in Chromium, also `page.pdf()` of Playwright, fires both events; `emulateMedia({ media: "print" })` fires none.
- `cascade` observes each container and animates its direct element children with the WAAPI delay `delay + index * interval`. `delay` moves the whole sequence, and there is no delay for each child separately: `interval` does that. It reads the children once, when it starts. Do not clamp a negative `interval`: WAAPI accepts a negative delay, which starts later children further into their entrance. Do not add a child selector or a timeline abstraction.
- `observe` uses the thresholds `[0, threshold]`. At each entry, it reveals at once when the viewport (`rootBounds`) is too small to show `threshold` of the element. A cross-origin frame gets `rootBounds: null`, so the check uses the frame viewport (`innerWidth` and `innerHeight`), which is the largest area that the frame can show. The viewport is the largest root, so in a scroll container that is too small, the element reveals when it leaves the visible area. Do not clamp the threshold instead: a clamp fails after the element grows.
- `observe` also reveals on `focusin`, and at the start when the element already contains focus, so a keyboard user does not focus invisible content. An element that matches `:focus-within` at the reveal plays no entrance, because a delay or a transparent start would hide the focused control: `reveal` and `cascade` cancel the animations, and the adapter store does not play but still calls `onReveal`. This check is at the reveal, not in the focus listener, so it also covers `when` and an attach again. Focus during a running entrance or its delay does not shorten it, because the observer has stopped. The adapters keep a `when: false` element hidden on focus, because `when` has priority over the viewport.
- `observe` also reveals on `focusin`, and at the start when the element already contains focus, so a keyboard user does not focus invisible content. An element that matches `:focus-within` at the reveal plays no entrance, because a delay or a transparent start would hide the focused control: `reveal` and `cascade` cancel the animations, and the adapter store does not play but still calls `onReveal`. This check is at the reveal, not in the focus listener, so it also covers `when` and an attach again. `motions()` also listens to `focusin`, so focus during a running entrance or its delay finishes it. It uses `finish()`, not `cancel()`, so the `finished` promises resolve. It finishes only running animations: a `focusin` with no real focus before the reveal must not finish a waiting animation, or `play()` skips it. The adapters keep a `when: false` element hidden on focus, because `when` has priority over the viewport.
- Do not throw when an API is missing. Without IntersectionObserver, reveal at once. Without `Element.animate`, reveal with no animation.
- Do not use `window` or `document` at module level. Server renderers import core. A selector resolves to no elements when `document` is undefined.
- The `.d.ts` files carry the JSDoc, and the JS output has none. Write the option docs and defaults in the type JSDoc.
Expand Down
3 changes: 2 additions & 1 deletion packages/astro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,8 @@ If the parser moves the tag, the host reports an error in the browser console, a

- With `prefers-reduced-motion: reduce`, all the content shows immediately, with no animation.
- Focus in a waiting element shows it at once, so a keyboard user does not focus invisible content. This does not apply with `when={false}`.
- Focus during a running entrance or its delay does not shorten it, so keep `delay` and `interval` short.
- Focus during the delay or the entrance finishes the entrance at once.
- Before the script loads, server markup shows while it has focus.
- Waiting content shows in print and when JavaScript is off.
- Hidden content stays in the accessibility tree. Do not make important content depend on decorative motion.

Expand Down
5 changes: 5 additions & 0 deletions packages/astro/src/reveal.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
[data-awesome-reveal="cascade"] > * {
animation: awesome-reveal-hold 5s !important;
}
/* A new duration keeps the start time, so a blur does not restart the hold. */
[data-awesome-reveal="hidden"]:focus-within,
[data-awesome-reveal="cascade"]:focus-within > * {
animation-duration: 0s !important;
}
[data-awesome-reveal="hidden"][data-awesome-reveal-attac 8000 hed],
[data-awesome-reveal="cascade"][data-awesome-reveal-attached] > * {
opacity: 0 !important;
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/package/dist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe("a static build of a page with the published component", () => {

expect(host).toHaveLength(1);
expect(control).toHaveLength(1);
expect(host[0]!.length).toBeLessThan(5150);
expect(host[0]!.length).toBeLessThan(5200);
expect(control[0]!.length).toBeLessThan(600);
});
});
Expand Down
2 changes: 1 addition & 1 deletion packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ The package also exports the types `Side`, `StartState`, `RevealOptions`, `Casca

- With `prefers-reduced-motion: reduce`, all the content shows immediately, with no animation and no delay. If the preference changes, core cancels the waiting and the running animations.
- Focus in a waiting element shows it at once, so a keyboard user does not focus invisible content. Focus in a waiting cascade container shows all its children.
- Focus during a running entrance or its delay does not shorten it, so keep `delay` and `interval` short.
- Focus during the delay or the entrance finishes the entrance at once.
- Waiting content shows in print. After the print, it waits again. Core uses the `beforeprint` and `afterprint` events, so a print emulation in developer tools does not show the content.
- Hidden content stays in the accessibility tree. Do not make important content depend on decorative motion.

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const restarts = ["when", "threshold"] as const;
// The cancel function tells if the entrance was still running.
function play(element: Element, options: CoreRevealOptions, interval?: number): () => boolean {
let animations = entrances(element, options, interval);
const group = motions(animations);
const group = motions(element, animations);
group.play();
// Keeps no removed cascade child. Then cancel() returns false, so the entrance does not replay.
Promise.allSettled(animations.map((animation) => animation?.finished)).then(() => {
Expand Down
17 changes: 16 additions & 1 deletion packages/core/src/animation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { focused } from "./observe.js";
import { report } from "./report.js";
import type { CascadeOptions, RevealOptions, StartState } from "./types.js";

Expand Down Expand Up @@ -98,7 +99,19 @@ export function entrances(element: Element, options: RevealOptions, interval?: n
return targets.map((target, index) => motion(target, options, delay + index * (interval ?? 0)));
}

export function motions(animations: (Animation | undefined)[]): Motions {
export function motions(element: Element, animations: (Animation | undefined)[]): Motions {
const finish = () => {
if (!focused(element)) return;
for (const animation of animations)
if (animation?.playState === "running")
try {
animation.finish();
} catch (error) {
// An entrance with no end, such as `duration: Infinity`, cannot finish.
report(error);
animation.cancel();
}
};
const group: Motions = {
play() {
for (const animation of animations)
Expand All @@ -119,11 +132,13 @@ export function motions(animations: (Animation | undefined)[]): Motions {
// A settled group passes keep: cancel() on a finished animation fires a cancel event and makes it idle.
dispose(keep) {
if (!keep) for (const animation of animations) animation?.cancel();
element.removeEventListener("focusin", finish);
animations = [];
following.delete(group);
if (!following.size) listenPrint("removeEventListener");
},
};
element.addEventListener("focusin", finish);
following.add(group);
listenPrint("addEventListener");
return group;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/reveal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function start(target: RevealTarget, options: RevealOptions, interval?: number):
if (preference?.matches) return { dispose };
for (const element of new Set(resolveTargets(target))) {
const animations = entrances(element, options, interval);
const group = motions(animations);
const group = motions(element, animations);
let disconnect: (() => void) | undefined;
const release = (keep?: boolean) => {
if (!releases.delete(release)) return;
Expand Down
26 changes: 25 additions & 1 deletion packages/core/test/browser/reveal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,29 @@ describe("zero-CSS reveal", () => {
(target.lastElementChild as HTMLElement).focus();
await expectShown(...target.children);
});
it.each([
["its delay", { delay: 60_000 }],
["its entrance", { duration: 60_000 }],
])("during %s", async (_, options: RevealOptions) => {
track(reveal(target, options));
await enter();
link().focus();
await expectShown(target);
});
it("during an entrance that cannot finish", async () => {
const reports = collectReports();
track(reveal(target, { duration: Infinity }));
await enter();
link().focus();
await expectShown(target);
expect(await reports()).toEqual([expect.objectContaining({ name: "InvalidStateError" })]);
});
it("during the interval of a later child of a cascade", async () => {
track(cascade(target, { duration: 60_000, interval: 10_000 }));
await enter(target.firstElementChild as HTMLElement);
(target.lastElementChild as HTMLElement).focus();
await expectShown(...target.children);
});
it("when the element has focus before the reveal starts", async () => {
link().focus();
track(reveal(target, { delay: 60_000 }));
Expand All @@ -253,7 +276,8 @@ describe("zero-CSS reveal", () => {
const unlisten = vi.spyOn(target, "removeEventListener");
track(reveal(target, native)).dispose();
expect(listen).toHaveBeenCalledWith("focusin", expect.any(Function));
expect(unlisten.mock.calls).toEqual(listen.mock.calls);
expect(new Set(unlisten.mock.calls)).toEqual(new Set(listen.mock.calls));
expect(unlisten).toHaveBeenCalledTimes(listen.mock.calls.length);
});
});
it("reveals an element taller than its scroll container when it leaves before the threshold", async () => {
Expand Down
19 changes: 18 additions & 1 deletion packages/core/test/browser/stylesheet.test.ts
Original fi 10BC8 le line number Diff line number Diff line change
Expand Up @@ -182,11 +182,28 @@ describe("reveal.css", () => {
it("shows server markup that has focus before the attach", () => {
target.setAttribute("data-awesome-reveal", "hidden");
last().focus();
expect(opacity(target)).toBe("0");
expect(opacity(target)).toBe("1");
bindStore({ delay: 60_000 });
expectShown(target);
});

it("shows all the children of cascade server markup that has focus before the attach", () => {
target.setAttribute("data-awesome-reveal", "cascade");
last().focus();
for (const child of target.children) expect(opacity(child)).toBe("1");
});

it("keeps the hold time when focus leaves server markup", () => {
target.setAttribute("data-awesome-reveal", "hidden");
last().focus();
last().blur();
expect(opacity(target)).toBe("0");
hold(target)!.finish();
last().focus();
last().blur();
expect(opacity(target)).toBe("1");
});

it("keeps the element hidden with when: false", async () => {
bindStore({ when: false });
last().focus();
Expand Down
8 changes: 4 additions & 4 deletions packages/core/test/package/tree-shaking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ it.concurrent.each([
{
entry: "reveal.js",
animationExports: ["entrance", "entrances", "motionPreference", "motions"],
bytes: 4025,
gzip: 1750,
bytes: 4175,
gzip: 1800,
},
{
entry: "both.js",
animationExports: ["cascadeInterval", "entrance", "entrances", "motionPreference", "motions"],
bytes: 4125,
gzip: 1800,
bytes: 4275,
gzip: 1850,
},
])(
"keeps only the imperative modules for $entry",
Expand Down
3 changes: 2 additions & 1 deletion packages/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,8 @@ The server markup is hidden until the element reveals. If the script fails, the

- With `prefers-reduced-motion: reduce`, all the content shows immediately, with no animation. Reduced motion has priority over the entrance and over `when={false}`, so `onReveal` does not run again.
- Focus in a waiting element shows it at once, so a keyboard user does not focus invisible content. This does not apply with `when={false}`.
- Focus during a running entrance or its delay does not shorten it, so keep `delay` and `interval` short.
- Focus during the delay or the entrance finishes the entrance at once.
- Before the script loads, server markup shows while it has focus.
- Waiting content shows in print and when JavaScript is off.
- Hidden content stays in the accessibility tree. Do not make important content depend on decorative motion.

Expand Down
5 changes: 5 additions & 0 deletions packages/react/src/reveal.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
[data-awesome-reveal="cascade"] > * {
animation: awesome-reveal-hold 5s !important;
}
/* A new duration keeps the start time, so a blur does not restart the hold. */
[data-awesome-reveal="hidden"]:focus-within,
[data-awesome-reveal="cascade"]:focus-within > * {
animation-duration: 0s !important;
}
[data-awesome-reveal="hidden"][data-awesome-reveal-attached],
[data-awesome-reveal="cascade"][data-awesome-reveal-attached] > * {
opacity: 0 !important;
Expand Down
4 changes: 2 additions & 2 deletions packages/react/test/package/tree-shaking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ describe("consumer bundle", () => {

expect(keptExports["core/dist/adapter.js"]).toContain("createReveal");
expect(css).toBeGreaterThan(0);
expect(bytes + css).toBeLessThan(6700);
expect(bytes + css).toBeLessThan(7025);
});

it("keeps no Reveal component for the hook alone", async () => {
const { keptExports, bytes, css } = await bundle("hook-only.js");

expect(keptExports["core/dist/adapter.js"]).toContain("createReveal");
expect(css).toBeGreaterThan(0);
expect(bytes + css).toBeLessThan(6325);
expect(bytes + css).toBeLessThan(6675);
expect(keptExports).not.toHaveProperty("react/dist/Reveal.js");
});
});
Loading
Loading
0