|
| 1 | +// @vitest-environment happy-dom |
| 2 | +import { readFileSync } from "node:fs"; |
| 3 | +import { dirname, resolve } from "node:path"; |
| 4 | +import { fileURLToPath } from "node:url"; |
| 5 | +import { afterEach, describe, expect, it } from "vitest"; |
| 6 | +import reference from "./__fixtures__/motion-blur-ae-reference.json"; |
| 7 | + |
| 8 | +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../.."); |
| 9 | + |
| 10 | +function readRepoFile(relativePath: string): string { |
| 11 | + return readFileSync(resolve(repoRoot, relativePath), "utf8"); |
| 12 | +} |
| 13 | + |
| 14 | +const snippetHtml = readRepoFile("registry/components/motion-blur/motion-blur.html"); |
| 15 | + |
| 16 | +/** First line of the snippet's IIFE body, which runs to the `};` closing it at the same indent. */ |
| 17 | +const BODY_FIRST_LINE = "if (!window._hfMbUid) window._hfMbUid = 0;"; |
| 18 | +const SNIPPET_INDENT = " ".repeat(4); |
| 19 | +const INLINED_INDENT = " ".repeat(10); |
| 20 | + |
| 21 | +/** |
| 22 | + * The snippet's IIFE body, leading whitespace dropped so the installable snippet and its inlined |
| 23 | + * copies compare regardless of how deeply each one nests it. |
| 24 | + */ |
| 25 | +function snippetBody(source: string, indent: string): string { |
| 26 | + const start = source.indexOf(indent + BODY_FIRST_LINE); |
| 27 | + const endMarker = `\n${indent}};`; |
| 28 | + const end = source.indexOf(endMarker, start); |
| 29 | + if (start < 0 || end < 0) { |
| 30 | + throw new Error(`could not locate the snippet body at indent ${indent.length}`); |
| 31 | + } |
| 32 | + return source |
| 33 | + .slice(start, end + endMarker.length) |
| 34 | + .split("\n") |
| 35 | + .map((line) => line.trimStart()) |
| 36 | + .join("\n"); |
| 37 | +} |
| 38 | + |
| 39 | +const FPS = 30; |
| 40 | +/** Timeline time of the frame under test, and a duration long enough that no seek is clamped. */ |
| 41 | +const FRAME_TIME_S = 5; |
| 42 | +const DURATION_S = 10; |
| 43 | +const WORD_WIDTH = 1046; |
| 44 | +const WORD_HEIGHT = 193; |
| 45 | + |
| 46 | +/** The slice of GSAP's timeline API the snippet drives; `time()` reads, `time(value)` seeks. */ |
| 47 | +interface Timeline { |
| 48 | + time(value?: number, suppressEvents?: boolean): number | Timeline; |
| 49 | + duration(): number; |
| 50 | + to(target: unknown, vars: { onUpdate?: () => void }): Timeline; |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * The reference's own trajectory around the measured frame: a parabola through the core centres of |
| 55 | + * frames 4, 5 and 6, with frame 5 at t = 0. Offsets are relative to the frame-time position, so the |
| 56 | + * shutter window's ends must land on exactly the trailing and leading displacements the fixture |
| 57 | + * records — which is the whole claim being pinned. |
| 58 | + */ |
| 59 | +function offsetAtFrames(df: number): number { |
| 60 | + const back = -reference.trailingDisplacementPx; |
| 61 | + const fwd = reference.leadingDisplacementPx; |
| 62 | + return ((fwd + back) / 2) * df * df + ((fwd - back) / 2) * df; |
| 63 | +} |
| 64 | + |
| 65 | +function installSnippet(): void { |
| 66 | + const body = snippetHtml.slice( |
| 67 | + snippetHtml.indexOf("<script>") + "<script>".length, |
| 68 | + snippetHtml.indexOf("</script>"), |
| 69 | + ); |
| 70 | + new Function(body)(); |
| 71 | +} |
| 72 | + |
| 73 | +function makeTimeline(): { tl: Timeline; currentTime: () => number; fire: () => void } { |
| 74 | + let now = FRAME_TIME_S; |
| 75 | + let onUpdate: (() => void) | undefined; |
| 76 | + const tl: Timeline = { |
| 77 | + time(value?: number) { |
| 78 | + if (value === undefined) return now; |
| 79 | + now = value; |
| 80 | + return tl; |
| 81 | + }, |
| 82 | + duration: () => DURATION_S, |
| 83 | + to(_target, vars) { |
| 84 | + onUpdate = vars.onUpdate; |
| 85 | + return tl; |
| 86 | + }, |
| 87 | + }; |
| 88 | + return { tl, currentTime: () => now, fire: () => onUpdate?.() }; |
| 89 | +} |
| 90 | + |
| 91 | +function installGsap(currentTime: () => number, trajectory: (df: number) => number): void { |
| 92 | + (globalThis as unknown as { gsap: unknown }).gsap = { |
| 93 | + getProperty(_el: Element, prop: string) { |
| 94 | + if (prop === "x") return `${trajectory((currentTime() - FRAME_TIME_S) * FPS)}px`; |
| 95 | + if (prop === "scaleX" || prop === "scaleY") return 1; |
| 96 | + return 0; |
| 97 | + }, |
| 98 | + }; |
| 99 | +} |
| 100 | + |
| 101 | +async function attach( |
| 102 | + options: Record<string, unknown>, |
| 103 | + trajectory: (df: number) => number = offsetAtFrames, |
| 104 | +): Promise<Element> { |
| 105 | + const el = document.createElement("div"); |
| 106 | + el.id = "word"; |
| 107 | + Object.defineProperty(el, "offsetWidth", { value: WORD_WIDTH }); |
| 108 | + Object.defineProperty(el, "offsetHeight", { value: WORD_HEIGHT }); |
| 109 | + document.body.appendChild(el); |
| 110 | + |
| 111 | + const { tl, currentTime, fire } = makeTimeline(); |
| 112 | + installGsap(currentTime, trajectory); |
| 113 | + installSnippet(); |
| 114 | + ( |
| 115 | + window as unknown as { attachMotionBlur: (s: string, t: Timeline, o: unknown) => void } |
| 116 | + ).attachMotionBlur("#word", tl, options); |
| 117 | + |
| 118 | + fire(); |
| 119 | + await Promise.resolve(); |
| 120 | + const filter = document.querySelector("filter"); |
| 121 | + if (!filter) throw new Error("motion-blur filter was not created"); |
| 122 | + return filter; |
| 123 | +} |
| 124 | + |
| 125 | +/** Horizontal offset of every duplicate, in window order. */ |
| 126 | +function copyOffsets(filter: Element): number[] { |
| 127 | + return [...filter.querySelectorAll("feOffset")].map((node) => Number(node.getAttribute("dx"))); |
| 128 | +} |
| 129 | + |
| 130 | +/** The duplicates sitting at the two ends of the shutter window. */ |
| 131 | +function windowEdges(offsets: number[]): { trailing: number; leading: number } { |
| 132 | + const [trailing] = offsets; |
| 133 | + const leading = offsets.at(-1); |
| 134 | + if (trailing === undefined || leading === undefined) { |
| 135 | + throw new Error("the filter carries no duplicates"); |
| 136 | + } |
| 137 | + return { trailing, leading }; |
| 138 | +} |
| 139 | + |
| 140 | +/** Gap between each pair of neighbouring duplicates. */ |
| 141 | +function copyPitches(offsets: number[]): number[] { |
| 142 | + const pitches: number[] = []; |
| 143 | + offsets.forEach((offset, index) => { |
| 144 | + const previous = offsets[index - 1]; |
| 145 | + if (previous !== undefined) pitches.push(offset - previous); |
| 146 | + }); |
| 147 | + return pitches; |
| 148 | +} |
| 149 | + |
| 150 | +afterEach(() => { |
| 151 | + document.body.innerHTML = ""; |
| 152 | +}); |
| 153 | + |
| 154 | +describe("motion-blur snippet copies", () => { |
| 155 | + // The demo and the example composition have to inline the snippet — a catalog demo is a single |
| 156 | + // self-contained file and cannot import one. That makes three copies of the same shutter model, so |
| 157 | + // the copies are asserted equal here rather than left to drift silently. |
| 158 | + it.each([ |
| 159 | + "registry/components/motion-blur/demo.html", |
| 160 | + "registry/examples/motion-blur/index.html", |
| 161 | + ])("%s inlines the installable snippet verbatim", (relativePath) => { |
| 162 | + expect(snippetBody(readRepoFile(relativePath), INLINED_INDENT)).toBe( |
| 163 | + snippetBody(snippetHtml, SNIPPET_INDENT), |
| 164 | + ); |
| 165 | + }); |
| 166 | +}); |
| 167 | + |
| 168 | +describe("motion-blur shutter matches the After Effects reference", () => { |
| 169 | + it("opens the shutter over the frame before and the frame after, at the measured sub-interval count", async () => { |
| 170 | + const offsets = copyOffsets(await attach({ fps: FPS })); |
| 171 | + const { trailing, leading } = windowEdges(offsets); |
| 172 | + |
| 173 | + expect(offsets).toHaveLength(reference.subIntervalsPerWindow + 1); |
| 174 | + expect(trailing).toBeCloseTo(-reference.trailingDisplacementPx, 1); |
| 175 | + expect(leading).toBeCloseTo(reference.leadingDisplacementPx, 1); |
| 176 | + }); |
| 177 | + |
| 178 | + it("spaces the duplicates at the measured staircase pitch", async () => { |
| 179 | + // The reference's staircase is even (15, 16, 16, 15, 16, 16, 16 px across a 125.8 px frame |
| 180 | + // displacement), so a constant-velocity trajectory has to come out evenly spaced at 1/8 frame. |
| 181 | + const speed = reference.trailingDisplacementPx; |
| 182 | + const offsets = copyOffsets(await attach({ fps: FPS }, (df) => speed * df)); |
| 183 | + const expected = speed / (reference.subIntervalsPerWindow / 2); |
| 184 | + |
| 185 | + for (const pitch of copyPitches(offsets)) expect(pitch).toBeCloseTo(expected, 3); |
| 186 | + }); |
| 187 | + |
| 188 | + it("gives every duplicate the measured 1/16 opacity and none full opacity", async () => { |
| 189 | + const filter = await attach({ fps: FPS }); |
| 190 | + const weights = [...filter.querySelectorAll("feComposite[operator='arithmetic']")].map((node) => |
| 191 | + Number(node.getAttribute("k3")), |
| 192 | + ); |
| 193 | + |
| 194 | + expect(weights).toHaveLength(reference.subIntervalsPerWindow); |
| 195 | + for (const weight of weights) expect(weight).toBeCloseTo(reference.copyOpacity, 6); |
| 196 | + // Flat, not tapered: the reference's plateau increments are all the same height. |
| 197 | + expect(new Set(weights).size).toBe(1); |
| 198 | + }); |
| 199 | + |
| 200 | + it("accumulates every duplicate exactly once, in one unbroken chain", async () => { |
| 201 | + const filter = await attach({ fps: FPS }); |
| 202 | + const adds = [...filter.querySelectorAll("feComposite[operator='arithmetic']")]; |
| 203 | + const weight = 1 / reference.subIntervalsPerWindow; |
| 204 | + |
| 205 | + // The first composite is the only one that has to scale BOTH inputs, because it is the |
| 206 | + // only one whose `in` is a raw duplicate rather than the running sum. Getting its k2 |
| 207 | + // wrong lets one duplicate through at full weight — the exact thing the reference rules out. |
| 208 | + expect(adds[0]?.getAttribute("in")).toBe("s0"); |
| 209 | + expect(Number(adds[0]?.getAttribute("k2"))).toBeCloseTo(weight, 6); |
| 210 | + for (const add of adds.slice(1)) expect(Number(add.getAttribute("k2"))).toBe(1); |
| 211 | + |
| 212 | + // Each composite must fold in the next duplicate and feed the one after it, so every |
| 213 | + // duplicate reaches the output and none is added twice. |
| 214 | + adds.forEach((add, index) => { |
| 215 | + expect(add.getAttribute("in")).toBe(index === 0 ? "s0" : `a${index}`); |
| 216 | + expect(add.getAttribute("in2")).toBe(`s${index + 1}`); |
| 217 | + expect(add.getAttribute("result")).toBe(`a${index + 1}`); |
| 218 | + }); |
| 219 | + }); |
| 220 | + |
| 221 | + it("composites the sharp frame-time instance over the full accumulated smear", async () => { |
| 222 | + const filter = await attach({ fps: FPS }); |
| 223 | + const last = filter.lastElementChild; |
| 224 | + |
| 225 | + expect(last?.tagName).toBe("feComposite"); |
| 226 | + expect(last?.getAttribute("operator")).toBe("over"); |
| 227 | + expect(last?.getAttribute("in")).toBe("SourceGraphic"); |
| 228 | + // in2 must be the END of the accumulation chain, not some intermediate or single copy. |
| 229 | + expect(last?.getAttribute("in2")).toBe(`a${reference.subIntervalsPerWindow}`); |
| 230 | + expect(last?.getAttribute("result")).toBeNull(); |
| 231 | + }); |
| 232 | + |
| 233 | + it("keeps the sharp instance inside the filter region when the window is entirely one-sided", async () => { |
| 234 | + // shutterPhase 0 opens the shutter at the frame time, so every duplicate is ahead of the |
| 235 | + // element and no duplicate sits at offset 0 — but the sharp instance still does. A region |
| 236 | + // derived from the duplicates alone starts inside the element's own box and clips it. |
| 237 | + const filter = await attach({ fps: FPS, shutterPhase: 360 }); |
| 238 | + const offsets = copyOffsets(filter); |
| 239 | + |
| 240 | + expect(Math.min(...offsets)).toBeGreaterThan(0); |
| 241 | + expect(Number.parseFloat(filter.getAttribute("x") ?? "")).toBeLessThanOrEqual(0); |
| 242 | + const right = |
| 243 | + Number.parseFloat(filter.getAttribute("x") ?? "") + |
| 244 | + Number.parseFloat(filter.getAttribute("width") ?? ""); |
| 245 | + expect(right).toBeGreaterThanOrEqual((Math.max(...offsets) / WORD_WIDTH) * 100 + 100); |
| 246 | + }); |
| 247 | +}); |
0 commit comments