From 3d42fdeb156396ce2754240c2a118ff6f1fa7a6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Thu, 17 Sep 2026 12:24:47 -0400 Subject: [PATCH] feat(registry): blur every transform driver, and ship the reference case as shutter-slam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The motion-blur snippet integrated translation only. Its output stage was one SVG filter per target whose copies were feOffset, and feOffset only translates, so a beat that only scaled or only turned sampled a displacement of zero and rendered sharp. No SVG filter primitive can give a copy its own affine transform, so the sampling loop was never the problem: the output stage was. Copies are now DOM clones of the element in an isolation:isolate group, each at 1/N opacity with mix-blend-mode plus-lighter, each carrying the element's resolved transform at its sample time. plus-lighter adds premultiplied colour, so N + 1 copies at 1/N sum to the average the shutter integral asks for; the isolation is load-bearing rather than tidy, because without a transparent backdrop of its own the first copy adds onto the page and blows a light background out to white. Reading the resolved matrix instead of a list of named GSAP properties is what makes every driver work at once: translation, scale, rotation, 3D rotation and skew arrive in the same one value. Measured against the After Effects export the shutter model was fitted to, per beat, previous stage to this one: scale +0.62 dB, rotate X +0.43, rotate Y +0.84, rotate Z +1.15, translate X -0.18, translate Y -0.04. The two small translate regressions are inherent and not tunable: the filter offset one rasterisation so every copy was pixel-identical, where each copy is now rasterised independently at its own fractional transform with its own subpixel antialiasing. Three consequences of the new stage, each carrying its own fix: - mix-blend-mode flattens preserve-3d, so a copy cannot inherit the parent's 3D context. Each copy carries the parent's perspective as its own first transform function instead. - A copy is styled by nothing that selected the original, since dropping the id also drops every #id rule that gave it size, colour and font. Each copy carries its own resolved style inline, read once and replayed. Those values are px, so a container-relative element needs them again when its box changes: a ResizeObserver re-snapshots rather than paying a subtree walk every frame. - A beat that moved and faded at once kept a full-strength smear behind a vanishing element. The element's opacity now rides the group; the 1/N weight stays on the copies. The axis option is gone. It selected which of x and y to sample, a question the resolved matrix does not have. shutter-slam is the new component: one word through six single-property beats, two translate slams, a scale punch, then a full turn about each axis, which exercises every driver the model covers in one mount. Easing is power2.inOut because it measured best, not because it was the default. A bezier fitted to the reference's own bbox centres looks like the better curve and renders worse: a blurred bbox centre is the shutter window's average rather than the instant, so on an accelerating segment the fit measures its own blur. Co-Authored-By: Miguel Ángel --- docs/catalog/components/motion-blur.mdx | 399 ++++++------ docs/catalog/components/shutter-slam.mdx | 586 ++++++++++++++++++ docs/docs.json | 1 + docs/public/catalog-index.json | 18 +- .../catalog/components/motion-blur.json | 2 +- .../catalog/components/shutter-slam.json | 1 + .../motionBlurShutter.browser.test.ts | 346 +++++++---- registry/catalog-artifact/local-vectors.bin | Bin 612864 -> 614400 bytes registry/catalog-artifact/local-vectors.json | 3 +- registry/components/motion-blur/demo.html | 324 +++++----- .../components/motion-blur/motion-blur.html | 385 +++++++----- .../components/motion-blur/registry-item.json | 2 +- registry/components/shutter-slam/demo.html | 524 ++++++++++++++++ .../shutter-slam/registry-item.json | 18 + .../components/shutter-slam/shutter-slam.html | 541 ++++++++++++++++ registry/examples/motion-blur/index.html | 324 +++++----- registry/registry.json | 6 +- 17 files changed, 2712 insertions(+), 768 deletions(-) create mode 100644 docs/catalog/components/shutter-slam.mdx create mode 100644 docs/public/catalog/components/shutter-slam.json create mode 100644 registry/components/shutter-slam/demo.html create mode 100644 registry/components/shutter-slam/registry-item.json create mode 100644 registry/components/shutter-slam/shutter-slam.html diff --git a/docs/catalog/components/motion-blur.mdx b/docs/catalog/components/motion-blur.mdx index 23c6c841474..d510e853130 100644 --- a/docs/catalog/components/motion-blur.mdx +++ b/docs/catalog/components/motion-blur.mdx @@ -1,6 +1,6 @@ --- title: "Motion Blur" -description: "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight SVG copies along the real trajectory" +description: "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight additive copies of the element along its real trajectory, so translation, scale, rotation, 3D rotation and skew all drive the smear" --- import { InstallCommand } from "/snippets/install-command.jsx"; @@ -35,22 +35,31 @@ That writes one file: `compositions/components/motion-blur.html`. 1. After every timeline update (each rendered frame), the snippet seeks the timeline to `samplesPerFrame` sub-frame times spread evenly across - the shutter window, reads each target's GSAP x/y at every sample, then - restores the frame time. Seeks run with events suppressed, so no user - callbacks fire and the DOM ends up exactly where the frame left it. - 2. An SVG filter stacks one copy of the element per sample (feOffset to - the sampled position relative to the current one) and adds them at - equal weight (feComposite arithmetic, 1/N each, sRGB space). Result: - a box smear along the actual trajectory whose length is speed × - shutter time, with no decaying one-sided trail. The tails — where - fewer copies overlap — step down evenly at 1/N per copy; wherever the - element travels less than its own size the copies pile up past 1 and - clamp, so the middle of the smear is solid rather than a plateau. - 3. The element itself is then composited over that smear, sharp and at - full opacity. No single duplicate ever exceeds 1/N, so a moving edge - resolves as a staircase of ghosts behind a solid frame-time instance. - 4. When the sampled positions collapse to the current one (element at - rest), the filter is removed so the element renders sharp. + the shutter window, reads each target's RESOLVED `transform` at every + sample, then restores the frame time. Seeks run with events suppressed, + so no user callbacks fire and the DOM ends up exactly where the frame + left it. Reading the resolved matrix rather than a list of named GSAP + properties is what makes every driver work: translation, scale, + rotation, 3D rotation and skew arrive in the same one value, and a + driver nobody thought of needs no change here. + 2. One copy of the element per sample is stacked in an isolated group, + each carrying its sample's transform, each at 1/N opacity with + `mix-blend-mode: plus-lighter`. plus-lighter adds premultiplied colour, + so N+1 copies at 1/N sum to the average — the shutter integral. The + isolation is load-bearing: without a transparent backdrop of its own + the first copy would add onto the page and blow a light background out + to white. Result: a smear along the actual trajectory whose extent is + speed × shutter time, with no decaying one-sided trail. The tails — + where fewer copies overlap — step down evenly at 1/N per copy; wherever + the element travels less than its own size the copies pile up past 1 + and clamp, so the middle of the smear is solid rather than a plateau. + 3. The element itself paints over that group, sharp and at full opacity. + No single copy ever exceeds 1/N, so a moving edge resolves as a + staircase of ghosts behind a solid frame-time instance. The group + carries the element's own opacity, so a beat that moves and fades at + once fades its smear with it. + 4. When every sampled transform collapses to the current one (element at + rest), the group is hidden so the element renders sharp. Shutter window (AE semantics, per frame at time t, frame interval 1/fps): shutterTime = shutterAngle / 360 / fps @@ -71,9 +80,23 @@ That writes one file: `compositions/components/motion-blur.html`. instance on top is what keeps total ink above the unblurred frame's. Requirements: - - Elements must be animated via GSAP x/y (transform), not left/top. The - element's own scale/rotation is compensated; skew, 3D rotation and - transformed ancestors are not. + - Elements must be animated via `transform` (GSAP x/y/scale/rotation and the + 3D and skew properties all qualify), not left/top. Transformed ancestors + are still not compensated. + - A 3D beat reads its perspective off the element's parent and applies it per + copy, so the vanishing point follows each copy's transform-origin rather + than the parent's perspective-origin. Those agree when the element is + centred in its perspective parent, which is how a 3D beat is authored. + - A copy drops the element's id but keeps its classes, because a class rule is + the only thing that can still style a copy's pseudo-elements. So a selector + written against a class matches the copies too: after attaching, address the + element by id or by reference, never by a class a copy also carries. + - A target is blurred once: a second attachMotionBlur() call naming the same + element leaves the first call's copies in place rather than stacking a + second set over them. + - Cost is N + 1 copies of the target's whole subtree, restyled on attach and + on resize and re-transformed every frame. Point it at the element that + moves, not at a container holding it. - The host must render the timeline for the blur to update — HyperFrames seeks every frame. A fresh paused timeline that is never seeked shows no blur on its first frame. @@ -96,12 +119,12 @@ That writes one file: `compositions/components/motion-blur.html`. fps — composition frame rate (default: the root's data-fps, else 30). Pass it explicitly when rendering with an fps override (`hyperframes render --fps`). - axis — "x" | "y" | "both" (default "both") --> + + + + + + +``` + + + +{/* hf:generated-footer */} + +Tagged `effect` `motion-blur` `shutter` `after-effects` `slam` `animation`. + +## Related topics + +- [Browse the complete Catalog](/catalog) +- [Add assets and Catalog items in Studio](/studio/assets-and-blocks) +- [Build a richer composition](/go-further) diff --git a/docs/docs.json b/docs/docs.json index 9b3ad993cc6..28546839fad 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -705,6 +705,7 @@ "catalog/components/parallax-zoom", "catalog/components/rubber-band-bumper", "catalog/components/settings-toggle-flow", + "catalog/components/shutter-slam", "catalog/components/signup-flow", "catalog/components/spotlight-card", "catalog/components/stagger-cascade", diff --git a/docs/public/catalog-index.json b/docs/public/catalog-index.json index 9bd94367e96..36291c70ea0 100644 --- a/docs/public/catalog-index.json +++ b/docs/public/catalog-index.json @@ -3340,7 +3340,7 @@ "name": "motion-blur", "type": "component", "title": "Motion Blur", - "description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight SVG copies along the real trajectory", + "description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight additive copies of the element along its real trajectory, so translation, scale, rotation, 3D rotation and skew all drive the smear", "tags": [ "effect", "motion-blur", @@ -4215,6 +4215,22 @@ "href": "/catalog/components/shimmer-sweep", "preview": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shimmer-sweep.png" }, + { + "name": "shutter-slam", + "type": "component", + "title": "Shutter Slam", + "description": "One word thrown through six single-property beats under integrated shutter blur — two translate slams, a scale punch, then a full turn about each axis — on the measured easing of the After Effects export the shutter model was fitted to", + "tags": [ + "effect", + "motion-blur", + "shutter", + "after-effects", + "slam", + "animation" + ], + "href": "/catalog/components/shutter-slam", + "preview": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shutter-slam.png" + }, { "name": "signup-flow", "type": "component", diff --git a/docs/public/catalog/components/motion-blur.json b/docs/public/catalog/components/motion-blur.json index 5b36ba67b6c..6f28b057886 100644 --- a/docs/public/catalog/components/motion-blur.json +++ b/docs/public/catalog/components/motion-blur.json @@ -1 +1 @@ -{"html":"\n\n \n \n \n Motion Blur — Demo\n \n \n \n \n \n
\n Motion Blur — Velocity Showcase\n 17 duplicates at 1/16 · 720° shutter · smear = speed × shutter time\n
\n\n
\n
3.0seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
DRIFT
\n
slow
\n
\n\n
\n
1.5seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
GLIDE
\n
medium
\n
\n\n
\n
0.7seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
RUSH
\n
fast
\n
\n\n
\n
\n 0.35seconds\n
\n
shape
\n
text
\n
\n
\n
\n
\n
BLAST
\n
faster
\n
\n\n
\n
0.2seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
WARP
\n
extreme
\n
\n\n \n \n \n\n"} \ No newline at end of file +{"html":"\n\n \n \n \n Motion Blur — Demo\n \n \n \n \n \n
\n Motion Blur — Velocity Showcase\n 17 duplicates at 1/16 · 720° shutter · smear = speed × shutter time\n
\n\n
\n
3.0seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
DRIFT
\n
slow
\n
\n\n
\n
1.5seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
GLIDE
\n
medium
\n
\n\n
\n
0.7seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
RUSH
\n
fast
\n
\n\n
\n
\n 0.35seconds\n
\n
shape
\n
text
\n
\n
\n
\n
\n
BLAST
\n
faster
\n
\n\n
\n
0.2seconds
\n
shape
\n
text
\n
\n
\n
\n
\n
WARP
\n
extreme
\n
\n\n \n \n \n\n"} \ No newline at end of file diff --git a/docs/public/catalog/components/shutter-slam.json b/docs/public/catalog/components/shutter-slam.json new file mode 100644 index 00000000000..eed8f790702 --- /dev/null +++ b/docs/public/catalog/components/shutter-slam.json @@ -0,0 +1 @@ +{"html":"\n\n\n \n \n \n \n\n\n
\n
\n \n\n
\n
\n
\n
\n
\n\n \n \n \n
\n
\n \n\n"} \ No newline at end of file diff --git a/packages/cli/src/registry/motionBlurShutter.browser.test.ts b/packages/cli/src/registry/motionBlurShutter.browser.test.ts index b018fad0426..25e5498d8d4 100644 --- a/packages/cli/src/registry/motionBlurShutter.browser.test.ts +++ b/packages/cli/src/registry/motionBlurShutter.browser.test.ts @@ -15,25 +15,39 @@ const snippetHtml = readRepoFile("registry/components/motion-blur/motion-blur.ht /** First line of the snippet's IIFE body, which runs to the `};` closing it at the same indent. */ const BODY_FIRST_LINE = "if (!window._hfMbUid) window._hfMbUid = 0;"; -const SNIPPET_INDENT = " ".repeat(4); -const INLINED_INDENT = " ".repeat(10); -/** - * The snippet's IIFE body, leading whitespace dropped so the installable snippet and its inlined - * copies compare regardless of how deeply each one nests it. - */ -function snippetBody(source: string, indent: string): string { - const start = source.indexOf(indent + BODY_FIRST_LINE); +/** The snippet's IIFE body verbatim, located by the indent of its own first line, so a copy + * nested in a component template is found as readily as one in a demo plate. */ +function snippetSource(source: string): string { + const escaped = BODY_FIRST_LINE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const match = new RegExp(`^([ ]*)${escaped}$`, "m").exec(source); + const indent = match?.[1]; + if (match === null || indent === undefined) { + throw new Error("could not locate the snippet body"); + } const endMarker = `\n${indent}};`; - const end = source.indexOf(endMarker, start); - if (start < 0 || end < 0) { - throw new Error(`could not locate the snippet body at indent ${indent.length}`); + const end = source.indexOf(endMarker, match.index); + if (end < 0) throw new Error("could not locate the end of the snippet body"); + return source.slice(match.index, end + endMarker.length); +} + +/** Runs of code lines joined, because oxfmt wraps a statement differently at each nesting depth. + * Comment lines stay on their own line, so prose drift is still caught. */ +function joinWrappedLines(body: string): string { + const lines: string[] = []; + for (const line of body.split("\n")) { + const text = line.trim(); + if (text === "") continue; + const previous = lines.at(-1); + const separate = previous === undefined || text.startsWith("//") || previous.startsWith("//"); + if (separate) lines.push(text); + else lines[lines.length - 1] = `${previous} ${text}`; } - return source - .slice(start, end + endMarker.length) - .split("\n") - .map((line) => line.trimStart()) - .join("\n"); + return lines.join("\n"); +} + +function snippetBody(source: string): string { + return joinWrappedLines(snippetSource(source)); } const FPS = 30; @@ -42,6 +56,8 @@ const FRAME_TIME_S = 5; const DURATION_S = 10; const WORD_WIDTH = 1046; const WORD_HEIGHT = 193; +const PERSPECTIVE = "2000px"; +const COPIES = reference.subIntervalsPerWindow + 1; /** The slice of GSAP's timeline API the snippet drives; `time()` reads, `time(value)` seeks. */ interface Timeline { @@ -50,6 +66,9 @@ interface Timeline { to(target: unknown, vars: { onUpdate?: () => void }): Timeline; } +/** A resolved transform at one sample time, as `getComputedStyle` would report it. */ +type Trajectory = (framesFromNow: number) => string; + /** * The reference's own trajectory around the measured frame: a parabola through the core centres of * frames 4, 5 and 6, with frame 5 at t = 0. Offsets are relative to the frame-time position, so the @@ -62,6 +81,8 @@ function offsetAtFrames(df: number): number { return ((fwd + back) / 2) * df * df + ((fwd - back) / 2) * df; } +const translating: Trajectory = (df) => `matrix(1, 0, 0, 1, ${offsetAtFrames(df)}, 0)`; + function installSnippet(): void { const body = snippetHtml.slice( snippetHtml.indexOf(" + + + + + + diff --git a/registry/components/shutter-slam/registry-item.json b/registry/components/shutter-slam/registry-item.json new file mode 100644 index 00000000000..32fc42e3e4a --- /dev/null +++ b/registry/components/shutter-slam/registry-item.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://hyperframes.heygen.com/schema/registry-item.json", + "name": "shutter-slam", + "type": "hyperframes:component", + "title": "Shutter Slam", + "description": "One word thrown through six single-property beats under integrated shutter blur — two translate slams, a scale punch, then a full turn about each axis — on the measured easing of the After Effects export the shutter model was fitted to", + "tags": ["effect", "motion-blur", "shutter", "after-effects", "slam", "animation"], + "files": [ + { + "path": "shutter-slam.html", + "target": "compositions/components/shutter-slam.html", + "type": "hyperframes:snippet" + } + ], + "preview": { + "poster": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shutter-slam.png" + } +} diff --git a/registry/components/shutter-slam/shutter-slam.html b/registry/components/shutter-slam/shutter-slam.html new file mode 100644 index 00000000000..2ad3207cf27 --- /dev/null +++ b/registry/components/shutter-slam/shutter-slam.html @@ -0,0 +1,541 @@ + + + + + + Shutter Slam + + + + + diff --git a/registry/examples/motion-blur/index.html b/registry/examples/motion-blur/index.html index b97741bcc02..96a5097f686 100644 --- a/registry/examples/motion-blur/index.html +++ b/registry/examples/motion-blur/index.html @@ -343,6 +343,7 @@ (function () { /* ── attachMotionBlur ─────────────────────────────────────── */ if (!window._hfMbUid) window._hfMbUid = 0; + if (!window._hfMbAttached) window._hfMbAttached = new WeakSet(); // Shutter length is measured in frames, so the snippet must know the // composition frame rate: explicit option, else the root's data-fps, else 30. @@ -361,9 +362,55 @@ return value !== undefined ? Number(value) : fallback; } - // objectBoundingBox percentage for a px offset plus padding. - function regionPercent(offset, size, padPercent) { - return ((offset / size) * 100 + padPercent).toFixed(2) + "%"; + // A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D + // matrix3d of 16. Splitting the numbers into the linear part and the + // translation is what lets the deadband below use a pixel tolerance on the + // one and an angle/ratio tolerance on the other. + function parseTransform(value) { + if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] }; + var nums = value + .slice(value.indexOf("(") + 1, -1) + .split(",") + .map(parseFloat); + if (nums.length === 16) { + return { + linear: [ + nums[0], + nums[1], + nums[2], + nums[4], + nums[5], + nums[6], + nums[8], + nums[9], + nums[10], + nums[3], + nums[7], + nums[11], + nums[15], + ], + translate: [nums[12], nums[13], nums[14]], + }; + } + return { + linear: [nums[0], nums[1], nums[2], nums[3]], + translate: [nums[4], nums[5], 0], + }; + } + + // Deadband: half a pixel of travel, a thousandth of a unit of linear change, + // about 0.06 degrees or 0.1% of scale. Below it the average is the source. + // The 2D and 3D forms have different arities, so a change of form counts as + // movement rather than being compared component by component. + function differs(a, b) { + if (a.linear.length !== b.linear.length) return true; + for (var i = 0; i < a.linear.length; i++) { + if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true; + } + for (var j = 0; j < 3; j++) { + if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true; + } + return false; } window.attachMotionBlur = function (selector, tl, opts) { @@ -374,49 +421,7 @@ var samples = Number.isFinite(requestedSamples) ? Math.max(2, Math.min(64, Math.round(requestedSamples))) : 16; - var axis = opts.axis || "both"; var fps = resolveFps(opts.fps); - var useX = axis !== "y"; - var useY = axis !== "x"; - - // Untransformed box size; SVG elements have no offsetWidth, so use the - // same bbox GSAP uses to resolve their percent transforms. - function boxSize(el, horizontal) { - var box = typeof el.offsetWidth === "number" ? el : el.getBBox ? el.getBBox() : null; - var size = box - ? horizontal - ? box.offsetWidth || box.width - : box.offsetHeight || box.height - : 0; - return size || el.getBoundingClientRect()[horizontal ? "width" : "height"] || 1; - } - - // GSAP x/y may carry a % unit and xPercent/yPercent is a separate term; - // resolve both against the element's own box so samples are in px. - function readAxis(el, prop, percentProp, size) { - var px = parseFloat(gsap.getProperty(el, prop, "px")) || 0; - var percent = parseFloat(gsap.getProperty(el, percentProp)) || 0; - return px + (percent * size) / 100; - } - - function readPosition(el) { - return { - x: useX ? readAxis(el, "x", "xPercent", boxSize(el, true)) : 0, - y: useY ? readAxis(el, "y", "yPercent", boxSize(el, false)) : 0, - }; - } - - // CSS filters run in the element's pre-transform space while GSAP x/y are - // post-transform, so a displacement is mapped through the inverse of the - // element's own scale/rotation. Ancestor transforms are not compensated. - function toFilterSpace(el, dx, dy) { - var sx = parseFloat(gsap.getProperty(el, "scaleX")) || 1; - var sy = parseFloat(gsap.getProperty(el, "scaleY")) || 1; - var theta = ((parseFloat(gsap.getProperty(el, "rotation")) || 0) * Math.PI) / 180; - var cos = Math.cos(theta); - var sin = Math.sin(theta); - return { dx: (dx * cos + dy * sin) / sx, dy: (-dx * sin + dy * cos) / sy }; - } var items = Array.isArray(selector) ? selector : [selector]; var targets = items.reduce(function (acc, s) { @@ -430,83 +435,103 @@ return acc; }, []); - var ns = "http://www.w3.org/2000/svg"; // `samples` counts sub-intervals of the shutter window, so there is one copy at // every interval boundary — both ends of the window included — and each carries // 1/samples of the source. That is what the reference export shows: the outermost // copy sits exactly one frame away from the frame time, not half a step short. var copies = samples + 1; - var weight = String(1 / samples); - - // One SVG filter per target: N+1 offset copies of SourceGraphic added at 1/N - // each, then the element itself over the top. Accumulating in sRGB matches - // AE's default (non-linear) 8-bpc working space. - var state = targets.map(function (el) { - var uid = "hf-mb-" + window._hfMbUid++; - var svg = document.createElementNS(ns, "svg"); - svg.setAttribute("style", "position:absolute;width:0;height:0;overflow:hidden;"); - - var filter = document.createElementNS(ns, "filter"); - filter.id = uid; - filter.setAttribute("color-interpolation-filters", "sRGB"); - - var offsets = []; - for (var k = 0; k < copies; k++) { - var feOff = document.createElementNS(ns, "feOffset"); - feOff.setAttribute("in", "SourceGraphic"); - feOff.setAttribute("dx", "0"); - feOff.setAttribute("dy", "0"); - feOff.setAttribute("result", "s" + k); - filter.appendChild(feOff); - offsets.push(feOff); + var alpha = String(1 / samples); + + // A copy is styled by nothing that selected the original: dropping the id also + // drops every `#id` rule that gave it size, colour and font. So each copy carries + // its own resolved style inline. Chrome returns "" for a computed style's cssText, + // so the declarations are enumerated rather than taken wholesale. + function resolvedStyles(source, out) { + var cs = getComputedStyle(source); + var text = ""; + for (var i = 0; i < cs.length; i++) { + text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";"; } - - // Pairwise accumulation: the first composite scales both inputs by 1/N, every - // later one adds the next copy at 1/N to the running sum. The N+1 weights total - // (N+1)/N, so an element wider than its own smear saturates through the middle - // and the filter clamps there. That is the saturation the reference shows, and - // the sharp instance covers the same region regardless. - var accumulated = "s0"; - for (var c = 1; c < copies; c++) { - var feComp = document.createElementNS(ns, "feComposite"); - feComp.setAttribute("operator", "arithmetic"); - feComp.setAttribute("in", accumulated); - feComp.setAttribute("in2", "s" + c); - feComp.setAttribute("k1", "0"); - feComp.setAttribute("k2", c === 1 ? weight : "1"); - feComp.setAttribute("k3", weight); - feComp.setAttribute("k4", "0"); - accumulated = "a" + c; - feComp.setAttribute("result", accumulated); - filter.appendChild(feComp); + // A copy is a still of one instant. Left live, an inherited transition or + // keyframe animation would carry it somewhere the timeline never sampled. + out.push(text + "transition:none;animation:none;"); + for (var c = 0; c < source.children.length; c++) { + resolvedStyles(source.children[c], out); } + return out; + } - // The frame-time instance is drawn sharp, at full opacity, over the smear. - // Every blurred copy stays at 1/N, so nothing but the instance the frame is - // actually at reads as solid. Unnamed, so it is the filter output. - var feOver = document.createElementNS(ns, "feComposite"); - feOver.setAttribute("operator", "over"); - feOver.setAttribute("in", "SourceGraphic"); - feOver.setAttribute("in2", accumulated); - filter.appendChild(feOver); - - svg.appendChild(filter); - document.body.appendChild(svg); + function paintResolvedStyles(copy, styles, cursor) { + copy.style.cssText = styles[cursor.i++]; + for (var c = 0; c < copy.children.length; c++) { + paintResolvedStyles(copy.children[c], styles, cursor); + } + } - return { el: el, offsets: offsets, filter: filter, filterId: uid, xs: [], ys: [] }; - }); + // Perspective applies to a parent's children only, and a copy is a grandchild. + // Sharing the parent's 3D context would need preserve-3d on the group, which + // mix-blend-mode flattens, so each copy carries the perspective itself. See the + // header for what that does to the vanishing point. + function parentPerspective(el) { + var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none"; + return value && value !== "none" ? "perspective(" + value + ") " : ""; + } - // The element may carry its own inline filter (authored or tweened by - // GSAP); the blur is appended to that chain and removed from it, never - // written over it. - var OWN_FILTER = /\s*url\(["']?#hf-mb-\d+["']?\)/g; + var state = targets + .filter(function (el) { + // One group per element. A second call on the same element would stack a + // second set of copies over the first and double the ink, so the first + // call owns it. + if (window._hfMbAttached.has(el)) return false; + window._hfMbAttached.add(el); + return true; + }) + .map(function (el) { + var group = document.createElement("div"); + group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++); + group.style.cssText = + "position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;"; + + var clones = []; + for (var k = 0; k < copies; k++) { + var clone = el.cloneNode(true); + clone.removeAttribute("id"); + clones.push(clone); + group.appendChild(clone); + } + el.parentNode.insertBefore(group, el); + + var s = { el: el, group: group, clones: clones, samples: [], perspective: "" }; + + // Resolved styles and the parent's perspective are px once read, so a + // container-relative element needs them again when its box changes. Per frame + // that would walk the whole subtree once per copy; on resize it costs nothing + // on a fixed-size render and keeps a live preview honest. + function snapshot() { + var styles = resolvedStyles(el, []); + s.perspective = parentPerspective(el); + for (var c = 0; c < clones.length; c++) { + paintResolvedStyles(clones[c], styles, { i: 0 }); + clones[c].style.position = "absolute"; + clones[c].style.margin = "0"; + clones[c].style.opacity = alpha; + clones[c].style.mixBlendMode = "plus-lighter"; + } + } - function baseFilter(el) { - return el.style.filter.replace(OWN_FILTER, "").trim(); - } + snapshot(); + if (typeof ResizeObserver === "function") new ResizeObserver(snapshot).observe(el); + return s; + }); - function clearBlur(s) { - s.el.style.filter = baseFilter(s.el); + function readTransform(el) { + var cs = getComputedStyle(el); + return { + css: cs.transform, + origin: cs.transformOrigin, + opacity: cs.opacity, + parsed: parseTransform(cs.transform), + }; } var scheduled = false; @@ -514,7 +539,9 @@ function applyShutter() { var shutterTime = shutterAngle / 360 / fps; if (!(shutterTime > 0)) { - state.forEach(clearBlur); + state.forEach(function (s) { + s.group.style.display = "none"; + }); return; } @@ -524,15 +551,13 @@ // Sample the real trajectory: seek to each sub-frame time with events // suppressed (so no tween callbacks, including this tracker's, fire), - // read positions, then restore the frame time. + // read the resolved transform, then restore the frame time. try { for (var k = 0; k < copies; k++) { var tk = windowStart + (k / samples) * shutterTime; tl.time(Math.min(duration, Math.max(0, tk)), true); state.forEach(function (s) { - var pos = readPosition(s.el); - s.xs[k] = pos.x; - s.ys[k] = pos.y; + s.samples[k] = readTransform(s.el); }); } } finally { @@ -540,48 +565,42 @@ } state.forEach(function (s) { - var current = readPosition(s.el); - var minDx = Infinity; - var maxDx = -Infinity; - var minDy = Infinity; - var maxDy = -Infinity; + var current = readTransform(s.el); + var moved = false; for (var i = 0; i < copies; i++) { - var d = toFilterSpace(s.el, s.xs[i] - current.x, s.ys[i] - current.y); - var dx = d.dx; - var dy = d.dy; - s.offsets[i].setAttribute("dx", dx.toFixed(3)); - s.offsets[i].setAttribute("dy", dy.toFixed(3)); - if (dx < minDx) minDx = dx; - if (dx > maxDx) maxDx = dx; - if (dy < minDy) minDy = dy; - if (dy > maxDy) maxDy = dy; + if (differs(s.samples[i].parsed, current.parsed)) { + moved = true; + break; + } } - - // Below half a pixel of smear the average is indistinguishable from - // the source — render sharp instead of paying for the filter. - if (maxDx - minDx < 0.5 && maxDy - minDy < 0.5) { - clearBlur(s); + if (!moved) { + s.group.style.display = "none"; return; } - // Grow the filter region to cover every copy AND the sharp instance the - // final composite draws at offset 0 (objectBoundingBox units, 10% padding - // so anti-aliased edges are not clipped). Clamping the bounds through 0 - // matters whenever the window sits entirely on one side of the frame time - // — any shutterPhase above 0 or below -shutterAngle — because then no copy - // is at 0 and a region derived from the copies alone cuts the instance off. - var x0 = Math.min(0, minDx); - var x1 = Math.max(0, maxDx); - var y0 = Math.min(0, minDy); - var y1 = Math.max(0, maxDy); - var w = boxSize(s.el, true); - var h = boxSize(s.el, false); - s.filter.setAttribute("x", regionPercent(x0, w, -10)); - s.filter.setAttribute("width", regionPercent(x1 - x0, w, 120)); - s.filter.setAttribute("y", regionPercent(y0, h, -10)); - s.filter.setAttribute("height", regionPercent(y1 - y0, h, 120)); - var base = baseFilter(s.el); - s.el.style.filter = (base ? base + " " : "") + "url(#" + s.filterId + ")"; + // The copies are absolutely positioned inside the group, and the group sits at + // the origin of the element's own containing block, so the element's offset box + // places them. Re-read every frame: a beat is free to move the box itself. + var left = s.el.offsetLeft + "px"; + var top = s.el.offsetTop + "px"; + var width = s.el.offsetWidth + "px"; + var height = s.el.offsetHeight + "px"; + for (var j = 0; j < copies; j++) { + var clone = s.clones[j]; + clone.style.left = left; + clone.style.top = top; + clone.style.width = width; + clone.style.height = height; + clone.style.transformOrigin = s.samples[j].origin; + clone.style.transform = + s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css); + } + // The copies are the element's own ink, so they have to carry its opacity too: + // a beat that moves and fades at once would otherwise leave a full-strength + // smear behind a vanishing element. It rides the group, not the copies, whose + // own opacity is the 1/N shutter weight. + s.group.style.opacity = current.opacity; + s.group.style.display = ""; }); } @@ -629,7 +648,6 @@ attachMotionBlur( ["#s1", "#s2", "#s3", "#s4", "#s5", "#t1", "#t2", "#t3", "#t4", "#t5"], tl, - { axis: "x" }, ); window.__timelines = window.__timelines || {}; diff --git a/registry/registry.json b/registry/registry.json index 79044ea9f97..37107a30703 100644 --- a/registry/registry.json +++ b/registry/registry.json @@ -1363,6 +1363,10 @@ "name": "shimmer-sweep", "type": "hyperframes:component" }, + { + "name": "shutter-slam", + "type": "hyperframes:component" + }, { "name": "signup-flow", "type": "hyperframes:component" @@ -1637,6 +1641,6 @@ } ], "catalogArtifact": { - "revision": "34370735fa1a93099519873178e547c43b14f3bd69491013577515f4bb4f5957" + "revision": "e1c1f6eb5505d4b68d8240850425465c8375fed95b0d30b31328a5a754ae7f24" } }