diff --git a/CHANGELOG.md b/CHANGELOG.md index fabff46..44e3ceb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `effects.goo.maxBlur` to cap the goo blur in pixels. + +### Changed + +- The default goo blur cap is now 40px instead of 100px, which cuts the most expensive frames. +- The host font size is cached per morph instead of read on every animation frame. +- Goo and rise blur are combined into a single blur pass per element. +- Fully transparent layers skip their blur. +- Redundant inline style writes are skipped when the value has not changed. +- Chunk spans no longer promote themselves for filter changes via `will-change`. + +### Fixed + +- `play()` no longer starts automatic cycling when `autoplay` is disabled. +- Playground examples animate again after switching to another example and back. + ## [0.1.0] - 2026-11-08 ### Added diff --git a/README.md b/README.md index 4802e72..a3089e0 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,7 @@ interface MorphEffects { | Option | Type | Default | Description | | ----------- | --------- | ------- | ---------------------------------------------------------------------------------------------------------- | | `blur` | `number` | `0.075` | Layer blur strength in `em`, scaled by the host's computed font size. | +| `maxBlur` | `number` | `40` | Upper bound for the goo blur in pixels. Clamped to 0–100. Lower values are cheaper to render. | | `threshold` | `number` | `140` | The `T` in the alpha row `0 0 0 255 -T`. Clamped to 0–255. | | `atRest` | `boolean` | `true` | Apply the goo CSS filter while the text is at rest. When false, the filter is only applied during a morph. | @@ -368,7 +369,7 @@ interface Morph { - **`setText(text)`** morphs from the current visual state. If a goo-only morph is running, the winning layer keeps its exact current opacity and blur, so the new morph does not jump. A rise or combined morph fast-forwards first. - **`next()`** advances one entry in `words`. It returns a resolved promise when there is nowhere to go (no words, or `loop: false` at the end). - **`setWords(words)`** replaces the list. The current reference text is kept if it is still in the list; otherwise the index resets to zero. -- **`play() / pause()`** resume or freeze the animation clock and automatic cycling. While paused, `setText()` and `next()` apply immediately instead of animating, so calls never hang. +- **`play() / pause()`** resume or freeze the animation clock and automatic cycling. `play()` only restarts automatic cycling when `autoplay` is enabled. While paused, `setText()` and `next()` apply immediately instead of animating, so calls never hang. - **`update(partial)`** changes options in place. Nested effect patches merge with current values, so `update({ effects: { rise: { stagger: 60 } } })` keeps the other rise settings. Changing the goo threshold releases and re-acquires the shared SVG filter. - **`destroy()`** cancels the loop, removes listeners and the filter reference, removes the layers and live region, and restores the host's original children, `dir`/`lang`, and touched inline styles. Safe to call twice. @@ -464,6 +465,14 @@ Atomization uses: The consequence: a font-specific ligature that is not identifiable from Unicode alone cannot always be predicted. Rare ligatures may animate as changed text instead of staying fixed. Common Arabic/Persian shaping, joins, ZWNJ and lam-alef are handled. This is the cost of staying fully zero-dependency. +## Performance + +- The host font size is read once per morph, not on every animation frame. +- Transparent layers skip their blur entirely. +- Goo and rise blur are composed into one blur pass per element. +- The goo blur is capped by `effects.goo.maxBlur` (40px by default). Raise it for a softer look, lower it for heavy pages. +- Use `effects.goo.atRest: false` when many morphs share a page. + ## Accessibility - Both animated layers are `aria-hidden="true"`. @@ -484,7 +493,7 @@ Importing the package is safe on the server: no DOM access happens at module loa - **One host filter.** If the host already has a CSS `filter`, the library overrides it while active and restores the inline value on `destroy()`. - **`filter` scale is not accounted for.** Blur uses the computed font size in CSS pixels. A parent `transform: scale()` scales the result but not the blur amount. - **Long strings do not wrap.** Layers use `white-space: nowrap`. Size the host for the longest phrase, or shorten the list. -- **Blur is capped at 100px**, exactly as in the original goo demo. +- **Blur is capped at `maxBlur`** (40px by default, hard maximum 100px). Lower it further on low-powered devices or when many morphs share a page. - **Rest-first timing.** Auto-cycling waits `restTime` before the first morph and after every completed morph. - **No font loading management.** Use `font-display` and wait for `document.fonts.ready` if the morph must begin after a webfont loads. diff --git a/demo/landing/examples/app-bar.ts b/demo/landing/examples/app-bar.ts index 444f590..ac22243 100644 --- a/demo/landing/examples/app-bar.ts +++ b/demo/landing/examples/app-bar.ts @@ -198,7 +198,7 @@ export function createTabsExample({ controls }: ExampleOptions): ExampleInstance lazy.morph?.pause(); }, resume() { - if (state.autoplay) lazy.morph?.play(); + lazy.morph?.play(); }, destroy() { lazy.destroy(); diff --git a/demo/landing/examples/button.ts b/demo/landing/examples/button.ts index 59b8726..cf875f3 100644 --- a/demo/landing/examples/button.ts +++ b/demo/landing/examples/button.ts @@ -347,7 +347,7 @@ export function createButtonExample({ controls }: ExampleOptions): ExampleInstan reset, pause, resume() { - if (state.autoplay) lazy.morph?.play(); + lazy.morph?.play(); }, destroy() { destroyed = true; diff --git a/demo/landing/examples/counter.ts b/demo/landing/examples/counter.ts index e700d7b..cdf81f9 100644 --- a/demo/landing/examples/counter.ts +++ b/demo/landing/examples/counter.ts @@ -218,7 +218,7 @@ export function createCounterExample({ controls }: ExampleOptions): ExampleInsta lazy.morph?.pause(); }, resume() { - if (state.autoplay) lazy.morph?.play(); + lazy.morph?.play(); }, destroy() { replayToken += 1; diff --git a/demo/landing/examples/toast.ts b/demo/landing/examples/toast.ts index ef7903e..c2fcfb7 100644 --- a/demo/landing/examples/toast.ts +++ b/demo/landing/examples/toast.ts @@ -122,7 +122,7 @@ export function createToastExample({ controls }: ExampleOptions): ExampleInstanc lazy.morph?.pause(); }, resume() { - if (state.autoplay) lazy.morph?.play(); + lazy.morph?.play(); }, destroy() { lazy.destroy(); diff --git a/demo/landing/examples/words.ts b/demo/landing/examples/words.ts index 6f67670..34b185e 100644 --- a/demo/landing/examples/words.ts +++ b/demo/landing/examples/words.ts @@ -240,7 +240,7 @@ export function createWordsExample({ controls }: ExampleOptions): ExampleInstanc lazy.morph?.pause(); }, resume() { - if (state.autoplay) lazy.morph?.play(); + lazy.morph?.play(); }, destroy() { window.clearTimeout(editTimer); diff --git a/src/core/controller.ts b/src/core/controller.ts index 4a30abe..787e5c8 100644 --- a/src/core/controller.ts +++ b/src/core/controller.ts @@ -18,6 +18,7 @@ import { resetLayer, setLayerText, setLiveText, + setStyleIfChanged, sizeHost, } from "./layers"; import type { MorphStage } from "./layers"; @@ -126,6 +127,12 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph return Number.isFinite(inline) && inline > 0 ? inline : DEFAULT_FONT_SIZE; } + let transitionFontSize = readFontSize(); + + function refreshFontSize(): void { + transitionFontSize = readFontSize(); + } + function readDirection(): { dir: MorphDirection; rtl: boolean } { const attr = dir ?? (el.getAttribute("dir") as MorphDirection | null) ?? "rtl"; const view = doc.defaultView; @@ -249,9 +256,14 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph function renderGooOrFade(tr: Transition, eased: number): void { if (tr.mode === "goo" && goo.enabled) { - const fontSize = readFontSize(); - applyGooState(stage.outgoing, tr.outStart * (1 - eased), fontSize, goo.blur); - applyGooState(stage.incoming, eased, fontSize, goo.blur); + applyGooState( + stage.outgoing, + tr.outStart * (1 - eased), + transitionFontSize, + goo.blur, + goo.maxBlur, + ); + applyGooState(stage.incoming, eased, transitionFontSize, goo.blur, goo.maxBlur); } else { applyFadeState(stage.outgoing, tr.outStart * (1 - eased)); applyFadeState(stage.incoming, eased); @@ -267,13 +279,13 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph const elapsed = Math.max(0, Math.min(duration, tr.elapsed)); const global = duration > 0 ? clamp01(elapsed / duration) : 1; const globalEased = ease(global); - const fontSize = readFontSize(); + const fontSize = transitionFontSize; for (let order = 0; order < tr.enter.length; order += 1) { const record = tr.enter[order]!; const local = easeRise(enterProgress(elapsed, order, timing)); const gooOpacity = goo.enabled ? opacityForFraction(local) : local; - const gooBlur = goo.enabled ? blurForFraction(local, fontSize, goo.blur) : 0; + const gooBlur = goo.enabled ? blurForFraction(local, fontSize, goo.blur, goo.maxBlur) : 0; const motion = enterTransform( local, rise.travel, @@ -281,9 +293,14 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph rise.blur, tr.flowByChunk?.get(record.chunk.id) ?? tr.flow, ); - record.span.style.opacity = String(gooOpacity); - record.span.style.filter = combineBlur(gooBlur, motion.blurEm * fontSize); - record.span.style.transform = `translate(${(motion.xEm * fontSize).toFixed(2)}px, ${(motion.yEm * fontSize).toFixed(2)}px) scale(${motion.scale.toFixed(4)})`; + const filter = gooOpacity < 0.01 ? "none" : combineBlur(gooBlur, motion.blurEm * fontSize); + setStyleIfChanged(record.span, "opacity", String(gooOpacity)); + setStyleIfChanged(record.span, "filter", filter); + setStyleIfChanged( + record.span, + "transform", + `translate(${(motion.xEm * fontSize).toFixed(2)}px, ${(motion.yEm * fontSize).toFixed(2)}px) scale(${motion.scale.toFixed(4)})`, + ); } for (let order = 0; order < tr.exit.length; order += 1) { @@ -291,7 +308,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph const local = easeRise(exitProgress(elapsed, order, timing)); const remaining = 1 - local; const gooOpacity = goo.enabled ? opacityForFraction(remaining) : remaining; - const gooBlur = goo.enabled ? blurForFraction(remaining, fontSize, goo.blur) : 0; + const gooBlur = goo.enabled ? blurForFraction(remaining, fontSize, goo.blur, goo.maxBlur) : 0; const motion = exitTransform( local, rise.travel, @@ -299,15 +316,24 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph rise.blur, tr.flowByChunk?.get(record.chunk.id) ?? tr.flow, ); - record.span.style.opacity = String(gooOpacity); - record.span.style.filter = combineBlur(gooBlur, motion.blurEm * fontSize); - record.span.style.transform = `translate(${(motion.xEm * fontSize).toFixed(2)}px, ${(motion.yEm * fontSize).toFixed(2)}px) scale(${motion.scale.toFixed(4)})`; + const filter = gooOpacity < 0.01 ? "none" : combineBlur(gooBlur, motion.blurEm * fontSize); + setStyleIfChanged(record.span, "opacity", String(gooOpacity)); + setStyleIfChanged(record.span, "filter", filter); + setStyleIfChanged( + record.span, + "transform", + `translate(${(motion.xEm * fontSize).toFixed(2)}px, ${(motion.yEm * fontSize).toFixed(2)}px) scale(${motion.scale.toFixed(4)})`, + ); } for (const record of scene.matched) { - record.span.style.opacity = "1"; - record.span.style.filter = "none"; - record.span.style.transform = `translate(${(record.dx * (1 - globalEased)).toFixed(2)}px, ${(record.dy * (1 - globalEased)).toFixed(2)}px)`; + setStyleIfChanged(record.span, "opacity", "1"); + setStyleIfChanged(record.span, "filter", "none"); + setStyleIfChanged( + record.span, + "transform", + `translate(${(record.dx * (1 - globalEased)).toFixed(2)}px, ${(record.dy * (1 - globalEased)).toFixed(2)}px)`, + ); } } @@ -406,6 +432,8 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph if (transition && transition.to === to) return transition.promise; if (!transition && to === currentText) return Promise.resolve(); + transitionFontSize = readFontSize(); + let fromText: string; let outStart = 1; const previous = transition; @@ -601,6 +629,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph let observer: IntersectionObserver | null = null; const view = doc.defaultView; + view?.addEventListener("resize", refreshFontSize); if (view && typeof view.IntersectionObserver === "function") { observer = new view.IntersectionObserver( (entries) => { @@ -662,7 +691,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph pending = null; void startMorph(queued.text).then(queued.resolve, queued.resolve); } - if (words.length > 1 && canAutoAdvance()) { + if (autoplay && words.length > 1 && canAutoAdvance()) { auto = true; if (!transition && autoRest === null) autoRest = restTime; } @@ -677,6 +706,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph function applyUpdate(partial: Partial): void { if (destroyed) return; + refreshFontSize(); if (partial.words !== undefined) { const nextWords = Array.isArray(partial.words) @@ -701,6 +731,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph nextGoo.enabled !== goo.enabled || nextGoo.threshold !== goo.threshold || nextGoo.blur !== goo.blur || + nextGoo.maxBlur !== goo.maxBlur || nextGoo.atRest !== goo.atRest; goo = nextGoo; } @@ -791,6 +822,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph paused = true; stopLoop(); doc.removeEventListener("visibilitychange", onVisibilityChange); + view?.removeEventListener("resize", refreshFontSize); observer?.disconnect(); observer = null; diff --git a/src/core/layers.ts b/src/core/layers.ts index 8bc8c44..8dff264 100644 --- a/src/core/layers.ts +++ b/src/core/layers.ts @@ -141,6 +141,15 @@ export function resetLayer(layer: MorphLayer): void { layer.line.style.transform = "none"; } +/** Write an inline style only when it changes. */ +export function setStyleIfChanged( + el: HTMLElement, + property: "opacity" | "filter" | "transform", + value: string, +): void { + if (el.style[property] !== value) el.style[property] = value; +} + export function clearLayer(layer: MorphLayer): void { layer.line.replaceChildren(); resetLayer(layer); @@ -157,20 +166,29 @@ export function setLayerText(layer: MorphLayer, text: string): void { layer.line.replaceChildren(text); } +const MIN_VISIBLE_OPACITY = 0.01; + export function applyGooState( layer: MorphLayer, lightFraction: number, fontSizePx: number, blurEm: number, + maxBlurPx?: number, ): void { - const visual = visualForFraction(lightFraction, fontSizePx, blurEm); - layer.line.style.opacity = String(visual.opacity); - layer.line.style.filter = visual.blurPx > 0 ? `blur(${visual.blurPx}px)` : "none"; + const visual = visualForFraction(lightFraction, fontSizePx, blurEm, maxBlurPx); + const opacity = visual.opacity; + const filter = + opacity < MIN_VISIBLE_OPACITY || visual.blurPx < 0.01 + ? "none" + : `blur(${visual.blurPx.toFixed(2)}px)`; + setStyleIfChanged(layer.line, "opacity", String(opacity)); + setStyleIfChanged(layer.line, "filter", filter); } export function applyFadeState(layer: MorphLayer, opacity: number): void { - layer.line.style.opacity = String(Math.max(0, Math.min(1, opacity))); - layer.line.style.filter = "none"; + const clamped = Math.max(0, Math.min(1, opacity)); + setStyleIfChanged(layer.line, "opacity", String(clamped)); + setStyleIfChanged(layer.line, "filter", "none"); } export function setLiveText(el: HTMLSpanElement, text: string): void { diff --git a/src/core/math.ts b/src/core/math.ts index 1be0f20..f0fe8b9 100644 --- a/src/core/math.ts +++ b/src/core/math.ts @@ -20,18 +20,25 @@ export function clamp01(value: number): number { /** * Blur in pixels for a layer at `fraction`. * - * `min(blurEm * fontSizePx * (1 / fraction - 1), 100)`. - * At fraction 1 the layer is sharp; at fraction 0 it is clamped to 100px. + * `min(blurEm * fontSizePx * (1 / fraction - 1), maxBlurPx)`. + * At fraction 1 the layer is sharp; at fraction 0 it hits the cap. */ -export function blurForFraction(fraction: number, fontSizePx: number, blurEm: number): number { +export function blurForFraction( + fraction: number, + fontSizePx: number, + blurEm: number, + maxBlurPx: number = MAX_BLUR_PX, +): number { const f = clamp01(fraction); if (f >= 1) return 0; - if (f <= 0) return MAX_BLUR_PX; + if (f <= 0) return Math.max(0, maxBlurPx); const fontSize = Number.isFinite(fontSizePx) && fontSizePx > 0 ? fontSizePx : 16; const blurEmSafe = Number.isFinite(blurEm) && blurEm > 0 ? blurEm : 0; + const cap = + Number.isFinite(maxBlurPx) && maxBlurPx > 0 ? Math.min(MAX_BLUR_PX, maxBlurPx) : MAX_BLUR_PX; const blur = blurEmSafe * fontSize * (1 / f - 1); - return Math.min(MAX_BLUR_PX, Math.max(0, blur)); + return Math.min(cap, Math.max(0, blur)); } /** Opacity for a layer at `fraction`: `fraction ** 0.4`. */ @@ -49,9 +56,10 @@ export function visualForFraction( fraction: number, fontSizePx: number, blurEm: number, + maxBlurPx: number = MAX_BLUR_PX, ): VisualState { return { - blurPx: blurForFraction(fraction, fontSizePx, blurEm), + blurPx: blurForFraction(fraction, fontSizePx, blurEm, maxBlurPx), opacity: opacityForFraction(fraction), }; } diff --git a/src/core/options.ts b/src/core/options.ts index a0a101f..7e0251e 100644 --- a/src/core/options.ts +++ b/src/core/options.ts @@ -1,5 +1,6 @@ import { DEFAULT_RISE_EASING } from "./easing"; import type { EasingFunction } from "./easing"; +import { MAX_BLUR_PX } from "./math"; export type MorphDirection = "rtl" | "ltr" | "auto"; @@ -41,6 +42,11 @@ export type MorphCallback = (from: string, to: string) => void; export interface GooEffectOptions { /** Blur strength in em, scaled by the host's computed font size. */ blur?: number; + /** + * Maximum goo blur in pixels. Defaults to 40px and is clamped to 0–100px. + * Lower values are cheaper to render. + */ + maxBlur?: number; /** Alpha threshold T in "0 0 0 255 -T". Clamped to 0–255. */ threshold?: number; /** Keep the SVG filter mounted while the text is at rest. */ @@ -123,6 +129,7 @@ export interface Morph { export interface ResolvedGoo { enabled: boolean; blur: number; + maxBlur: number; threshold: number; atRest: boolean; } @@ -146,9 +153,12 @@ export interface ResolvedEffects { rise: ResolvedRise; } +export const DEFAULT_MAX_GOO_BLUR_PX = 40; + export const DEFAULT_GOO: ResolvedGoo = { enabled: true, blur: 0.075, + maxBlur: DEFAULT_MAX_GOO_BLUR_PX, threshold: 140, atRest: true, }; @@ -185,6 +195,7 @@ function gooFromOptions(options: GooEffectOptions, base: ResolvedGoo): ResolvedG return { enabled: true, blur: nonNegative(options.blur, base.blur), + maxBlur: clamp(options.maxBlur, 0, MAX_BLUR_PX, base.maxBlur), threshold: options.threshold === undefined ? base.threshold : normalizeThreshold(options.threshold), atRest: typeof options.atRest === "boolean" ? options.atRest : base.atRest, diff --git a/src/core/scene.ts b/src/core/scene.ts index 7aa1df0..65d81e6 100644 --- a/src/core/scene.ts +++ b/src/core/scene.ts @@ -103,7 +103,7 @@ function styleChunk(span: HTMLSpanElement, dir: SceneOptions["dir"]): void { span.style.direction = dir === "auto" ? "inherit" : dir; span.style.verticalAlign = "baseline"; span.style.transformOrigin = "center center"; - span.style.willChange = "transform, opacity, filter"; + span.style.willChange = "transform, opacity"; span.style.pointerEvents = "none"; span.style.setProperty("letter-spacing", "0", "important"); } diff --git a/src/core/transition.ts b/src/core/transition.ts index b94d0de..db99832 100644 --- a/src/core/transition.ts +++ b/src/core/transition.ts @@ -73,12 +73,10 @@ export function reportCallbackError(error: unknown): void { } export function combineBlur(gooPx: number, risePx: number): string { - const goo = Math.max(0, gooPx); - const rise = Math.max(0, risePx); - if (goo < 0.01 && rise < 0.01) return "none"; - if (goo < 0.01) return `blur(${rise.toFixed(2)}px)`; - if (rise < 0.01) return `blur(${goo.toFixed(2)}px)`; - return `blur(${goo.toFixed(2)}px) blur(${rise.toFixed(2)}px)`; + // Two Gaussian blurs compose into one with a root-sum-square radius. A single + // filter pass is both more accurate and cheaper than chaining two blurs. + const total = Math.hypot(Math.max(0, gooPx), Math.max(0, risePx)); + return total < 0.01 ? "none" : `blur(${total.toFixed(2)}px)`; } function resolveFlow(flow: RiseFlowValue, context: RiseFlowContext): RiseFlow { diff --git a/tests/controller.test.ts b/tests/controller.test.ts index 91054ae..dc90cfc 100644 --- a/tests/controller.test.ts +++ b/tests/controller.test.ts @@ -304,6 +304,40 @@ describe("goo morph", () => { morph.destroy(); }); + + it("unpauses manual morphs without starting autoplay", async () => { + const clock = installFrameClock(); + const host = createHost("A"); + const morph = createMorph(host, { + words: ["A", "B"], + autoplay: false, + morphTime: 1, + restTime: 0, + effects: { goo: { atRest: false } }, + }); + const { incoming, live } = layers(host); + + morph.pause(); + morph.play(); + clock.step(0); + clock.step(100); + + // autoplay was never enabled, so no automatic morph starts. + expect(live.textContent).toBe("A"); + + const promise = morph.setText("B"); + clock.step(0); + clock.step(100); + + expect(Number.parseFloat(incoming.style.opacity)).toBeGreaterThan(0); + expect(Number.parseFloat(incoming.style.opacity)).toBeLessThan(1); + + clock.frames(10, 100); + await promise; + expect(live.textContent).toBe("B"); + + morph.destroy(); + }); }); describe("rise morph", () => { @@ -331,7 +365,8 @@ describe("rise morph", () => { expect(Number.parseFloat(enter[0]!.style.opacity)).toBe(0); expect(enter[0]!.style.transform).toContain("translate("); - expect(enter[0]!.style.filter).toMatch(/^blur\(/); + // A fully transparent hunk skips its blur entirely. + expect(enter[0]!.style.filter).toBe("none"); expect(matched[0]!.style.opacity).toBe("1"); expect(matched[0]!.style.filter).toBe("none"); expect(host.style.filter).toBe("none"); @@ -502,7 +537,8 @@ describe("combined morph", () => { clock.frames(5, 100); const enterFilter = enter[0]!.style.filter; - expect(enterFilter.match(/blur\(/g)).toHaveLength(2); + expect(enterFilter.match(/blur\(/g)).toHaveLength(1); + expect(enterFilter).toMatch(/^blur\([\d.]+px\)$/); expect(Number.parseFloat(enter[0]!.style.opacity)).toBeGreaterThan(0); expect(Number.parseFloat(enter[0]!.style.opacity)).toBeLessThan(1); expect(matched[0]!.style.filter).toBe("none"); @@ -596,3 +632,34 @@ describe("reduced motion", () => { morph.destroy(); }); }); + +describe("frame budget", () => { + it("does not read computed styles on every animation frame", async () => { + const clock = installFrameClock(); + const host = createHost("سلام"); + const morph = createMorph(host, { + morphTime: 1, + effects: { goo: true, rise: true }, + autoplay: false, + }); + const { incoming } = layers(host); + const spy = vi.spyOn(window, "getComputedStyle"); + + const promise = morph.setText("سلام جهان"); + const callsAfterStart = spy.mock.calls.length; + expect(callsAfterStart).toBeLessThanOrEqual(2); + + clock.step(0); + clock.step(100); + clock.step(100); + + expect(spy.mock.calls.length).toBe(callsAfterStart); + expect(chunks(incoming, "add")[0]!.style.filter).toMatch(/^blur\(/); + + clock.frames(10, 100); + + await promise; + morph.destroy(); + spy.mockRestore(); + }); +}); diff --git a/tests/math.test.ts b/tests/math.test.ts index 27bfc32..d7bfa6c 100644 --- a/tests/math.test.ts +++ b/tests/math.test.ts @@ -28,6 +28,17 @@ describe("blurForFraction", () => { expect(blurForFraction(0.0001, 400, 1)).toBe(MAX_BLUR_PX); }); + it("honours a custom blur cap", () => { + expect(blurForFraction(0, 100, 0.075, 40)).toBe(40); + expect(blurForFraction(0.1, 100, 0.075, 40)).toBe(40); + expect(blurForFraction(0.5, 100, 0.075, 40)).toBeCloseTo(7.5, 6); + }); + + it("falls back to the hard cap for an invalid custom cap", () => { + expect(blurForFraction(0.1, 100, 10, Number.NaN)).toBe(MAX_BLUR_PX); + expect(blurForFraction(0.1, 100, 10, 500)).toBe(MAX_BLUR_PX); + }); + it("is monotonic as the layer becomes sharper", () => { const samples = [0, 0.01, 0.1, 0.25, 0.5, 0.75, 0.99, 1].map((f) => blurForFraction(f, 120, 0.075), diff --git a/tests/options.test.ts b/tests/options.test.ts index 5e8c244..45ad9d5 100644 --- a/tests/options.test.ts +++ b/tests/options.test.ts @@ -29,12 +29,13 @@ describe("resolveInitialEffects", () => { it("merges effect objects with the defaults", () => { const effects = resolveInitialEffects({ - goo: { blur: 0.2, threshold: 400 }, + goo: { blur: 0.2, threshold: 400, maxBlur: 64 }, rise: { travel: 0.5, scale: 2, flow: "down", minChunk: 3.9 }, }); expect(effects.goo.enabled).toBe(true); expect(effects.goo.blur).toBe(0.2); + expect(effects.goo.maxBlur).toBe(64); expect(effects.goo.threshold).toBe(255); expect(effects.goo.atRest).toBe(DEFAULT_GOO.atRest); @@ -54,6 +55,13 @@ describe("resolveInitialEffects", () => { } }); + it("clamps the goo blur budget into 0–100px", () => { + expect(resolveInitialEffects(undefined).goo.maxBlur).toBe(40); + expect(resolveInitialEffects({ goo: { maxBlur: -5 } }).goo.maxBlur).toBe(0); + expect(resolveInitialEffects({ goo: { maxBlur: 999 } }).goo.maxBlur).toBe(100); + expect(resolveInitialEffects({ goo: { maxBlur: Number.NaN } }).goo.maxBlur).toBe(40); + }); + it("ignores non-finite numbers", () => { const effects = resolveInitialEffects({ goo: { blur: Number.NaN, threshold: Number.POSITIVE_INFINITY }, diff --git a/tests/transition.test.ts b/tests/transition.test.ts new file mode 100644 index 0000000..2b13cea --- /dev/null +++ b/tests/transition.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { combineBlur } from "../src/core/transition"; + +describe("combineBlur", () => { + it("composes two gaussian radii into one filter pass", () => { + expect(combineBlur(3, 4)).toBe("blur(5.00px)"); + }); + + it("never emits more than one blur function", () => { + expect(combineBlur(10, 0.5).match(/blur\(/g)).toHaveLength(1); + }); + + it("returns none when both radii are negligible", () => { + expect(combineBlur(0, 0)).toBe("none"); + expect(combineBlur(0.005, 0.005)).toBe("none"); + }); +});