@editframe/elements 0.46.4 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/elements/EFCaptions.d.ts +2 -2
- package/dist/elements/EFMedia/BufferedSeekingInput.d.ts +50 -0
- package/dist/elements/EFMedia/BufferedSeekingInput.js +6 -5
- package/dist/elements/EFMedia/BufferedSeekingInput.js.map +1 -1
- package/dist/elements/EFMedia/CachedFetcher.js +23 -33
- package/dist/elements/EFMedia/CachedFetcher.js.map +1 -1
- package/dist/elements/EFMedia/SegmentTransport.d.ts +2 -2
- package/dist/elements/EFMedia/SegmentTransport.js.map +1 -1
- package/dist/elements/EFMedia/shared/ThumbnailExtractor.js +53 -0
- package/dist/elements/EFMedia/shared/ThumbnailExtractor.js.map +1 -1
- package/dist/elements/EFMedia/videoTasks/MainVideoInputCache.js +20 -5
- package/dist/elements/EFMedia/videoTasks/MainVideoInputCache.js.map +1 -1
- package/dist/elements/EFMedia/videoTasks/ScrubInputCache.d.ts +48 -0
- package/dist/elements/EFMedia/videoTasks/ScrubInputCache.js +36 -7
- package/dist/elements/EFMedia/videoTasks/ScrubInputCache.js.map +1 -1
- package/dist/elements/EFMedia.d.ts +2 -2
- package/dist/elements/EFMotionBlur.d.ts +130 -0
- package/dist/elements/EFMotionBlur.js +808 -0
- package/dist/elements/EFMotionBlur.js.map +1 -0
- package/dist/elements/EFTemporal.js +1 -2
- package/dist/elements/EFTemporal.js.map +1 -1
- package/dist/elements/EFText.d.ts +20 -0
- package/dist/elements/EFText.js +66 -9
- package/dist/elements/EFText.js.map +1 -1
- package/dist/elements/EFTimegroup.d.ts +12 -0
- package/dist/elements/EFTimegroup.js +43 -4
- package/dist/elements/EFTimegroup.js.map +1 -1
- package/dist/elements/EFVideo.d.ts +26 -0
- package/dist/elements/EFVideo.js +114 -36
- package/dist/elements/EFVideo.js.map +1 -1
- package/dist/elements/SampleBuffer.d.ts +19 -0
- package/dist/elements/updateAnimations.js +49 -3
- package/dist/elements/updateAnimations.js.map +1 -1
- package/dist/gui/EFWorkbench.d.ts +1 -0
- package/dist/gui/EFWorkbench.js +15 -0
- package/dist/gui/EFWorkbench.js.map +1 -1
- package/dist/gui/EFWorkbench.spacebar.js +26 -0
- package/dist/gui/EFWorkbench.spacebar.js.map +1 -0
- package/dist/gui/TWMixin.js +1 -1
- package/dist/gui/TWMixin.js.map +1 -1
- package/dist/gui/timeline/EFTimeline.d.ts +18 -1
- package/dist/gui/timeline/EFTimeline.js +119 -25
- package/dist/gui/timeline/EFTimeline.js.map +1 -1
- package/dist/gui/timeline/timelineStateContext.d.ts +2 -0
- package/dist/gui/timeline/timelineStateContext.js.map +1 -1
- package/dist/gui/timeline/tracks/EFThumbnailStrip.js +14 -8
- package/dist/gui/timeline/tracks/EFThumbnailStrip.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/preview/FrameController.d.ts +22 -1
- package/dist/preview/FrameController.js +26 -5
- package/dist/preview/FrameController.js.map +1 -1
- package/dist/preview/QualityUpgradeScheduler.d.ts +11 -2
- package/dist/preview/QualityUpgradeScheduler.js +31 -21
- package/dist/preview/QualityUpgradeScheduler.js.map +1 -1
- package/dist/preview/renderTimegroupToCanvas.js +4 -0
- package/dist/preview/renderTimegroupToCanvas.js.map +1 -1
- package/dist/preview/renderTimegroupToCanvas.types.d.ts +2 -0
- package/dist/preview/renderTimegroupToVideo.js +3 -0
- package/dist/preview/renderTimegroupToVideo.js.map +1 -1
- package/dist/preview/rendering/serializeTimelineDirect.js +30 -35
- package/dist/preview/rendering/serializeTimelineDirect.js.map +1 -1
- package/dist/style.css +4 -0
- package/dist/utils/LRUCache.js +17 -5
- package/dist/utils/LRUCache.js.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"updateAnimations.js","names":["warnings: string[]","timeSource: AnimatableElement | null","staggerElement: AnimatableElement | null","data: CachedAnimationData","node: Element | null","childContexts: ElementUpdateContext[]","visibleChildContexts: ElementUpdateContext[]"],"sources":["../../src/elements/updateAnimations.ts"],"sourcesContent":["import {\n deepGetTemporalElements,\n isEFTemporal,\n type TemporalMixinInterface,\n} from \"./EFTemporal.ts\";\n\n// All animatable elements are temporal elements with HTMLElement interface\nexport type AnimatableElement = TemporalMixinInterface & HTMLElement;\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst ANIMATION_PRECISION_OFFSET = 0.1; // Use 0.1ms to safely avoid completion threshold\nconst DEFAULT_ANIMATION_ITERATIONS = 1;\nconst PROGRESS_PROPERTY = \"--ef-progress\";\nconst DURATION_PROPERTY = \"--ef-duration\";\nconst TRANSITION_DURATION_PROPERTY = \"--ef-transition-duration\";\nconst TRANSITION_OUT_START_PROPERTY = \"--ef-transition-out-start\";\n\n// ============================================================================\n// Animation Tracking\n// ============================================================================\n\n/**\n * Tracks animations per element to prevent them from being lost when they complete.\n * Once an animation reaches 100% completion, it's removed from getAnimations(),\n * but we keep a reference to it so we can continue controlling it.\n */\nconst animationTracker = new WeakMap<Element, Set<Animation>>();\n\n/**\n * Tracks whether DOM structure has changed for an element, requiring animation rediscovery.\n * For render clones (static DOM), this stays false after initial discovery.\n * For prime timeline (interactive), this is set to true when mutations occur.\n */\nconst domStructureChanged = new WeakMap<Element, boolean>();\n\n/**\n * Tracks the last known animation count for an element to detect new animations.\n * Used as a lightweight check before calling expensive getAnimations().\n */\nconst lastAnimationCount = new WeakMap<Element, number>();\n\n/**\n * Tracks which animations have already been validated to avoid duplicate warnings.\n * Uses animation name + duration as the unique key.\n */\nconst validatedAnimations = new Set<string>();\n\n/**\n * Tracks animations that have already been taken under manual control.\n * Once an animation is here, its playState is known to be \"paused\" or \"idle\" —\n * both accept currentTime writes without preconditions and without causing reflow.\n * This lets prepareAnimation skip cancel()/pause() on every subsequent frame.\n */\nconst preparedAnimations = new WeakSet<Animation>();\n\n/**\n * Per-animation data derived once from the animation's immutable properties:\n * timing (duration/delay/iterations/direction), time source (nearest ef-timegroup),\n * stagger element (nearest ef-text-segment), and effective delay.\n *\n * All of these are fixed for the lifetime of an animation — the target's position\n * in the DOM and the animation's keyframe timing never change during scrubbing.\n * Caching avoids effect.getTiming() and target.closest() on every frame.\n */\ninterface CachedAnimationData {\n timing: AnimationTiming;\n timeSource: AnimatableElement | null; // null means \"use the root element passed in\"\n staggerElement: AnimatableElement | null; // null means \"use timeSource\"\n effectiveDelay: number;\n}\nconst animationCache = new WeakMap<Animation, CachedAnimationData>();\n\n/**\n * Validates that an animation is still valid and controllable.\n * Animations become invalid when:\n * - They've been cancelled (idle state and not in getAnimations())\n * - Their effect is null (animation was removed)\n * - Their target is no longer in the DOM\n */\nconst isAnimationValid = (animation: Animation, currentAnimations: Animation[]): boolean => {\n // Check if animation is no longer in the live animation list.\n // Avoid reading animation.playState — it forces style recalculation in Chromium.\n if (!currentAnimations.includes(animation)) {\n return false;\n }\n\n // Check if animation effect is still valid\n const effect = animation.effect;\n if (!effect) {\n return false;\n }\n\n // Check if target is still in DOM\n if (effect instanceof KeyframeEffect) {\n const target = effect.target;\n if (target && target instanceof Element) {\n if (!target.isConnected) {\n return false;\n }\n }\n }\n\n return true;\n};\n\n/**\n * Discovers and tracks animations on an element and its subtree.\n * This ensures we have references to animations even after they complete.\n *\n * Tracks animations per element where they exist, not just on the root element.\n * This allows us to find animations on any element in the subtree.\n *\n * OPTIMIZATION: For render clones (static DOM), discovery happens once at creation.\n * For prime timeline (interactive), discovery is responsive to DOM changes.\n *\n * Also cleans up invalid animations (cancelled, removed from DOM, etc.)\n *\n * @param providedAnimations - Optional pre-discovered animations to avoid redundant getAnimations() calls\n */\nconst discoverAndTrackAnimations = (\n element: AnimatableElement,\n providedAnimations?: Animation[],\n): { tracked: Set<Animation>; current: Animation[] } => {\n animationTracker.has(element);\n const structureChanged = domStructureChanged.get(element) ?? true;\n\n // REMOVED: Clone optimization that cached animation references.\n // The optimization assumed animations were \"static\" for clones, but this was incorrect.\n // After seeking to a new time, we need fresh animation state from the browser.\n // Caching caused animations to be stuck at their discovery state (often 0ms).\n\n // For prime timeline or first discovery: get current animations from the browser (includes subtree)\n // CRITICAL: This is expensive, so we return it to avoid calling it again\n // If animations were provided by caller (to avoid redundant calls), use those\n const currentAnimations = providedAnimations ?? element.getAnimations({ subtree: true });\n\n // Mark structure as stable after discovery\n // This prevents redundant getAnimations() calls when DOM hasn't changed\n domStructureChanged.set(element, false);\n\n // Track animation count for lightweight change detection\n lastAnimationCount.set(element, currentAnimations.length);\n\n // Track animations on each element where they exist\n for (const animation of currentAnimations) {\n const effect = animation.effect;\n const target = effect && effect instanceof KeyframeEffect ? effect.target : null;\n if (target && target instanceof Element) {\n let tracked = animationTracker.get(target);\n if (!tracked) {\n tracked = new Set<Animation>();\n animationTracker.set(target, tracked);\n }\n tracked.add(animation);\n }\n }\n\n // Also maintain a set on the root element for coordination\n let rootTracked = animationTracker.get(element);\n if (!rootTracked) {\n rootTracked = new Set<Animation>();\n animationTracker.set(element, rootTracked);\n }\n\n // Update root set with all current animations\n for (const animation of currentAnimations) {\n rootTracked.add(animation);\n }\n\n // Clean up invalid animations from root set\n // This handles animations that were cancelled, removed from DOM, or had their effects removed\n for (const animation of rootTracked) {\n if (!isAnimationValid(animation, currentAnimations)) {\n rootTracked.delete(animation);\n }\n }\n\n // Build a map of element -> current animations from the subtree lookup we already did\n // This avoids calling getAnimations() repeatedly on each element (expensive!)\n const elementAnimationsMap = new Map<Element, Animation[]>();\n for (const animation of currentAnimations) {\n const effect = animation.effect;\n const target = effect && effect instanceof KeyframeEffect ? effect.target : null;\n if (target && target instanceof Element) {\n let anims = elementAnimationsMap.get(target);\n if (!anims) {\n anims = [];\n elementAnimationsMap.set(target, anims);\n }\n anims.push(animation);\n }\n }\n\n // Clean up invalid animations from per-element sets.\n // Only walk the full subtree when DOM structure has changed (elements added/removed).\n // During scrubbing with static DOM, skip this expensive querySelectorAll(\"*\").\n if (structureChanged) {\n for (const [el, tracked] of elementAnimationsMap) {\n const existingTracked = animationTracker.get(el);\n if (existingTracked) {\n for (const animation of existingTracked) {\n if (!isAnimationValid(animation, tracked)) {\n existingTracked.delete(animation);\n }\n }\n if (existingTracked.size === 0) {\n animationTracker.delete(el);\n }\n }\n }\n }\n\n return { tracked: rootTracked, current: currentAnimations };\n};\n\n/**\n * Returns the number of animations tracked for an element.\n * Exported for testing only.\n */\nexport const getTrackedAnimationCount = (element: Element): number => {\n return animationTracker.get(element)?.size ?? 0;\n};\n\n/**\n * Cancels all tracked animations for an element and removes them from tracking.\n * Called when an element is hidden so paused WAAPI animations leave getAnimations(),\n * preventing unbounded growth of getAnimations({subtree:true}) during scrubbing.\n */\nconst cancelTrackedAnimations = (element: Element): void => {\n // Cancel animations from the tracker. cancel() is safe on any state including idle.\n const tracked = animationTracker.get(element);\n if (tracked) {\n for (const animation of tracked) {\n animation.cancel();\n preparedAnimations.delete(animation);\n animationCache.delete(animation);\n }\n tracked.clear();\n }\n // Also cancel any live animations on the element's subtree that may not be tracked yet.\n // getAnimations() only returns non-idle animations, so no guard needed.\n const subtreeAnims = (element as HTMLElement).getAnimations?.({ subtree: true });\n if (subtreeAnims) {\n for (const animation of subtreeAnims) {\n animation.cancel();\n preparedAnimations.delete(animation);\n animationCache.delete(animation);\n }\n }\n};\n\n/**\n * Cleans up tracked animations when an element is disconnected.\n * This prevents memory leaks.\n */\nexport const cleanupTrackedAnimations = (element: Element): void => {\n animationTracker.delete(element);\n domStructureChanged.delete(element);\n lastAnimationCount.delete(element);\n};\n\n/**\n * Marks that DOM structure has changed for an element, requiring animation rediscovery.\n * Should be called when elements are added/removed or CSS classes change that affect animations.\n */\nexport const markDomStructureChanged = (element: Element): void => {\n domStructureChanged.set(element, true);\n};\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Represents the phase an element is in relative to the timeline.\n * This is the primary concept that drives all visibility and animation decisions.\n */\nexport type ElementPhase = \"before-start\" | \"active\" | \"at-end-boundary\" | \"after-end\";\n\n/**\n * Represents the temporal state of an element relative to the timeline\n */\ninterface TemporalState {\n progress: number;\n isVisible: boolean;\n timelineTimeMs: number;\n phase: ElementPhase;\n}\n\n/**\n * Context object that holds all evaluated state for an element update.\n * This groups related state together, reducing parameter passing and making\n * the data flow clearer.\n */\ninterface ElementUpdateContext {\n element: AnimatableElement;\n state: TemporalState;\n}\n\n/**\n * Animation timing information extracted from an animation effect.\n * Groups related timing properties together.\n */\ninterface AnimationTiming {\n duration: number;\n delay: number;\n iterations: number;\n direction: string;\n}\n\n/**\n * Capability interface for elements that support stagger offset.\n * This encapsulates the stagger behavior behind a capability check rather than\n * leaking tag name checks throughout the codebase.\n */\ninterface StaggerableElement extends AnimatableElement {\n staggerOffsetMs?: number;\n}\n\n// ============================================================================\n// Phase Determination\n// ============================================================================\n\n/**\n * Determines what phase an element is in relative to the timeline.\n *\n * WHY: Phase is the primary concept that drives all decisions. By explicitly\n * enumerating phases, we make the code's logic clear: phase determines visibility,\n * animation coordination, and visual state.\n *\n * Phases:\n * - before-start: Timeline is before element's start time\n * - active: Timeline is within element's active range (start to end, exclusive of end)\n * - at-end-boundary: Timeline is exactly at element's end time\n * - after-end: Timeline is after element's end time\n *\n * Note: We detect \"at-end-boundary\" by checking if timeline equals end time.\n * The boundary policy will then determine if this should be treated as visible/active\n * or not based on element characteristics.\n */\nconst determineElementPhase = (\n element: AnimatableElement,\n timelineTimeMs: number,\n): ElementPhase => {\n // Read endTimeMs once to avoid recalculation issues\n const endTimeMs = element.endTimeMs;\n const startTimeMs = element.startTimeMs;\n\n // Invalid range (end <= start) means element hasn't computed its duration yet,\n // or has no temporal children (e.g., timegroup with only static HTML).\n // Treat as always active - these elements should be visible at all times.\n if (endTimeMs <= startTimeMs) {\n return \"active\";\n }\n\n if (timelineTimeMs < startTimeMs) {\n return \"before-start\";\n }\n // Use epsilon to handle floating point precision issues\n const epsilon = 0.001;\n const diff = timelineTimeMs - endTimeMs;\n\n // If clearly after end (difference > epsilon), return 'after-end'\n if (diff > epsilon) {\n return \"after-end\";\n }\n // If at or very close to end boundary (within epsilon), return 'at-end-boundary'\n if (Math.abs(diff) <= epsilon) {\n return \"at-end-boundary\";\n }\n // Otherwise, we're before the end, so check if we're active\n return \"active\";\n};\n\n// ============================================================================\n// Boundary Policies\n// ============================================================================\n\n/**\n * Policy interface for determining behavior at boundaries.\n * Different policies apply different rules for when elements should be visible\n * or have animations coordinated at exact boundary times.\n */\ninterface BoundaryPolicy {\n /**\n * Determines if an element should be considered visible/active at the end boundary\n * based on the element's characteristics.\n */\n shouldIncludeEndBoundary(element: AnimatableElement): boolean;\n}\n\n/**\n * Visibility policy: determines when elements should be visible for display purposes.\n *\n * WHY: Root elements, elements aligned with composition end, and text segments\n * should remain visible at exact end time to prevent flicker and show final frames.\n * Other elements use exclusive end for clean transitions between elements.\n */\nclass VisibilityPolicy implements BoundaryPolicy {\n shouldIncludeEndBoundary(element: AnimatableElement): boolean {\n // Root elements should remain visible at exact end time to prevent flicker\n const isRootElement = !element.parentTimegroup;\n if (isRootElement) {\n return true;\n }\n\n // Elements aligned with composition end should remain visible at exact end time\n const isLastElementInComposition = element.endTimeMs === element.rootTimegroup?.endTimeMs;\n if (isLastElementInComposition) {\n return true;\n }\n\n // Text segments use inclusive end since they're meant to be visible for full duration\n if (this.isTextSegment(element)) {\n return true;\n }\n\n // Other elements use exclusive end for clean transitions\n return false;\n }\n\n /**\n * Checks if element is a text segment.\n * Encapsulates the tag name check to hide implementation detail.\n */\n protected isTextSegment(element: AnimatableElement): boolean {\n return element.tagName === \"EF-TEXT-SEGMENT\";\n }\n}\n\n// Policy instances (singleton pattern for stateless policies)\nconst visibilityPolicy = new VisibilityPolicy();\n\n/**\n * Determines if an element should be visible based on its phase and visibility policy.\n */\nconst shouldBeVisible = (phase: ElementPhase, element: AnimatableElement): boolean => {\n if (phase === \"before-start\" || phase === \"after-end\") {\n return false;\n }\n if (phase === \"active\") {\n return true;\n }\n // phase === \"at-end-boundary\"\n return visibilityPolicy.shouldIncludeEndBoundary(element);\n};\n\n/**\n * Determines if animations should be coordinated based on element phase and animation policy.\n *\n * CRITICAL: Always returns true to support scrubbing to arbitrary times.\n *\n * Previously, this function skipped coordination for before-start and after-end phases as an\n * optimization for live playback. However, this broke scrubbing scenarios where we seek to\n * arbitrary times (timeline scrubbing, thumbnails, video export).\n *\n * The performance cost of always coordinating is minimal:\n * - Animations only update when element time changes\n * - Paused animation updates are optimized by the browser\n * - The benefit is correct animation state at all times, regardless of phase\n */\nconst shouldCoordinateAnimations = (_phase: ElementPhase, _element: AnimatableElement): boolean => {\n return true;\n};\n\n// ============================================================================\n// Temporal State Evaluation\n// ============================================================================\n\n/**\n * Evaluates what the element's state should be based on the timeline.\n *\n * WHY: This function determines the complete temporal state including phase,\n * which becomes the primary driver for all subsequent decisions.\n */\nexport const evaluateTemporalState = (element: AnimatableElement): TemporalState => {\n // Get timeline time from root timegroup, or use element's own time if it IS a timegroup\n const timelineTimeMs = (element.rootTimegroup ?? element).currentTimeMs;\n\n const progress =\n element.durationMs <= 0\n ? 1\n : Math.max(0, Math.min(1, element.currentTimeMs / element.durationMs));\n\n const phase = determineElementPhase(element, timelineTimeMs);\n const isVisible = shouldBeVisible(phase, element);\n\n return { progress, isVisible, timelineTimeMs, phase };\n};\n\n/**\n * Evaluates element visibility state specifically for animation coordination.\n * Uses inclusive end boundaries to prevent animation jumps at exact boundaries.\n *\n * This is exported for external use cases that need animation-specific visibility\n * evaluation without the full ElementUpdateContext.\n */\nexport const evaluateAnimationVisibilityState = (element: AnimatableElement): TemporalState => {\n const state = evaluateTemporalState(element);\n // Override visibility based on animation policy\n const shouldCoordinate = shouldCoordinateAnimations(state.phase, element);\n return { ...state, isVisible: shouldCoordinate };\n};\n\n// ============================================================================\n// Animation Time Mapping\n// ============================================================================\n\n/**\n * Capability check: determines if an element supports stagger offset.\n * Encapsulates the knowledge of which element types support this feature.\n */\nconst supportsStaggerOffset = (element: AnimatableElement): element is StaggerableElement => {\n // Currently only text segments support stagger offset\n return element.tagName === \"EF-TEXT-SEGMENT\";\n};\n\n/**\n * Calculates effective delay including stagger offset if applicable.\n *\n * Stagger offset allows elements (like text segments) to have their animations\n * start at different times while keeping their visibility timing unchanged.\n * This enables staggered animation effects within a single timegroup.\n */\nconst calculateEffectiveDelay = (delay: number, element: AnimatableElement): number => {\n if (supportsStaggerOffset(element)) {\n // Read stagger offset - try property first (more reliable), then CSS variable\n // The staggerOffsetMs property is set directly on the element and is always available\n const segment = element as any;\n if (segment.staggerOffsetMs !== undefined && segment.staggerOffsetMs !== null) {\n return delay + segment.staggerOffsetMs;\n }\n\n // Fallback to CSS variable if property not available\n let cssValue = (element as HTMLElement).style.getPropertyValue(\"--ef-stagger-offset\").trim();\n\n if (!cssValue) {\n cssValue = window.getComputedStyle(element).getPropertyValue(\"--ef-stagger-offset\").trim();\n }\n\n if (cssValue) {\n // Parse \"100ms\" format to milliseconds\n const match = cssValue.match(/(\\d+(?:\\.\\d+)?)\\s*ms?/);\n if (match) {\n const staggerOffset = parseFloat(match[1]!);\n if (!isNaN(staggerOffset)) {\n return delay + staggerOffset;\n }\n } else {\n // Try parsing as just a number\n const numValue = parseFloat(cssValue);\n if (!isNaN(numValue)) {\n return delay + numValue;\n }\n }\n }\n }\n return delay;\n};\n\n/**\n * Calculates maximum safe animation time to prevent completion.\n *\n * WHY: Once an animation reaches \"finished\" state, it can no longer be manually controlled\n * via currentTime. By clamping to just before completion (using ANIMATION_PRECISION_OFFSET),\n * we ensure the animation remains in a controllable state, allowing us to synchronize it\n * with the timeline even when it would naturally be complete.\n */\nconst calculateMaxSafeAnimationTime = (duration: number, iterations: number): number => {\n return duration * iterations - ANIMATION_PRECISION_OFFSET;\n};\n\n/**\n * Determines if the current iteration should be reversed based on direction\n */\nconst shouldReverseIteration = (direction: string, currentIteration: number): boolean => {\n return (\n direction === \"reverse\" ||\n (direction === \"alternate\" && currentIteration % 2 === 1) ||\n (direction === \"alternate-reverse\" && currentIteration % 2 === 0)\n );\n};\n\n/**\n * Applies direction to iteration time (reverses if needed)\n */\nconst applyDirectionToIterationTime = (\n currentIterationTime: number,\n duration: number,\n direction: string,\n currentIteration: number,\n): number => {\n if (shouldReverseIteration(direction, currentIteration)) {\n return duration - currentIterationTime;\n }\n return currentIterationTime;\n};\n\n/**\n * Maps element time to animation time for normal direction.\n * Uses cumulative time throughout the animation.\n * Note: elementTime should already be adjusted (elementTime - effectiveDelay).\n */\nconst mapNormalDirectionTime = (\n elementTime: number,\n duration: number,\n maxSafeTime: number,\n): number => {\n const currentIteration = Math.floor(elementTime / duration);\n const iterationTime = elementTime % duration;\n const cumulativeTime = currentIteration * duration + iterationTime;\n return Math.min(cumulativeTime, maxSafeTime);\n};\n\n/**\n * Maps element time to animation time for reverse direction.\n * Uses cumulative time with reversed iterations.\n * Note: elementTime should already be adjusted (elementTime - effectiveDelay).\n */\nconst mapReverseDirectionTime = (\n elementTime: number,\n duration: number,\n maxSafeTime: number,\n): number => {\n const currentIteration = Math.floor(elementTime / duration);\n const rawIterationTime = elementTime % duration;\n const reversedIterationTime = duration - rawIterationTime;\n const cumulativeTime = currentIteration * duration + reversedIterationTime;\n return Math.min(cumulativeTime, maxSafeTime);\n};\n\n/**\n * Maps element time to animation time for alternate/alternate-reverse directions.\n *\n * WHY SPECIAL HANDLING: Alternate directions oscillate between forward and reverse iterations.\n * Without delay, we use iteration time (0 to duration) because the animation naturally\n * resets each iteration. However, with delay, iteration 0 needs to account for the delay\n * offset (using ownCurrentTimeMs), and later iterations need cumulative time to properly\n * track progress across multiple iterations. This complexity requires a dedicated mapper\n * rather than trying to handle it in the general case.\n */\nconst mapAlternateDirectionTime = (\n elementTime: number,\n effectiveDelay: number,\n duration: number,\n direction: string,\n maxSafeTime: number,\n): number => {\n const adjustedTime = elementTime - effectiveDelay;\n\n if (effectiveDelay > 0) {\n // With delay: iteration 0 uses elementTime to include delay offset,\n // later iterations use cumulative time to track progress across iterations\n const currentIteration = Math.floor(adjustedTime / duration);\n if (currentIteration === 0) {\n return Math.min(elementTime, maxSafeTime);\n }\n return Math.min(adjustedTime, maxSafeTime);\n }\n\n // Without delay: use iteration time (after direction applied) since animation\n // naturally resets each iteration\n const currentIteration = Math.floor(elementTime / duration);\n const rawIterationTime = elementTime % duration;\n const iterationTime = applyDirectionToIterationTime(\n rawIterationTime,\n duration,\n direction,\n currentIteration,\n );\n return Math.min(iterationTime, maxSafeTime);\n};\n\n/**\n * Maps element time to animation time based on direction.\n *\n * WHY: This function explicitly transforms element time to animation time, making\n * the time mapping concept clear. Different directions require different transformations\n * to achieve the desired visual effect.\n */\nconst mapElementTimeToAnimationTime = (\n elementTime: number,\n timing: AnimationTiming,\n effectiveDelay: number,\n): number => {\n const { duration, iterations, direction } = timing;\n const maxSafeTime = calculateMaxSafeAnimationTime(duration, iterations);\n // Calculate adjusted time (element time minus delay) for normal/reverse directions\n const adjustedTime = elementTime - effectiveDelay;\n\n if (direction === \"reverse\") {\n return mapReverseDirectionTime(adjustedTime, duration, maxSafeTime);\n }\n if (direction === \"alternate\" || direction === \"alternate-reverse\") {\n return mapAlternateDirectionTime(elementTime, effectiveDelay, duration, direction, maxSafeTime);\n }\n // normal direction - use adjustedTime to account for delay\n return mapNormalDirectionTime(adjustedTime, duration, maxSafeTime);\n};\n\n/**\n * Determines the animation time for a completed animation based on direction.\n */\nconst getCompletedAnimationTime = (timing: AnimationTiming, maxSafeTime: number): number => {\n const { direction, iterations, duration } = timing;\n\n if (direction === \"alternate\" || direction === \"alternate-reverse\") {\n // For alternate directions, determine if final iteration is reversed\n const finalIteration = iterations - 1;\n const isFinalIterationReversed =\n (direction === \"alternate\" && finalIteration % 2 === 1) ||\n (direction === \"alternate-reverse\" && finalIteration % 2 === 0);\n\n if (isFinalIterationReversed) {\n // At end of reversed iteration, currentTime should be near 0 (but clamped)\n return Math.min(duration - ANIMATION_PRECISION_OFFSET, maxSafeTime);\n }\n }\n\n // For normal, reverse, or forward final iteration of alternate: use max safe time\n return maxSafeTime;\n};\n\n/**\n * Validates that animation effect is a KeyframeEffect with a target\n */\nconst validateAnimationEffect = (\n effect: AnimationEffect | null,\n): effect is KeyframeEffect & { target: Element } => {\n return effect !== null && effect instanceof KeyframeEffect && effect.target !== null;\n};\n\n/**\n * Extracts timing information from an animation effect.\n * Duration and delay from getTiming() are already in milliseconds.\n * We use getTiming().delay directly from the animation object.\n */\nconst extractAnimationTiming = (effect: KeyframeEffect): AnimationTiming => {\n const timing = effect.getTiming();\n\n return {\n duration: Number(timing.duration) || 0,\n delay: Number(timing.delay) || 0,\n iterations: Number(timing.iterations) || DEFAULT_ANIMATION_ITERATIONS,\n direction: timing.direction || \"normal\",\n };\n};\n\n// ============================================================================\n// Animation Fill Mode Validation (Development Mode)\n// ============================================================================\n\n/**\n * Analyzes keyframes to detect if animation is a fade-in or fade-out effect.\n * Returns 'fade-in', 'fade-out', 'both', or null.\n */\nconst detectFadePattern = (keyframes: Keyframe[]): \"fade-in\" | \"fade-out\" | \"both\" | null => {\n if (!keyframes || keyframes.length < 2) return null;\n\n const firstFrame = keyframes[0];\n const lastFrame = keyframes[keyframes.length - 1];\n\n const firstOpacity = firstFrame && \"opacity\" in firstFrame ? Number(firstFrame.opacity) : null;\n const lastOpacity = lastFrame && \"opacity\" in lastFrame ? Number(lastFrame.opacity) : null;\n\n if (firstOpacity === null || lastOpacity === null) return null;\n\n const isFadeIn = firstOpacity < lastOpacity;\n const isFadeOut = firstOpacity > lastOpacity;\n\n if (isFadeIn && isFadeOut) return \"both\";\n if (isFadeIn) return \"fade-in\";\n if (isFadeOut) return \"fade-out\";\n return null;\n};\n\n/**\n * Analyzes keyframes to detect if animation has transform changes (slide, scale, etc).\n */\nconst hasTransformAnimation = (keyframes: Keyframe[]): boolean => {\n if (!keyframes || keyframes.length < 2) return false;\n\n return keyframes.some(\n (frame) =>\n \"transform\" in frame || \"translate\" in frame || \"scale\" in frame || \"rotate\" in frame,\n );\n};\n\n/**\n * Validates CSS animation fill-mode to prevent flashing issues.\n *\n * CRITICAL: Editframe's timeline system pauses animations and manually controls them\n * via animation.currentTime. This means elements exist in the DOM before their animations\n * start. Without proper fill-mode, elements will \"flash\" to their natural state before\n * the animation begins.\n *\n * Common issues:\n * - Delayed animations without 'backwards': Element shows natural state during delay\n * - Fade-in without 'backwards': Element visible before fade starts\n * - Fade-out without 'forwards': Element snaps back after fade completes\n *\n * Only runs in development mode to avoid performance impact in production.\n */\nconst validateAnimationFillMode = (animation: Animation, timing: AnimationTiming): void => {\n // Only validate in development mode\n if (typeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\") {\n return;\n }\n\n const effect = animation.effect;\n if (!validateAnimationEffect(effect)) {\n return;\n }\n\n const effectTiming = effect.getTiming();\n const fill = effectTiming.fill || \"none\";\n const target = effect.target;\n\n // Get animation name for better error messages\n let animationName = \"unknown\";\n if (animation.id) {\n animationName = animation.id;\n } else if (target instanceof HTMLElement) {\n const computedStyle = window.getComputedStyle(target);\n const animationNameValue = computedStyle.animationName;\n if (animationNameValue && animationNameValue !== \"none\") {\n animationName = animationNameValue.split(\",\")[0]?.trim() || \"unknown\";\n }\n }\n\n // Create unique key based on animation name and duration\n const validationKey = `${animationName}-${timing.duration}`;\n\n // Skip if already validated\n if (validatedAnimations.has(validationKey)) {\n return;\n }\n validatedAnimations.add(validationKey);\n\n const warnings: string[] = [];\n\n // Check 1: Delayed animations without backwards/both\n if (timing.delay > 0 && fill !== \"backwards\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" has a ${timing.delay}ms delay but no 'backwards' fill-mode.`,\n ` This will cause the element to show its natural state during the delay, then suddenly jump when the animation starts.`,\n ` Fix: Add 'backwards' or 'both' to the animation shorthand.`,\n ` Example: animation: ${animationName} ${timing.duration}ms ${timing.delay}ms backwards;`,\n );\n }\n\n // Check 2: Analyze keyframes for fade/transform patterns\n try {\n const keyframes = effect.getKeyframes();\n const fadePattern = detectFadePattern(keyframes);\n const hasTransform = hasTransformAnimation(keyframes);\n\n // Fade-in or transform-in animations should use backwards\n if ((fadePattern === \"fade-in\" || hasTransform) && fill !== \"backwards\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" modifies initial state but lacks 'backwards' fill-mode.`,\n ` The element will be visible in its natural state before the animation starts.`,\n ` Fix: Add 'backwards' or 'both' to the animation.`,\n ` Example: animation: ${animationName} ${timing.duration}ms backwards;`,\n );\n }\n\n // Fade-out animations should use forwards\n if (fadePattern === \"fade-out\" && fill !== \"forwards\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" modifies final state but lacks 'forwards' fill-mode.`,\n ` The element will snap back to its natural state after the animation completes.`,\n ` Fix: Add 'forwards' or 'both' to the animation.`,\n ` Example: animation: ${animationName} ${timing.duration}ms forwards;`,\n );\n }\n\n // Combined effects should use both\n if (fadePattern === \"both\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" modifies both initial and final state but doesn't use 'both' fill-mode.`,\n ` Fix: Use 'both' to apply initial and final states.`,\n ` Example: animation: ${animationName} ${timing.duration}ms both;`,\n );\n }\n } catch (_e) {\n // Silently skip keyframe analysis if it fails\n }\n\n if (warnings.length > 0 && typeof window !== \"undefined\") {\n console.groupCollapsed(\n \"%c🎬 Editframe Animation Fill-Mode Warning\",\n \"color: #f59e0b; font-weight: bold\",\n );\n warnings.forEach((warning) => console.log(warning));\n console.log(\n \"\\n📚 Learn more: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode\",\n );\n console.groupEnd();\n }\n};\n\n/**\n * Prepares animation for manual control on first encounter.\n *\n * Reading animation.playState forces style recalculation in Chromium (layout thrash).\n * Instead we track prepared animations in a WeakSet. On first encounter we optimistically\n * cancel the animation — cancel() is safe on any state (paused/running/finished/idle)\n * and leaves the animation in \"idle\", from which currentTime writes work freely.\n * On subsequent frames the animation is already under our control so we skip this entirely.\n */\nconst prepareAnimation = (animation: Animation): void => {\n if (preparedAnimations.has(animation)) {\n return;\n }\n animation.cancel();\n preparedAnimations.add(animation);\n};\n\n/**\n * Maps element time to animation currentTime and sets it on the animation.\n *\n * WHY: This function explicitly performs the time mapping transformation,\n * making it clear that we're transforming element time to animation time.\n */\nconst mapAndSetAnimationTime = (\n animation: Animation,\n element: AnimatableElement,\n timing: AnimationTiming,\n effectiveDelay: number,\n): void => {\n // Use ownCurrentTimeMs for all elements (timegroups and other temporal elements)\n // This gives us time relative to when the element started, which ensures animations\n // on child elements are synchronized with their containing timegroup's timeline.\n // For timegroups, ownCurrentTimeMs is the time relative to when the timegroup started.\n // For other temporal elements, ownCurrentTimeMs is the time relative to their start.\n const elementTime = element.ownCurrentTimeMs ?? 0;\n\n // Calculate adjusted time (element time minus delay)\n const adjustedTime = elementTime - effectiveDelay;\n\n // If before delay, show initial keyframe state (0% of animation)\n if (adjustedTime < 0) {\n // Before delay: show initial keyframe state.\n // For CSS animations with delay > 0, currentTime is in \"absolute timeline time\"\n // (delay period + animation progress). Subtracting the stagger offset shifts\n // each segment's delay window so they enter their animation at different times.\n if (timing.delay > 0) {\n animation.currentTime = elementTime - (effectiveDelay - timing.delay);\n } else {\n animation.currentTime = 0;\n }\n return;\n }\n\n // At delay time (adjustedTime = 0) or after, the animation should be active\n const { duration, iterations } = timing;\n const currentIteration = Math.floor(adjustedTime / duration);\n\n if (currentIteration >= iterations) {\n // Animation is completed - use completed time mapping\n const maxSafeTime = calculateMaxSafeAnimationTime(duration, iterations);\n const completedAnimationTime = getCompletedAnimationTime(timing, maxSafeTime);\n\n // CRITICAL: For CSS animations, currentTime behavior differs based on whether delay > 0:\n // - If timing.delay > 0: currentTime includes the delay (absolute timeline time)\n // - If timing.delay === 0: currentTime is just animation progress (0 to duration)\n if (timing.delay > 0) {\n // Completed: anchor to timing.delay (not effectiveDelay) so all segments land at\n // the same final keyframe regardless of their individual stagger offsets.\n animation.currentTime = timing.delay + completedAnimationTime;\n } else {\n // Completed: currentTime should be just the completed animation time (animation progress)\n animation.currentTime = completedAnimationTime;\n }\n } else {\n // Animation is in progress - map element time to animation time\n const animationTime = mapElementTimeToAnimationTime(elementTime, timing, effectiveDelay);\n\n // CRITICAL: For CSS animations, currentTime behavior differs based on whether delay > 0:\n // - If timing.delay > 0: currentTime includes the delay (absolute timeline time)\n // - If timing.delay === 0: currentTime is just animation progress (0 to duration)\n // Stagger offset is handled via adjustedTime calculation, but doesn't affect currentTime format\n const { direction, delay } = timing;\n\n if (delay > 0) {\n // CSS animation with delay: currentTime is in \"absolute timeline time\" (delay + progress).\n // Anchor to timing.delay (the CSS base delay) rather than effectiveDelay so that the\n // stagger offset shifts each segment's window without cancelling out.\n const staggerShift = effectiveDelay - timing.delay;\n const isAlternateWithDelay =\n (direction === \"alternate\" || direction === \"alternate-reverse\") && effectiveDelay > 0;\n if (isAlternateWithDelay && currentIteration === 0) {\n animation.currentTime = elementTime - staggerShift;\n } else {\n animation.currentTime = timing.delay + animationTime;\n }\n } else {\n // CSS animation with delay = 0: currentTime is just animation progress\n // Stagger offset is already accounted for in adjustedTime, so animationTime is the progress\n animation.currentTime = animationTime;\n }\n }\n};\n\n/**\n * Builds and caches per-animation data derived from immutable properties.\n * Called once per animation on first synchronization; subsequent frames use the cache.\n */\nconst buildAnimationCache = (\n animation: Animation,\n effect: KeyframeEffect & { target: Element },\n fallbackElement: AnimatableElement,\n): CachedAnimationData => {\n const timing = extractAnimationTiming(effect);\n const target = effect.target;\n\n // Resolve time source: nearest ef-timegroup ancestor (or fallback to root)\n let timeSource: AnimatableElement | null = null;\n if (target instanceof HTMLElement) {\n const nearestTimegroup = target.closest(\"ef-timegroup\");\n if (nearestTimegroup && isEFTemporal(nearestTimegroup)) {\n timeSource = nearestTimegroup as AnimatableElement;\n }\n }\n\n // Resolve stagger element: nearest ef-text-segment ancestor (or fallback to timeSource)\n let staggerElement: AnimatableElement | null = null;\n if (target instanceof HTMLElement) {\n const targetAsAnimatable = target as AnimatableElement;\n if (supportsStaggerOffset(targetAsAnimatable)) {\n staggerElement = targetAsAnimatable;\n } else {\n const parentSegment = target.closest(\"ef-text-segment\");\n if (parentSegment && supportsStaggerOffset(parentSegment as AnimatableElement)) {\n staggerElement = parentSegment as AnimatableElement;\n }\n }\n }\n\n const resolvedStagger = staggerElement ?? timeSource ?? fallbackElement;\n const effectiveDelay = calculateEffectiveDelay(timing.delay, resolvedStagger);\n\n const data: CachedAnimationData = { timing, timeSource, staggerElement, effectiveDelay };\n animationCache.set(animation, data);\n\n // Validate fill-mode once at cache-build time (first encounter per animation).\n // Moved here from synchronizeAnimation to avoid re-entering on every subsequent frame.\n validateAnimationFillMode(animation, timing);\n\n return data;\n};\n\n/**\n * Synchronizes a single animation with the timeline using the element as the time source.\n *\n * Timing, time-source, and stagger lookups are cached per animation — they are derived\n * from immutable properties (keyframe timing, DOM parent chain) and never change during\n * the lifetime of an animation.\n */\nconst synchronizeAnimation = (animation: Animation, element: AnimatableElement): void => {\n const effect = animation.effect;\n if (!validateAnimationEffect(effect)) {\n return;\n }\n\n // Use cached data when available; build and cache on first encounter\n let cached = animationCache.get(animation);\n if (!cached) {\n cached = buildAnimationCache(animation, effect, element);\n }\n\n const { timing } = cached;\n\n if (timing.duration <= 0) {\n animation.currentTime = 0;\n return;\n }\n\n const timeSource = cached.timeSource ?? element;\n mapAndSetAnimationTime(animation, timeSource, timing, cached.effectiveDelay);\n};\n\n/**\n * Coordinates animations for a single element and its subtree, using the element as the time source.\n *\n * Uses tracked animations to ensure we can control animations even after they complete.\n * Both CSS animations (created via the 'animation' property) and WAAPI animations are included.\n *\n * CRITICAL: CSS animations are created asynchronously when classes are added. This function\n * discovers new animations on each call and tracks them in memory. Once animations complete,\n * they're removed from getAnimations(), but we keep references to them so we can continue\n * controlling them.\n */\nconst coordinateElementAnimations = (\n element: AnimatableElement,\n providedAnimations?: Animation[],\n): void => {\n // Discover and track animations (includes both current and previously completed ones)\n // Reuse the current animations array to avoid calling getAnimations() twice\n // Accept pre-discovered animations to avoid redundant getAnimations() calls\n const { tracked: trackedAnimations, current: currentAnimations } = discoverAndTrackAnimations(\n element,\n providedAnimations,\n );\n\n for (const animation of trackedAnimations) {\n // Skip invalid animations (cancelled, removed from DOM, etc.)\n if (!isAnimationValid(animation, currentAnimations)) {\n continue;\n }\n\n prepareAnimation(animation);\n synchronizeAnimation(animation, element);\n }\n};\n\n// ============================================================================\n// Visual State Application\n// ============================================================================\n\n/**\n * Applies visual state (CSS + display) to match temporal state.\n *\n * WHY: This function applies visual state based on the element's phase and state.\n * Phase determines what should be visible, and this function applies that decision.\n */\nconst applyVisualState = (element: AnimatableElement, state: TemporalState): void => {\n // Always set progress (needed for many use cases)\n element.style.setProperty(PROGRESS_PROPERTY, `${state.progress}`);\n\n // Handle visibility based on phase\n if (!state.isVisible) {\n element.style.setProperty(\"display\", \"none\");\n cancelTrackedAnimations(element);\n return;\n }\n element.style.removeProperty(\"display\");\n\n // Set other CSS properties for visible elements only\n element.style.setProperty(DURATION_PROPERTY, `${element.durationMs}ms`);\n element.style.setProperty(\n TRANSITION_DURATION_PROPERTY,\n `${element.parentTimegroup?.overlapMs ?? 0}ms`,\n );\n element.style.setProperty(\n TRANSITION_OUT_START_PROPERTY,\n `${element.durationMs - (element.parentTimegroup?.overlapMs ?? 0)}ms`,\n );\n};\n\n/**\n * Applies animation coordination if the element phase requires it.\n *\n * WHY: Animation coordination is driven by phase. If the element is in a phase\n * where animations should be coordinated, we coordinate them.\n */\nconst applyAnimationCoordination = (\n element: AnimatableElement,\n phase: ElementPhase,\n providedAnimations?: Animation[],\n): void => {\n if (shouldCoordinateAnimations(phase, element)) {\n coordinateElementAnimations(element, providedAnimations);\n }\n};\n\n// ============================================================================\n// SVG SMIL Synchronization\n// ============================================================================\n\n/**\n * Finds the nearest temporal ancestor (or self) for a given element.\n * Returns the element itself if it is a temporal element, otherwise walks up.\n * Falls back to the provided root element.\n */\nconst findNearestTemporalAncestor = (\n element: Element,\n root: AnimatableElement,\n): AnimatableElement => {\n let node: Element | null = element;\n while (node) {\n if (isEFTemporal(node)) {\n return node as AnimatableElement;\n }\n node = node.parentElement;\n }\n return root;\n};\n\n/**\n * Synchronizes all SVG SMIL animations in the subtree with the timeline.\n *\n * SVG has its own animation clock on each SVGSVGElement. We pause it and\n * seek it to the owning temporal element's current time (converted to seconds).\n */\nconst synchronizeSvgAnimations = (root: AnimatableElement): void => {\n const svgElements = (root as HTMLElement).querySelectorAll(\"svg\");\n for (const svg of svgElements) {\n const owner = findNearestTemporalAncestor(svg, root);\n const timeMs = owner.currentTimeMs ?? 0;\n svg.setCurrentTime(timeMs / 1000);\n svg.pauseAnimations();\n }\n};\n\n// ============================================================================\n// Media Element Synchronization\n// ============================================================================\n\n/**\n * Synchronizes all <video> and <audio> elements in the subtree with the timeline.\n *\n * Sets currentTime (in seconds) to match the owning temporal element's position\n * and ensures the elements are paused (playback is controlled by the timeline).\n */\nconst synchronizeMediaElements = (root: AnimatableElement): void => {\n const mediaElements = (root as HTMLElement).querySelectorAll(\"video, audio\");\n for (const media of mediaElements as NodeListOf<HTMLMediaElement>) {\n const owner = findNearestTemporalAncestor(media, root);\n const timeMs = owner.currentTimeMs ?? 0;\n const timeSec = timeMs / 1000;\n if (media.currentTime !== timeSec) {\n media.currentTime = timeSec;\n }\n if (!media.paused) {\n media.pause();\n }\n }\n};\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Evaluates the complete state for an element update.\n * This separates evaluation (what should the state be?) from application (apply that state).\n */\nconst evaluateElementState = (element: AnimatableElement): ElementUpdateContext => {\n return {\n element,\n state: evaluateTemporalState(element),\n };\n};\n\n/**\n * Main function: synchronizes DOM element with timeline.\n *\n * Orchestrates clear flow: Phase → Policy → Time Mapping → State Application\n *\n * WHY: This function makes the conceptual flow explicit:\n * 1. Determine phase (what phase is the element in?)\n * 2. Apply policies (should it be visible/coordinated based on phase?)\n * 3. Map time for animations (transform element time to animation time)\n * 4. Apply visual state (update CSS and display based on phase and policies)\n */\nexport const updateAnimations = (element: AnimatableElement): void => {\n const rootContext = evaluateElementState(element);\n const timelineTimeMs = (element.rootTimegroup ?? element).currentTimeMs;\n const { elements: collectedElements, pruned } = deepGetTemporalElements(element, timelineTimeMs);\n\n // For pruned elements (invisible containers whose subtrees were skipped),\n // cancel their animations and hide them before fetching allAnimations.\n // This ensures the subsequent getAnimations() call reflects only active animations.\n for (const prunedElement of pruned) {\n prunedElement.style.setProperty(\"display\", \"none\");\n cancelTrackedAnimations(prunedElement);\n }\n\n // Fetch allAnimations after pruned elements are cancelled so they don't appear in the list.\n const allAnimations = element.getAnimations({ subtree: true });\n\n // Evaluate state only for non-pruned elements (visible + individually\n // invisible leaf elements that weren't behind a pruned container).\n const childContexts: ElementUpdateContext[] = [];\n for (const temporalElement of collectedElements) {\n if (!pruned.has(temporalElement)) {\n childContexts.push(evaluateElementState(temporalElement));\n }\n }\n\n // Separate visible and invisible children.\n // Only visible children need animation coordination (expensive).\n // Invisible children just need display:none applied (cheap).\n const visibleChildContexts: ElementUpdateContext[] = [];\n for (const ctx of childContexts) {\n if (shouldBeVisible(ctx.state.phase, ctx.element)) {\n visibleChildContexts.push(ctx);\n }\n }\n\n // Partition allAnimations by closest VISIBLE temporal parent.\n // Only visible elements need their animations partitioned and coordinated.\n // Build a Set of visible temporal elements for O(1) lookup, then walk up\n // from each animation target to find its closest temporal owner.\n const temporalSet = new Set<Element>(visibleChildContexts.map((c) => c.element));\n temporalSet.add(element); // Include root\n const childAnimations = new Map<AnimatableElement, Animation[]>();\n for (const animation of allAnimations) {\n const effect = animation.effect;\n const target = effect && effect instanceof KeyframeEffect ? effect.target : null;\n if (!target || !(target instanceof Element)) continue;\n\n let node: Element | null = target;\n while (node) {\n if (temporalSet.has(node)) {\n let anims = childAnimations.get(node as AnimatableElement);\n if (!anims) {\n anims = [];\n childAnimations.set(node as AnimatableElement, anims);\n }\n anims.push(animation);\n break;\n }\n node = node.parentElement;\n }\n }\n\n // Coordinate animations for root and VISIBLE children only.\n // Invisible children (display:none) have no CSS animations to coordinate,\n // and when they become visible again, coordination runs on that frame.\n applyAnimationCoordination(rootContext.element, rootContext.state.phase, allAnimations);\n for (const context of visibleChildContexts) {\n applyAnimationCoordination(\n context.element,\n context.state.phase,\n childAnimations.get(context.element) || [],\n );\n }\n\n // Apply visual state for non-pruned children (pruned ones already got display:none above)\n applyVisualState(rootContext.element, rootContext.state);\n for (const context of childContexts) {\n applyVisualState(context.element, context.state);\n }\n\n // Synchronize non-CSS animation systems\n synchronizeSvgAnimations(element);\n synchronizeMediaElements(element);\n};\n"],"mappings":";;;AAaA,MAAM,6BAA6B;AACnC,MAAM,+BAA+B;AACrC,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,+BAA+B;AACrC,MAAM,gCAAgC;;;;;;AAWtC,MAAM,mCAAmB,IAAI,SAAkC;;;;;;AAO/D,MAAM,sCAAsB,IAAI,SAA2B;;;;;AAM3D,MAAM,qCAAqB,IAAI,SAA0B;;;;;AAMzD,MAAM,sCAAsB,IAAI,KAAa;;;;;;;AAQ7C,MAAM,qCAAqB,IAAI,SAAoB;AAiBnD,MAAM,iCAAiB,IAAI,SAAyC;;;;;;;;AASpE,MAAM,oBAAoB,WAAsB,sBAA4C;AAG1F,KAAI,CAAC,kBAAkB,SAAS,UAAU,CACxC,QAAO;CAIT,MAAM,SAAS,UAAU;AACzB,KAAI,CAAC,OACH,QAAO;AAIT,KAAI,kBAAkB,gBAAgB;EACpC,MAAM,SAAS,OAAO;AACtB,MAAI,UAAU,kBAAkB,SAC9B;OAAI,CAAC,OAAO,YACV,QAAO;;;AAKb,QAAO;;;;;;;;;;;;;;;;AAiBT,MAAM,8BACJ,SACA,uBACsD;AACtD,kBAAiB,IAAI,QAAQ;CAC7B,MAAM,mBAAmB,oBAAoB,IAAI,QAAQ,IAAI;CAU7D,MAAM,oBAAoB,sBAAsB,QAAQ,cAAc,EAAE,SAAS,MAAM,CAAC;AAIxF,qBAAoB,IAAI,SAAS,MAAM;AAGvC,oBAAmB,IAAI,SAAS,kBAAkB,OAAO;AAGzD,MAAK,MAAM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","names":["result: Animation[]","warnings: string[]","timeSource: AnimatableElement | null","staggerElement: AnimatableElement | null","data: CachedAnimationData","node: Element | null","childContexts: ElementUpdateContext[]","visibleChildContexts: ElementUpdateContext[]"],"sources":["../../src/elements/updateAnimations.ts"],"sourcesContent":["import {\n deepGetTemporalElements,\n isEFTemporal,\n type TemporalMixinInterface,\n} from \"./EFTemporal.ts\";\n\n// All animatable elements are temporal elements with HTMLElement interface\nexport type AnimatableElement = TemporalMixinInterface & HTMLElement;\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst ANIMATION_PRECISION_OFFSET = 0.1; // Use 0.1ms to safely avoid completion threshold\nconst DEFAULT_ANIMATION_ITERATIONS = 1;\nconst PROGRESS_PROPERTY = \"--ef-progress\";\nconst DURATION_PROPERTY = \"--ef-duration\";\nconst TRANSITION_DURATION_PROPERTY = \"--ef-transition-duration\";\nconst TRANSITION_OUT_START_PROPERTY = \"--ef-transition-out-start\";\n\n// ============================================================================\n// Animation Tracking\n// ============================================================================\n\n/**\n * Tracks animations per element to prevent them from being lost when they complete.\n * Once an animation reaches 100% completion, it's removed from getAnimations(),\n * but we keep a reference to it so we can continue controlling it.\n */\nconst animationTracker = new WeakMap<Element, Set<Animation>>();\n\n/**\n * Tracks whether DOM structure has changed for an element, requiring animation rediscovery.\n * For render clones (static DOM), this stays false after initial discovery.\n * For prime timeline (interactive), this is set to true when mutations occur.\n */\nconst domStructureChanged = new WeakMap<Element, boolean>();\n\n/**\n * Tracks the last known animation count for an element to detect new animations.\n * Used as a lightweight check before calling expensive getAnimations().\n */\nconst lastAnimationCount = new WeakMap<Element, number>();\n\n/**\n * Tracks which animations have already been validated to avoid duplicate warnings.\n * Uses animation name + duration as the unique key.\n */\nconst validatedAnimations = new Set<string>();\n\n/**\n * Tracks animations that have already been taken under manual control.\n * Once an animation is here, its playState is known to be \"paused\" or \"idle\" —\n * both accept currentTime writes without preconditions and without causing reflow.\n * This lets prepareAnimation skip cancel()/pause() on every subsequent frame.\n */\nconst preparedAnimations = new WeakSet<Animation>();\n\n/**\n * Per-animation data derived once from the animation's immutable properties:\n * timing (duration/delay/iterations/direction), time source (nearest ef-timegroup),\n * stagger element (nearest ef-text-segment), and effective delay.\n *\n * All of these are fixed for the lifetime of an animation — the target's position\n * in the DOM and the animation's keyframe timing never change during scrubbing.\n * Caching avoids effect.getTiming() and target.closest() on every frame.\n */\ninterface CachedAnimationData {\n timing: AnimationTiming;\n timeSource: AnimatableElement | null; // null means \"use the root element passed in\"\n staggerElement: AnimatableElement | null; // null means \"use timeSource\"\n effectiveDelay: number;\n}\nconst animationCache = new WeakMap<Animation, CachedAnimationData>();\n\n/**\n * Validates that an animation is still valid and controllable.\n * Animations become invalid when:\n * - They've been cancelled (idle state and not in getAnimations())\n * - Their effect is null (animation was removed)\n * - Their target is no longer in the DOM\n */\nconst isAnimationValid = (animation: Animation, currentAnimations: Animation[]): boolean => {\n // Check if animation effect is still valid\n const effect = animation.effect;\n if (!effect) {\n return false;\n }\n\n // Check if target is still in DOM\n if (effect instanceof KeyframeEffect) {\n const target = effect.target;\n if (target && target instanceof Element) {\n if (!target.isConnected) {\n return false;\n }\n }\n }\n\n // Animations that prepareAnimation() has cancelled are still valid — they're\n // under manual control with currentTime set explicitly. getAnimations() won't\n // return them (idle state after cancel()), but they must stay in the tracker\n // so ef-motionblur's sample() can find them for velocity measurement.\n if (preparedAnimations.has(animation)) {\n return true;\n }\n\n // Check if animation is in the live animation list.\n if (!currentAnimations.includes(animation)) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Discovers and tracks animations on an element and its subtree.\n * This ensures we have references to animations even after they complete.\n *\n * Tracks animations per element where they exist, not just on the root element.\n * This allows us to find animations on any element in the subtree.\n *\n * OPTIMIZATION: For render clones (static DOM), discovery happens once at creation.\n * For prime timeline (interactive), discovery is responsive to DOM changes.\n *\n * Also cleans up invalid animations (cancelled, removed from DOM, etc.)\n *\n * @param providedAnimations - Optional pre-discovered animations to avoid redundant getAnimations() calls\n */\nconst discoverAndTrackAnimations = (\n element: AnimatableElement,\n providedAnimations?: Animation[],\n): { tracked: Set<Animation>; current: Animation[] } => {\n animationTracker.has(element);\n const structureChanged = domStructureChanged.get(element) ?? true;\n\n // REMOVED: Clone optimization that cached animation references.\n // The optimization assumed animations were \"static\" for clones, but this was incorrect.\n // After seeking to a new time, we need fresh animation state from the browser.\n // Caching caused animations to be stuck at their discovery state (often 0ms).\n\n // For prime timeline or first discovery: get current animations from the browser (includes subtree)\n // CRITICAL: This is expensive, so we return it to avoid calling it again\n // If animations were provided by caller (to avoid redundant calls), use those\n const currentAnimations = providedAnimations ?? element.getAnimations({ subtree: true });\n\n // Mark structure as stable after discovery\n // This prevents redundant getAnimations() calls when DOM hasn't changed\n domStructureChanged.set(element, false);\n\n // Track animation count for lightweight change detection\n lastAnimationCount.set(element, currentAnimations.length);\n\n // Track animations on each element where they exist\n for (const animation of currentAnimations) {\n const effect = animation.effect;\n const target = effect && effect instanceof KeyframeEffect ? effect.target : null;\n if (target && target instanceof Element) {\n let tracked = animationTracker.get(target);\n if (!tracked) {\n tracked = new Set<Animation>();\n animationTracker.set(target, tracked);\n }\n tracked.add(animation);\n }\n }\n\n // Also maintain a set on the root element for coordination\n let rootTracked = animationTracker.get(element);\n if (!rootTracked) {\n rootTracked = new Set<Animation>();\n animationTracker.set(element, rootTracked);\n }\n\n // Update root set with all current animations\n for (const animation of currentAnimations) {\n rootTracked.add(animation);\n }\n\n // Clean up invalid animations from root set\n // This handles animations that were cancelled, removed from DOM, or had their effects removed\n for (const animation of rootTracked) {\n if (!isAnimationValid(animation, currentAnimations)) {\n rootTracked.delete(animation);\n }\n }\n\n // Build a map of element -> current animations from the subtree lookup we already did\n // This avoids calling getAnimations() repeatedly on each element (expensive!)\n const elementAnimationsMap = new Map<Element, Animation[]>();\n for (const animation of currentAnimations) {\n const effect = animation.effect;\n const target = effect && effect instanceof KeyframeEffect ? effect.target : null;\n if (target && target instanceof Element) {\n let anims = elementAnimationsMap.get(target);\n if (!anims) {\n anims = [];\n elementAnimationsMap.set(target, anims);\n }\n anims.push(animation);\n }\n }\n\n // Clean up invalid animations from per-element sets.\n // Only walk the full subtree when DOM structure has changed (elements added/removed).\n // During scrubbing with static DOM, skip this expensive querySelectorAll(\"*\").\n if (structureChanged) {\n for (const [el, tracked] of elementAnimationsMap) {\n const existingTracked = animationTracker.get(el);\n if (existingTracked) {\n for (const animation of existingTracked) {\n if (!isAnimationValid(animation, tracked)) {\n existingTracked.delete(animation);\n }\n }\n if (existingTracked.size === 0) {\n animationTracker.delete(el);\n }\n }\n }\n }\n\n return { tracked: rootTracked, current: currentAnimations };\n};\n\n/**\n * Returns the number of animations tracked for an element.\n * Exported for testing only.\n */\nexport const getTrackedAnimationCount = (element: Element): number => {\n return animationTracker.get(element)?.size ?? 0;\n};\n\n/**\n * Returns all tracked animations for an element and its subtree.\n *\n * Unlike `element.getAnimations({ subtree: true })`, this includes animations that\n * have been cancelled by `prepareAnimation()` (which puts them in the `idle` play\n * state, making them invisible to `getAnimations()`). Once `updateAnimations` takes\n * control of a CSS animation it cancels it, so callers that need to seek those\n * animations for side-effects (e.g. `EFMotionBlur` reading positions at t−shutterMs)\n * must use this function instead of `getAnimations()`.\n *\n * Walks `element` and every descendant, collecting the union of all tracked sets.\n * Returns an empty array when no animations have been tracked yet.\n */\nexport const getTrackedAnimationsForSubtree = (element: Element): Animation[] => {\n const result: Animation[] = [];\n const seen = new Set<Animation>();\n\n const collect = (el: Element): void => {\n const tracked = animationTracker.get(el);\n if (tracked) {\n for (const anim of tracked) {\n if (!seen.has(anim)) {\n seen.add(anim);\n result.push(anim);\n }\n }\n }\n for (const child of el.children) {\n collect(child);\n }\n };\n\n collect(element);\n return result;\n};\n\n/**\n * Cancels all tracked animations for an element and removes them from tracking.\n * Called when an element is hidden so paused WAAPI animations leave getAnimations(),\n * preventing unbounded growth of getAnimations({subtree:true}) during scrubbing.\n */\nconst cancelTrackedAnimations = (element: Element): void => {\n // Cancel animations from the tracker. cancel() is safe on any state including idle.\n const tracked = animationTracker.get(element);\n if (tracked) {\n for (const animation of tracked) {\n animation.cancel();\n preparedAnimations.delete(animation);\n animationCache.delete(animation);\n }\n tracked.clear();\n }\n // Also cancel any live animations on the element's subtree that may not be tracked yet.\n // getAnimations() only returns non-idle animations, so no guard needed.\n const subtreeAnims = (element as HTMLElement).getAnimations?.({ subtree: true });\n if (subtreeAnims) {\n for (const animation of subtreeAnims) {\n animation.cancel();\n preparedAnimations.delete(animation);\n animationCache.delete(animation);\n }\n }\n};\n\n/**\n * Cleans up tracked animations when an element is disconnected.\n * This prevents memory leaks.\n */\nexport const cleanupTrackedAnimations = (element: Element): void => {\n animationTracker.delete(element);\n domStructureChanged.delete(element);\n lastAnimationCount.delete(element);\n};\n\n/**\n * Marks that DOM structure has changed for an element, requiring animation rediscovery.\n * Should be called when elements are added/removed or CSS classes change that affect animations.\n */\nexport const markDomStructureChanged = (element: Element): void => {\n domStructureChanged.set(element, true);\n};\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Represents the phase an element is in relative to the timeline.\n * This is the primary concept that drives all visibility and animation decisions.\n */\nexport type ElementPhase = \"before-start\" | \"active\" | \"at-end-boundary\" | \"after-end\";\n\n/**\n * Represents the temporal state of an element relative to the timeline\n */\ninterface TemporalState {\n progress: number;\n isVisible: boolean;\n timelineTimeMs: number;\n phase: ElementPhase;\n}\n\n/**\n * Context object that holds all evaluated state for an element update.\n * This groups related state together, reducing parameter passing and making\n * the data flow clearer.\n */\ninterface ElementUpdateContext {\n element: AnimatableElement;\n state: TemporalState;\n}\n\n/**\n * Animation timing information extracted from an animation effect.\n * Groups related timing properties together.\n */\ninterface AnimationTiming {\n duration: number;\n delay: number;\n iterations: number;\n direction: string;\n}\n\n/**\n * Capability interface for elements that support stagger offset.\n * This encapsulates the stagger behavior behind a capability check rather than\n * leaking tag name checks throughout the codebase.\n */\ninterface StaggerableElement extends AnimatableElement {\n staggerOffsetMs?: number;\n}\n\n// ============================================================================\n// Phase Determination\n// ============================================================================\n\n/**\n * Determines what phase an element is in relative to the timeline.\n *\n * WHY: Phase is the primary concept that drives all decisions. By explicitly\n * enumerating phases, we make the code's logic clear: phase determines visibility,\n * animation coordination, and visual state.\n *\n * Phases:\n * - before-start: Timeline is before element's start time\n * - active: Timeline is within element's active range (start to end, exclusive of end)\n * - at-end-boundary: Timeline is exactly at element's end time\n * - after-end: Timeline is after element's end time\n *\n * Note: We detect \"at-end-boundary\" by checking if timeline equals end time.\n * The boundary policy will then determine if this should be treated as visible/active\n * or not based on element characteristics.\n */\nconst determineElementPhase = (\n element: AnimatableElement,\n timelineTimeMs: number,\n): ElementPhase => {\n // Read endTimeMs once to avoid recalculation issues\n const endTimeMs = element.endTimeMs;\n const startTimeMs = element.startTimeMs;\n\n // Invalid range (end <= start) means element hasn't computed its duration yet,\n // or has no temporal children (e.g., timegroup with only static HTML).\n // Treat as always active - these elements should be visible at all times.\n if (endTimeMs <= startTimeMs) {\n return \"active\";\n }\n\n if (timelineTimeMs < startTimeMs) {\n return \"before-start\";\n }\n // Use epsilon to handle floating point precision issues\n const epsilon = 0.001;\n const diff = timelineTimeMs - endTimeMs;\n\n // If clearly after end (difference > epsilon), return 'after-end'\n if (diff > epsilon) {\n return \"after-end\";\n }\n // If at or very close to end boundary (within epsilon), return 'at-end-boundary'\n if (Math.abs(diff) <= epsilon) {\n return \"at-end-boundary\";\n }\n // Otherwise, we're before the end, so check if we're active\n return \"active\";\n};\n\n// ============================================================================\n// Boundary Policies\n// ============================================================================\n\n/**\n * Policy interface for determining behavior at boundaries.\n * Different policies apply different rules for when elements should be visible\n * or have animations coordinated at exact boundary times.\n */\ninterface BoundaryPolicy {\n /**\n * Determines if an element should be considered visible/active at the end boundary\n * based on the element's characteristics.\n */\n shouldIncludeEndBoundary(element: AnimatableElement): boolean;\n}\n\n/**\n * Visibility policy: determines when elements should be visible for display purposes.\n *\n * WHY: Root elements, elements aligned with composition end, and text segments\n * should remain visible at exact end time to prevent flicker and show final frames.\n * Other elements use exclusive end for clean transitions between elements.\n */\nclass VisibilityPolicy implements BoundaryPolicy {\n shouldIncludeEndBoundary(element: AnimatableElement): boolean {\n // Root elements should remain visible at exact end time to prevent flicker\n const isRootElement = !element.parentTimegroup;\n if (isRootElement) {\n return true;\n }\n\n // Elements aligned with composition end should remain visible at exact end time\n const isLastElementInComposition = element.endTimeMs === element.rootTimegroup?.endTimeMs;\n if (isLastElementInComposition) {\n return true;\n }\n\n // Text segments use inclusive end since they're meant to be visible for full duration\n if (this.isTextSegment(element)) {\n return true;\n }\n\n // Other elements use exclusive end for clean transitions\n return false;\n }\n\n /**\n * Checks if element is a text segment.\n * Encapsulates the tag name check to hide implementation detail.\n */\n protected isTextSegment(element: AnimatableElement): boolean {\n return element.tagName === \"EF-TEXT-SEGMENT\";\n }\n}\n\n// Policy instances (singleton pattern for stateless policies)\nconst visibilityPolicy = new VisibilityPolicy();\n\n/**\n * Determines if an element should be visible based on its phase and visibility policy.\n */\nconst shouldBeVisible = (phase: ElementPhase, element: AnimatableElement): boolean => {\n if (phase === \"before-start\" || phase === \"after-end\") {\n return false;\n }\n if (phase === \"active\") {\n return true;\n }\n // phase === \"at-end-boundary\"\n return visibilityPolicy.shouldIncludeEndBoundary(element);\n};\n\n/**\n * Determines if animations should be coordinated based on element phase and animation policy.\n *\n * CRITICAL: Always returns true to support scrubbing to arbitrary times.\n *\n * Previously, this function skipped coordination for before-start and after-end phases as an\n * optimization for live playback. However, this broke scrubbing scenarios where we seek to\n * arbitrary times (timeline scrubbing, thumbnails, video export).\n *\n * The performance cost of always coordinating is minimal:\n * - Animations only update when element time changes\n * - Paused animation updates are optimized by the browser\n * - The benefit is correct animation state at all times, regardless of phase\n */\nconst shouldCoordinateAnimations = (_phase: ElementPhase, _element: AnimatableElement): boolean => {\n return true;\n};\n\n// ============================================================================\n// Temporal State Evaluation\n// ============================================================================\n\n/**\n * Evaluates what the element's state should be based on the timeline.\n *\n * WHY: This function determines the complete temporal state including phase,\n * which becomes the primary driver for all subsequent decisions.\n */\nexport const evaluateTemporalState = (element: AnimatableElement): TemporalState => {\n // Get timeline time from root timegroup, or use element's own time if it IS a timegroup\n const timelineTimeMs = (element.rootTimegroup ?? element).currentTimeMs;\n\n const progress =\n element.durationMs <= 0\n ? 1\n : Math.max(0, Math.min(1, element.currentTimeMs / element.durationMs));\n\n const phase = determineElementPhase(element, timelineTimeMs);\n const isVisible = shouldBeVisible(phase, element);\n\n return { progress, isVisible, timelineTimeMs, phase };\n};\n\n/**\n * Evaluates element visibility state specifically for animation coordination.\n * Uses inclusive end boundaries to prevent animation jumps at exact boundaries.\n *\n * This is exported for external use cases that need animation-specific visibility\n * evaluation without the full ElementUpdateContext.\n */\nexport const evaluateAnimationVisibilityState = (element: AnimatableElement): TemporalState => {\n const state = evaluateTemporalState(element);\n // Override visibility based on animation policy\n const shouldCoordinate = shouldCoordinateAnimations(state.phase, element);\n return { ...state, isVisible: shouldCoordinate };\n};\n\n// ============================================================================\n// Animation Time Mapping\n// ============================================================================\n\n/**\n * Capability check: determines if an element supports stagger offset.\n * Encapsulates the knowledge of which element types support this feature.\n */\nconst supportsStaggerOffset = (element: AnimatableElement): element is StaggerableElement => {\n // Currently only text segments support stagger offset\n return element.tagName === \"EF-TEXT-SEGMENT\";\n};\n\n/**\n * Calculates effective delay including stagger offset if applicable.\n *\n * Stagger offset allows elements (like text segments) to have their animations\n * start at different times while keeping their visibility timing unchanged.\n * This enables staggered animation effects within a single timegroup.\n */\nconst calculateEffectiveDelay = (delay: number, element: AnimatableElement): number => {\n if (supportsStaggerOffset(element)) {\n // Read stagger offset - try property first (more reliable), then CSS variable\n // The staggerOffsetMs property is set directly on the element and is always available\n const segment = element as any;\n if (segment.staggerOffsetMs !== undefined && segment.staggerOffsetMs !== null) {\n return delay + segment.staggerOffsetMs;\n }\n\n // Fallback to CSS variable if property not available\n let cssValue = (element as HTMLElement).style.getPropertyValue(\"--ef-stagger-offset\").trim();\n\n if (!cssValue) {\n cssValue = window.getComputedStyle(element).getPropertyValue(\"--ef-stagger-offset\").trim();\n }\n\n if (cssValue) {\n // Parse \"100ms\" format to milliseconds\n const match = cssValue.match(/(\\d+(?:\\.\\d+)?)\\s*ms?/);\n if (match) {\n const staggerOffset = parseFloat(match[1]!);\n if (!isNaN(staggerOffset)) {\n return delay + staggerOffset;\n }\n } else {\n // Try parsing as just a number\n const numValue = parseFloat(cssValue);\n if (!isNaN(numValue)) {\n return delay + numValue;\n }\n }\n }\n }\n return delay;\n};\n\n/**\n * Calculates maximum safe animation time to prevent completion.\n *\n * WHY: Once an animation reaches \"finished\" state, it can no longer be manually controlled\n * via currentTime. By clamping to just before completion (using ANIMATION_PRECISION_OFFSET),\n * we ensure the animation remains in a controllable state, allowing us to synchronize it\n * with the timeline even when it would naturally be complete.\n */\nconst calculateMaxSafeAnimationTime = (duration: number, iterations: number): number => {\n return duration * iterations - ANIMATION_PRECISION_OFFSET;\n};\n\n/**\n * Determines if the current iteration should be reversed based on direction\n */\nconst shouldReverseIteration = (direction: string, currentIteration: number): boolean => {\n return (\n direction === \"reverse\" ||\n (direction === \"alternate\" && currentIteration % 2 === 1) ||\n (direction === \"alternate-reverse\" && currentIteration % 2 === 0)\n );\n};\n\n/**\n * Applies direction to iteration time (reverses if needed)\n */\nconst applyDirectionToIterationTime = (\n currentIterationTime: number,\n duration: number,\n direction: string,\n currentIteration: number,\n): number => {\n if (shouldReverseIteration(direction, currentIteration)) {\n return duration - currentIterationTime;\n }\n return currentIterationTime;\n};\n\n/**\n * Maps element time to animation time for normal direction.\n * Uses cumulative time throughout the animation.\n * Note: elementTime should already be adjusted (elementTime - effectiveDelay).\n */\nconst mapNormalDirectionTime = (\n elementTime: number,\n duration: number,\n maxSafeTime: number,\n): number => {\n const currentIteration = Math.floor(elementTime / duration);\n const iterationTime = elementTime % duration;\n const cumulativeTime = currentIteration * duration + iterationTime;\n return Math.min(cumulativeTime, maxSafeTime);\n};\n\n/**\n * Maps element time to animation time for reverse direction.\n * Uses cumulative time with reversed iterations.\n * Note: elementTime should already be adjusted (elementTime - effectiveDelay).\n */\nconst mapReverseDirectionTime = (\n elementTime: number,\n duration: number,\n maxSafeTime: number,\n): number => {\n const currentIteration = Math.floor(elementTime / duration);\n const rawIterationTime = elementTime % duration;\n const reversedIterationTime = duration - rawIterationTime;\n const cumulativeTime = currentIteration * duration + reversedIterationTime;\n return Math.min(cumulativeTime, maxSafeTime);\n};\n\n/**\n * Maps element time to animation time for alternate/alternate-reverse directions.\n *\n * WHY SPECIAL HANDLING: Alternate directions oscillate between forward and reverse iterations.\n * Without delay, we use iteration time (0 to duration) because the animation naturally\n * resets each iteration. However, with delay, iteration 0 needs to account for the delay\n * offset (using ownCurrentTimeMs), and later iterations need cumulative time to properly\n * track progress across multiple iterations. This complexity requires a dedicated mapper\n * rather than trying to handle it in the general case.\n */\nconst mapAlternateDirectionTime = (\n elementTime: number,\n effectiveDelay: number,\n duration: number,\n direction: string,\n maxSafeTime: number,\n): number => {\n const adjustedTime = elementTime - effectiveDelay;\n\n if (effectiveDelay > 0) {\n // With delay: iteration 0 uses elementTime to include delay offset,\n // later iterations use cumulative time to track progress across iterations\n const currentIteration = Math.floor(adjustedTime / duration);\n if (currentIteration === 0) {\n return Math.min(elementTime, maxSafeTime);\n }\n return Math.min(adjustedTime, maxSafeTime);\n }\n\n // Without delay: use iteration time (after direction applied) since animation\n // naturally resets each iteration\n const currentIteration = Math.floor(elementTime / duration);\n const rawIterationTime = elementTime % duration;\n const iterationTime = applyDirectionToIterationTime(\n rawIterationTime,\n duration,\n direction,\n currentIteration,\n );\n return Math.min(iterationTime, maxSafeTime);\n};\n\n/**\n * Maps element time to animation time based on direction.\n *\n * WHY: This function explicitly transforms element time to animation time, making\n * the time mapping concept clear. Different directions require different transformations\n * to achieve the desired visual effect.\n */\nconst mapElementTimeToAnimationTime = (\n elementTime: number,\n timing: AnimationTiming,\n effectiveDelay: number,\n): number => {\n const { duration, iterations, direction } = timing;\n const maxSafeTime = calculateMaxSafeAnimationTime(duration, iterations);\n // Calculate adjusted time (element time minus delay) for normal/reverse directions\n const adjustedTime = elementTime - effectiveDelay;\n\n if (direction === \"reverse\") {\n return mapReverseDirectionTime(adjustedTime, duration, maxSafeTime);\n }\n if (direction === \"alternate\" || direction === \"alternate-reverse\") {\n return mapAlternateDirectionTime(elementTime, effectiveDelay, duration, direction, maxSafeTime);\n }\n // normal direction - use adjustedTime to account for delay\n return mapNormalDirectionTime(adjustedTime, duration, maxSafeTime);\n};\n\n/**\n * Determines the animation time for a completed animation based on direction.\n */\nconst getCompletedAnimationTime = (timing: AnimationTiming, maxSafeTime: number): number => {\n const { direction, iterations, duration } = timing;\n\n if (direction === \"alternate\" || direction === \"alternate-reverse\") {\n // For alternate directions, determine if final iteration is reversed\n const finalIteration = iterations - 1;\n const isFinalIterationReversed =\n (direction === \"alternate\" && finalIteration % 2 === 1) ||\n (direction === \"alternate-reverse\" && finalIteration % 2 === 0);\n\n if (isFinalIterationReversed) {\n // At end of reversed iteration, currentTime should be near 0 (but clamped)\n return Math.min(duration - ANIMATION_PRECISION_OFFSET, maxSafeTime);\n }\n }\n\n // For normal, reverse, or forward final iteration of alternate: use max safe time\n return maxSafeTime;\n};\n\n/**\n * Validates that animation effect is a KeyframeEffect with a target\n */\nconst validateAnimationEffect = (\n effect: AnimationEffect | null,\n): effect is KeyframeEffect & { target: Element } => {\n return effect !== null && effect instanceof KeyframeEffect && effect.target !== null;\n};\n\n/**\n * Extracts timing information from an animation effect.\n * Duration and delay from getTiming() are already in milliseconds.\n * We use getTiming().delay directly from the animation object.\n */\nconst extractAnimationTiming = (effect: KeyframeEffect): AnimationTiming => {\n const timing = effect.getTiming();\n\n return {\n duration: Number(timing.duration) || 0,\n delay: Number(timing.delay) || 0,\n iterations: Number(timing.iterations) || DEFAULT_ANIMATION_ITERATIONS,\n direction: timing.direction || \"normal\",\n };\n};\n\n// ============================================================================\n// Animation Fill Mode Validation (Development Mode)\n// ============================================================================\n\n/**\n * Analyzes keyframes to detect if animation is a fade-in or fade-out effect.\n * Returns 'fade-in', 'fade-out', 'both', or null.\n */\nconst detectFadePattern = (keyframes: Keyframe[]): \"fade-in\" | \"fade-out\" | \"both\" | null => {\n if (!keyframes || keyframes.length < 2) return null;\n\n const firstFrame = keyframes[0];\n const lastFrame = keyframes[keyframes.length - 1];\n\n const firstOpacity = firstFrame && \"opacity\" in firstFrame ? Number(firstFrame.opacity) : null;\n const lastOpacity = lastFrame && \"opacity\" in lastFrame ? Number(lastFrame.opacity) : null;\n\n if (firstOpacity === null || lastOpacity === null) return null;\n\n const isFadeIn = firstOpacity < lastOpacity;\n const isFadeOut = firstOpacity > lastOpacity;\n\n if (isFadeIn && isFadeOut) return \"both\";\n if (isFadeIn) return \"fade-in\";\n if (isFadeOut) return \"fade-out\";\n return null;\n};\n\n/**\n * Analyzes keyframes to detect if animation has transform changes (slide, scale, etc).\n */\nconst hasTransformAnimation = (keyframes: Keyframe[]): boolean => {\n if (!keyframes || keyframes.length < 2) return false;\n\n return keyframes.some(\n (frame) =>\n \"transform\" in frame || \"translate\" in frame || \"scale\" in frame || \"rotate\" in frame,\n );\n};\n\n/**\n * Validates CSS animation fill-mode to prevent flashing issues.\n *\n * CRITICAL: Editframe's timeline system pauses animations and manually controls them\n * via animation.currentTime. This means elements exist in the DOM before their animations\n * start. Without proper fill-mode, elements will \"flash\" to their natural state before\n * the animation begins.\n *\n * Common issues:\n * - Delayed animations without 'backwards': Element shows natural state during delay\n * - Fade-in without 'backwards': Element visible before fade starts\n * - Fade-out without 'forwards': Element snaps back after fade completes\n *\n * Only runs in development mode to avoid performance impact in production.\n */\nconst validateAnimationFillMode = (animation: Animation, timing: AnimationTiming): void => {\n // Only validate in development mode\n if (typeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\") {\n return;\n }\n\n const effect = animation.effect;\n if (!validateAnimationEffect(effect)) {\n return;\n }\n\n const effectTiming = effect.getTiming();\n const fill = effectTiming.fill || \"none\";\n const target = effect.target;\n\n // Get animation name for better error messages\n let animationName = \"unknown\";\n if (animation.id) {\n animationName = animation.id;\n } else if (target instanceof HTMLElement) {\n const computedStyle = window.getComputedStyle(target);\n const animationNameValue = computedStyle.animationName;\n if (animationNameValue && animationNameValue !== \"none\") {\n animationName = animationNameValue.split(\",\")[0]?.trim() || \"unknown\";\n }\n }\n\n // Create unique key based on animation name and duration\n const validationKey = `${animationName}-${timing.duration}`;\n\n // Skip if already validated\n if (validatedAnimations.has(validationKey)) {\n return;\n }\n validatedAnimations.add(validationKey);\n\n const warnings: string[] = [];\n\n // Check 1: Delayed animations without backwards/both\n if (timing.delay > 0 && fill !== \"backwards\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" has a ${timing.delay}ms delay but no 'backwards' fill-mode.`,\n ` This will cause the element to show its natural state during the delay, then suddenly jump when the animation starts.`,\n ` Fix: Add 'backwards' or 'both' to the animation shorthand.`,\n ` Example: animation: ${animationName} ${timing.duration}ms ${timing.delay}ms backwards;`,\n );\n }\n\n // Check 2: Analyze keyframes for fade/transform patterns\n try {\n const keyframes = effect.getKeyframes();\n const fadePattern = detectFadePattern(keyframes);\n const hasTransform = hasTransformAnimation(keyframes);\n\n // Fade-in or transform-in animations should use backwards\n if ((fadePattern === \"fade-in\" || hasTransform) && fill !== \"backwards\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" modifies initial state but lacks 'backwards' fill-mode.`,\n ` The element will be visible in its natural state before the animation starts.`,\n ` Fix: Add 'backwards' or 'both' to the animation.`,\n ` Example: animation: ${animationName} ${timing.duration}ms backwards;`,\n );\n }\n\n // Fade-out animations should use forwards\n if (fadePattern === \"fade-out\" && fill !== \"forwards\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" modifies final state but lacks 'forwards' fill-mode.`,\n ` The element will snap back to its natural state after the animation completes.`,\n ` Fix: Add 'forwards' or 'both' to the animation.`,\n ` Example: animation: ${animationName} ${timing.duration}ms forwards;`,\n );\n }\n\n // Combined effects should use both\n if (fadePattern === \"both\" && fill !== \"both\") {\n warnings.push(\n `⚠️ Animation \"${animationName}\" modifies both initial and final state but doesn't use 'both' fill-mode.`,\n ` Fix: Use 'both' to apply initial and final states.`,\n ` Example: animation: ${animationName} ${timing.duration}ms both;`,\n );\n }\n } catch (_e) {\n // Silently skip keyframe analysis if it fails\n }\n\n if (warnings.length > 0 && typeof window !== \"undefined\") {\n console.groupCollapsed(\n \"%c🎬 Editframe Animation Fill-Mode Warning\",\n \"color: #f59e0b; font-weight: bold\",\n );\n warnings.forEach((warning) => console.log(warning));\n console.log(\n \"\\n📚 Learn more: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode\",\n );\n console.groupEnd();\n }\n};\n\n/**\n * Prepares animation for manual control on first encounter.\n *\n * Reading animation.playState forces style recalculation in Chromium (layout thrash).\n * Instead we track prepared animations in a WeakSet. On first encounter we optimistically\n * cancel the animation — cancel() is safe on any state (paused/running/finished/idle)\n * and leaves the animation in \"idle\", from which currentTime writes work freely.\n * On subsequent frames the animation is already under our control so we skip this entirely.\n */\nconst prepareAnimation = (animation: Animation): void => {\n if (preparedAnimations.has(animation)) {\n return;\n }\n animation.cancel();\n preparedAnimations.add(animation);\n};\n\n/**\n * Maps element time to animation currentTime and sets it on the animation.\n *\n * WHY: This function explicitly performs the time mapping transformation,\n * making it clear that we're transforming element time to animation time.\n */\nconst mapAndSetAnimationTime = (\n animation: Animation,\n element: AnimatableElement,\n timing: AnimationTiming,\n effectiveDelay: number,\n): void => {\n // Use ownCurrentTimeMs for all elements (timegroups and other temporal elements)\n // This gives us time relative to when the element started, which ensures animations\n // on child elements are synchronized with their containing timegroup's timeline.\n // For timegroups, ownCurrentTimeMs is the time relative to when the timegroup started.\n // For other temporal elements, ownCurrentTimeMs is the time relative to their start.\n const elementTime = element.ownCurrentTimeMs ?? 0;\n\n // Calculate adjusted time (element time minus delay)\n const adjustedTime = elementTime - effectiveDelay;\n\n // If before delay, show initial keyframe state (0% of animation)\n if (adjustedTime < 0) {\n // Before delay: show initial keyframe state.\n // For CSS animations with delay > 0, currentTime is in \"absolute timeline time\"\n // (delay period + animation progress). Subtracting the stagger offset shifts\n // each segment's delay window so they enter their animation at different times.\n if (timing.delay > 0) {\n animation.currentTime = elementTime - (effectiveDelay - timing.delay);\n } else {\n animation.currentTime = 0;\n }\n return;\n }\n\n // At delay time (adjustedTime = 0) or after, the animation should be active\n const { duration, iterations } = timing;\n const currentIteration = Math.floor(adjustedTime / duration);\n\n if (currentIteration >= iterations) {\n // Animation is completed - use completed time mapping\n const maxSafeTime = calculateMaxSafeAnimationTime(duration, iterations);\n const completedAnimationTime = getCompletedAnimationTime(timing, maxSafeTime);\n\n // CRITICAL: For CSS animations, currentTime behavior differs based on whether delay > 0:\n // - If timing.delay > 0: currentTime includes the delay (absolute timeline time)\n // - If timing.delay === 0: currentTime is just animation progress (0 to duration)\n if (timing.delay > 0) {\n // Completed: anchor to timing.delay (not effectiveDelay) so all segments land at\n // the same final keyframe regardless of their individual stagger offsets.\n animation.currentTime = timing.delay + completedAnimationTime;\n } else {\n // Completed: currentTime should be just the completed animation time (animation progress)\n animation.currentTime = completedAnimationTime;\n }\n } else {\n // Animation is in progress - map element time to animation time\n const animationTime = mapElementTimeToAnimationTime(elementTime, timing, effectiveDelay);\n\n // CRITICAL: For CSS animations, currentTime behavior differs based on whether delay > 0:\n // - If timing.delay > 0: currentTime includes the delay (absolute timeline time)\n // - If timing.delay === 0: currentTime is just animation progress (0 to duration)\n // Stagger offset is handled via adjustedTime calculation, but doesn't affect currentTime format\n const { direction, delay } = timing;\n\n if (delay > 0) {\n // CSS animation with delay: currentTime is in \"absolute timeline time\" (delay + progress).\n // Anchor to timing.delay (the CSS base delay) rather than effectiveDelay so that the\n // stagger offset shifts each segment's window without cancelling out.\n const staggerShift = effectiveDelay - timing.delay;\n const isAlternateWithDelay =\n (direction === \"alternate\" || direction === \"alternate-reverse\") && effectiveDelay > 0;\n if (isAlternateWithDelay && currentIteration === 0) {\n animation.currentTime = elementTime - staggerShift;\n } else {\n animation.currentTime = timing.delay + animationTime;\n }\n } else {\n // CSS animation with delay = 0: currentTime is just animation progress\n // Stagger offset is already accounted for in adjustedTime, so animationTime is the progress\n animation.currentTime = animationTime;\n }\n }\n};\n\n/**\n * Builds and caches per-animation data derived from immutable properties.\n * Called once per animation on first synchronization; subsequent frames use the cache.\n */\nconst buildAnimationCache = (\n animation: Animation,\n effect: KeyframeEffect & { target: Element },\n fallbackElement: AnimatableElement,\n): CachedAnimationData => {\n const timing = extractAnimationTiming(effect);\n const target = effect.target;\n\n // Resolve time source: nearest ef-timegroup ancestor (or fallback to root)\n let timeSource: AnimatableElement | null = null;\n if (target instanceof HTMLElement) {\n const nearestTimegroup = target.closest(\"ef-timegroup\");\n if (nearestTimegroup && isEFTemporal(nearestTimegroup)) {\n timeSource = nearestTimegroup as AnimatableElement;\n }\n }\n\n // Resolve stagger element: nearest ef-text-segment ancestor (or fallback to timeSource)\n let staggerElement: AnimatableElement | null = null;\n if (target instanceof HTMLElement) {\n const targetAsAnimatable = target as AnimatableElement;\n if (supportsStaggerOffset(targetAsAnimatable)) {\n staggerElement = targetAsAnimatable;\n } else {\n const parentSegment = target.closest(\"ef-text-segment\");\n if (parentSegment && supportsStaggerOffset(parentSegment as AnimatableElement)) {\n staggerElement = parentSegment as AnimatableElement;\n }\n }\n }\n\n const resolvedStagger = staggerElement ?? timeSource ?? fallbackElement;\n const effectiveDelay = calculateEffectiveDelay(timing.delay, resolvedStagger);\n\n const data: CachedAnimationData = { timing, timeSource, staggerElement, effectiveDelay };\n animationCache.set(animation, data);\n\n // Validate fill-mode once at cache-build time (first encounter per animation).\n // Moved here from synchronizeAnimation to avoid re-entering on every subsequent frame.\n validateAnimationFillMode(animation, timing);\n\n return data;\n};\n\n/**\n * Synchronizes a single animation with the timeline using the element as the time source.\n *\n * Timing, time-source, and stagger lookups are cached per animation — they are derived\n * from immutable properties (keyframe timing, DOM parent chain) and never change during\n * the lifetime of an animation.\n */\nconst synchronizeAnimation = (animation: Animation, element: AnimatableElement): void => {\n const effect = animation.effect;\n if (!validateAnimationEffect(effect)) {\n return;\n }\n\n // Use cached data when available; build and cache on first encounter\n let cached = animationCache.get(animation);\n if (!cached) {\n cached = buildAnimationCache(animation, effect, element);\n }\n\n const { timing } = cached;\n\n if (timing.duration <= 0) {\n animation.currentTime = 0;\n return;\n }\n\n const timeSource = cached.timeSource ?? element;\n mapAndSetAnimationTime(animation, timeSource, timing, cached.effectiveDelay);\n};\n\n/**\n * Coordinates animations for a single element and its subtree, using the element as the time source.\n *\n * Uses tracked animations to ensure we can control animations even after they complete.\n * Both CSS animations (created via the 'animation' property) and WAAPI animations are included.\n *\n * CRITICAL: CSS animations are created asynchronously when classes are added. This function\n * discovers new animations on each call and tracks them in memory. Once animations complete,\n * they're removed from getAnimations(), but we keep references to them so we can continue\n * controlling them.\n */\nconst coordinateElementAnimations = (\n element: AnimatableElement,\n providedAnimations?: Animation[],\n): void => {\n // Discover and track animations (includes both current and previously completed ones)\n // Reuse the current animations array to avoid calling getAnimations() twice\n // Accept pre-discovered animations to avoid redundant getAnimations() calls\n const { tracked: trackedAnimations, current: currentAnimations } = discoverAndTrackAnimations(\n element,\n providedAnimations,\n );\n\n for (const animation of trackedAnimations) {\n // Skip invalid animations (cancelled, removed from DOM, etc.)\n if (!isAnimationValid(animation, currentAnimations)) {\n continue;\n }\n\n // Record playState before prepareAnimation so we can detect the\n // 'finished' → 'idle' cancellation path specifically.\n const wasFinished = animation.playState === \"finished\";\n prepareAnimation(animation);\n // Capture post-prepareAnimation playState in a fresh variable so TypeScript\n // does not apply the 'wasFinished' type-guard narrowing here.\n const playStateAfter = animation.playState;\n\n // Do NOT synchronize animations that prepareAnimation just cancelled out of\n // the 'finished' state — i.e., the animation was 'finished' before the call\n // and is now 'idle' because prepareAnimation() called cancel() on it.\n //\n // The bug: prepareAnimation() calls cancel() on 'finished' animations, transitioning\n // them to 'idle'. Calling synchronizeAnimation() immediately after sets currentTime on\n // the idle animation, which per the Web Animations API spec transitions it back to\n // 'paused' — resurrecting the cancelled animation.\n //\n // For CSS animations, the browser also creates a fresh CSSAnimation for the same CSS\n // rule once cancel() clears the old one. This leaves two animations where there should\n // be one: the manually-resurrected old animation AND the browser-created replacement.\n // Neither is cleaned up (both are 'paused', connected, valid), so they accumulate on\n // every loop cycle — exactly the unbounded growth observed in long-running previews.\n //\n // Using the pre-cancel state ensures we only skip this specific 'finished' → 'idle'\n // path. Animations that become idle for other reasons (e.g., out-of-range elements\n // that were already idle) are still synchronized so they can be correctly positioned.\n if (!(wasFinished && playStateAfter === \"idle\")) {\n synchronizeAnimation(animation, element);\n }\n }\n};\n\n// ============================================================================\n// Visual State Application\n// ============================================================================\n\n/**\n * Applies visual state (CSS + display) to match temporal state.\n *\n * WHY: This function applies visual state based on the element's phase and state.\n * Phase determines what should be visible, and this function applies that decision.\n */\nconst applyVisualState = (element: AnimatableElement, state: TemporalState): void => {\n // Always set progress (needed for many use cases)\n element.style.setProperty(PROGRESS_PROPERTY, `${state.progress}`);\n\n // Handle visibility based on phase\n if (!state.isVisible) {\n element.style.setProperty(\"display\", \"none\");\n cancelTrackedAnimations(element);\n return;\n }\n element.style.removeProperty(\"display\");\n\n // Set other CSS properties for visible elements only\n element.style.setProperty(DURATION_PROPERTY, `${element.durationMs}ms`);\n element.style.setProperty(\n TRANSITION_DURATION_PROPERTY,\n `${element.parentTimegroup?.overlapMs ?? 0}ms`,\n );\n element.style.setProperty(\n TRANSITION_OUT_START_PROPERTY,\n `${element.durationMs - (element.parentTimegroup?.overlapMs ?? 0)}ms`,\n );\n};\n\n/**\n * Applies animation coordination if the element phase requires it.\n *\n * WHY: Animation coordination is driven by phase. If the element is in a phase\n * where animations should be coordinated, we coordinate them.\n */\nconst applyAnimationCoordination = (\n element: AnimatableElement,\n phase: ElementPhase,\n providedAnimations?: Animation[],\n): void => {\n if (shouldCoordinateAnimations(phase, element)) {\n coordinateElementAnimations(element, providedAnimations);\n }\n};\n\n// ============================================================================\n// SVG SMIL Synchronization\n// ============================================================================\n\n/**\n * Finds the nearest temporal ancestor (or self) for a given element.\n * Returns the element itself if it is a temporal element, otherwise walks up.\n * Falls back to the provided root element.\n */\nconst findNearestTemporalAncestor = (\n element: Element,\n root: AnimatableElement,\n): AnimatableElement => {\n let node: Element | null = element;\n while (node) {\n if (isEFTemporal(node)) {\n return node as AnimatableElement;\n }\n node = node.parentElement;\n }\n return root;\n};\n\n/**\n * Synchronizes all SVG SMIL animations in the subtree with the timeline.\n *\n * SVG has its own animation clock on each SVGSVGElement. We pause it and\n * seek it to the owning temporal element's current time (converted to seconds).\n */\nconst synchronizeSvgAnimations = (root: AnimatableElement): void => {\n const svgElements = (root as HTMLElement).querySelectorAll(\"svg\");\n for (const svg of svgElements) {\n const owner = findNearestTemporalAncestor(svg, root);\n const timeMs = owner.currentTimeMs ?? 0;\n svg.setCurrentTime(timeMs / 1000);\n svg.pauseAnimations();\n }\n};\n\n// ============================================================================\n// Media Element Synchronization\n// ============================================================================\n\n/**\n * Synchronizes all <video> and <audio> elements in the subtree with the timeline.\n *\n * Sets currentTime (in seconds) to match the owning temporal element's position\n * and ensures the elements are paused (playback is controlled by the timeline).\n */\nconst synchronizeMediaElements = (root: AnimatableElement): void => {\n const mediaElements = (root as HTMLElement).querySelectorAll(\"video, audio\");\n for (const media of mediaElements as NodeListOf<HTMLMediaElement>) {\n const owner = findNearestTemporalAncestor(media, root);\n const timeMs = owner.currentTimeMs ?? 0;\n const timeSec = timeMs / 1000;\n if (media.currentTime !== timeSec) {\n media.currentTime = timeSec;\n }\n if (!media.paused) {\n media.pause();\n }\n }\n};\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Evaluates the complete state for an element update.\n * This separates evaluation (what should the state be?) from application (apply that state).\n */\nconst evaluateElementState = (element: AnimatableElement): ElementUpdateContext => {\n return {\n element,\n state: evaluateTemporalState(element),\n };\n};\n\n/**\n * Main function: synchronizes DOM element with timeline.\n *\n * Orchestrates clear flow: Phase → Policy → Time Mapping → State Application\n *\n * WHY: This function makes the conceptual flow explicit:\n * 1. Determine phase (what phase is the element in?)\n * 2. Apply policies (should it be visible/coordinated based on phase?)\n * 3. Map time for animations (transform element time to animation time)\n * 4. Apply visual state (update CSS and display based on phase and policies)\n */\nexport const updateAnimations = (element: AnimatableElement): void => {\n const rootContext = evaluateElementState(element);\n const timelineTimeMs = (element.rootTimegroup ?? element).currentTimeMs;\n const { elements: collectedElements, pruned } = deepGetTemporalElements(element, timelineTimeMs);\n\n // For pruned elements (invisible containers whose subtrees were skipped),\n // cancel their animations and hide them before fetching allAnimations.\n // This ensures the subsequent getAnimations() call reflects only active animations.\n for (const prunedElement of pruned) {\n prunedElement.style.setProperty(\"display\", \"none\");\n cancelTrackedAnimations(prunedElement);\n }\n\n // Fetch allAnimations after pruned elements are cancelled so they don't appear in the list.\n const allAnimations = element.getAnimations({ subtree: true });\n\n // Evaluate state only for non-pruned elements (visible + individually\n // invisible leaf elements that weren't behind a pruned container).\n const childContexts: ElementUpdateContext[] = [];\n for (const temporalElement of collectedElements) {\n if (!pruned.has(temporalElement)) {\n childContexts.push(evaluateElementState(temporalElement));\n }\n }\n\n // Separate visible and invisible children.\n // Only visible children need animation coordination (expensive).\n // Invisible children just need display:none applied (cheap).\n const visibleChildContexts: ElementUpdateContext[] = [];\n for (const ctx of childContexts) {\n if (shouldBeVisible(ctx.state.phase, ctx.element)) {\n visibleChildContexts.push(ctx);\n }\n }\n\n // Partition allAnimations by closest VISIBLE temporal parent.\n // Only visible elements need their animations partitioned and coordinated.\n // Build a Set of visible temporal elements for O(1) lookup, then walk up\n // from each animation target to find its closest temporal owner.\n const temporalSet = new Set<Element>(visibleChildContexts.map((c) => c.element));\n temporalSet.add(element); // Include root\n const childAnimations = new Map<AnimatableElement, Animation[]>();\n for (const animation of allAnimations) {\n const effect = animation.effect;\n const target = effect && effect instanceof KeyframeEffect ? effect.target : null;\n if (!target || !(target instanceof Element)) continue;\n\n let node: Element | null = target;\n while (node) {\n if (temporalSet.has(node)) {\n let anims = childAnimations.get(node as AnimatableElement);\n if (!anims) {\n anims = [];\n childAnimations.set(node as AnimatableElement, anims);\n }\n anims.push(animation);\n break;\n }\n node = node.parentElement;\n }\n }\n\n // Coordinate animations for root and VISIBLE children only.\n // Invisible children (display:none) have no CSS animations to coordinate,\n // and when they become visible again, coordination runs on that frame.\n applyAnimationCoordination(rootContext.element, rootContext.state.phase, allAnimations);\n for (const context of visibleChildContexts) {\n applyAnimationCoordination(\n context.element,\n context.state.phase,\n childAnimations.get(context.element) || [],\n );\n }\n\n // Apply visual state for non-pruned children (pruned ones already got display:none above)\n applyVisualState(rootContext.element, rootContext.state);\n for (const context of childContexts) {\n applyVisualState(context.element, context.state);\n }\n\n // Synchronize non-CSS animation systems\n synchronizeSvgAnimations(element);\n synchronizeMediaElements(element);\n\n // Drive ef-motionblur elements. All animation currentTimes are settled at this\n // point, so each motionblur element can do its two-seek position measurement\n // with fully-accurate animation state — producing deterministic, scrub-stable blur.\n // Only sample elements that are currently in the visible subtree — elements inside\n // display:none ancestors have zero-size rects and would produce bogus deltas.\n const motionBlurElements = (element as HTMLElement).querySelectorAll(\"ef-motionblur\");\n for (const mb of motionBlurElements) {\n let hidden = false;\n let node: Element | null = mb.parentElement;\n while (node) {\n if ((node as HTMLElement).style?.display === \"none\") {\n hidden = true;\n break;\n }\n node = node.parentElement;\n }\n if (hidden) continue;\n (mb as any).sample?.();\n }\n};\n"],"mappings":";;;AAaA,MAAM,6BAA6B;AACnC,MAAM,+BAA+B;AACrC,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,+BAA+B;AACrC,MAAM,gCAAgC;;;;;;AAWtC,MAAM,mCAAmB,IAAI,SAAkC;;;;;;AAO/D,MAAM,sCAAsB,IAAI,SAA2B;;;;;AAM3D,MAAM,qCAAqB,IAAI,SAA0B;;;;;AAMzD,MAAM,sCAAsB,IAAI,KAAa;;;;;;;AAQ7C,MAAM,qCAAqB,IAAI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AAM;AACX,OAAK,KAAqB,OAAO,YAAY,QAAQ;AACnD,aAAS;AACT;;AAEF,UAAO,KAAK;;AAEd,MAAI,OAAQ;AACZ,EAAC,GAAW,UAAU"}
|
|
@@ -69,6 +69,7 @@ declare class EFWorkbench extends EFWorkbench_base {
|
|
|
69
69
|
private canvasPreviewResult;
|
|
70
70
|
private canvasAnimationFrame;
|
|
71
71
|
private boundHandleTransformChanged;
|
|
72
|
+
private boundHandleKeyDown;
|
|
72
73
|
focusOverlay: lit_html_directives_ref_js2.Ref<HTMLDivElement>;
|
|
73
74
|
handleStageWheel(event: WheelEvent): void;
|
|
74
75
|
connectedCallback(): void;
|
package/dist/gui/EFWorkbench.js
CHANGED
|
@@ -6,10 +6,12 @@ import { findRootTemporal } from "../elements/findRootTemporal.js";
|
|
|
6
6
|
import { ICONS, phosphorIcon } from "./icons.js";
|
|
7
7
|
import { getPreviewPresentationMode, getPreviewResolutionScale, getRenderMode, getShowStats, getShowThumbnailTimestamps, isNativeCanvasApiAvailable, setPreviewPresentationMode, setRenderMode, setShowStats, setShowThumbnailTimestamps } from "../preview/previewSettings.js";
|
|
8
8
|
import { previewSettingsContext } from "./previewSettingsContext.js";
|
|
9
|
+
import { EFMotionBlur } from "../elements/EFMotionBlur.js";
|
|
9
10
|
import { AdaptiveResolutionTracker } from "../preview/AdaptiveResolutionTracker.js";
|
|
10
11
|
import { RenderStats } from "../preview/RenderStats.js";
|
|
11
12
|
import { DomStatsStrategy } from "../preview/statsTrackingStrategy.js";
|
|
12
13
|
import "./EFFitScale.js";
|
|
14
|
+
import { handleSpacebarToggle } from "./EFWorkbench.spacebar.js";
|
|
13
15
|
import { EFTimegroup } from "../elements/EFTimegroup.js";
|
|
14
16
|
import { provide } from "@lit/context";
|
|
15
17
|
import { LitElement, css, html } from "lit";
|
|
@@ -69,6 +71,11 @@ let EFWorkbench = class EFWorkbench$1 extends ContextMixin(TWMixin(LitElement))
|
|
|
69
71
|
this.canvasPreviewResult = null;
|
|
70
72
|
this.canvasAnimationFrame = null;
|
|
71
73
|
this.boundHandleTransformChanged = this.handleTransformChanged.bind(this);
|
|
74
|
+
this.boundHandleKeyDown = (e) => {
|
|
75
|
+
if (e.key !== " ") return;
|
|
76
|
+
e.preventDefault();
|
|
77
|
+
handleSpacebarToggle(() => this.getTimegroup(), document.activeElement);
|
|
78
|
+
};
|
|
72
79
|
this.focusOverlay = createRef();
|
|
73
80
|
this.lastCanvasZoom = 1;
|
|
74
81
|
this.zoomReinitTimeout = null;
|
|
@@ -566,6 +573,7 @@ let EFWorkbench = class EFWorkbench$1 extends ContextMixin(TWMixin(LitElement))
|
|
|
566
573
|
this.applyTheme();
|
|
567
574
|
if (!this.hasAttribute("rendering") && typeof window !== "undefined" && "FRAMEGEN_BRIDGE" in window) this.rendering = true;
|
|
568
575
|
this.addEventListener("transform-changed", this.boundHandleTransformChanged);
|
|
576
|
+
document.addEventListener("keydown", this.boundHandleKeyDown);
|
|
569
577
|
this.startMotionStateTracking();
|
|
570
578
|
this.adaptiveTracker = new AdaptiveResolutionTracker({ onScaleChange: (scale) => {
|
|
571
579
|
const oldScale = this.currentAdaptiveScale;
|
|
@@ -596,6 +604,7 @@ let EFWorkbench = class EFWorkbench$1 extends ContextMixin(TWMixin(LitElement))
|
|
|
596
604
|
timegroup.style.pointerEvents = "";
|
|
597
605
|
}
|
|
598
606
|
this.removeEventListener("transform-changed", this.boundHandleTransformChanged);
|
|
607
|
+
document.removeEventListener("keydown", this.boundHandleKeyDown);
|
|
599
608
|
if (this.systemThemeMediaQuery && this.systemThemeListener) this.systemThemeMediaQuery.removeEventListener("change", this.systemThemeListener);
|
|
600
609
|
this.stopMotionStateTracking();
|
|
601
610
|
if (typeof this.stopCacheStatsUpdates === "function") this.stopCacheStatsUpdates();
|
|
@@ -806,6 +815,7 @@ let EFWorkbench = class EFWorkbench$1 extends ContextMixin(TWMixin(LitElement))
|
|
|
806
815
|
this.restDebounceTimer = null;
|
|
807
816
|
}
|
|
808
817
|
this.isAtRest = false;
|
|
818
|
+
EFMotionBlur.renderQuality = "preview";
|
|
809
819
|
this.setOverlaysPaused(true);
|
|
810
820
|
if (this.previewResolutionScale === "auto" && this.adaptiveTracker) {
|
|
811
821
|
const timegroup = this.getTimegroup();
|
|
@@ -842,6 +852,11 @@ let EFWorkbench = class EFWorkbench$1 extends ContextMixin(TWMixin(LitElement))
|
|
|
842
852
|
this.currentAdaptiveScale = 1;
|
|
843
853
|
if (this.canvasPreviewResult) this.canvasPreviewResult.setResolutionScale(1);
|
|
844
854
|
}
|
|
855
|
+
EFMotionBlur.renderQuality = "render";
|
|
856
|
+
if (this.canvasPreviewResult) {
|
|
857
|
+
this.canvasPreviewResult.invalidate();
|
|
858
|
+
this.canvasPreviewResult.refresh();
|
|
859
|
+
}
|
|
845
860
|
}
|
|
846
861
|
/**
|
|
847
862
|
* Get the effective resolution scale based on current mode and motion state.
|