Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(registry): add echo-smear component (#5980)
Vance Ingalls23e7a384b623
diff --git a/package.json b/package.jsonindex 40514cb2b9..9bb2b46cef 100644--- a/package.json+++ b/package.json@@ -54,7 +54,7 @@"player:perf": "bun run --filter @hyperframes/player perf","format:check": "oxfmt --check .","knip": "knip",- "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/ci/base-file.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",+ "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/ci/base-file.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts","typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json","test:skills": "HYPERFRAMES_MEDIA_HOME_REQUIRED=1 node --import ./packages/cli/scripts/test-home.mjs --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'","generate:previews": "tsx scripts/generate-template-previews.ts",diff --git a/registry/components/echo-smear/README.md b/registry/components/echo-smear/README.mdnew file mode 100644index 0000000000..2f9cf57dad--- /dev/null+++ b/registry/components/echo-smear/README.md@@ -0,0 +1,27 @@+# echo-smear++A streak that follows speed. As an element moves faster, more time-offset copies of it trail behind;+when it slows below a threshold they vanish. It is After Effects' Echo effect (Maximum operator) with+the copy count and spacing driven by the element's own motion, so you animate the element and the smear+follows without keyframes of its own.++`attachEchoSmear(targets, timeline, options)` records each target's real trajectory (position, rotation,+scale, opacity) once, with a forward sweep of the timeline, then draws the copies from that record. The+frame at time `t` is the same however you reach it: seeking, scrubbing and parallel render workers agree.++## Mounting++Paste `echo-smear.html` into the composition, define every tween, then attach before registering the+timeline:++```js+attachEchoSmear(".card", tl, { length: 100, threshold: 40 });+```++Targets are anything GSAP moves with a transform (not an element inside an `<svg>`; attach to the+`<svg>`). The header comment in the snippet documents every option and the limits.++## Demo++`demo.html` shows a logo skimming under a word and kicking each letter up, then spiralling away. Letters+and logo both smear, and the spiral shows the streak following a curve.diff --git a/registry/components/echo-smear/demo.html b/registry/components/echo-smear/demo.htmlnew file mode 100644index 0000000000..053f7a25eb--- /dev/null+++ b/registry/components/echo-smear/demo.html@@ -0,0 +1,850 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=1920, height=1080" />+ <title>Echo Smear — Demo</title>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }+ html,+ body {+ width: 1920px;+ height: 1080px;+ overflow: hidden;+ background: #0b0c10;+ }+ #es-root {+ position: relative;+ width: 1920px;+ height: 1080px;+ overflow: hidden;+ background: #0b0c10;+ }+ #es-word {+ position: absolute;+ left: 0;+ top: 0;+ width: 1920px;+ height: 640px;+ }+ /* Targets are absolutely positioned and styled by class: the copies drop ids. */+ .es-letter {+ position: absolute;+ display: block;+ overflow: visible;+ }+ .es-logo {+ position: absolute;+ left: 0;+ top: 0;+ overflow: visible;+ }+ </style>+ </head>+ <body>+ <div+ id="es-root"+ data-composition-id="echo-smear-demo"+ data-width="1920"+ data-height="1080"+ data-fps="24"+ data-start="0"+ data-duration="5"+ >+ <div id="es-word"></div>+ </div>+ <script>+ (function () {+ function resolveFps(root, opts) {+ var cfg = window.__HF_EXPORT_RENDER_SEEK_CONFIG;+ var fps =+ Number(opts.fps) ||+ (cfg && Number(cfg.fps)) ||+ Number(root && root.getAttribute("data-fps")) ||+ 30;+ return fps > 0 ? fps : 30;+ }++ function lerpTrack(track, step, t, out) {+ var f = Math.max(0, Math.min(track.length - 1, t / step));+ var i = Math.floor(f),+ j = Math.min(track.length - 1, i + 1),+ u = f - i;+ var a = track[i],+ b = track[j];+ for (var k = 0; k < a.length; k++) out[k] = a[k] + (b[k] - a[k]) * u;+ return out;+ }++ // Echo count for one frame: AE's formula (the half-frame travel of the measured point, gated by+ // threshold/2), then raised so the element's farthest point moves at most edgeSpacing px between+ // copies, then capped. The raise never turns a smear on; edgeSpacing 0 gives AE's exact count.+ function count(move, extent, o) {+ var n = move > o.threshold / 2 ? Math.round(move * (o.length / 100) * o.countMult) : 0;+ if (n > 0 && o.edgeSpacing > 0) n = Math.max(n, Math.ceil(extent / o.edgeSpacing));+ return Math.min(n, o.maxEchoes);+ }++ var IDENTITY = [1, 0, 0, 1, 0, 0];++ // A computed `transform` as [a, b, c, d, e, f]: "none" is the identity; a matrix3d (or anything+ // else) is null, because it has no 2D matrix.+ function parseMatrix(css) {+ if (!css || css === "none") return IDENTITY.slice();+ var m = /^matrix\(([^)]+)\)$/.exec(css);+ if (!m) return null;+ var v = m[1].split(",").map(parseFloat);+ return v.length === 6 && v.every(isFinite) ? v : null;+ }++ // The 2D part of any computed transform, and whether it is exactly 2D. A matrix3d keeps its own string+ // for the copies; its x/y/scale/turn part (m11 m12 m21 m22 m41 m42) is what travel and extent read.+ function matrixOf(css) {+ var flat = parseMatrix(css);+ if (flat) return { m: flat, flat: true };+ var d = /^matrix3d\(([^)]+)\)$/.exec(css || "");+ if (!d) return { m: IDENTITY.slice(), flat: true };+ var v = d[1].split(",").map(parseFloat);+ return { m: [v[0], v[1], v[4], v[5], v[12], v[13]], flat: false };+ }++ function multiply(a, b) {+ return [+ a[0] * b[0] + a[2] * b[1],+ a[1] * b[0] + a[3] * b[1],+ a[0] * b[2] + a[2] * b[3],+ a[1] * b[2] + a[3] * b[3],+ a[0] * b[4] + a[2] * b[5] + a[4],+ a[1] * b[4] + a[3] * b[5] + a[5],+ ];+ }++ // A computed length or percentage as CSS px: a percentage is a share of `reference` (the element's own+ // box: its width for x, its height for y), a bare number or px is itself, anything else is 0.+ function lengthPx(value, reference) {+ var n = parseFloat(value);+ if (!isFinite(n)) return 0;+ return /%$/.test(value) ? (n * reference) / 100 : n;+ }++ // The individual CSS properties `translate`, `rotate` and `scale` apply before `transform`, about the same+ // origin, as translate · rotate · scale. GSAP can drive them, and the browser leaves `transform` as+ // `none` when it does. 2D only: a rotation about an axis, or a third component, is left out. `box` is+ // [width, height] in CSS px, which a percentage translate is a share of.+ function individualMatrix(translate, rotate, scale, box) {+ box = box || [0, 0];+ var m = IDENTITY.slice();+ if (translate && translate !== "none") {+ var t = translate.split(" ");+ m = multiply(m, [1, 0, 0, 1, lengthPx(t[0], box[0]), lengthPx(t[1], box[1])]);+ }+ var r = rotate && /^(-?[\d.e+-]+)(deg|rad|turn|grad)$/.exec(rotate);+ if (r) {+ var unit = { deg: Math.PI / 180, rad: 1, turn: 2 * Math.PI, grad: Math.PI / 200 }[r[2]];+ var q = parseFloat(r[1]) * unit;+ m = multiply(m, [Math.cos(q), Math.sin(q), -Math.sin(q), Math.cos(q), 0, 0]);+ }+ if (scale && scale !== "none") {+ var k = scale.split(" ").map(function (part) {+ var n = parseFloat(part);+ return /%$/.test(part) ? n / 100 : n;+ });+ var kx = isFinite(k[0]) ? k[0] : 1;+ m = multiply(m, [kx, 0, 0, isFinite(k[1]) ? k[1] : kx, 0, 0]);+ }+ return m;+ }++ // A point of the element's box, given as fractions of it, after its transform: the transform turns and+ // scales about `origin` (CSS px from the box's top-left), then translates. AE measures a layer's origin,+ // so a spinning layer registers travel; a box fraction lets a spin or squash count as motion.+ function boxPoint(m, box, origin, fx, fy) {+ var dx = fx * box[0] - origin[0],+ dy = fy * box[1] - origin[1];+ return [+ origin[0] + m[0] * dx + m[2] * dy + m[4],+ origin[1] + m[1] * dx + m[3] * dy + m[5],+ ];+ }++ // How far the farthest corner of the box moves between two poses: what the copies have to cover.+ var CORNERS = [+ [0, 0],+ [1, 0],+ [0, 1],+ [1, 1],+ ];+ function cornerShift(ma, mb, box, origin) {+ var worst = 0;+ for (var k = 0; k < 4; k++) {+ var p = boxPoint(ma, box, origin, CORNERS[k][0], CORNERS[k][1]);+ var q = boxPoint(mb, box, origin, CORNERS[k][0], CORNERS[k][1]);+ worst = Math.max(worst, Math.hypot(p[0] - q[0], p[1] - q[1]));+ }+ return worst;+ }++ // An element's box in CSS px. SVG elements have no offsetWidth: fall back to the width/height+ // attributes, then the computed size.+ function boxOf(el) {+ var cs = getComputedStyle(el);+ return [+ el.offsetWidth || parseFloat(el.getAttribute("width")) || parseFloat(cs.width) || 0,+ el.offsetHeight || parseFloat(el.getAttribute("height")) || parseFloat(cs.height) || 0,+ ];+ }++ function originOf(el, box) {+ var o = getComputedStyle(el).transformOrigin.split(" ").map(parseFloat);+ return o.length >= 2 && isFinite(o[0]) && isFinite(o[1])+ ? [o[0], o[1]]+ : [box[0] / 2, box[1] / 2];+ }++ window.__echoSmear = {+ count: count,+ lerpTrack: lerpTrack,+ parseMatrix: parseMatrix,+ individualMatrix: individualMatrix,+ boxPoint: boxPoint,+ };++ window.attachEchoSmear = function (selector, tl, opts) {+ opts = opts || {};+ var length = opts.length != null ? opts.length : 100;+ var threshold = opts.threshold != null ? opts.threshold : 40;+ var countMult = opts.countMult != null ? opts.countMult : 1;+ var maxEchoes = opts.maxEchoes != null ? opts.maxEchoes : 60;++ var targets = [];+ (Array.isArray(selector) ? selector : [selector]).forEach(function (s) {+ if (typeof s === "string") targets.push.apply(targets, document.querySelectorAll(s));+ else if (s instanceof Element) targets.push(s);+ });+ // One group per element, and never one around a copy: a selector that also matches an earlier call's+ // copies (they keep the target's classes) must not turn them into targets.+ if (!window._hfEsAttached) window._hfEsAttached = new WeakSet();+ targets = targets.filter(function (el, i) {+ return (+ targets.indexOf(el) === i && // named twice in this call+ !window._hfEsAttached.has(el) &&+ !el.closest("[data-hf-echo-group]")+ );+ });+ // The copies' group is an HTML element: inside an <svg> it would render nothing.+ targets = targets.filter(function (el) {+ if (!el.ownerSVGElement) return true;+ console.warn(+ "echo-smear: " ++ (el.id || el.tagName) ++ " is inside an <svg>; attach to the <svg> itself. Skipped.",+ );+ return false;+ });+ if (!targets.length) return;+ var fd = 1 / resolveFps(targets[0].closest("[data-composition-id]"), opts);+ // Sample densely enough that sub-frame curves stay curves (AE evaluates each echo time exactly).+ var step = fd / (opts.subframes || 8);+ var mp = opts.measurePoint || [0.5, 0.5];+ // AE's count only follows the origin's travel, so a spinning or scaling layer's outer edge leaves+ // visible steps between copies. edgeSpacing (px) raises the count until the farthest point of the+ // element moves at most that far between copies. Set 0 for AE's exact count.+ var edgeSpacing = opts.edgeSpacing != null ? opts.edgeSpacing : 1.5;+ // The sweep seeks without events: a composition's callbacks (audio cues, counters, other effects)+ // would otherwise fire thousands of times at attach. Motion that is written FROM a callback (an+ // onUpdate that sets a transform) is only recorded with callbacks: true.+ var quiet = !opts.callbacks;++ // Bake: one forward sweep, the resolved transform and opacity per target at every sample, plus+ // the measured point. All of it is local to the element's own box, so motion that comes only from+ // an ancestor is not this element's (attach to the ancestor).+ var saved = tl.time();+ var dur = tl.duration();+ var samples = Math.ceil(dur / step) + 2;+ var boxes = targets.map(boxOf);+ var origins = targets.map(function (el, ti) {+ return originOf(el, boxes[ti]);+ });+ var poses = targets.map(function () {+ return [];+ });+ var centres = targets.map(function () {+ return [];+ });+ var matrix3d = targets.map(function () {+ return [];+ });+ // What else the timeline can write that a copy must show as it was: not interpolated, so each copy+ // takes the nearest sample.+ var LOOKS = ["filter", "clipPath", "transformOrigin"];+ var looks = targets.map(function () {+ return [];+ });+ // Everything a copy needs besides its pose is recorded in the sweep too, so a frame never depends+ // on reading the target while it may not have rendered that time yet (a backward seek renders the+ // snippet's own update tween before the target's): the group's visibility and the target's box.+ var showing = targets.map(function () {+ return [];+ });+ var boxAt = targets.map(function () {+ return [];+ });+ var hosts = targets.map(function (el) {+ return el.parentElement || (el.getRootNode && el.getRootNode().host) || null;+ });+ var api = window.__echoSmear;+ api.baking = (api.baking || 0) + 1; // other attached smears skip their update while this one records+ try {+ for (var s = 0; s < samples; s++) {+ tl.time(Math.min(s * step, dur), quiet);+ for (var ti = 0; ti < targets.length; ti++) {+ var cs = getComputedStyle(targets[ti]);+ var resolved = matrixOf(cs.transform);+ if (resolved.flat) {+ resolved.m = multiply(+ individualMatrix(cs.translate, cs.rotate, cs.scale, boxes[ti]),+ resolved.m,+ );+ }+ var opacity = parseFloat(cs.opacity);+ poses[ti].push(resolved.m.concat([isFinite(opacity) ? opacity : 1]));+ matrix3d[ti].push(resolved.flat ? null : cs.transform);+ looks[ti].push(+ LOOKS.map(function (k) {+ return cs[k] || "";+ }),+ );+ centres[ti].push(boxPoint(resolved.m, boxes[ti], origins[ti], mp[0], mp[1]));+ // Set only where the target differs from its parent: an explicit value would outlive an+ // ancestor that hides later, like a clip that has ended.+ var parentSees = hosts[ti] ? getComputedStyle(hosts[ti]).visibility : "visible";+ showing[ti].push(cs.visibility === parentSees ? "" : cs.visibility);+ // An <svg> root has no offset box: its copies keep the left/top/size they were cloned with.+ var el0 = targets[ti];+ boxAt[ti].push(+ el0.offsetLeft === undefined+ ? null+ : [+ el0.offsetLeft + "px",+ el0.offsetTop + "px",+ el0.offsetWidth + "px",+ el0.offsetHeight + "px",+ ],+ );+ }+ }+ } finally {+ api.baking--;+ tl.time(saved, quiet);+ }++ var MEDIA = "video,audio,iframe";++ // A copy loses the `#id` rules that styled the original, so it carries the target's resolved style.+ // Every copy of a target shares ONE class per element (a rule written once), instead of an inline+ // style per copy: hundreds of copies would otherwise each parse a few hundred declarations.+ // Visibility is not frozen: the group follows the target, so a target hidden at attach still smears.+ function resolvedStyles(source, out, parentVisibility) {+ var cs = getComputedStyle(source);+ var text = "";+ for (var i = 0; i < cs.length; i++) {+ var value = cs.getPropertyValue(cs[i]);+ var inherited = parentVisibility === undefined || value === parentVisibility;+ if (cs[i] === "visibility" && inherited) continue;+ text += cs[i] + ":" + value + ";";+ }+ // A copy is a still of one instant: a live transition or animation would carry it somewhere+ // the timeline never sampled.+ out.push(text + "transition:none;animation:none;");+ // The copy holds an empty box where media was, so the media's own children have no counterpart.+ if (source.matches && source.matches(MEDIA)) return out;+ for (var c = 0; c < source.children.length; c++) {+ resolvedStyles(source.children[c], out, cs.getPropertyValue("visibility"));+ }+ return out;+ }++ // One rule per element of the target's subtree, kept as text nodes. They go in the target's own+ // root: a shadow root is its own style scope, and the document's rules do not reach into it.+ function sheetFor(el) {+ var root = el.getRootNode ? el.getRootNode() : document;+ var scope = root.nodeType === 11 ? root : document.head || document.documentElement;+ var found = scope.querySelector && scope.querySelector("style#hf-es-styles");+ if (found) return found;+ var made = document.createElement("style");+ made.id = "hf-es-styles";+ scope.appendChild(made);+ return made;+ }+ function writeRules(sheet, rules, texts, tag) {+ for (var r = 0; r < texts.length; r++) {+ var css = "." + tag + "-" + r + "{" + texts[r] + "}";+ if (rules[r]) rules[r].data = css;+ else sheet.appendChild((rules[r] = document.createTextNode(css)));+ }+ }+ function classCopies(copy, tag, cursor) {+ copy.setAttribute("class", tag + "-" + cursor.i++);+ for (var c = 0; c < copy.children.length; c++)+ classCopies(copy.children[c], tag, cursor);+ }++ // Copies are stills, and the runtime does not manage media it did not mark: a live copy would show+ // a frozen frame and fetch its source again. A box of the same size stands in for it.+ function inertMedia(source, copy) {+ var from = source.querySelectorAll(MEDIA);+ var to = copy.querySelectorAll(MEDIA);+ for (var m = 0; m < to.length; m++) {+ var stand = document.createElement("div");+ stand.style.cssText =+ "display:inline-block;width:" ++ (from[m].offsetWidth || 0) ++ "px;height:" ++ (from[m].offsetHeight || 0) ++ "px;";+ to[m].parentNode.replaceChild(stand, to[m]);+ }+ }++ var maximum = opts.operator !== "normal";+ var cfg = {+ threshold: threshold,+ length: length,+ countMult: countMult,+ maxEchoes: maxEchoes,+ edgeSpacing: edgeSpacing,+ };+ var pa = [0, 0, 0, 0, 0, 0, 1],+ pb = [0, 0, 0, 0, 0, 0, 1],+ p0 = [0, 0],+ p1 = [0, 0];+ // The copy count for one target at time t.+ function countAt(st, t) {+ lerpTrack(st.centres, step, t, p0);+ lerpTrack(st.centres, step, t - fd / 2, p1);+ var move = Math.hypot(p0[0] - p1[0], p0[1] - p1[1]);+ var extent = 0;+ if (edgeSpacing > 0) {+ lerpTrack(st.poses, step, t, pa);+ lerpTrack(st.poses, step, t - fd * (length / 100), pb);+ extent = cornerShift(pa, pb, st.box, st.origin);+ }+ return count(move, extent, cfg);+ }++ if (!window._hfEsUid) window._hfEsUid = 0;+ var state = [];+ targets.forEach(function (el, ti) {+ window._hfEsAttached.add(el);+ var st = {+ el: el,+ poses: poses[ti],+ centres: centres[ti],+ matrix3d: matrix3d[ti],+ looks: looks[ti],+ showing: showing[ti],+ boxAt: boxAt[ti],+ box: boxes[ti],+ origin: origins[ti],+ };+ // The recording already holds the whole trajectory, so the most copies this target ever shows is+ // known now: build that many, not maxEchoes. A target that never smears gets nothing.+ var peak = 0;+ for (var t = 0; t <= dur; t += step) peak = Math.max(peak, countAt(st, t));+ if (peak === 0) return;++ // The copies sit in a zero-size group just before the target, so the target itself is untouched:+ // it keeps its parent, its blend mode and its pointer events. Isolated, so the lighten between+ // copies never mixes with the background.+ var group = document.createElement("div");+ group.setAttribute("data-hf-echo-group", "");+ group.style.cssText =+ "position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;";+ // The group is what the siblings stack against, so it takes the target's z-index.+ var z = getComputedStyle(el).zIndex;+ if (z && z !== "auto") group.style.zIndex = z;++ var tag = "hf-es" + window._hfEsUid++;+ var rules = [];+ var sheet = sheetFor(el);+ // A copy is a grandchild of its parent, and perspective reaches children only: each copy carries+ // the parent's perspective in its own transform (the vanishing point is then the copy's own).+ var host = el.parentElement || (el.getRootNode && el.getRootNode().host) || null;+ var persp = host ? getComputedStyle(host).perspective : "none";+ st.perspective = persp && persp !== "none" ? "perspective(" + persp + ") " : "";+ function snapshot() {+ // A target hidden right now (an autoAlpha entrance) is read as shown, so the copies' own+ // resolved style is not a hidden one; the inline value goes back exactly.+ var hidden = getComputedStyle(el).visibility !== "visible";+ var inline = el.style.getPropertyValue("visibility");+ var priority = el.style.getPropertyPriority("visibility");+ if (hidden) el.style.setProperty("visibility", "visible", "important");+ try {+ writeRules(sheet, rules, resolvedStyles(el, []), tag);+ } finally {+ if (hidden) el.style.setProperty("visibility", inline, priority);+ }+ }+ snapshot();++ var clones = [];+ for (var i = 0; i < peak; i++) {+ var c = el.cloneNode(true);+ c.removeAttribute("id");+ [c]+ .concat(+ Array.prototype.slice.call(+ c.querySelectorAll("[data-start],[data-duration],[data-track-index]"),+ ),+ )+ .forEach(function (n) {+ n.removeAttribute("data-start");+ n.removeAttribute("data-duration");+ n.removeAttribute("data-track-index");+ });+ c.querySelectorAll("[id]").forEach(function (n) {+ n.removeAttribute("id");+ });+ c.setAttribute("aria-hidden", "true");+ inertMedia(el, c);+ classCopies(c, tag, { i: 0 });+ c.classList.add("es-clone");+ c.style.position = "absolute";+ c.style.margin = "0";+ // The copy is sized to the target's offset box, which includes padding and border.+ c.style.boxSizing = "border-box";+ // translate, rotate and scale are folded into the copy's transform: left on, they would apply twice.+ c.style.translate = "none";+ c.style.rotate = "none";+ c.style.scale = "none";+ c.style.mixBlendMode = maximum ? "lighten" : "normal";+ c.style.visibility = "hidden";+ clones.push(c);+ }+ // Nearest copy on top: the first copy is the last child.+ for (var k = clones.length - 1; k >= 0; k--) group.appendChild(clones[k]);+ el.parentNode.insertBefore(group, el);+ st.group = group;+ st.clones = clones;+ st.host = host;+ state.push(st);+ });++ var pose = [0, 0, 0, 0, 0, 0, 1];+ function render() {+ if (window.__echoSmear.baking) return;+ var t = tl.time();+ state.forEach(function (st) {+ var n = countAt(st, t);+ // The target's visibility and box at this time, from the recording.+ var now = Math.max(0, Math.min(st.poses.length - 1, Math.round(t / step)));+ var view = { box: st.boxAt[now] };+ // The group follows the target's own visibility.+ if (st.group.style.visibility !== st.showing[now])+ st.group.style.visibility = st.showing[now];+ var boxKey = view.box ? view.box.join() : "";+ for (var i = 0; i < st.clones.length; i++) {+ var c = st.clones[i];+ if (i >= n) {+ if (c.style.visibility !== "hidden") c.style.visibility = "hidden";+ continue;+ }+ var back = t - ((i + 1) * fd * (length / 100)) / n;+ lerpTrack(st.poses, step, back, pose);+ // The copy sits on the target's own box, so the box follows it: a beat is free to move or+ // resize it. Written when a copy last saw a different box: a copy hidden while the box+ // changed must catch up when it is shown, so the key is per copy, not per target.+ if (view.box && c._esBox !== boxKey) {+ c._esBox = boxKey;+ c.style.left = view.box[0];+ c.style.top = view.box[1];+ c.style.width = view.box[2];+ c.style.height = view.box[3];+ }+ var near = Math.max(0, Math.min(st.poses.length - 1, Math.round(back / step)));+ c.style.transform =+ st.perspective ++ (st.matrix3d[near] || "matrix(" + pose.slice(0, 6).join(",") + ")");+ var look = st.looks[near];+ if (c._esLook !== look) {+ c._esLook = look;+ for (var k = 0; k < LOOKS.length; k++) if (look[k]) c.style[LOOKS[k]] = look[k];+ }+ c.style.opacity = pose[6];+ c.style.visibility = "inherit";+ }+ });+ }+ // Runtime proxies the timeline, so hook updates with a full-length tween (see registry motion-blur).+ tl.to(+ { v: 0 },+ { v: 1, duration: Math.max(dur, 0.1), ease: "none", onUpdate: render },+ 0,+ );+ render();+ };+ })();+ </script>+ <script>+ /*+ Demo: a logo skims along under a word, kicks each letter up in turn, then sweeps into a spiral and+ settles. Letters and logo both carry the echo smear: a short streak on a slow tap, a long curved one+ on the spiral. Every motion is a formula (a parabola per letter, a spiral for the exit), so nothing+ here depends on hand-keyed tables.++ Beats (24 fps, 5 s)+ f0-3 letters hidden, logo off screen+ f4-18 logo swoops in low and slides under the first letter+ f18-82 one letter every 5 frames: the logo slips under it, pushes it up, the letter appears and flies a parabola+ and lands on the baseline (each letter in the air for 14 frames)+ f70-102 the logo leaves the last letter, spirals 1.6 turns around a point above the word and comes+ to rest after the last letter+ f102-120 hold+ */+ (function () {+ var WORD = [+ "M0 71.9996V42.7256H7.7367V53.1806H17.9826V42.7256H25.7193V71.9996H17.9826V59.8718H7.7367V71.9996H0Z",+ "M31.9606 78.4405L36.0171 69.5329L26.9004 48.5811H35.1389L40.0737 60.6252L44.9666 48.5811H52.5779L39.8646 78.4405H31.9606Z",+ "M53.3711 78.4404V48.5809H60.9823V52.052C62.446 49.501 65.0807 48.0791 68.3008 48.0791C74.3647 48.0791 78.9649 53.3066 78.9649 60.2487C78.9649 67.2745 74.3229 72.4602 68.259 72.4602C65.0807 72.4602 62.446 71.1637 60.9823 68.78V78.4404H53.3711ZM66.1262 66.1872C69.2627 66.1872 71.3119 63.7616 71.3119 60.2905C71.3119 56.8195 69.2627 54.4357 66.1262 54.4357C62.7388 54.4357 60.9823 57.2795 60.9823 59.7051V60.9178C60.9823 63.3434 62.7388 66.1872 66.1262 66.1872Z",+ "M93.4397 72.6269C85.4939 72.6269 80.2246 67.5667 80.2246 60.4155C80.2246 53.2643 85.4521 47.9531 92.5615 47.9531C99.1273 47.9531 103.686 52.7206 103.686 59.7045C103.686 60.7082 103.56 61.6701 103.518 62.4647H87.5849C88.2541 65.2666 90.7214 66.8139 94.6525 66.8139C97.1199 66.8139 99.4618 66.1866 101.135 65.0993V70.7868C99.3782 71.916 96.4508 72.6269 93.4397 72.6269ZM87.5849 57.5717H96.869C96.7435 54.9789 95.0289 53.4734 92.4779 53.4734C89.9687 53.4734 88.1286 54.9789 87.5849 57.5717Z",+ "M105.645 72V48.5808H113.214V52.9719C114.218 50.0445 116.183 48.2881 118.692 48.2881C119.361 48.2881 119.989 48.4135 120.407 48.6645V55.8993C119.822 55.5648 119.111 55.4393 118.274 55.4393C115.138 55.4393 113.256 57.6558 113.256 61.2941V72H105.645Z",+ "M122.643 71.9996V42.7256H139.371V49.124H130.379V54.477H138.911V60.5827H130.379V71.9996H122.643Z",+ "M141.258 72V48.5808H148.827V52.9719C149.831 50.0445 151.796 48.2881 154.306 48.2881C154.975 48.2881 155.602 48.4135 156.02 48.6645V55.8993C155.435 55.5648 154.724 55.4393 153.887 55.4393C150.751 55.4393 148.869 57.6558 148.869 61.2941V72H141.258Z",+ "M167.26 72.4602C161.154 72.4602 156.596 67.2745 156.596 60.3324C156.596 53.3066 161.196 48.0791 167.302 48.0791C170.438 48.0791 173.031 49.4173 174.536 51.8429V48.5809H182.148V72.0001H174.536V68.4873C173.031 71.0801 170.438 72.4602 167.26 72.4602ZM169.393 66.1872C172.78 66.1872 174.536 63.3434 174.536 60.876V59.6632C174.536 57.2377 172.78 54.4357 169.393 54.4357C166.298 54.4357 164.207 56.7777 164.207 60.2905C164.207 63.7616 166.298 66.1872 169.393 66.1872Z",+ "M184.998 72.0001V48.5809H192.609V51.6756C193.989 49.4173 196.373 48.0791 199.426 48.0791C202.521 48.0791 204.779 49.5428 206.075 52.052C207.497 49.5846 210.132 48.0791 213.352 48.0791C218.245 48.0791 221.214 51.592 221.214 57.0286V72.0001H213.603V58.5341C213.603 55.774 212.557 54.4357 210.634 54.4357C208.459 54.4357 206.912 56.234 206.912 59.0778V72.0001H199.3V58.5341C199.3 55.774 198.255 54.4357 196.373 54.4357C194.157 54.4357 192.609 56.234 192.609 59.0778V72.0001H184.998Z",+ "M236.338 72.6269C228.392 72.6269 223.123 67.5667 223.123 60.4155C223.123 53.2643 228.351 47.9531 235.46 47.9531C242.026 47.9531 246.584 52.7206 246.584 59.7045C246.584 60.7082 246.459 61.6701 246.417 62.4647H230.483C231.152 65.2666 233.62 66.8139 237.551 66.8139C240.018 66.8139 242.36 66.1866 244.033 65.0993V70.7868C242.277 71.916 239.349 72.6269 236.338 72.6269ZM230.483 57.5717H239.767C239.642 54.9789 237.927 53.4734 235.376 53.4734C232.867 53.4734 231.027 54.9789 230.483 57.5717Z",+ "M252.115 72.502C250.192 72.502 248.268 72.0838 246.93 71.3728V65.6853C247.808 66.3126 248.937 66.689 250.066 66.689C251.739 66.689 252.784 65.8526 252.784 64.5562C252.784 63.8452 252.492 63.0925 251.655 62.0888L249.899 59.956C248.728 58.4923 248.226 56.9031 248.226 55.2721C248.226 51.0065 251.864 48.0791 256.883 48.0791C258.723 48.0791 260.438 48.4555 261.65 49.0828V54.7703C260.898 54.2266 259.768 53.8503 258.723 53.8503C257.092 53.8503 256.046 54.6867 256.046 55.8994C256.046 56.6522 256.423 57.405 257.259 58.4086L258.974 60.4996C260.187 62.047 260.73 63.5943 260.73 65.2671C260.73 69.5746 257.05 72.502 252.115 72.502Z",+ ];+ var SYM = [+ "M195.219 26.1937L213.529 38.9937C216.009 40.7237 220.239 38.7637 221.009 35.5337L228.419 4.33374C229.189 1.10374 225.879 -0.856262 222.589 0.873738L198.199 13.6737C192.649 16.5837 191.059 23.2837 195.219 26.1937Z",+ "M256.97 25.9638L232.58 38.7638C229.28 40.4938 225.98 38.5338 226.75 35.3038L234.16 4.10376C234.93 0.873757 239.16 -1.08624 241.64 0.643757L259.95 13.4438C264.12 16.3538 262.52 23.0538 256.97 25.9638Z",+ ];+ var F = 1 / 24,+ NS = "http://www.w3.org/2000/svg";+ var S = 3.4,+ BASE_UNIT = 72,+ BASE_Y = 600,+ CX = 960; // wordmark scale, baseline row (logo units), baseline y, centre x+ var K0 = 18,+ GAP = 5,+ AIR = 14,+ LOGO_W = 88;+ var word = document.getElementById("es-word"),+ root = document.getElementById("es-root");++ function catmull(a, b, c, d, t) {+ var t2 = t * t,+ t3 = t2 * t;+ return (+ 0.5 *+ (2 * b + (c - a) * t + (2 * a - 5 * b + 4 * c - d) * t2 + (3 * b - a - 3 * c + d) * t3)+ );+ }+ // keys: [[frame, v1, ...]], played as a spline on tl; apply(values) writes them to the element.+ function track(tl, keys, apply) {+ var st = { u: 0 },+ n = keys.length,+ vals = [];+ function upd() {+ var i = Math.min(n - 2, Math.floor(st.u)),+ t = st.u - i;+ var a = keys[Math.max(0, i - 1)],+ b = keys[i],+ c = keys[i + 1],+ d = keys[Math.min(n - 1, i + 2)];+ for (var k = 1; k < b.length; k++) vals[k - 1] = catmull(a[k], b[k], c[k], d[k], t);+ apply(vals);+ }+ for (var j = 1; j < n; j++) {+ tl.to(+ st,+ { u: j, duration: (keys[j][0] - keys[j - 1][0]) * F, ease: "none", onUpdate: upd },+ keys[j - 1][0] * F,+ );+ }+ // Rewinding replays the first key, so it must equal the element's rest state at frame 0.+ if (keys[0][0] === 0) upd();+ }+ function svgOf(paths, cls) {+ var s = document.createElementNS(NS, "svg");+ s.setAttribute("class", cls);+ paths.forEach(function (d) {+ var p = document.createElementNS(NS, "path");+ p.setAttribute("d", d);+ p.setAttribute("fill", "#ffffff");+ s.appendChild(p);+ });+ return s;+ }++ // Measure each glyph in the logo's own units, then lay the word out centred at scale S.+ var probe = svgOf(WORD, "es-letter");+ probe.setAttribute("width", "300");+ probe.setAttribute("height", "100");+ probe.style.left = "-999px";+ document.body.appendChild(probe);+ var boxes = Array.prototype.map.call(probe.querySelectorAll("path"), function (p) {+ var b = p.getBBox();+ return { x: b.x, y: b.y, w: b.width, h: b.height };+ });+ document.body.removeChild(probe);+ var x0 = Math.min.apply(+ null,+ boxes.map(function (b) {+ return b.x;+ }),+ );+ var x1 = Math.max.apply(+ null,+ boxes.map(function (b) {+ return b.x + b.w;+ }),+ );+ var left = CX - ((x1 - x0) * S) / 2,+ width = (x1 - x0) * S;+ var letters = boxes.map(function (b, i) {+ var s = svgOf([WORD[i]], "es-letter");+ s.setAttribute("viewBox", b.x + " " + b.y + " " + b.w + " " + b.h);+ s.setAttribute("width", b.w * S);+ s.setAttribute("height", b.h * S);+ s.style.left = left + (b.x - x0) * S + "px";+ s.style.top = BASE_Y - (BASE_UNIT - b.y) * S + "px";+ word.appendChild(s);+ return s;+ });+ var cx = boxes.map(function (b) {+ return left + (b.x - x0 + b.w / 2) * S;+ });++ // The logo: two arrowheads in their own gradients.+ var LS = LOGO_W / 62,+ LH = 41 * LS,+ R = LOGO_W / 2,+ logo = document.createElementNS(NS, "svg");+ logo.setAttribute("class", "es-logo");+ logo.setAttribute("viewBox", "195 0 62 41");+ logo.setAttribute("width", LOGO_W);+ logo.setAttribute("height", LH);+ logo.innerHTML =+ '<defs><linearGradient id="es-g0" x1="225.869" y1="0" x2="222.845" y2="37.4821" gradientUnits="userSpaceOnUse"><stop stop-color="#06E3FA"/><stop offset="1" stop-color="#4FDB5E"/></linearGradient>' ++ '<linearGradient id="es-g1" x1="230.87" y1="39" x2="244.661" y2="6.30303" gradientUnits="userSpaceOnUse"><stop stop-color="#06E3FA"/><stop offset="1" stop-color="#4FDB5E"/></linearGradient></defs>' ++ '<path d="' ++ SYM[0] ++ '" fill="url(#es-g0)"/><path d="' ++ SYM[1] ++ '" fill="url(#es-g1)"/>';+ root.appendChild(logo);++ var tl = gsap.timeline({ paused: true });+ gsap.set(logo, { x: -300, y: BASE_Y + 300, opacity: 0, rotation: 0 });++ // Each letter: hidden until its kick, then a parabola up from the baseline and back down onto it.+ // y(u) = -4h u(1-u): fastest at launch and landing (that is where it smears), peaks at h.+ var kick = letters.map(function (_, i) {+ return K0 + GAP * i;+ });+ letters.forEach(function (el, i) {+ var h = 230 + 70 * Math.sin(i * 1.7),+ dx = (i % 2 ? 1 : -1) * 34,+ tilt = (i % 2 ? 1 : -1) * (14 + 6 * Math.sin(i));+ var keys = [+ [0, 0, 0, 0],+ [kick[i] - 1, 0, 0, 0],+ ];+ for (var f = 0; f <= AIR; f++) {+ var u = f / AIR;+ keys.push([+ kick[i] + f,+ dx * Math.sin(Math.PI * u),+ -4 * h * u * (1 - u),+ tilt * Math.sin(Math.PI * u) * (1 - 0.4 * u),+ ]);+ }+ keys.push([kick[i] + AIR + 1, 0, 0, 0]);+ gsap.set(el, { opacity: 0 });+ tl.set(el, { opacity: 1 }, (kick[i] - 1) * F);+ track(tl, keys, function (v) {+ gsap.set(el, { x: v[0], y: v[1], rotation: v[2] });+ });+ });++ // Logo path: in low from the left, then under each letter in turn (touch, push up a little, drop away).+ var low = BASE_Y + 24,+ DOT = [+ [0, -300, BASE_Y + 300],+ [4, -160, BASE_Y + 220],+ [kick[0] - 6, cx[0] - 260, BASE_Y + 120],+ ];+ letters.forEach(function (_, i) {+ var k = kick[i];+ DOT.push([k - 2, cx[i] - 46, low + 30], [k, cx[i], low], [k + 2, cx[i] + 8, low - 56]);+ });+ // After the last kick: a spiral of 1.6 turns around a point above the word, ending after the last letter.+ var kL = kick[kick.length - 1],+ endX = left + width + 46 + R,+ endY = BASE_Y - LH / 2 - 4;+ var SW0 = kL + 4,+ SW1 = SW0 + 26,+ C = [endX + 40, endY - 330];+ var S0 = [cx[cx.length - 1] + 30, low],+ th0 = Math.atan2(S0[1] - C[1], S0[0] - C[0]),+ R0 = Math.hypot(S0[0] - C[0], S0[1] - C[1]);+ var th1 = Math.atan2(endY - C[1], endX - C[0]),+ R1 = Math.hypot(endX - C[0], endY - C[1]);+ var dth = th1 - th0 - 2 * Math.PI * 1.6;+ for (var f = SW0; f <= SW1; f++) {+ var u = (f - SW0) / (SW1 - SW0),+ e = u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2;+ var th = th0 + dth * e,+ rad = R0 + (R1 - R0) * e + 300 * Math.sin(Math.PI * Math.pow(u, 0.8)); // not R: that is the logo's radius+ DOT.push([f, C[0] + rad * Math.cos(th), C[1] + rad * Math.sin(th)]);+ }+ DOT.push([SW1 + 2, endX, endY], [SW1 + 4, endX, endY]);+ tl.set(logo, { opacity: 1 }, 4 * F);+ track(tl, DOT, function (v) {+ gsap.set(logo, { x: v[0] - R, y: v[1] - LH / 2 });+ });+ // The logo turns about twice on the spiral, then rests upright.+ track(+ tl,+ [+ [0, 0],+ [SW0 - 1, 0],+ [SW0 + 4, 130],+ [SW1 - 4, 560],+ [SW1, 720],+ [SW1 + 4, 720],+ ],+ function (v) {+ gsap.set(logo, { rotation: v[0] });+ },+ );+ tl.set({}, {}, 5);++ attachEchoSmear(letters, tl, {+ length: 100,+ threshold: 40,+ countMult: 1,+ maxEchoes: 160,+ measurePoint: [0, 0.85],+ callbacks: true,+ });+ attachEchoSmear(logo, tl, {+ length: 100,+ threshold: 40,+ countMult: 1,+ maxEchoes: 200,+ callbacks: true,+ });++ window.__timelines = window.__timelines || {};+ window.__timelines["echo-smear-demo"] = tl;+ })();+ </script>+ </body>+</html>diff --git a/registry/components/echo-smear/echo-smear.html b/registry/components/echo-smear/echo-smear.htmlnew file mode 100644index 0000000000..541bb1ba8e--- /dev/null+++ b/registry/components/echo-smear/echo-smear.html@@ -0,0 +1,607 @@+<!--+ Echo Smear — a distance-adaptive streak. The faster an element moves, the more time-offset copies trail+ behind it; below a speed threshold there are none. It is After Effects' Echo effect (Maximum operator)+ with its copy count and spacing driven by the layer's own speed.++ Usage: paste this snippet into your composition, then call attachEchoSmear() once, after every tween on+ the timeline is defined and before window.__timelines is registered.++ attachEchoSmear(targets, timeline, options?)++ targets a selector, an Element, or an array of either; anything GSAP (or CSS) moves with a transform. Each is+ attached once: a later call that names it, or one of its copies, adds nothing. An element inside an+ <svg> is skipped with a console warning: attach to the <svg> itself.+ Copies carry the element's resolved style (one shared class rule per element), so id-based CSS+ reaches them, but they drop the original's classes and its pseudo-elements. A copy shows the+ target's transform (with the individual translate, rotate and scale properties folded in),+ opacity, filter, clip-path and transform-origin as they were at its time; every other style, and+ anything on a child, is frozen at attach. The group's visibility and the box the copies sit on are+ also recorded from the timeline, not read live, so a frame never depends on the path taken to it.+ Media inside (video, audio, iframe) is replaced by an empty box of the same size.+ options length % of the last frame's travel the streak spans (default 100)+ threshold px of travel per frame before any smear shows (default 40)+ countMult multiplies the number of copies (default 1); raise it if you see stepping+ maxEchoes most copies per element per frame (default 60). Copies are built once, up to the most+ the element ever shows (known from the recording), and an element that never+ smears gets none; this is also the DOM cost+ measurePoint [x, y] as fractions of the element's box, the point whose travel is measured+ (default null = the box centre). Text uses [0, 0.85], near its baseline origin,+ so a spinning or squashing letter counts as moving+ edgeSpacing px (default 1.5). The count is raised until the element's farthest point moves at+ most this far between copies, so a spinning element's outer edge stays smooth.+ 0 gives After Effects' exact count, with visible steps on a spin+ subframes samples per frame when the motion is recorded (default 8)+ operator "maximum" (default): copies combine by per-pixel brightest value inside an+ isolated group, never with the background. "normal" stacks them+ fps frame rate (default: the render's, then the root's data-fps, then 30)+ callbacks false (default): the recording sweep seeks without events, so none of the timeline's+ callbacks (tl.call, onStart, onUpdate, other effects) fire during it. Set true only+ when an element's motion is WRITTEN by a callback (an onUpdate that sets a+ transform), which is otherwise not recorded++ Poses are read from the browser, not from GSAP: the element's resolved transform and opacity at every+ sample (8 per frame), so a percent shift (xPercent), a skew or a transform written any other way survives+ in the copies. Travel is measured on the element's own box: motion that comes only from an ancestor is not+ its own, so attach to the ancestor that moves. A 3D transform (matrix3d) is carried by the nearest sample+ instead of being interpolated.++ How the count works, per frame:+ travel = how far the measured point moved over the last half frame+ n = travel > threshold / 2 ? round(travel * length / 100 * countMult) : 0+ then, if edgeSpacing > 0, n is raised to cover the element's edge travel, and capped at maxEchoes.+ Copy i (1..n) shows the element as it was i * (frame * length / 100) / n seconds earlier.++ The output depends only on the timeline's time, never on how you got there: the motion is recorded once in+ attachEchoSmear (one forward sweep, then the timeline returns to where it was), so seeking, scrubbing and+ parallel render workers all give the same frame.++ Limits+ - Copies are the element's past pose, not a re-render: rotation, scale and opacity smear, but a change in+ the element's contents (a counter, a morph) does not.+ - The copies live in a zero-size group inserted just before the element; the element itself is not moved or+ restyled. The group is a new previous sibling, so sibling selectors (:first-child, +, ~) see it. It takes the+ target's z-index and its visibility, so it keeps its place in the stack.+ - Copies use mix-blend-mode, so a composition using this takes the screenshot capture path (not the+ drawElement fast path).+ - Cost grows with maxEchoes times the number of targets; keep both modest on long films.+-->++<script>+ (function () {+ function resolveFps(root, opts) {+ var cfg = window.__HF_EXPORT_RENDER_SEEK_CONFIG;+ var fps =+ Number(opts.fps) ||+ (cfg && Number(cfg.fps)) ||+ Number(root && root.getAttribute("data-fps")) ||+ 30;+ return fps > 0 ? fps : 30;+ }++ function lerpTrack(track, step, t, out) {+ var f = Math.max(0, Math.min(track.length - 1, t / step));+ var i = Math.floor(f),+ j = Math.min(track.length - 1, i + 1),+ u = f - i;+ var a = track[i],+ b = track[j];+ for (var k = 0; k < a.length; k++) out[k] = a[k] + (b[k] - a[k]) * u;+ return out;+ }++ // Echo count for one frame: AE's formula (the half-frame travel of the measured point, gated by+ // threshold/2), then raised so the element's farthest point moves at most edgeSpacing px between+ // copies, then capped. The raise never turns a smear on; edgeSpacing 0 gives AE's exact count.+ function count(move, extent, o) {+ var n = move > o.threshold / 2 ? Math.round(move * (o.length / 100) * o.countMult) : 0;+ if (n > 0 && o.edgeSpacing > 0) n = Math.max(n, Math.ceil(extent / o.edgeSpacing));+ return Math.min(n, o.maxEchoes);+ }++ var IDENTITY = [1, 0, 0, 1, 0, 0];++ // A computed `transform` as [a, b, c, d, e, f]: "none" is the identity; a matrix3d (or anything+ // else) is null, because it has no 2D matrix.+ function parseMatrix(css) {+ if (!css || css === "none") return IDENTITY.slice();+ var m = /^matrix\(([^)]+)\)$/.exec(css);+ if (!m) return null;+ var v = m[1].split(",").map(parseFloat);+ return v.length === 6 && v.every(isFinite) ? v : null;+ }++ // The 2D part of any computed transform, and whether it is exactly 2D. A matrix3d keeps its own string+ // for the copies; its x/y/scale/turn part (m11 m12 m21 m22 m41 m42) is what travel and extent read.+ function matrixOf(css) {+ var flat = parseMatrix(css);+ if (flat) return { m: flat, flat: true };+ var d = /^matrix3d\(([^)]+)\)$/.exec(css || "");+ if (!d) return { m: IDENTITY.slice(), flat: true };+ var v = d[1].split(",").map(parseFloat);+ return { m: [v[0], v[1], v[4], v[5], v[12], v[13]], flat: false };+ }++ function multiply(a, b) {+ return [+ a[0] * b[0] + a[2] * b[1],+ a[1] * b[0] + a[3] * b[1],+ a[0] * b[2] + a[2] * b[3],+ a[1] * b[2] + a[3] * b[3],+ a[0] * b[4] + a[2] * b[5] + a[4],+ a[1] * b[4] + a[3] * b[5] + a[5],+ ];+ }++ // A computed length or percentage as CSS px: a percentage is a share of `reference` (the element's own+ // box: its width for x, its height for y), a bare number or px is itself, anything else is 0.+ function lengthPx(value, reference) {+ var n = parseFloat(value);+ if (!isFinite(n)) return 0;+ return /%$/.test(value) ? (n * reference) / 100 : n;+ }++ // The individual CSS properties `translate`, `rotate` and `scale` apply before `transform`, about the same+ // origin, as translate · rotate · scale. GSAP can drive them, and the browser leaves `transform` as+ // `none` when it does. 2D only: a rotation about an axis, or a third component, is left out. `box` is+ // [width, height] in CSS px, which a percentage translate is a share of.+ function individualMatrix(translate, rotate, scale, box) {+ box = box || [0, 0];+ var m = IDENTITY.slice();+ if (translate && translate !== "none") {+ var t = translate.split(" ");+ m = multiply(m, [1, 0, 0, 1, lengthPx(t[0], box[0]), lengthPx(t[1], box[1])]);+ }+ var r = rotate && /^(-?[\d.e+-]+)(deg|rad|turn|grad)$/.exec(rotate);+ if (r) {+ var unit = { deg: Math.PI / 180, rad: 1, turn: 2 * Math.PI, grad: Math.PI / 200 }[r[2]];+ var q = parseFloat(r[1]) * unit;+ m = multiply(m, [Math.cos(q), Math.sin(q), -Math.sin(q), Math.cos(q), 0, 0]);+ }+ if (scale && scale !== "none") {+ var k = scale.split(" ").map(function (part) {+ var n = parseFloat(part);+ return /%$/.test(part) ? n / 100 : n;+ });+ var kx = isFinite(k[0]) ? k[0] : 1;+ m = multiply(m, [kx, 0, 0, isFinite(k[1]) ? k[1] : kx, 0, 0]);+ }+ return m;+ }++ // A point of the element's box, given as fractions of it, after its transform: the transform turns and+ // scales about `origin` (CSS px from the box's top-left), then translates. AE measures a layer's origin,+ // so a spinning layer registers travel; a box fraction lets a spin or squash count as motion.+ function boxPoint(m, box, origin, fx, fy) {+ var dx = fx * box[0] - origin[0],+ dy = fy * box[1] - origin[1];+ return [origin[0] + m[0] * dx + m[2] * dy + m[4], origin[1] + m[1] * dx + m[3] * dy + m[5]];+ }++ // How far the farthest corner of the box moves between two poses: what the copies have to cover.+ var CORNERS = [+ [0, 0],+ [1, 0],+ [0, 1],+ [1, 1],+ ];+ function cornerShift(ma, mb, box, origin) {+ var worst = 0;+ for (var k = 0; k < 4; k++) {+ var p = boxPoint(ma, box, origin, CORNERS[k][0], CORNERS[k][1]);+ var q = boxPoint(mb, box, origin, CORNERS[k][0], CORNERS[k][1]);+ worst = Math.max(worst, Math.hypot(p[0] - q[0], p[1] - q[1]));+ }+ return worst;+ }++ // An element's box in CSS px. SVG elements have no offsetWidth: fall back to the width/height+ // attributes, then the computed size.+ function boxOf(el) {+ var cs = getComputedStyle(el);+ return [+ el.offsetWidth || parseFloat(el.getAttribute("width")) || parseFloat(cs.width) || 0,+ el.offsetHeight || parseFloat(el.getAttribute("height")) || parseFloat(cs.height) || 0,+ ];+ }++ function originOf(el, box) {+ var o = getComputedStyle(el).transformOrigin.split(" ").map(parseFloat);+ return o.length >= 2 && isFinite(o[0]) && isFinite(o[1])+ ? [o[0], o[1]]+ : [box[0] / 2, box[1] / 2];+ }++ window.__echoSmear = {+ count: count,+ lerpTrack: lerpTrack,+ parseMatrix: parseMatrix,+ individualMatrix: individualMatrix,+ boxPoint: boxPoint,+ };++ window.attachEchoSmear = function (selector, tl, opts) {+ opts = opts || {};+ var length = opts.length != null ? opts.length : 100;+ var threshold = opts.threshold != null ? opts.threshold : 40;+ var countMult = opts.countMult != null ? opts.countMult : 1;+ var maxEchoes = opts.maxEchoes != null ? opts.maxEchoes : 60;++ var targets = [];+ (Array.isArray(selector) ? selector : [selector]).forEach(function (s) {+ if (typeof s === "string") targets.push.apply(targets, document.querySelectorAll(s));+ else if (s instanceof Element) targets.push(s);+ });+ // One group per element, and never one around a copy: a selector that also matches an earlier call's+ // copies (they keep the target's classes) must not turn them into targets.+ if (!window._hfEsAttached) window._hfEsAttached = new WeakSet();+ targets = targets.filter(function (el, i) {+ return (+ targets.indexOf(el) === i && // named twice in this call+ !window._hfEsAttached.has(el) &&+ !el.closest("[data-hf-echo-group]")+ );+ });+ // The copies' group is an HTML element: inside an <svg> it would render nothing.+ targets = targets.filter(function (el) {+ if (!el.ownerSVGElement) return true;+ console.warn(+ "echo-smear: " ++ (el.id || el.tagName) ++ " is inside an <svg>; attach to the <svg> itself. Skipped.",+ );+ return false;+ });+ if (!targets.length) return;+ var fd = 1 / resolveFps(targets[0].closest("[data-composition-id]"), opts);+ // Sample densely enough that sub-frame curves stay curves (AE evaluates each echo time exactly).+ var step = fd / (opts.subframes || 8);+ var mp = opts.measurePoint || [0.5, 0.5];+ // AE's count only follows the origin's travel, so a spinning or scaling layer's outer edge leaves+ // visible steps between copies. edgeSpacing (px) raises the count until the farthest point of the+ // element moves at most that far between copies. Set 0 for AE's exact count.+ var edgeSpacing = opts.edgeSpacing != null ? opts.edgeSpacing : 1.5;+ // The sweep seeks without events: a composition's callbacks (audio cues, counters, other effects)+ // would otherwise fire thousands of times at attach. Motion that is written FROM a callback (an+ // onUpdate that sets a transform) is only recorded with callbacks: true.+ var quiet = !opts.callbacks;++ // Bake: one forward sweep, the resolved transform and opacity per target at every sample, plus+ // the measured point. All of it is local to the element's own box, so motion that comes only from+ // an ancestor is not this element's (attach to the ancestor).+ var saved = tl.time();+ var dur = tl.duration();+ var samples = Math.ceil(dur / step) + 2;+ var boxes = targets.map(boxOf);+ var origins = targets.map(function (el, ti) {+ return originOf(el, boxes[ti]);+ });+ var poses = targets.map(function () {+ return [];+ });+ var centres = targets.map(function () {+ return [];+ });+ var matrix3d = targets.map(function () {+ return [];+ });+ // What else the timeline can write that a copy must show as it was: not interpolated, so each copy+ // takes the nearest sample.+ var LOOKS = ["filter", "clipPath", "transformOrigin"];+ var looks = targets.map(function () {+ return [];+ });+ // Everything a copy needs besides its pose is recorded in the sweep too, so a frame never depends+ // on reading the target while it may not have rendered that time yet (a backward seek renders the+ // snippet's own update tween before the target's): the group's visibility and the target's box.+ var showing = targets.map(function () {+ return [];+ });+ var boxAt = targets.map(function () {+ return [];+ });+ var hosts = targets.map(function (el) {+ return el.parentElement || (el.getRootNode && el.getRootNode().host) || null;+ });+ var api = window.__echoSmear;+ api.baking = (api.baking || 0) + 1; // other attached smears skip their update while this one records+ try {+ for (var s = 0; s < samples; s++) {+ tl.time(Math.min(s * step, dur), quiet);+ for (var ti = 0; ti < targets.length; ti++) {+ var cs = getComputedStyle(targets[ti]);+ var resolved = matrixOf(cs.transform);+ if (resolved.flat) {+ resolved.m = multiply(+ individualMatrix(cs.translate, cs.rotate, cs.scale, boxes[ti]),+ resolved.m,+ );+ }+ var opacity = parseFloat(cs.opacity);+ poses[ti].push(resolved.m.concat([isFinite(opacity) ? opacity : 1]));+ matrix3d[ti].push(resolved.flat ? null : cs.transform);+ looks[ti].push(+ LOOKS.map(function (k) {+ return cs[k] || "";+ }),+ );+ centres[ti].push(boxPoint(resolved.m, boxes[ti], origins[ti], mp[0], mp[1]));+ // Set only where the target differs from its parent: an explicit value would outlive an+ // ancestor that hides later, like a clip that has ended.+ var parentSees = hosts[ti] ? getComputedStyle(hosts[ti]).visibility : "visible";+ showing[ti].push(cs.visibility === parentSees ? "" : cs.visibility);+ // An <svg> root has no offset box: its copies keep the left/top/size they were cloned with.+ var el0 = targets[ti];+ boxAt[ti].push(+ el0.offsetLeft === undefined+ ? null+ : [+ el0.offsetLeft + "px",+ el0.offsetTop + "px",+ el0.offsetWidth + "px",+ el0.offsetHeight + "px",+ ],+ );+ }+ }+ } finally {+ api.baking--;+ tl.time(saved, quiet);+ }++ var MEDIA = "video,audio,iframe";++ // A copy loses the `#id` rules that styled the original, so it carries the target's resolved style.+ // Every copy of a target shares ONE class per element (a rule written once), instead of an inline+ // style per copy: hundreds of copies would otherwise each parse a few hundred declarations.+ // Visibility is not frozen: the group follows the target, so a target hidden at attach still smears.+ function resolvedStyles(source, out, parentVisibility) {+ var cs = getComputedStyle(source);+ var text = "";+ for (var i = 0; i < cs.length; i++) {+ var value = cs.getPropertyValue(cs[i]);+ var inherited = parentVisibility === undefined || value === parentVisibility;+ if (cs[i] === "visibility" && inherited) continue;+ text += cs[i] + ":" + value + ";";+ }+ // A copy is a still of one instant: a live transition or animation would carry it somewhere+ // the timeline never sampled.+ out.push(text + "transition:none;animation:none;");+ // The copy holds an empty box where media was, so the media's own children have no counterpart.+ if (source.matches && source.matches(MEDIA)) return out;+ for (var c = 0; c < source.children.length; c++) {+ resolvedStyles(source.children[c], out, cs.getPropertyValue("visibility"));+ }+ return out;+ }++ // One rule per element of the target's subtree, kept as text nodes. They go in the target's own+ // root: a shadow root is its own style scope, and the document's rules do not reach into it.+ function sheetFor(el) {+ var root = el.getRootNode ? el.getRootNode() : document;+ var scope = root.nodeType === 11 ? root : document.head || document.documentElement;+ var found = scope.querySelector && scope.querySelector("style#hf-es-styles");+ if (found) return found;+ var made = document.createElement("style");+ made.id = "hf-es-styles";+ scope.appendChild(made);+ return made;+ }+ function writeRules(sheet, rules, texts, tag) {+ for (var r = 0; r < texts.length; r++) {+ var css = "." + tag + "-" + r + "{" + texts[r] + "}";+ if (rules[r]) rules[r].data = css;+ else sheet.appendChild((rules[r] = document.createTextNode(css)));+ }+ }+ function classCopies(copy, tag, cursor) {+ copy.setAttribute("class", tag + "-" + cursor.i++);+ for (var c = 0; c < copy.children.length; c++) classCopies(copy.children[c], tag, cursor);+ }++ // Copies are stills, and the runtime does not manage media it did not mark: a live copy would show+ // a frozen frame and fetch its source again. A box of the same size stands in for it.+ function inertMedia(source, copy) {+ var from = source.querySelectorAll(MEDIA);+ var to = copy.querySelectorAll(MEDIA);+ for (var m = 0; m < to.length; m++) {+ var stand = document.createElement("div");+ stand.style.cssText =+ "display:inline-block;width:" ++ (from[m].offsetWidth || 0) ++ "px;height:" ++ (from[m].offsetHeight || 0) ++ "px;";+ to[m].parentNode.replaceChild(stand, to[m]);+ }+ }++ var maximum = opts.operator !== "normal";+ var cfg = {+ threshold: threshold,+ length: length,+ countMult: countMult,+ maxEchoes: maxEchoes,+ edgeSpacing: edgeSpacing,+ };+ var pa = [0, 0, 0, 0, 0, 0, 1],+ pb = [0, 0, 0, 0, 0, 0, 1],+ p0 = [0, 0],+ p1 = [0, 0];+ // The copy count for one target at time t.+ function countAt(st, t) {+ lerpTrack(st.centres, step, t, p0);+ lerpTrack(st.centres, step, t - fd / 2, p1);+ var move = Math.hypot(p0[0] - p1[0], p0[1] - p1[1]);+ var extent = 0;+ if (edgeSpacing > 0) {+ lerpTrack(st.poses, step, t, pa);+ lerpTrack(st.poses, step, t - fd * (length / 100), pb);+ extent = cornerShift(pa, pb, st.box, st.origin);+ }+ return count(move, extent, cfg);+ }++ if (!window._hfEsUid) window._hfEsUid = 0;+ var state = [];+ targets.forEach(function (el, ti) {+ window._hfEsAttached.add(el);+ var st = {+ el: el,+ poses: poses[ti],+ centres: centres[ti],+ matrix3d: matrix3d[ti],+ looks: looks[ti],+ showing: showing[ti],+ boxAt: boxAt[ti],+ box: boxes[ti],+ origin: origins[ti],+ };+ // The recording already holds the whole trajectory, so the most copies this target ever shows is+ // known now: build that many, not maxEchoes. A target that never smears gets nothing.+ var peak = 0;+ for (var t = 0; t <= dur; t += step) peak = Math.max(peak, countAt(st, t));+ if (peak === 0) return;++ // The copies sit in a zero-size group just before the target, so the target itself is untouched:+ // it keeps its parent, its blend mode and its pointer events. Isolated, so the lighten between+ // copies never mixes with the background.+ var group = document.createElement("div");+ group.setAttribute("data-hf-echo-group", "");+ group.style.cssText =+ "position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;";+ // The group is what the siblings stack against, so it takes the target's z-index.+ var z = getComputedStyle(el).zIndex;+ if (z && z !== "auto") group.style.zIndex = z;++ var tag = "hf-es" + window._hfEsUid++;+ var rules = [];+ var sheet = sheetFor(el);+ // A copy is a grandchild of its parent, and perspective reaches children only: each copy carries+ // the parent's perspective in its own transform (the vanishing point is then the copy's own).+ var host = el.parentElement || (el.getRootNode && el.getRootNode().host) || null;+ var persp = host ? getComputedStyle(host).perspective : "none";+ st.perspective = persp && persp !== "none" ? "perspective(" + persp + ") " : "";+ function snapshot() {+ // A target hidden right now (an autoAlpha entrance) is read as shown, so the copies' own+ // resolved style is not a hidden one; the inline value goes back exactly.+ var hidden = getComputedStyle(el).visibility !== "visible";+ var inline = el.style.getPropertyValue("visibility");+ var priority = el.style.getPropertyPriority("visibility");+ if (hidden) el.style.setProperty("visibility", "visible", "important");+ try {+ writeRules(sheet, rules, resolvedStyles(el, []), tag);+ } finally {+ if (hidden) el.style.setProperty("visibility", inline, priority);+ }+ }+ snapshot();++ var clones = [];+ for (var i = 0; i < peak; i++) {+ var c = el.cloneNode(true);+ c.removeAttribute("id");+ [c]+ .concat(+ Array.prototype.slice.call(+ c.querySelectorAll("[data-start],[data-duration],[data-track-index]"),+ ),+ )+ .forEach(function (n) {+ n.removeAttribute("data-start");+ n.removeAttribute("data-duration");+ n.removeAttribute("data-track-index");+ });+ c.querySelectorAll("[id]").forEach(function (n) {+ n.removeAttribute("id");+ });+ c.setAttribute("aria-hidden", "true");+ inertMedia(el, c);+ classCopies(c, tag, { i: 0 });+ c.classList.add("es-clone");+ c.style.position = "absolute";+ c.style.margin = "0";+ // The copy is sized to the target's offset box, which includes padding and border.+ c.style.boxSizing = "border-box";+ // translate, rotate and scale are folded into the copy's transform: left on, they would apply twice.+ c.style.translate = "none";+ c.style.rotate = "none";+ c.style.scale = "none";+ c.style.mixBlendMode = maximum ? "lighten" : "normal";+ c.style.visibility = "hidden";+ clones.push(c);+ }+ // Nearest copy on top: the first copy is the last child.+ for (var k = clones.length - 1; k >= 0; k--) group.appendChild(clones[k]);+ el.parentNode.insertBefore(group, el);+ st.group = group;+ st.clones = clones;+ st.host = host;+ state.push(st);+ });++ var pose = [0, 0, 0, 0, 0, 0, 1];+ function render() {+ if (window.__echoSmear.baking) return;+ var t = tl.time();+ state.forEach(function (st) {+ var n = countAt(st, t);+ // The target's visibility and box at this time, from the recording.+ var now = Math.max(0, Math.min(st.poses.length - 1, Math.round(t / step)));+ var view = { box: st.boxAt[now] };+ // The group follows the target's own visibility.+ if (st.group.style.visibility !== st.showing[now])+ st.group.style.visibility = st.showing[now];+ var boxKey = view.box ? view.box.join() : "";+ for (var i = 0; i < st.clones.length; i++) {+ var c = st.clones[i];+ if (i >= n) {+ if (c.style.visibility !== "hidden") c.style.visibility = "hidden";+ continue;+ }+ var back = t - ((i + 1) * fd * (length / 100)) / n;+ lerpTrack(st.poses, step, back, pose);+ // The copy sits on the target's own box, so the box follows it: a beat is free to move or+ // resize it. Written when a copy last saw a different box: a copy hidden while the box+ // changed must catch up when it is shown, so the key is per copy, not per target.+ if (view.box && c._esBox !== boxKey) {+ c._esBox = boxKey;+ c.style.left = view.box[0];+ c.style.top = view.box[1];+ c.style.width = view.box[2];+ c.style.height = view.box[3];+ }+ var near = Math.max(0, Math.min(st.poses.length - 1, Math.round(back / step)));+ c.style.transform =+ st.perspective + (st.matrix3d[near] || "matrix(" + pose.slice(0, 6).join(",") + ")");+ var look = st.looks[near];+ if (c._esLook !== look) {+ c._esLook = look;+ for (var k = 0; k < LOOKS.length; k++) if (look[k]) c.style[LOOKS[k]] = look[k];+ }+ c.style.opacity = pose[6];+ c.style.visibility = "inherit";+ }+ });+ }+ // Runtime proxies the timeline, so hook updates with a full-length tween (see registry motion-blur).+ tl.to({ v: 0 }, { v: 1, duration: Math.max(dur, 0.1), ease: "none", onUpdate: render }, 0);+ render();+ };+ })();+</script>++<!--+ Timeline integration:++ var tl = gsap.timeline({ paused: true });+ tl.fromTo(".card", { x: 100 }, { x: 1700, duration: 0.6, ease: "power3.inOut" }, 0.5);++ // Extend to data-duration so seeks past the last tween reach the smear's update.+ tl.set(document.body, {}, DATA_DURATION);++ // After all tweens, before registration.+ attachEchoSmear(".card", tl, { length: 100, threshold: 40 });++ window.__timelines = window.__timelines || {};+ window.__timelines["my-composition"] = tl;+-->diff --git a/registry/components/echo-smear/echo-smear.test.mjs b/registry/components/echo-smear/echo-smear.test.mjsnew file mode 100644index 0000000000..fb44f8d3d6--- /dev/null+++ b/registry/components/echo-smear/echo-smear.test.mjs@@ -0,0 +1,753 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import test from "node:test";+import vm from "node:vm";+import { Window } from "happy-dom";++const html = await readFile(new URL("./echo-smear.html", import.meta.url), "utf8");+const library = html.match(/<script>([\s\S]*?)<\/script>/i)[1];++// The snippet only touches window, document and gsap inside attachEchoSmear; the pure seams+// (count, lerpTrack, measurePoint) are reachable without a page.+function load() {+ const window = {};+ vm.runInNewContext(library, { window, document: {}, gsap: {}, Element: class {}, console });+ return window.__echoSmear;+}++const defaults = { threshold: 40, length: 100, countMult: 1, maxEchoes: 60, edgeSpacing: 1.5 };+const exact = { ...defaults, edgeSpacing: 0 };++test("count is zero below the half-frame threshold and rounds above it", () => {+ const { count } = load();+ assert.equal(count(19.9, 0, exact), 0);+ assert.equal(count(20.5, 0, exact), 21);+});++test("count scales with smear length", () => {+ const { count } = load();+ assert.equal(count(30, 0, { ...exact, length: 50 }), 15);+});++test("count is raised until the edge moves at most edgeSpacing per copy, then capped", () => {+ const { count } = load();+ assert.equal(count(30, 300, { ...defaults, maxEchoes: 400 }), 200);+ assert.equal(count(30, 300, defaults), 60);+});++test("the edge raise never turns a smear on by itself", () => {+ const { count } = load();+ assert.equal(count(10, 300, defaults), 0);+});++test("parseMatrix reads a 2D matrix, treats none as identity, and refuses matrix3d", () => {+ const { parseMatrix } = load();+ assert.deepEqual(Array.from(parseMatrix("matrix(1, 0, 0, 1, 10, 20)")), [1, 0, 0, 1, 10, 20]); // Array.from: the vm context has its own Array+ assert.deepEqual(Array.from(parseMatrix("none")), [1, 0, 0, 1, 0, 0]);+ assert.equal(parseMatrix("matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, 5,6,0,1)"), null);+});++test("boxPoint maps a box fraction through the matrix about the transform origin", () => {+ const { boxPoint } = load();+ // rotate(90deg) is matrix(0, 1, -1, 0, 0, 0). Box 40x20, origin at its centre, point (0, 0.5) = (0, 10).+ const [x, y] = boxPoint([0, 1, -1, 0, 0, 0], [40, 20], [20, 10], 0, 0.5);+ assert.ok(Math.abs(x - 20) < 1e-9, `x ${x}`);+ assert.ok(Math.abs(y + 10) < 1e-9, `y ${y}`);+ // The matrix's own translation is added after the turn.+ const [tx, ty] = boxPoint([1, 0, 0, 1, 30, 5], [40, 20], [20, 10], 0.5, 0.5);+ assert.ok(Math.abs(tx - 50) < 1e-9 && Math.abs(ty - 15) < 1e-9, `${tx},${ty}`);+});++test("individualMatrix composes translate, rotate and scale in that order", () => {+ const { individualMatrix } = load();+ assert.deepEqual(Array.from(individualMatrix("600px 0px", "none", "none")), [1, 0, 0, 1, 600, 0]);+ assert.deepEqual(Array.from(individualMatrix("none", "none", "2")), [2, 0, 0, 2, 0, 0]);+ const [a, b, c, d] = individualMatrix("none", "90deg", "none");+ assert.ok(+ Math.abs(a) < 1e-9 && Math.abs(b - 1) < 1e-9 && Math.abs(c + 1) < 1e-9 && Math.abs(d) < 1e-9,+ );+ // Percentages resolve against the element's own box: x against its width, y against its height.+ assert.deepEqual(+ Array.from(individualMatrix("150% 50%", "none", "none", [200, 80])),+ [1, 0, 0, 1, 300, 40],+ );+ assert.deepEqual(+ Array.from(individualMatrix("50%", "none", "none", [200, 80])),+ [1, 0, 0, 1, 100, 0],+ );+ assert.deepEqual(+ Array.from(individualMatrix("none", "none", "150%", [200, 80])),+ [1.5, 0, 0, 1.5, 0, 0],+ );+ // translate applies outermost: a scaled element still moves its full translate.+ assert.deepEqual(Array.from(individualMatrix("10px 0px", "none", "2")), [2, 0, 0, 2, 10, 0]);+});++test("boxPoint scales about the origin, so a scaled element's corner moves", () => {+ const { boxPoint } = load();+ const [x, y] = boxPoint([2, 0, 0, 2, 0, 0], [40, 20], [0, 0], 1, 1);+ assert.ok(Math.abs(x - 80) < 1e-9 && Math.abs(y - 40) < 1e-9, `${x},${y}`);+});++test("lerpTrack interpolates opacity and clamps before the start", () => {+ const { lerpTrack } = load();+ const track = [+ [0, 0, 0, 1, 1, 0],+ [0, 0, 0, 1, 1, 1],+ ];+ assert.equal(lerpTrack(track, 1, 0.5, [])[5], 0.5);+ assert.equal(lerpTrack(track, 1, -3, [])[5], 0);+});++// Fixes after the final review: mutation-resistant seam cases.+test("count rounds the half-frame travel to the nearest copy, and the edge raise rounds up", () => {+ const { count } = load();+ assert.equal(count(20.4, 0, exact), 20);+ assert.equal(count(20.6, 0, exact), 21);+ assert.equal(count(30, 300.3, { ...defaults, maxEchoes: 400 }), 201);+});++test("count needs travel strictly above half the threshold", () => {+ const { count } = load();+ assert.equal(count(20, 0, exact), 0);+});++test("lerpTrack clamps after the end of the record", () => {+ const { lerpTrack } = load();+ const track = [+ [0, 0, 0, 1, 1, 0],+ [0, 0, 0, 1, 1, 1],+ ];+ assert.equal(lerpTrack(track, 1, 5, [])[5], 1);+});++// A page: happy-dom for the tree and a fake timeline, so the snippet's own logic (the recording sweep, the+// copy poses, visibility, selection) runs without a browser. The fake timeline writes each driven element's+// transform and opacity as inline style on every time change, as GSAP would, then fires the proxy tween's+// onUpdate and any user callbacks unless events are suppressed.+function matrixCss(p) {+ if (p.css) return p.css;+ const sx = p.scaleX ?? 1;+ const sy = p.scaleY ?? 1;+ const r = ((p.rotation ?? 0) * Math.PI) / 180;+ return `matrix(${sx * Math.cos(r)}, ${sx * Math.sin(r)}, ${-sy * Math.sin(r)}, ${sy * Math.cos(r)}, ${p.x ?? 0}, ${p.y ?? 0})`;+}++// happy-dom does not implement the individual `translate` property: serve what the drive set.+const withTranslate = (cs, el) =>+ new Proxy(cs, {+ get(target, key) {+ if (key === "translate") return el.__translate ?? "none";+ const value = Reflect.get(target, key, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });++function page(poseOf) {+ const win = new Window({ url: "http://localhost/" });+ const warnings = [];+ const counts = { user: 0 };+ const updates = [];+ const tl = {+ t: 0,+ userCallback: null,+ time(v, suppress) {+ if (v === undefined) return this.t;+ // GSAP renders its children in reverse order on a backward seek, and the snippet's own update tween+ // was added last: it runs BEFORE the target has rendered the destination time. Simulated here, so a+ // callback that reads the target's live state sees what it was at the time we came from.+ const backward = v < this.t;+ this.t = v;+ const drive = () => {+ for (const [el, fn] of poseOf) {+ const p = fn(v);+ el.style.transform = matrixCss(p);+ if (p.opacity !== undefined) el.style.opacity = String(p.opacity);+ if (p.filter !== undefined) el.style.filter = p.filter;+ if (p.visibility !== undefined) el.style.visibility = p.visibility;+ if (p.translate !== undefined) el.__translate = p.translate; // happy-dom has no `translate` property+ if (p.off) el.__off = p.off;+ }+ };+ const fire = () => {+ updates.forEach((u) => u());+ if (this.userCallback) this.userCallback();+ };+ if (backward && !suppress) {+ fire();+ drive();+ } else {+ drive();+ if (!suppress) fire();+ }+ return this;+ },+ seek(v, suppress) {+ return this.time(v, suppress);+ },+ duration() {+ return 1;+ },+ to(_t, vars) {+ updates.push(vars.onUpdate);+ },+ };+ const con = { warn: (m) => warnings.push(String(m)), log() {}, error() {} };+ vm.runInNewContext(library, {+ window: win,+ document: win.document,+ Element: win.Element,+ getComputedStyle: (e) => withTranslate(win.getComputedStyle(e), e),+ // The snippet must not observe resizes: a callback's first run depends on the first frame drawn.+ ResizeObserver: class {+ constructor() {+ throw new Error("echo-smear must not construct a ResizeObserver");+ }+ },+ console: con,+ });+ return { win, tl, counts, warnings, attach: win.attachEchoSmear };+}++const ROOT = (inner) => `<div id="root" data-composition-id="c" data-fps="30">${inner}</div>`;+const ABS = 'style="position:absolute;width:40px;height:20px"';+function setup(html, drives) {+ const poseOf = new Map();+ const pg = page(poseOf);+ pg.win.document.body.innerHTML = html;+ for (const [id, fn] of Object.entries(drives)) {+ const el = pg.win.document.getElementById(id);+ poseOf.set(el, fn);+ // happy-dom has no layout: the offset box is whatever the drive last said (default 40x20 at 0,0).+ for (const [prop, key] of [+ ["offsetLeft", "l"],+ ["offsetTop", "t"],+ ["offsetWidth", "w"],+ ["offsetHeight", "h"],+ ]) {+ Object.defineProperty(el, prop, {+ get: () => (el.__off || { l: 0, t: 0, w: 40, h: 20 })[key],+ });+ }+ }+ return { pg, doc: pg.win.document };+}+const shownCopies = (doc) =>+ [...doc.querySelectorAll(".es-clone")].filter((c) => c.style.visibility !== "hidden");+const translateX = (c) => Number(/matrix\(([^)]+)\)/.exec(c.style.transform)[1].split(",")[4]);+const RUN = { x: 600 }; // 600 px/s: a fast mover at 30 fps++test("copies use visibility inherit, so a hidden scene hides them too", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0, "a fast mover has copies");+ assert.ok(+ shown.every((c) => c.style.visibility === "inherit"),+ "no copy forces visibility: visible",+ );+});++test("copy i shows the pose from i copy-intervals earlier", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ // 600 px/s over a half frame (1/60 s) = 10 px, so n = 10 copies spaced fd/10 apart.+ assert.equal(shown.length, 10);+ const xs = shown.map(translateX).sort((p, q) => q - p);+ assert.ok(Math.abs(xs[0] - 600 * (0.5 - 1 / 300)) < 0.5, `nearest copy ${xs[0]}`);+ assert.ok(Math.abs(xs[9] - 600 * (0.5 - 10 / 300)) < 0.5, `farthest copy ${xs[9]}`);+});++test("an element already attached is not attached again, and copies lose timing attributes", () => {+ const { pg, doc } = setup(+ ROOT(`<div class="card" id="a" ${ABS} data-start="0" data-duration="1"></div>`),+ { a: (t) => ({ x: RUN.x * t }) },+ );+ pg.attach(".card", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 20 });+ pg.attach(".card", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 20 });+ // The peak count over the timeline is 10 (600 px/s, threshold 10), so 10 copies are built, not maxEchoes.+ assert.equal(+ doc.querySelectorAll(".es-clone").length,+ 10,+ "one set of copies, sized to the peak",+ );+ assert.equal(+ doc.querySelectorAll(".card").length,+ 1,+ "copies do not keep the original's classes",+ );+ assert.equal(doc.querySelectorAll(".es-clone[data-start]").length, 0);+ assert.equal(doc.querySelectorAll(".es-clone[data-duration]").length, 0);+});++test("a later attach does not redraw earlier copies while it records", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div><div id="b" ${ABS}></div>`), {+ a: (t) => ({ x: RUN.x * t }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0, callbacks: true });+ const groupA = doc.getElementById("a").previousElementSibling;+ const watch = new pg.win.MutationObserver(() => {});+ watch.observe(groupA, { attributes: true, subtree: true });+ watch.takeRecords();+ pg.attach("#b", pg.tl, { callbacks: true });+ assert.ok(+ watch.takeRecords().length <= 1,+ "attach A's copies are redrawn once to restore the frame, not once per recording sample",+ );+});++test("the group takes the target's z-index, so the target keeps its place in the stack", () => {+ const { pg, doc } = setup(+ ROOT('<div id="a" style="position:absolute;z-index:7;width:40px;height:20px"></div>'),+ { a: (t) => ({ x: RUN.x * t }) },+ );+ pg.attach("#a", pg.tl, { threshold: 10 });+ assert.equal(doc.querySelector("[data-hf-echo-group]").style.zIndex, "7");+});++test("the target is not re-parented or restyled", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ const a = doc.getElementById("a");+ const parent = a.parentNode;+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ assert.ok(a.parentNode === parent, "same parent"); // not assert.equal: a failing diff of DOM nodes never finishes+ assert.equal(a.style.mixBlendMode, "");+ assert.equal(a.style.pointerEvents, "");+ assert.ok(+ a.previousElementSibling && a.previousElementSibling.hasAttribute("data-hf-echo-group"),+ "the group sits just before it",+ );+});++test("a statically positioned target smears in place", () => {+ const { pg, doc } = setup(+ ROOT('<div id="a" style="width:40px;height:20px"></div><div id="after"></div>'),+ {+ a: (t) => ({ x: RUN.x * t }),+ },+ );+ const a = doc.getElementById("a");+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0, "copies show");+ assert.ok(+ shown.every((c) => c.style.position === "absolute"),+ "copies are out of flow",+ );+ assert.ok(doc.getElementById("after").previousElementSibling === a, "the layout is untouched");+});++test("the group mirrors the target's own visibility, as the timeline wrote it", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), {+ a: (t) => ({ x: RUN.x * t, visibility: t >= 0.4 ? "hidden" : "" }),+ });+ const a = doc.getElementById("a");+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ const group = a.previousElementSibling;+ pg.tl.seek(0.2);+ assert.equal(group.style.visibility, "", "visible target: the group follows its parent");+ pg.tl.seek(0.5);+ assert.equal(group.style.visibility, "hidden");+});++test("copies of copies are never targets, and an element is attached once", () => {+ const { pg, doc } = setup(+ ROOT(+ '<div class="word" id="w" style="position:absolute"><span class="char" id="c1"></span></div>',+ ),+ { w: (t) => ({ x: RUN.x * t }), c1: (t) => ({ x: 400 * t }) },+ );+ pg.attach(".word", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 5 });+ pg.attach(".word .char", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 5 });+ assert.equal(+ doc.querySelectorAll("[data-hf-echo-group]").length,+ 2,+ "one group for .word, one for the original .char",+ );+ pg.attach(".word .char", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 5 });+ assert.equal(+ doc.querySelectorAll("[data-hf-echo-group]").length,+ 2,+ "attaching it again adds nothing",+ );+});++test("media inside a target is not cloned live", () => {+ const { pg, doc } = setup(+ ROOT(`<div id="a" ${ABS}><video poster="p.png"></video><audio></audio></div>`),+ { a: (t) => ({ x: RUN.x * t }) },+ );+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 4 });+ assert.equal(+ doc.querySelectorAll(".es-clone video, .es-clone audio, .es-clone iframe").length,+ 0,+ );+ assert.equal(doc.querySelectorAll("#a video").length, 1, "the original keeps its video");+});++// Task 2 of the review-fix plan: poses come from the resolved transform, not from GSAP properties.+test("a target outside any composition still smears", () => {+ const { pg, doc } = setup(`<div id="a" ${ABS}></div>`, { a: (t) => ({ x: RUN.x * t }) });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ assert.ok(shownCopies(doc).length > 0);+});++test("an attach that throws mid-sweep leaves the other smears working", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div><div id="b" ${ABS}></div>`), {+ a: (t) => ({ x: RUN.x * t }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ const realTime = pg.tl.time.bind(pg.tl);+ let calls = 0;+ pg.tl.time = (v, quiet) => {+ if (v !== undefined && ++calls === 5) throw new Error("boom");+ return realTime(v, quiet);+ };+ assert.throws(() => pg.attach("#b", pg.tl, {}), /boom/);+ pg.tl.time = realTime;+ pg.tl.seek(0.5);+ assert.ok(shownCopies(doc).length > 0, "attach A still renders");+});++test("the recording sweep fires no timeline callbacks unless asked", () => {+ const quiet = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ let fired = 0;+ quiet.pg.tl.userCallback = () => fired++;+ quiet.pg.attach("#a", quiet.pg.tl, {});+ assert.equal(fired, 0, "default: quiet");+ const loud = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ let heard = 0;+ loud.pg.tl.userCallback = () => heard++;+ loud.pg.attach("#a", loud.pg.tl, { callbacks: true });+ assert.ok(heard > 0, "callbacks: true lets motion written from onUpdate be recorded");+});++test("copies keep the target's whole transform, so a percent shift survives", () => {+ // The drive writes translate(-50%, -50%) first, then a 600 px/s move, as xPercent -50 with x does.+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), {+ a: (t) => ({ css: `matrix(1, 0, 0, 1, ${-20 + 600 * t}, -10)` }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const nearest = shownCopies(doc)+ .map(translateX)+ .sort((p, q) => q - p)[0];+ assert.ok(Math.abs(nearest - (-20 + 600 * (0.5 - 1 / 300))) < 0.5, `nearest copy ${nearest}`);+ const f = Number(/matrix\(([^)]+)\)/.exec(shownCopies(doc)[0].style.transform)[1].split(",")[5]);+ assert.equal(f, -10, "the vertical shift is kept");+});++test("motion that comes only from an ancestor draws no copies", () => {+ const { pg, doc } = setup(+ ROOT(`<div id="p" style="position:absolute"><div id="a" ${ABS}></div></div>`),+ { p: (t) => ({ x: RUN.x * t }) },+ );+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ assert.equal(shownCopies(doc).length, 0);+});++test("a matrix3d target gets copies taken from the nearest recorded sample, never NaN", () => {+ const css = (t) => `matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, ${600 * t},0,0,1)`;+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ css: css(t) }) });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0, "a 3D mover has copies");+ assert.ok(+ shown.every((c) => /^matrix3d\(/.test(c.style.transform) && !/NaN/.test(c.style.transform)),+ );+});++test("a transform-origin at the corner measures from the corner", () => {+ const spin = (t) => ({ rotation: 720 * t });+ const corner = setup(+ ROOT(+ '<div id="a" style="position:absolute;width:100px;height:100px;transform-origin:0px 0px"></div>',+ ),+ { a: spin },+ );+ corner.pg.attach("#a", corner.pg.tl, { threshold: 10, edgeSpacing: 0, measurePoint: [1, 1] });+ corner.pg.tl.seek(0.5);+ assert.ok(shownCopies(corner.doc).length > 0, "the far corner of a spinning box travels");+ const origin = setup(+ ROOT(+ '<div id="a" style="position:absolute;width:100px;height:100px;transform-origin:0px 0px"></div>',+ ),+ { a: spin },+ );+ origin.pg.attach("#a", origin.pg.tl, { threshold: 10, edgeSpacing: 0, measurePoint: [0, 0] });+ origin.pg.tl.seek(0.5);+ assert.equal(shownCopies(origin.doc).length, 0, "the pivot itself does not move");+});++test("a target that never smears gets no group and no copies", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: 10 * t }) });+ pg.attach("#a", pg.tl, { threshold: 40 });+ assert.equal(doc.querySelectorAll("[data-hf-echo-group], .es-clone").length, 0);+});++test("copies are built to the peak count, capped by maxEchoes", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 4 });+ assert.equal(doc.querySelectorAll(".es-clone").length, 4, "capped");+ const more = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ more.pg.attach("#a", more.pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 60 });+ assert.equal(more.doc.querySelectorAll(".es-clone").length, 10, "the peak, not 60");+});++// Task 3: the demo inlines the snippet, and nothing else keeps the two in step.+test("demo.html carries the component's snippet verbatim", async () => {+ const demo = await readFile(new URL("./demo.html", import.meta.url), "utf8");+ // Whitespace and trailing commas: oxfmt formats the same code differently at another depth.+ const squash = (text) => text.replace(/\s+/g, "").replace(/,(?=[\])}])/g, "");+ assert.ok(+ squash(demo).includes(squash(library)),+ "the demo's inlined snippet differs from echo-smear.html",+ );+});++// Fix pass after the final review of the rewrite.+test("copies are placed on the target's box even when they were hidden at the last box change", () => {+ const drive = (t) => ({+ x: 1500 * t * t,+ off: t >= 0.5 ? { l: 200, t: 30, w: 40, h: 20 } : { l: 350, t: 150, w: 40, h: 20 },+ });+ const { pg, doc } = setup(ROOT('<div id="a" style="width:40px;height:20px"></div>'), {+ a: drive,+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.1); // few copies shown, the box is (350, 150)+ pg.tl.seek(0.9); // many shown, the box is now (200, 30)+ const shown = shownCopies(doc);+ assert.ok(shown.length > 5, `copies ${shown.length}`);+ assert.ok(+ shown.every((c) => c.style.left === "200px" && c.style.top === "30px"),+ "every shown copy is on the current box",+ );+});++test("a static target's copies sit on its box from the first frame", () => {+ const { pg, doc } = setup(ROOT('<div id="a" style="width:40px;height:20px"></div>'), {+ a: (t) => ({ x: RUN.x * t, off: { l: 350, t: 150, w: 40, h: 20 } }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0);+ assert.ok(shown.every((c) => c.style.left === "350px" && c.style.top === "150px"));+});++test("a target inside a shadow root attaches, and its rules live in that root", () => {+ const poseOf = new Map();+ const pg = page(poseOf);+ const host = pg.win.document.createElement("div");+ pg.win.document.body.appendChild(host);+ const shadow = host.attachShadow({ mode: "open" });+ shadow.innerHTML = '<div id="a" style="position:absolute;width:40px;height:20px"></div>';+ const a = shadow.getElementById("a");+ poseOf.set(a, (t) => ({ x: RUN.x * t }));+ assert.doesNotThrow(() => pg.attach(a, pg.tl, { threshold: 10, edgeSpacing: 0 }));+ assert.doesNotThrow(() => pg.tl.seek(0.5));+ assert.ok(shadow.querySelector("style"), "the copies' rules are in the shadow root");+});++test("filter and the other non-transform styles follow the recorded time", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), {+ a: (t) => ({ x: RUN.x * t, filter: t < 0.2 ? "none" : "blur(2px)" }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0);+ assert.ok(+ shown.every((c) => c.style.filter === "blur(2px)"),+ "a copy carries the filter the target had then",+ );+});++test("the snippet never constructs a ResizeObserver", () => {+ const { pg } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ assert.doesNotThrow(() => pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 }));+});++test("copies carry the parent's perspective, because they are grandchildren of it", () => {+ const { pg, doc } = setup(+ ROOT(`<div id="p" style="position:absolute;perspective:400px"><div id="a" ${ABS}></div></div>`),+ { a: (t) => ({ x: RUN.x * t }) },+ );+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0);+ assert.ok(+ shown.every((c) => c.style.transform.startsWith("perspective(400px) ")),+ shown[0].style.transform,+ );+});++test("media with children does not shift the style rules of what follows it", () => {+ const { pg, doc } = setup(+ ROOT(`<div id="a" ${ABS}><video><source src="x.mp4"></video><p class="t">x</p></div>`),+ { a: (t) => ({ x: RUN.x * t }) },+ );+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0, maxEchoes: 2 });+ // root, the media's stand-in, the paragraph: three rules, not four.+ assert.equal(doc.getElementById("hf-es-styles").childNodes.length, 3);+});++test("a copy is sized to the offset box with border-box, so padding is not added twice", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ assert.ok(shownCopies(doc).every((c) => c.style.boxSizing === "border-box"));+});++test("an SVG child target is skipped with a warning", () => {+ const { pg, doc } = setup(+ ROOT(`<svg id="s" ${ABS}><rect id="r" width="10" height="10"></rect></svg>`),+ {+ r: (t) => ({ x: RUN.x * t }),+ },+ );+ pg.attach("#r", pg.tl, { threshold: 10, edgeSpacing: 0 });+ assert.equal(doc.querySelectorAll("[data-hf-echo-group]").length, 0);+ assert.ok(+ pg.warnings.some((w) => /svg/i.test(w)),+ pg.warnings.join(" | "),+ );+});++test("copies carry the recorded opacity", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), {+ a: (t) => ({ x: RUN.x * t, opacity: 0.5 }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ assert.ok(shownCopies(doc).every((c) => c.style.opacity === "0.5"));+});++// Real GSAP, not the fake timeline: the callbacks a composition puts on its timeline must not fire at attach.+test("attaching leaves real GSAP callbacks unfired, and a removal callback cannot remove the target", () => {+ const win = new Window({ url: "http://localhost/" });+ globalThis.window = win;+ globalThis.document = win.document;+ globalThis.getComputedStyle = (e) => win.getComputedStyle(e);+ const { gsap } = createRequire(new URL("../../../packages/core/package.json", import.meta.url))(+ "gsap",+ );+ win.document.body.innerHTML = ROOT(`<div id="a" ${ABS}></div>`);+ const a = win.document.getElementById("a");+ const tl = gsap.timeline({ paused: true });+ const fired = { call: 0, complete: 0, reverse: 0 };+ tl.to(+ a,+ {+ x: 600,+ duration: 1,+ ease: "none",+ onComplete: () => {+ fired.complete++;+ a.remove();+ },+ onReverseComplete: () => fired.reverse++,+ },+ 0,+ );+ tl.call(() => fired.call++, [], 0.5);+ vm.runInNewContext(library, {+ window: win,+ document: win.document,+ Element: win.Element,+ getComputedStyle: (e) => win.getComputedStyle(e),+ console,+ });+ assert.doesNotThrow(() => win.attachEchoSmear(a, tl, { threshold: 10, edgeSpacing: 0 }));+ assert.deepEqual({ ...fired }, { call: 0, complete: 0, reverse: 0 });+ assert.ok(a.parentNode, "the target is still in the document");+ assert.equal(tl.time(), 0, "the playhead is back where it was");+});++// Round 3: findings from the re-review at 161796db4.+test("the group's visibility does not depend on the path taken to a time", () => {+ // autoAlpha 0 arrives at t = 1: visible at 0.5 however it is reached.+ const drive = (t) => ({ x: RUN.x * t, visibility: t >= 1 ? "hidden" : "" });+ const cold = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: drive });+ cold.pg.attach("#a", cold.pg.tl, { threshold: 10, edgeSpacing: 0 });+ cold.pg.tl.seek(0.5);+ const viaEnd = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: drive });+ viaEnd.pg.attach("#a", viaEnd.pg.tl, { threshold: 10, edgeSpacing: 0 });+ viaEnd.pg.tl.seek(1);+ viaEnd.pg.tl.seek(0.5);+ assert.ok(shownCopies(cold.doc).length > 0, "cold: copies show");+ assert.equal(+ shownCopies(viaEnd.doc).length,+ shownCopies(cold.doc).length,+ "after 1 -> 0.5: the same copies",+ );+ assert.equal(+ viaEnd.doc.getElementById("a").previousElementSibling.style.visibility,+ cold.doc.getElementById("a").previousElementSibling.style.visibility,+ );+});++test("the copies' box does not depend on the path taken to a time", () => {+ const drive = (t) => ({+ x: RUN.x * t,+ off: t >= 0.7 ? { l: 200, t: 30, w: 40, h: 20 } : { l: 350, t: 150, w: 40, h: 20 },+ });+ const cold = setup(ROOT('<div id="a" style="width:40px;height:20px"></div>'), { a: drive });+ cold.pg.attach("#a", cold.pg.tl, { threshold: 10, edgeSpacing: 0 });+ cold.pg.tl.seek(0.5);+ const viaEnd = setup(ROOT('<div id="a" style="width:40px;height:20px"></div>'), { a: drive });+ viaEnd.pg.attach("#a", viaEnd.pg.tl, { threshold: 10, edgeSpacing: 0 });+ viaEnd.pg.tl.seek(1);+ viaEnd.pg.tl.seek(0.5);+ const lefts = (doc) => shownCopies(doc).map((c) => c.style.left);+ assert.ok(lefts(cold.doc).length > 0 && lefts(cold.doc).every((l) => l === "350px"));+ assert.deepEqual(lefts(viaEnd.doc), lefts(cold.doc));+});++test("motion written only through the CSS translate property counts, and copies carry it in transform", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), {+ a: (t) => ({ css: "none", translate: `${RUN.x * t}px 0px` }),+ });+ pg.attach("#a", pg.tl, { threshold: 10, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0, "a translate-only mover has copies");+ const nearest = shown.map(translateX).sort((p, q) => q - p)[0];+ assert.ok(Math.abs(nearest - 600 * (0.5 - 1 / 300)) < 0.5, `nearest copy ${nearest}`);+ assert.ok(+ shown.every((c) => c.style.translate === "none"),+ "the copy's own translate is cleared so it is not applied twice",+ );+});++test("overlapping inputs in one call attach an element once", () => {+ const { pg, doc } = setup(ROOT(`<div id="a" ${ABS}></div>`), { a: (t) => ({ x: RUN.x * t }) });+ pg.attach(["#a", doc.getElementById("a"), "#a"], pg.tl, { threshold: 10, edgeSpacing: 0 });+ assert.equal(doc.querySelectorAll("[data-hf-echo-group]").length, 1);+});++test("a percentage translate moves by that share of the element's own width", () => {+ // 0% -> 300% over one second on a 200 px wide box: 300% = 600 px, 150% = 300 px at 0.5 s.+ const { pg, doc } = setup(+ ROOT('<div id="a" style="position:absolute;width:200px;height:80px"></div>'),+ { a: (t) => ({ css: "none", translate: `${300 * t}%` }) },+ );+ doc.getElementById("a").__off = { l: 0, t: 0, w: 200, h: 80 }; // the box a percentage is a share of+ pg.attach("#a", pg.tl, { threshold: 2, edgeSpacing: 0 });+ pg.tl.seek(0.5);+ const shown = shownCopies(doc);+ assert.ok(shown.length > 0);+ const nearest = shown.map(translateX).sort((p, q) => q - p)[0];+ // The nearest copy is one copy-interval back from 300 px: about 298 px, not 140.+ assert.ok(nearest > 280 && nearest < 300, `nearest copy ${nearest}`);+});diff --git a/registry/components/echo-smear/registry-item.json b/registry/components/echo-smear/registry-item.jsonnew file mode 100644index 0000000000..7a6f40b7ba--- /dev/null+++ b/registry/components/echo-smear/registry-item.json@@ -0,0 +1,18 @@+{+ "$schema": "https://hyperframes.heygen.com/schema/registry-item.json",+ "name": "echo-smear",+ "type": "hyperframes:component",+ "title": "Echo Smear",+ "description": "Distance-adaptive streak — records each element's real trajectory (position, rotation, scale, opacity), then trails time-offset copies behind it in proportion to its speed, combined by brightest pixel, so fast moves smear and slow ones stay sharp; spinning edges stay smooth",+ "tags": ["effect", "smear", "echo", "motion-blur", "velocity", "after-effects", "animation"],+ "files": [+ {+ "path": "echo-smear.html",+ "target": "compositions/components/echo-smear.html",+ "type": "hyperframes:snippet"+ }+ ],+ "preview": {+ "poster": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/echo-smear.png"+ }+}