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
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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"`.
Expand All @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion demo/landing/examples/app-bar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion demo/landing/examples/button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion demo/landing/examples/counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion demo/landing/examples/toast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion demo/landing/examples/words.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
64 changes: 48 additions & 16 deletions src/core/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
resetLayer,
setLayerText,
setLiveText,
setStyleIfChanged,
sizeHost,
} from "./layers";
import type { MorphStage } from "./layers";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -267,47 +279,61 @@ 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,
rise.scale,
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) {
const record = tr.exit[order]!;
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,
rise.scale,
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)`,
);
}
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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;
}
Expand All @@ -677,6 +706,7 @@ export function createMorph(el: HTMLElement, options: MorphOptions = {}): Morph

function applyUpdate(partial: Partial<MorphOptions>): void {
if (destroyed) return;
refreshFontSize();

if (partial.words !== undefined) {
const nextWords = Array.isArray(partial.words)
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;

Expand Down
28 changes: 23 additions & 5 deletions src/core/layers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 {
Expand Down
20 changes: 14 additions & 6 deletions src/core/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`. */
Expand All @@ -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),
};
}
Expand Down
Loading
Loading