@editframe/elements 0.40.5 → 0.40.7

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.
@@ -545,6 +545,47 @@ const applyAnimationCoordination = (element, phase, providedAnimations) => {
545
545
  if (shouldCoordinateAnimations(phase, element)) coordinateElementAnimations(element, providedAnimations);
546
546
  };
547
547
  /**
548
+ * Finds the nearest temporal ancestor (or self) for a given element.
549
+ * Returns the element itself if it is a temporal element, otherwise walks up.
550
+ * Falls back to the provided root element.
551
+ */
552
+ const findNearestTemporalAncestor = (element, root) => {
553
+ let node = element;
554
+ while (node) {
555
+ if (isEFTemporal(node)) return node;
556
+ node = node.parentElement;
557
+ }
558
+ return root;
559
+ };
560
+ /**
561
+ * Synchronizes all SVG SMIL animations in the subtree with the timeline.
562
+ *
563
+ * SVG has its own animation clock on each SVGSVGElement. We pause it and
564
+ * seek it to the owning temporal element's current time (converted to seconds).
565
+ */
566
+ const synchronizeSvgAnimations = (root) => {
567
+ const svgElements = root.querySelectorAll("svg");
568
+ for (const svg of svgElements) {
569
+ const timeMs = findNearestTemporalAncestor(svg, root).currentTimeMs ?? 0;
570
+ svg.setCurrentTime(timeMs / 1e3);
571
+ svg.pauseAnimations();
572
+ }
573
+ };
574
+ /**
575
+ * Synchronizes all <video> and <audio> elements in the subtree with the timeline.
576
+ *
577
+ * Sets currentTime (in seconds) to match the owning temporal element's position
578
+ * and ensures the elements are paused (playback is controlled by the timeline).
579
+ */
580
+ const synchronizeMediaElements = (root) => {
581
+ const mediaElements = root.querySelectorAll("video, audio");
582
+ for (const media of mediaElements) {
583
+ const timeSec = (findNearestTemporalAncestor(media, root).currentTimeMs ?? 0) / 1e3;
584
+ if (media.currentTime !== timeSec) media.currentTime = timeSec;
585
+ if (!media.paused) media.pause();
586
+ }
587
+ };
588
+ /**
548
589
  * Evaluates the complete state for an element update.
549
590
  * This separates evaluation (what should the state be?) from application (apply that state).
550
591
  */
@@ -600,6 +641,8 @@ const updateAnimations = (element) => {
600
641
  for (const context of visibleChildContexts) applyAnimationCoordination(context.element, context.state.phase, childAnimations.get(context.element) || []);
601
642
  applyVisualState(rootContext.element, rootContext.state);
602
643
  for (const context of childContexts) applyVisualState(context.element, context.state);
644
+ synchronizeSvgAnimations(element);
645
+ synchronizeMediaElements(element);
603
646
  };
604
647
 
605
648
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"updateAnimations.js","names":["warnings: string[]","timeSource: AnimatableElement","staggerElement: AnimatableElement","childContexts: ElementUpdateContext[]","visibleChildContexts: ElementUpdateContext[]","node: Element | null"],"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 * 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 = (\n animation: Animation,\n currentAnimations: Animation[],\n): boolean => {\n // Check if animation has been cancelled\n if (\n animation.playState === \"idle\" &&\n !currentAnimations.includes(animation)\n ) {\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 =\n 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 =\n 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 =\n 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 * 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 =\n | \"before-start\"\n | \"active\"\n | \"at-end-boundary\"\n | \"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 =\n 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 = (\n phase: ElementPhase,\n element: AnimatableElement,\n): 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 = (\n _phase: ElementPhase,\n _element: AnimatableElement,\n): 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 = (\n element: AnimatableElement,\n): 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 = (\n element: AnimatableElement,\n): 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 = (\n element: AnimatableElement,\n): 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 = (\n delay: number,\n element: AnimatableElement,\n): 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 (\n segment.staggerOffsetMs !== undefined &&\n segment.staggerOffsetMs !== null\n ) {\n return delay + segment.staggerOffsetMs;\n }\n\n // Fallback to CSS variable if property not available\n let cssValue = (element as HTMLElement).style\n .getPropertyValue(\"--ef-stagger-offset\")\n .trim();\n\n if (!cssValue) {\n cssValue = window\n .getComputedStyle(element)\n .getPropertyValue(\"--ef-stagger-offset\")\n .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 = (\n duration: number,\n iterations: number,\n): 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 = (\n direction: string,\n currentIteration: number,\n): 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(\n elementTime,\n effectiveDelay,\n duration,\n direction,\n maxSafeTime,\n );\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 = (\n timing: AnimationTiming,\n maxSafeTime: number,\n): 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 (\n effect !== null &&\n effect instanceof KeyframeEffect &&\n effect.target !== null\n );\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 = (\n keyframes: Keyframe[],\n): \"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 =\n firstFrame && \"opacity\" in firstFrame ? Number(firstFrame.opacity) : null;\n const lastOpacity =\n 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 ||\n \"translate\" in frame ||\n \"scale\" in frame ||\n \"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 = (\n animation: Animation,\n timing: AnimationTiming,\n): void => {\n // Only validate in development mode\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV === \"production\"\n ) {\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 (\n (fadePattern === \"fade-in\" || hasTransform) &&\n fill !== \"backwards\" &&\n fill !== \"both\"\n ) {\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 (\n warnings.length > 0 &&\n typeof window !== \"undefined\" &&\n (window as any).__EDITFRAME_FILL_MODE_WARNINGS__\n ) {\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 by ensuring it's paused\n */\nconst prepareAnimation = (animation: Animation): void => {\n // Ensure animation is in a controllable state\n // Finished animations can't be controlled, so reset them\n if (animation.playState === \"finished\") {\n animation.cancel();\n // After cancel, animation is in idle state - we can set currentTime directly\n // No need to play/pause - we'll control it via currentTime\n } else if (animation.playState === \"running\") {\n // Pause running animations so we can control them manually\n animation.pause();\n }\n // For \"idle\" or \"paused\" state, we can set currentTime directly without play/pause\n // Setting currentTime on a paused animation will apply the keyframes\n // No initialization needed - we control everything via currentTime\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 // Ensure animation is paused before setting currentTime\n if (animation.playState === \"running\") {\n animation.pause();\n }\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 includes the delay, so set to elementTime\n // For CSS animations with delay = 0, currentTime is just animation progress, so set to 0\n if (timing.delay > 0) {\n animation.currentTime = elementTime;\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(\n timing,\n maxSafeTime,\n );\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: currentTime should be delay + completed animation time (absolute timeline time)\n animation.currentTime = effectiveDelay + 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(\n elementTime,\n timing,\n effectiveDelay,\n );\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 absolute timeline time\n const isAlternateWithDelay =\n (direction === \"alternate\" || direction === \"alternate-reverse\") &&\n effectiveDelay > 0;\n if (isAlternateWithDelay && currentIteration === 0) {\n // For alternate direction iteration 0 with delay, use elementTime directly\n animation.currentTime = elementTime;\n } else {\n // For other cases with delay, currentTime should be delay + animation time (absolute timeline time)\n animation.currentTime = effectiveDelay + 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 * Synchronizes a single animation with the timeline using the element as the time source.\n *\n * For animations in this element's subtree, always use this element as the time source.\n * This handles both animations directly on the temporal element and on its non-temporal children.\n */\nconst synchronizeAnimation = (\n animation: Animation,\n element: AnimatableElement,\n): void => {\n const effect = animation.effect;\n if (!validateAnimationEffect(effect)) {\n return;\n }\n\n const timing = extractAnimationTiming(effect);\n\n if (timing.duration <= 0) {\n animation.currentTime = 0;\n return;\n }\n\n // Validate fill-mode in development mode\n validateAnimationFillMode(animation, timing);\n\n // Find the containing timegroup for the animation target.\n // Temporal elements are always synced to timegroups, so animations should use\n // the timegroup's timeline as the time source.\n const target = effect.target;\n let timeSource: AnimatableElement = element;\n\n if (target && target instanceof HTMLElement) {\n // Find the nearest timegroup in the DOM tree\n const nearestTimegroup = target.closest(\"ef-timegroup\");\n if (nearestTimegroup && isEFTemporal(nearestTimegroup)) {\n timeSource = nearestTimegroup as AnimatableElement;\n }\n }\n\n // For stagger offset, we need to find the actual text segment element.\n // CSS animations might be on the segment itself or on a child element.\n // If the target is not a text segment, try to find the parent text segment.\n let staggerElement: AnimatableElement = timeSource;\n if (target && target instanceof HTMLElement) {\n // Check if target is a text segment\n const targetAsAnimatable = target as AnimatableElement;\n if (supportsStaggerOffset(targetAsAnimatable)) {\n staggerElement = targetAsAnimatable;\n } else {\n // Target might be a child element - find the parent text segment\n const parentSegment = target.closest(\"ef-text-segment\");\n if (\n parentSegment &&\n supportsStaggerOffset(parentSegment as AnimatableElement)\n ) {\n staggerElement = parentSegment as AnimatableElement;\n }\n }\n }\n\n const effectiveDelay = calculateEffectiveDelay(timing.delay, staggerElement);\n mapAndSetAnimationTime(animation, timeSource, timing, 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 } =\n discoverAndTrackAnimations(element, providedAnimations);\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 = (\n element: AnimatableElement,\n state: TemporalState,\n): 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 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// 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 = (\n element: AnimatableElement,\n): 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 allAnimations = element.getAnimations({ subtree: true });\n\n const rootContext = evaluateElementState(element);\n const timelineTimeMs = (element.rootTimegroup ?? element).currentTimeMs;\n const { elements: collectedElements, pruned } = deepGetTemporalElements(\n element,\n timelineTimeMs,\n );\n\n // For pruned elements (invisible containers whose subtrees were skipped),\n // just set display:none directly — no need to evaluate phase/state since\n // we already know they're outside their time range.\n for (const prunedElement of pruned) {\n prunedElement.style.setProperty(\"display\", \"none\");\n }\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>(\n visibleChildContexts.map((c) => c.element),\n );\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 =\n 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(\n rootContext.element,\n rootContext.state.phase,\n allAnimations,\n );\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"],"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;;;;;;;;AAS7C,MAAM,oBACJ,WACA,sBACY;AAEZ,KACE,UAAU,cAAc,UACxB,CAAC,kBAAkB,SAAS,UAAU,CAEtC,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,QAA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AnimatableElement","staggerElement: AnimatableElement","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 * 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 = (\n animation: Animation,\n currentAnimations: Animation[],\n): boolean => {\n // Check if animation has been cancelled\n if (\n animation.playState === \"idle\" &&\n !currentAnimations.includes(animation)\n ) {\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 =\n 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 =\n 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 =\n 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 * 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 =\n | \"before-start\"\n | \"active\"\n | \"at-end-boundary\"\n | \"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 =\n 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 = (\n phase: ElementPhase,\n element: AnimatableElement,\n): 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 = (\n _phase: ElementPhase,\n _element: AnimatableElement,\n): 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 = (\n element: AnimatableElement,\n): 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 = (\n element: AnimatableElement,\n): 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 = (\n element: AnimatableElement,\n): 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 = (\n delay: number,\n element: AnimatableElement,\n): 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 (\n segment.staggerOffsetMs !== undefined &&\n segment.staggerOffsetMs !== null\n ) {\n return delay + segment.staggerOffsetMs;\n }\n\n // Fallback to CSS variable if property not available\n let cssValue = (element as HTMLElement).style\n .getPropertyValue(\"--ef-stagger-offset\")\n .trim();\n\n if (!cssValue) {\n cssValue = window\n .getComputedStyle(element)\n .getPropertyValue(\"--ef-stagger-offset\")\n .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 = (\n duration: number,\n iterations: number,\n): 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 = (\n direction: string,\n currentIteration: number,\n): 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(\n elementTime,\n effectiveDelay,\n duration,\n direction,\n maxSafeTime,\n );\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 = (\n timing: AnimationTiming,\n maxSafeTime: number,\n): 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 (\n effect !== null &&\n effect instanceof KeyframeEffect &&\n effect.target !== null\n );\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 = (\n keyframes: Keyframe[],\n): \"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 =\n firstFrame && \"opacity\" in firstFrame ? Number(firstFrame.opacity) : null;\n const lastOpacity =\n 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 ||\n \"translate\" in frame ||\n \"scale\" in frame ||\n \"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 = (\n animation: Animation,\n timing: AnimationTiming,\n): void => {\n // Only validate in development mode\n if (\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV === \"production\"\n ) {\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 (\n (fadePattern === \"fade-in\" || hasTransform) &&\n fill !== \"backwards\" &&\n fill !== \"both\"\n ) {\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 (\n warnings.length > 0 &&\n typeof window !== \"undefined\" &&\n (window as any).__EDITFRAME_FILL_MODE_WARNINGS__\n ) {\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 by ensuring it's paused\n */\nconst prepareAnimation = (animation: Animation): void => {\n // Ensure animation is in a controllable state\n // Finished animations can't be controlled, so reset them\n if (animation.playState === \"finished\") {\n animation.cancel();\n // After cancel, animation is in idle state - we can set currentTime directly\n // No need to play/pause - we'll control it via currentTime\n } else if (animation.playState === \"running\") {\n // Pause running animations so we can control them manually\n animation.pause();\n }\n // For \"idle\" or \"paused\" state, we can set currentTime directly without play/pause\n // Setting currentTime on a paused animation will apply the keyframes\n // No initialization needed - we control everything via currentTime\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 // Ensure animation is paused before setting currentTime\n if (animation.playState === \"running\") {\n animation.pause();\n }\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 includes the delay, so set to elementTime\n // For CSS animations with delay = 0, currentTime is just animation progress, so set to 0\n if (timing.delay > 0) {\n animation.currentTime = elementTime;\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(\n timing,\n maxSafeTime,\n );\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: currentTime should be delay + completed animation time (absolute timeline time)\n animation.currentTime = effectiveDelay + 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(\n elementTime,\n timing,\n effectiveDelay,\n );\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 absolute timeline time\n const isAlternateWithDelay =\n (direction === \"alternate\" || direction === \"alternate-reverse\") &&\n effectiveDelay > 0;\n if (isAlternateWithDelay && currentIteration === 0) {\n // For alternate direction iteration 0 with delay, use elementTime directly\n animation.currentTime = elementTime;\n } else {\n // For other cases with delay, currentTime should be delay + animation time (absolute timeline time)\n animation.currentTime = effectiveDelay + 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 * Synchronizes a single animation with the timeline using the element as the time source.\n *\n * For animations in this element's subtree, always use this element as the time source.\n * This handles both animations directly on the temporal element and on its non-temporal children.\n */\nconst synchronizeAnimation = (\n animation: Animation,\n element: AnimatableElement,\n): void => {\n const effect = animation.effect;\n if (!validateAnimationEffect(effect)) {\n return;\n }\n\n const timing = extractAnimationTiming(effect);\n\n if (timing.duration <= 0) {\n animation.currentTime = 0;\n return;\n }\n\n // Validate fill-mode in development mode\n validateAnimationFillMode(animation, timing);\n\n // Find the containing timegroup for the animation target.\n // Temporal elements are always synced to timegroups, so animations should use\n // the timegroup's timeline as the time source.\n const target = effect.target;\n let timeSource: AnimatableElement = element;\n\n if (target && target instanceof HTMLElement) {\n // Find the nearest timegroup in the DOM tree\n const nearestTimegroup = target.closest(\"ef-timegroup\");\n if (nearestTimegroup && isEFTemporal(nearestTimegroup)) {\n timeSource = nearestTimegroup as AnimatableElement;\n }\n }\n\n // For stagger offset, we need to find the actual text segment element.\n // CSS animations might be on the segment itself or on a child element.\n // If the target is not a text segment, try to find the parent text segment.\n let staggerElement: AnimatableElement = timeSource;\n if (target && target instanceof HTMLElement) {\n // Check if target is a text segment\n const targetAsAnimatable = target as AnimatableElement;\n if (supportsStaggerOffset(targetAsAnimatable)) {\n staggerElement = targetAsAnimatable;\n } else {\n // Target might be a child element - find the parent text segment\n const parentSegment = target.closest(\"ef-text-segment\");\n if (\n parentSegment &&\n supportsStaggerOffset(parentSegment as AnimatableElement)\n ) {\n staggerElement = parentSegment as AnimatableElement;\n }\n }\n }\n\n const effectiveDelay = calculateEffectiveDelay(timing.delay, staggerElement);\n mapAndSetAnimationTime(animation, timeSource, timing, 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 } =\n discoverAndTrackAnimations(element, providedAnimations);\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 = (\n element: AnimatableElement,\n state: TemporalState,\n): 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 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 = (\n element: AnimatableElement,\n): 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 allAnimations = element.getAnimations({ subtree: true });\n\n const rootContext = evaluateElementState(element);\n const timelineTimeMs = (element.rootTimegroup ?? element).currentTimeMs;\n const { elements: collectedElements, pruned } = deepGetTemporalElements(\n element,\n timelineTimeMs,\n );\n\n // For pruned elements (invisible containers whose subtrees were skipped),\n // just set display:none directly — no need to evaluate phase/state since\n // we already know they're outside their time range.\n for (const prunedElement of pruned) {\n prunedElement.style.setProperty(\"display\", \"none\");\n }\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>(\n visibleChildContexts.map((c) => c.element),\n );\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 =\n 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(\n rootContext.element,\n rootContext.state.phase,\n allAnimations,\n );\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;;;;;;;;AAS7C,MAAM,oBACJ,WACA,sBACY;AAEZ,KACE,UAAU,cAAc,UACxB,CAAC,kBAAkB,SAAS,UAAU,CAEtC,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,oBACJ,sBAAsB,QAAQ,cAAc,EAAE,SAAS,MAAM,CAAC;AAIhE,qBAAoB,IAAI,SAAS,MAAM;AAGvC,oBAAmB,IAAI,SAAS,kBAAkB,OAAO;AAGzD,MAAK,MAAM,aAAa,mBAAmB;EACzC,MAAM,SAAS,UAAU;EACzB,MAAM,SACJ,UAAU,kBAAkB,iBAAiB,OAAO,SAAS;AAC/D,MAAI,UAAU,kBAAkB,SAAS;GACvC,IAAI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AAI,EAAE,CAC3C;AAIH,kBAAiB,YAAY,SAAS,YAAY,MAAM;AACxD,MAAK,MAAM,WAAW,cACpB,kBAAiB,QAAQ,SAAS,QAAQ,MAAM;AAIlD,0BAAyB,QAAQ;AACjC,0BAAyB,QAAQ"}
@@ -10,6 +10,7 @@ import { efConfigurationContext } from "./EFConfiguration.js";
10
10
  import { fetchContext } from "./fetchContext.js";
11
11
  import { focusContext } from "./focusContext.js";
12
12
  import { focusedElementContext } from "./focusedElementContext.js";
13
+ import { shouldSignUrl } from "./shouldSignUrl.js";
13
14
  import { ContextProvider, consume, createContext, provide } from "@lit/context";
14
15
  import { property, state } from "lit/decorators.js";
15
16
 
@@ -33,8 +34,7 @@ function ContextMixin(superClass) {
33
34
  init.headers ||= {};
34
35
  Object.assign(init.headers, { "Content-Type": "application/json" });
35
36
  }
36
- const isLocalEndpoint = url.startsWith("/@ef-");
37
- if (!EF_RENDERING() && this.signingURL && !isLocalEndpoint) {
37
+ if (!EF_RENDERING() && this.signingURL && shouldSignUrl(url, window.location.origin)) {
38
38
  const { cacheKey, signingPayload } = this.#getTokenCacheKey(url);
39
39
  const urlToken = await globalURLTokenDeduplicator.getToken(cacheKey, async () => {
40
40
  try {
@@ -52,7 +52,7 @@ function ContextMixin(superClass) {
52
52
  init.headers ||= {};
53
53
  Object.assign(init.headers, { authorization: `Bearer ${urlToken}` });
54
54
  } else {
55
- if (!this.#isCrossOrigin(url)) init.credentials = "include";
55
+ if (!shouldSignUrl(url, window.location.origin)) init.credentials = "include";
56
56
  if (this.#isEditframeDomain(url)) console.warn(`[Editframe] Request to ${new URL(url).hostname} has no signing URL configured. Ensure <ef-configuration signing-url="..."> is an ancestor of your <ef-preview> or <ef-workbench>.`);
57
57
  }
58
58
  try {
@@ -146,22 +146,6 @@ function ContextMixin(superClass) {
146
146
  break;
147
147
  }
148
148
  };
149
- /**
150
- * Generate a cache key for URL token based on signing strategy
151
- *
152
- * Uses unified prefix + parameter matching approach:
153
- * - For transcode URLs: signs base "/api/v1/transcode" + params like {url: "source.mp4"}
154
- * - For regular URLs: signs full URL with empty params {}
155
- * - All validation uses prefix matching + exhaustive parameter matching
156
- * - Multiple transcode segments with same source share one token (reduces round-trips)
157
- */
158
- #isCrossOrigin(url) {
159
- try {
160
- return new URL(url, window.location.origin).origin !== window.location.origin;
161
- } catch {
162
- return false;
163
- }
164
- }
165
149
  #isEditframeDomain(url) {
166
150
  try {
167
151
  const hostname = new URL(url).hostname;
@@ -1 +1 @@
1
- {"version":3,"file":"ContextMixin.js","names":["#getTokenCacheKey","#parseTokenExpiration","#isCrossOrigin","#isEditframeDomain","#apiHost","#targetTemporal","#subscribedController","#controllerSubscribed","#onControllerUpdate","#targetTemporalProvider","#loop","#playingProvider","#loopProvider","#currentTimeMsProvider","#signingURL","#collectUndefinedEFTags","#retryTemporalDiscovery","#timegroupObserver"],"sources":["../../src/gui/ContextMixin.ts"],"sourcesContent":["import { ContextProvider, consume, createContext, provide } from \"@lit/context\";\nimport type { LitElement } from \"lit\";\nimport { property, state } from \"lit/decorators.js\";\nimport { EF_RENDERING } from \"../EF_RENDERING.ts\";\nimport {\n isEFTemporal,\n type TemporalMixinInterface,\n} from \"../elements/EFTemporal.js\";\nimport { globalURLTokenDeduplicator } from \"../transcoding/cache/URLTokenDeduplicator.js\";\nimport { currentTimeContext } from \"./currentTimeContext.js\";\nimport { durationContext } from \"./durationContext.js\";\nimport {\n type EFConfiguration,\n efConfigurationContext,\n} from \"./EFConfiguration.ts\";\nimport { efContext } from \"./efContext.js\";\nimport { fetchContext } from \"./fetchContext.js\";\nimport { type FocusContext, focusContext } from \"./focusContext.js\";\nimport { focusedElementContext } from \"./focusedElementContext.js\";\nimport { loopContext, playingContext } from \"./playingContext.js\";\n\nexport const targetTemporalContext =\n createContext<TemporalMixinInterface | null>(Symbol(\"target-temporal\"));\n\nexport declare class ContextMixinInterface extends LitElement {\n signingURL?: string;\n apiHost?: string;\n rendering: boolean;\n playing: boolean;\n loop: boolean;\n currentTimeMs: number;\n focusedElement?: HTMLElement;\n targetTemporal: TemporalMixinInterface | null;\n play(): Promise<void>;\n pause(): void;\n}\n\nconst contextMixinSymbol = Symbol(\"contextMixin\");\n\nexport function isContextMixin(value: any): value is ContextMixinInterface {\n return (\n typeof value === \"object\" &&\n value !== null &&\n contextMixinSymbol in value.constructor\n );\n}\n\ntype Constructor<T = {}> = new (...args: any[]) => T;\nexport function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {\n class ContextElement extends superClass {\n static [contextMixinSymbol] = true;\n\n @consume({ context: efConfigurationContext, subscribe: true })\n efConfiguration: EFConfiguration | null = null;\n\n @provide({ context: focusContext })\n focusContext = this as FocusContext;\n\n @provide({ context: focusedElementContext })\n @state()\n focusedElement?: HTMLElement;\n\n #playingProvider!: ContextProvider<typeof playingContext>;\n #loopProvider!: ContextProvider<typeof loopContext>;\n #currentTimeMsProvider!: ContextProvider<typeof currentTimeContext>;\n #targetTemporalProvider!: ContextProvider<typeof targetTemporalContext>;\n\n #loop = false;\n\n #apiHost?: string;\n @property({ type: String, attribute: \"api-host\" })\n get apiHost() {\n return this.#apiHost ?? this.efConfiguration?.apiHost ?? \"\";\n }\n\n set apiHost(value: string) {\n this.#apiHost = value;\n }\n\n @provide({ context: efContext })\n efContext = this;\n\n #targetTemporal: TemporalMixinInterface | null = null;\n\n @state()\n get targetTemporal(): TemporalMixinInterface | null {\n return this.#targetTemporal;\n }\n #controllerSubscribed = false;\n\n /**\n * Find the first root temporal element (recursively searches through children)\n * Supports ef-timegroup, ef-video, ef-audio, and any other temporal elements\n * even when they're wrapped in non-temporal elements like divs\n */\n private findRootTemporal(): TemporalMixinInterface | null {\n const findRecursive = (\n element: Element,\n ): TemporalMixinInterface | null => {\n if (isEFTemporal(element)) {\n return element as TemporalMixinInterface & HTMLElement;\n }\n\n for (const child of element.children) {\n const found = findRecursive(child);\n if (found) return found;\n }\n\n return null;\n };\n\n for (const child of this.children) {\n const found = findRecursive(child);\n if (found) return found;\n }\n\n return null;\n }\n\n #subscribedController: any = null;\n\n set targetTemporal(value: TemporalMixinInterface | null) {\n if (\n this.#targetTemporal === value &&\n value?.playbackController === this.#subscribedController &&\n this.#controllerSubscribed\n )\n return;\n\n // Unsubscribe from old controller updates\n if (this.#subscribedController) {\n this.#subscribedController.removeListener(this.#onControllerUpdate);\n this.#controllerSubscribed = false;\n this.#subscribedController = null;\n }\n\n this.#targetTemporal = value;\n this.#targetTemporalProvider?.setValue(value);\n\n // Sync all provided contexts\n this.requestUpdate(\"targetTemporal\");\n this.requestUpdate(\"playing\");\n this.requestUpdate(\"loop\");\n this.requestUpdate(\"currentTimeMs\");\n\n // If the new targetTemporal has a playbackController, apply stored loop value immediately\n if (value?.playbackController && this.#loop) {\n value.playbackController.setLoop(this.#loop);\n }\n\n // If the new targetTemporal doesn't have a playbackController yet,\n // wait for it to complete its updates (it might be initializing)\n if (value && !value.playbackController) {\n // Wait for the temporal element to initialize\n (value as any).updateComplete?.then(() => {\n if (value === this.#targetTemporal && !this.#controllerSubscribed) {\n this.requestUpdate();\n }\n });\n }\n }\n\n #onControllerUpdate = (\n event: import(\"./PlaybackController.js\").PlaybackControllerUpdateEvent,\n ) => {\n switch (event.property) {\n case \"playing\":\n this.#playingProvider.setValue(event.value as boolean);\n break;\n case \"loop\":\n this.#loopProvider.setValue(event.value as boolean);\n break;\n case \"currentTimeMs\":\n this.#currentTimeMsProvider.setValue(event.value as number);\n break;\n }\n };\n\n // Add reactive properties that depend on the targetTemporal\n @provide({ context: durationContext })\n @property({ type: Number })\n durationMs = 0;\n\n @property({ type: Number })\n endTimeMs = 0;\n\n @provide({ context: fetchContext })\n fetch = async (url: string, init: RequestInit = {}) => {\n if (init.body) {\n init.headers ||= {};\n Object.assign(init.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // Check if this is a local @ef-* endpoint that doesn't need authentication\n // These endpoints are handled by the Vite plugin locally and don't require signing\n const isLocalEndpoint = url.startsWith(\"/@ef-\");\n\n if (!EF_RENDERING() && this.signingURL && !isLocalEndpoint) {\n const { cacheKey, signingPayload } = this.#getTokenCacheKey(url);\n\n // Use global token deduplicator to share tokens across all context providers\n const urlToken = await globalURLTokenDeduplicator.getToken(\n cacheKey,\n async () => {\n try {\n const response = await fetch(this.signingURL, {\n method: \"POST\",\n body: JSON.stringify(signingPayload),\n });\n\n if (response.ok) {\n const tokenData = await response.json();\n return tokenData.token;\n }\n throw new Error(\n `Failed to sign URL: ${url}. SigningURL: ${this.signingURL} ${response.status} ${response.statusText}`,\n );\n } catch (error) {\n console.error(\"ContextMixin urlToken fetch error\", url, error);\n throw error;\n }\n },\n (token: string) => this.#parseTokenExpiration(token),\n );\n\n init.headers ||= {};\n Object.assign(init.headers, {\n authorization: `Bearer ${urlToken}`,\n });\n } else {\n // Only include credentials for same-origin requests where session cookies\n // are relevant. For cross-origin requests without a signing URL, credentials\n // cause CORS failures when the server responds with Access-Control-Allow-Origin: *\n if (!this.#isCrossOrigin(url)) {\n init.credentials = \"include\";\n }\n\n if (this.#isEditframeDomain(url)) {\n console.warn(\n `[Editframe] Request to ${new URL(url).hostname} has no signing URL configured. ` +\n `Ensure <ef-configuration signing-url=\"...\"> is an ancestor of your <ef-preview> or <ef-workbench>.`,\n );\n }\n }\n\n try {\n const fetchPromise = fetch(url, init);\n // Wrap the promise to catch rejections and log the URL\n // Return the promise chain so errors are logged but still propagate\n return fetchPromise.catch((error) => {\n // For AbortErrors, re-throw directly without modification\n // DOMException properties like 'name' are read-only\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n\n console.error(\n \"ContextMixin fetch error\",\n url,\n error,\n window.location.href,\n );\n // Create a new error with the URL in the message, preserving the original error type\n const ErrorConstructor =\n error instanceof Error ? error.constructor : Error;\n const enhancedError = new (ErrorConstructor as typeof Error)(\n `Failed to fetch: ${url}. Original error: ${error instanceof Error ? error.message : String(error)}`,\n );\n // Preserve the original error's properties (except for DOMException which has read-only properties)\n if (error instanceof Error && !(error instanceof DOMException)) {\n enhancedError.name = error.name;\n enhancedError.stack = error.stack;\n // Copy any additional properties from the original error\n Object.assign(enhancedError, error);\n }\n throw enhancedError;\n });\n } catch (error) {\n console.error(\n \"ContextMixin fetch error (synchronous)\",\n url,\n error,\n window.location.href,\n );\n throw error;\n }\n };\n\n // Note: URL token caching is now handled globally via URLTokenDeduplicator\n // Keeping these for any potential backwards compatibility, but they're no longer used\n\n /**\n * Generate a cache key for URL token based on signing strategy\n *\n * Uses unified prefix + parameter matching approach:\n * - For transcode URLs: signs base \"/api/v1/transcode\" + params like {url: \"source.mp4\"}\n * - For regular URLs: signs full URL with empty params {}\n * - All validation uses prefix matching + exhaustive parameter matching\n * - Multiple transcode segments with same source share one token (reduces round-trips)\n */\n #isCrossOrigin(url: string): boolean {\n try {\n const targetUrl = new URL(url, window.location.origin);\n return targetUrl.origin !== window.location.origin;\n } catch {\n return false;\n }\n }\n\n #isEditframeDomain(url: string): boolean {\n try {\n const hostname = new URL(url).hostname;\n return (\n hostname === \"editframe.dev\" ||\n hostname === \"editframe.com\" ||\n hostname.endsWith(\".editframe.dev\") ||\n hostname.endsWith(\".editframe.com\")\n );\n } catch {\n return false;\n }\n }\n\n #getTokenCacheKey(url: string): {\n cacheKey: string;\n signingPayload: { url: string; params?: Record<string, string> };\n } {\n try {\n const urlObj = new URL(url);\n\n // Check if this is a transcode URL pattern\n if (urlObj.pathname.includes(\"/api/v1/transcode/\")) {\n const urlParam = urlObj.searchParams.get(\"url\");\n if (urlParam) {\n // For transcode URLs, sign the base path + url parameter\n const basePath = `${urlObj.origin}/api/v1/transcode`;\n const cacheKey = `${basePath}?url=${urlParam}`;\n return {\n cacheKey,\n signingPayload: { url: basePath, params: { url: urlParam } },\n };\n }\n }\n\n // For non-transcode URLs, use full URL (existing behavior)\n return {\n cacheKey: url,\n signingPayload: { url },\n };\n } catch {\n // If URL parsing fails, fall back to full URL\n return {\n cacheKey: url,\n signingPayload: { url },\n };\n }\n }\n\n /**\n * Parse JWT token to extract safe expiration time (with buffer)\n * @param token JWT token string\n * @returns Safe expiration timestamp in milliseconds (actual expiry minus buffer), or 0 if parsing fails\n */\n #parseTokenExpiration(token: string): number {\n try {\n // JWT has 3 parts separated by dots: header.payload.signature\n const parts = token.split(\".\");\n if (parts.length !== 3) return 0;\n\n // Decode the payload (second part)\n const payload = parts[1];\n if (!payload) return 0;\n\n const decoded = atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const parsed = JSON.parse(decoded);\n\n // Extract timestamps (in seconds)\n const exp = parsed.exp;\n const iat = parsed.iat;\n if (!exp) return 0;\n\n // Calculate token lifetime and buffer\n const lifetimeSeconds = iat ? exp - iat : 3600; // Default to 1 hour if no iat\n const tenPercentBufferMs = lifetimeSeconds * 0.1 * 1000; // 10% of lifetime in ms\n const fiveMinutesMs = 5 * 60 * 1000; // 5 minutes in ms\n\n // Use whichever buffer is smaller (more conservative)\n const bufferMs = Math.min(fiveMinutesMs, tenPercentBufferMs);\n\n // Return expiration time minus buffer\n return exp * 1000 - bufferMs;\n } catch {\n return 0;\n }\n }\n\n #signingURL?: string;\n /**\n * A URL that will be used to generated signed tokens for accessing media files from the\n * editframe API. This is used to authenticate media requests per-user.\n */\n @property({ type: String, attribute: \"signing-url\" })\n get signingURL() {\n return this.#signingURL ?? this.efConfiguration?.signingURL ?? \"\";\n }\n set signingURL(value: string) {\n this.#signingURL = value;\n }\n\n @property({ type: Boolean, reflect: true })\n get playing(): boolean {\n return this.targetTemporal?.playbackController?.playing ?? false;\n }\n set playing(value: boolean) {\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.setPlaying(value);\n }\n }\n\n @property({ type: Boolean, reflect: true, attribute: \"loop\" })\n get loop(): boolean {\n return this.targetTemporal?.playbackController?.loop ?? this.#loop;\n }\n set loop(value: boolean) {\n const oldValue = this.#loop;\n this.#loop = value;\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.setLoop(value);\n }\n this.requestUpdate(\"loop\", oldValue);\n }\n\n @property({ type: Boolean })\n rendering = false;\n\n @property({ type: Number })\n get currentTimeMs(): number {\n return (\n this.targetTemporal?.playbackController?.currentTimeMs ?? Number.NaN\n );\n }\n set currentTimeMs(value: number) {\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.setCurrentTimeMs(value);\n }\n }\n\n #timegroupObserver = new MutationObserver((mutations) => {\n let shouldUpdate = false;\n const undefinedEFTags = new Set<string>();\n\n for (const mutation of mutations) {\n if (mutation.type === \"childList\") {\n const newTemporal = this.findRootTemporal();\n if (newTemporal !== this.targetTemporal) {\n this.targetTemporal = newTemporal;\n shouldUpdate = true;\n } else if (\n mutation.target instanceof Element &&\n isEFTemporal(mutation.target)\n ) {\n // Handle childList changes within existing temporal elements\n shouldUpdate = true;\n }\n\n // Collect ef-* tags from added nodes that haven't upgraded yet.\n // When React hydrates or TimelineRoot renders, the custom element\n // may be inserted before its class is defined, so isEFTemporal()\n // returns false. We need to retry after the element upgrades.\n if (!this.targetTemporal) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n this.#collectUndefinedEFTags(node, undefinedEFTags);\n }\n }\n }\n } else if (mutation.type === \"attributes\") {\n // Watch for attribute changes that might affect duration\n const durationAffectingAttributes = [\n \"duration\",\n \"mode\",\n \"trimstart\",\n \"trimend\",\n \"sourcein\",\n \"sourceout\",\n ];\n\n if (\n durationAffectingAttributes.includes(\n mutation.attributeName || \"\",\n ) ||\n (mutation.target instanceof Element &&\n isEFTemporal(mutation.target))\n ) {\n shouldUpdate = true;\n }\n }\n }\n\n if (undefinedEFTags.size > 0) {\n this.#retryTemporalDiscovery(undefinedEFTags);\n }\n\n if (shouldUpdate) {\n // Trigger an update to ensure reactive properties recalculate\n // Use a microtask to ensure DOM updates are complete\n queueMicrotask(() => {\n // Recalculate duration and endTime when temporal element changes\n this.updateDurationProperties();\n this.requestUpdate();\n // Also ensure the targetTemporal updates its computed properties\n if (this.targetTemporal) {\n (this.targetTemporal as any).requestUpdate();\n }\n });\n }\n });\n\n /**\n * Recursively collect ef-* tag names from an element tree that\n * have not yet been registered as custom elements.\n */\n #collectUndefinedEFTags(el: Element, tags: Set<string>): void {\n const tag = el.tagName.toLowerCase();\n if (tag.startsWith(\"ef-\") && !customElements.get(tag)) {\n tags.add(tag);\n }\n for (const child of el.children) {\n this.#collectUndefinedEFTags(child, tags);\n }\n }\n\n /**\n * Wait for unregistered ef-* custom elements to upgrade, then\n * retry findRootTemporal(). Mirrors the whenDefined pattern in play().\n */\n async #retryTemporalDiscovery(tags: Set<string>): Promise<void> {\n await Promise.all(\n [...tags].map((tag) => customElements.whenDefined(tag).catch(() => {})),\n );\n\n if (this.targetTemporal) return; // already found by another path\n\n const found = this.findRootTemporal();\n if (found) {\n this.targetTemporal = found;\n await (found as any).updateComplete;\n this.updateDurationProperties();\n this.requestUpdate();\n }\n }\n\n /**\n * Update duration properties when temporal element changes\n */\n updateDurationProperties(): void {\n const newDuration = this.targetTemporal?.durationMs ?? 0;\n const newEndTime = this.targetTemporal?.endTimeMs ?? 0;\n\n if (this.durationMs !== newDuration) {\n this.durationMs = newDuration;\n }\n\n if (this.endTimeMs !== newEndTime) {\n this.endTimeMs = newEndTime;\n }\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n\n // Create manual context providers for playback state\n this.#playingProvider = new ContextProvider(this, {\n context: playingContext,\n initialValue: this.playing,\n });\n this.#loopProvider = new ContextProvider(this, {\n context: loopContext,\n initialValue: this.loop,\n });\n this.#currentTimeMsProvider = new ContextProvider(this, {\n context: currentTimeContext,\n initialValue: this.currentTimeMs,\n });\n this.#targetTemporalProvider = new ContextProvider(this, {\n context: targetTemporalContext,\n initialValue: this.targetTemporal,\n });\n\n // Initialize targetTemporal to first root temporal element\n this.targetTemporal = this.findRootTemporal();\n // Initialize duration properties\n this.updateDurationProperties();\n\n this.#timegroupObserver.observe(this, {\n childList: true,\n subtree: true,\n attributes: true,\n });\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#timegroupObserver.disconnect();\n\n // Unsubscribe from controller\n if (this.#subscribedController) {\n this.#subscribedController.removeListener(this.#onControllerUpdate);\n this.#controllerSubscribed = false;\n this.#subscribedController = null;\n }\n\n this.pause();\n }\n\n updated(changedProperties: Map<string | number | symbol, unknown>) {\n super.updated?.(changedProperties);\n\n // Subscribe to controller when it becomes available or changes\n const currentController = this.#targetTemporal?.playbackController;\n if (\n currentController &&\n (!this.#controllerSubscribed ||\n this.#subscribedController !== currentController)\n ) {\n // Unsubscribe from old controller if it changed\n if (\n this.#subscribedController &&\n this.#subscribedController !== currentController\n ) {\n this.#subscribedController.removeListener(this.#onControllerUpdate);\n }\n currentController.addListener(this.#onControllerUpdate);\n this.#controllerSubscribed = true;\n this.#subscribedController = currentController;\n\n // Apply stored loop value when playbackController becomes available\n if (this.#loop) {\n currentController.setLoop(this.#loop);\n }\n\n // Trigger initial sync of context providers\n this.#playingProvider.setValue(this.playing);\n this.#loopProvider.setValue(this.loop);\n this.#currentTimeMsProvider.setValue(this.currentTimeMs);\n }\n }\n\n async play() {\n // If targetTemporal is not set, try to find it now\n // This handles cases where the DOM may not have been fully ready during connectedCallback\n if (!this.targetTemporal) {\n // Wait for any temporal custom elements to be defined\n const potentialTemporalTags = Array.from(this.children)\n .map((el) => el.tagName.toLowerCase())\n .filter((tag) => tag.startsWith(\"ef-\"));\n\n await Promise.all(\n potentialTemporalTags.map((tag) =>\n customElements.whenDefined(tag).catch(() => {}),\n ),\n );\n\n const foundTemporal = this.findRootTemporal();\n if (foundTemporal) {\n this.targetTemporal = foundTemporal;\n // Wait for it to initialize\n await (foundTemporal as any).updateComplete;\n } else {\n console.warn(\"No temporal element found to play\");\n return;\n }\n }\n\n // If playbackController doesn't exist yet, wait for it\n if (!this.targetTemporal.playbackController) {\n await (this.targetTemporal as any).updateComplete;\n // After waiting, check again\n if (!this.targetTemporal.playbackController) {\n console.warn(\"PlaybackController not available for temporal element\");\n return;\n }\n }\n\n this.targetTemporal.playbackController.play();\n }\n\n pause() {\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.pause();\n }\n }\n }\n\n return ContextElement as Constructor<ContextMixinInterface> & T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,wBACX,cAA6C,OAAO,kBAAkB,CAAC;AAezE,MAAM,qBAAqB,OAAO,eAAe;AAEjD,SAAgB,eAAe,OAA4C;AACzE,QACE,OAAO,UAAU,YACjB,UAAU,QACV,sBAAsB,MAAM;;AAKhC,SAAgB,aAAgD,YAAe;CAC7E,MAAM,uBAAuB,WAAW;;;0BAII;uBAG3B;oBAwBH;qBAqGC;oBAGD;gBAGJ,OAAO,KAAa,OAAoB,EAAE,KAAK;AACrD,QAAI,KAAK,MAAM;AACb,UAAK,YAAY,EAAE;AACnB,YAAO,OAAO,KAAK,SAAS,EAC1B,gBAAgB,oBACjB,CAAC;;IAKJ,MAAM,kBAAkB,IAAI,WAAW,QAAQ;AAE/C,QAAI,CAAC,cAAc,IAAI,KAAK,cAAc,CAAC,iBAAiB;KAC1D,MAAM,EAAE,UAAU,mBAAmB,MAAKA,iBAAkB,IAAI;KAGhE,MAAM,WAAW,MAAM,2BAA2B,SAChD,UACA,YAAY;AACV,UAAI;OACF,MAAM,WAAW,MAAM,MAAM,KAAK,YAAY;QAC5C,QAAQ;QACR,MAAM,KAAK,UAAU,eAAe;QACrC,CAAC;AAEF,WAAI,SAAS,GAEX,SADkB,MAAM,SAAS,MAAM,EACtB;AAEnB,aAAM,IAAI,MACR,uBAAuB,IAAI,gBAAgB,KAAK,WAAW,GAAG,SAAS,OAAO,GAAG,SAAS,aAC3F;eACM,OAAO;AACd,eAAQ,MAAM,qCAAqC,KAAK,MAAM;AAC9D,aAAM;;SAGT,UAAkB,MAAKC,qBAAsB,MAAM,CACrD;AAED,UAAK,YAAY,EAAE;AACnB,YAAO,OAAO,KAAK,SAAS,EAC1B,eAAe,UAAU,YAC1B,CAAC;WACG;AAIL,SAAI,CAAC,MAAKC,cAAe,IAAI,CAC3B,MAAK,c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CAAC;aAGlC,QAAQ,EAAE,SAAS,uBAAuB,CAAC,EAC3C,OAAO;aAWP,SAAS;EAAE,MAAM;EAAQ,WAAW;EAAY,CAAC;aASjD,QAAQ,EAAE,SAAS,WAAW,CAAC;aAK/B,OAAO;aA+FP,QAAQ,EAAE,SAAS,iBAAiB,CAAC,EACrC,SAAS,EAAE,MAAM,QAAQ,CAAC;aAG1B,SAAS,EAAE,MAAM,QAAQ,CAAC;aAG1B,QAAQ,EAAE,SAAS,cAAc,CAAC;aAyNlC,SAAS;EAAE,MAAM;EAAQ,WAAW;EAAe,CAAC;aAQpD,SAAS;EAAE,MAAM;EAAS,SAAS;EAAM,CAAC;aAU1C,SAAS;EAAE,MAAM;EAAS,SAAS;EAAM,WAAW;EAAQ,CAAC;aAa7D,SAAS,EAAE,MAAM,SAAS,CAAC;aAG3B,SAAS,EAAE,MAAM,QAAQ,CAAC;AAmQ7B,QAAO"}
1
+ {"version":3,"file":"ContextMixin.js","names":["#getTokenCacheKey","#parseTokenExpiration","#isEditframeDomain","#apiHost","#targetTemporal","#subscribedController","#controllerSubscribed","#onControllerUpdate","#targetTemporalProvider","#loop","#playingProvider","#loopProvider","#currentTimeMsProvider","#signingURL","#collectUndefinedEFTags","#retryTemporalDiscovery","#timegroupObserver"],"sources":["../../src/gui/ContextMixin.ts"],"sourcesContent":["import { ContextProvider, consume, createContext, provide } from \"@lit/context\";\nimport type { LitElement } from \"lit\";\nimport { property, state } from \"lit/decorators.js\";\nimport { EF_RENDERING } from \"../EF_RENDERING.ts\";\nimport {\n isEFTemporal,\n type TemporalMixinInterface,\n} from \"../elements/EFTemporal.js\";\nimport { globalURLTokenDeduplicator } from \"../transcoding/cache/URLTokenDeduplicator.js\";\nimport { currentTimeContext } from \"./currentTimeContext.js\";\nimport { durationContext } from \"./durationContext.js\";\nimport {\n type EFConfiguration,\n efConfigurationContext,\n} from \"./EFConfiguration.ts\";\nimport { efContext } from \"./efContext.js\";\nimport { fetchContext } from \"./fetchContext.js\";\nimport { type FocusContext, focusContext } from \"./focusContext.js\";\nimport { focusedElementContext } from \"./focusedElementContext.js\";\nimport { loopContext, playingContext } from \"./playingContext.js\";\nimport { shouldSignUrl } from \"./shouldSignUrl.js\";\n\nexport const targetTemporalContext =\n createContext<TemporalMixinInterface | null>(Symbol(\"target-temporal\"));\n\nexport declare class ContextMixinInterface extends LitElement {\n signingURL?: string;\n apiHost?: string;\n rendering: boolean;\n playing: boolean;\n loop: boolean;\n currentTimeMs: number;\n focusedElement?: HTMLElement;\n targetTemporal: TemporalMixinInterface | null;\n play(): Promise<void>;\n pause(): void;\n}\n\nconst contextMixinSymbol = Symbol(\"contextMixin\");\n\nexport function isContextMixin(value: any): value is ContextMixinInterface {\n return (\n typeof value === \"object\" &&\n value !== null &&\n contextMixinSymbol in value.constructor\n );\n}\n\ntype Constructor<T = {}> = new (...args: any[]) => T;\nexport function ContextMixin<T extends Constructor<LitElement>>(superClass: T) {\n class ContextElement extends superClass {\n static [contextMixinSymbol] = true;\n\n @consume({ context: efConfigurationContext, subscribe: true })\n efConfiguration: EFConfiguration | null = null;\n\n @provide({ context: focusContext })\n focusContext = this as FocusContext;\n\n @provide({ context: focusedElementContext })\n @state()\n focusedElement?: HTMLElement;\n\n #playingProvider!: ContextProvider<typeof playingContext>;\n #loopProvider!: ContextProvider<typeof loopContext>;\n #currentTimeMsProvider!: ContextProvider<typeof currentTimeContext>;\n #targetTemporalProvider!: ContextProvider<typeof targetTemporalContext>;\n\n #loop = false;\n\n #apiHost?: string;\n @property({ type: String, attribute: \"api-host\" })\n get apiHost() {\n return this.#apiHost ?? this.efConfiguration?.apiHost ?? \"\";\n }\n\n set apiHost(value: string) {\n this.#apiHost = value;\n }\n\n @provide({ context: efContext })\n efContext = this;\n\n #targetTemporal: TemporalMixinInterface | null = null;\n\n @state()\n get targetTemporal(): TemporalMixinInterface | null {\n return this.#targetTemporal;\n }\n #controllerSubscribed = false;\n\n /**\n * Find the first root temporal element (recursively searches through children)\n * Supports ef-timegroup, ef-video, ef-audio, and any other temporal elements\n * even when they're wrapped in non-temporal elements like divs\n */\n private findRootTemporal(): TemporalMixinInterface | null {\n const findRecursive = (\n element: Element,\n ): TemporalMixinInterface | null => {\n if (isEFTemporal(element)) {\n return element as TemporalMixinInterface & HTMLElement;\n }\n\n for (const child of element.children) {\n const found = findRecursive(child);\n if (found) return found;\n }\n\n return null;\n };\n\n for (const child of this.children) {\n const found = findRecursive(child);\n if (found) return found;\n }\n\n return null;\n }\n\n #subscribedController: any = null;\n\n set targetTemporal(value: TemporalMixinInterface | null) {\n if (\n this.#targetTemporal === value &&\n value?.playbackController === this.#subscribedController &&\n this.#controllerSubscribed\n )\n return;\n\n // Unsubscribe from old controller updates\n if (this.#subscribedController) {\n this.#subscribedController.removeListener(this.#onControllerUpdate);\n this.#controllerSubscribed = false;\n this.#subscribedController = null;\n }\n\n this.#targetTemporal = value;\n this.#targetTemporalProvider?.setValue(value);\n\n // Sync all provided contexts\n this.requestUpdate(\"targetTemporal\");\n this.requestUpdate(\"playing\");\n this.requestUpdate(\"loop\");\n this.requestUpdate(\"currentTimeMs\");\n\n // If the new targetTemporal has a playbackController, apply stored loop value immediately\n if (value?.playbackController && this.#loop) {\n value.playbackController.setLoop(this.#loop);\n }\n\n // If the new targetTemporal doesn't have a playbackController yet,\n // wait for it to complete its updates (it might be initializing)\n if (value && !value.playbackController) {\n // Wait for the temporal element to initialize\n (value as any).updateComplete?.then(() => {\n if (value === this.#targetTemporal && !this.#controllerSubscribed) {\n this.requestUpdate();\n }\n });\n }\n }\n\n #onControllerUpdate = (\n event: import(\"./PlaybackController.js\").PlaybackControllerUpdateEvent,\n ) => {\n switch (event.property) {\n case \"playing\":\n this.#playingProvider.setValue(event.value as boolean);\n break;\n case \"loop\":\n this.#loopProvider.setValue(event.value as boolean);\n break;\n case \"currentTimeMs\":\n this.#currentTimeMsProvider.setValue(event.value as number);\n break;\n }\n };\n\n // Add reactive properties that depend on the targetTemporal\n @provide({ context: durationContext })\n @property({ type: Number })\n durationMs = 0;\n\n @property({ type: Number })\n endTimeMs = 0;\n\n @provide({ context: fetchContext })\n fetch = async (url: string, init: RequestInit = {}) => {\n if (init.body) {\n init.headers ||= {};\n Object.assign(init.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n if (\n !EF_RENDERING() &&\n this.signingURL &&\n shouldSignUrl(url, window.location.origin)\n ) {\n const { cacheKey, signingPayload } = this.#getTokenCacheKey(url);\n\n // Use global token deduplicator to share tokens across all context providers\n const urlToken = await globalURLTokenDeduplicator.getToken(\n cacheKey,\n async () => {\n try {\n const response = await fetch(this.signingURL, {\n method: \"POST\",\n body: JSON.stringify(signingPayload),\n });\n\n if (response.ok) {\n const tokenData = await response.json();\n return tokenData.token;\n }\n throw new Error(\n `Failed to sign URL: ${url}. SigningURL: ${this.signingURL} ${response.status} ${response.statusText}`,\n );\n } catch (error) {\n console.error(\"ContextMixin urlToken fetch error\", url, error);\n throw error;\n }\n },\n (token: string) => this.#parseTokenExpiration(token),\n );\n\n init.headers ||= {};\n Object.assign(init.headers, {\n authorization: `Bearer ${urlToken}`,\n });\n } else {\n // Only include credentials for same-origin requests where session cookies\n // are relevant. For cross-origin requests without a signing URL, credentials\n // cause CORS failures when the server responds with Access-Control-Allow-Origin: *\n if (!shouldSignUrl(url, window.location.origin)) {\n init.credentials = \"include\";\n }\n\n if (this.#isEditframeDomain(url)) {\n console.warn(\n `[Editframe] Request to ${new URL(url).hostname} has no signing URL configured. ` +\n `Ensure <ef-configuration signing-url=\"...\"> is an ancestor of your <ef-preview> or <ef-workbench>.`,\n );\n }\n }\n\n try {\n const fetchPromise = fetch(url, init);\n // Wrap the promise to catch rejections and log the URL\n // Return the promise chain so errors are logged but still propagate\n return fetchPromise.catch((error) => {\n // For AbortErrors, re-throw directly without modification\n // DOMException properties like 'name' are read-only\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n\n console.error(\n \"ContextMixin fetch error\",\n url,\n error,\n window.location.href,\n );\n // Create a new error with the URL in the message, preserving the original error type\n const ErrorConstructor =\n error instanceof Error ? error.constructor : Error;\n const enhancedError = new (ErrorConstructor as typeof Error)(\n `Failed to fetch: ${url}. Original error: ${error instanceof Error ? error.message : String(error)}`,\n );\n // Preserve the original error's properties (except for DOMException which has read-only properties)\n if (error instanceof Error && !(error instanceof DOMException)) {\n enhancedError.name = error.name;\n enhancedError.stack = error.stack;\n // Copy any additional properties from the original error\n Object.assign(enhancedError, error);\n }\n throw enhancedError;\n });\n } catch (error) {\n console.error(\n \"ContextMixin fetch error (synchronous)\",\n url,\n error,\n window.location.href,\n );\n throw error;\n }\n };\n\n #isEditframeDomain(url: string): boolean {\n try {\n const hostname = new URL(url).hostname;\n return (\n hostname === \"editframe.dev\" ||\n hostname === \"editframe.com\" ||\n hostname.endsWith(\".editframe.dev\") ||\n hostname.endsWith(\".editframe.com\")\n );\n } catch {\n return false;\n }\n }\n\n #getTokenCacheKey(url: string): {\n cacheKey: string;\n signingPayload: { url: string; params?: Record<string, string> };\n } {\n try {\n const urlObj = new URL(url);\n\n // Check if this is a transcode URL pattern\n if (urlObj.pathname.includes(\"/api/v1/transcode/\")) {\n const urlParam = urlObj.searchParams.get(\"url\");\n if (urlParam) {\n // For transcode URLs, sign the base path + url parameter\n const basePath = `${urlObj.origin}/api/v1/transcode`;\n const cacheKey = `${basePath}?url=${urlParam}`;\n return {\n cacheKey,\n signingPayload: { url: basePath, params: { url: urlParam } },\n };\n }\n }\n\n // For non-transcode URLs, use full URL (existing behavior)\n return {\n cacheKey: url,\n signingPayload: { url },\n };\n } catch {\n // If URL parsing fails, fall back to full URL\n return {\n cacheKey: url,\n signingPayload: { url },\n };\n }\n }\n\n /**\n * Parse JWT token to extract safe expiration time (with buffer)\n * @param token JWT token string\n * @returns Safe expiration timestamp in milliseconds (actual expiry minus buffer), or 0 if parsing fails\n */\n #parseTokenExpiration(token: string): number {\n try {\n // JWT has 3 parts separated by dots: header.payload.signature\n const parts = token.split(\".\");\n if (parts.length !== 3) return 0;\n\n // Decode the payload (second part)\n const payload = parts[1];\n if (!payload) return 0;\n\n const decoded = atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const parsed = JSON.parse(decoded);\n\n // Extract timestamps (in seconds)\n const exp = parsed.exp;\n const iat = parsed.iat;\n if (!exp) return 0;\n\n // Calculate token lifetime and buffer\n const lifetimeSeconds = iat ? exp - iat : 3600; // Default to 1 hour if no iat\n const tenPercentBufferMs = lifetimeSeconds * 0.1 * 1000; // 10% of lifetime in ms\n const fiveMinutesMs = 5 * 60 * 1000; // 5 minutes in ms\n\n // Use whichever buffer is smaller (more conservative)\n const bufferMs = Math.min(fiveMinutesMs, tenPercentBufferMs);\n\n // Return expiration time minus buffer\n return exp * 1000 - bufferMs;\n } catch {\n return 0;\n }\n }\n\n #signingURL?: string;\n /**\n * A URL that will be used to generated signed tokens for accessing media files from the\n * editframe API. This is used to authenticate media requests per-user.\n */\n @property({ type: String, attribute: \"signing-url\" })\n get signingURL() {\n return this.#signingURL ?? this.efConfiguration?.signingURL ?? \"\";\n }\n set signingURL(value: string) {\n this.#signingURL = value;\n }\n\n @property({ type: Boolean, reflect: true })\n get playing(): boolean {\n return this.targetTemporal?.playbackController?.playing ?? false;\n }\n set playing(value: boolean) {\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.setPlaying(value);\n }\n }\n\n @property({ type: Boolean, reflect: true, attribute: \"loop\" })\n get loop(): boolean {\n return this.targetTemporal?.playbackController?.loop ?? this.#loop;\n }\n set loop(value: boolean) {\n const oldValue = this.#loop;\n this.#loop = value;\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.setLoop(value);\n }\n this.requestUpdate(\"loop\", oldValue);\n }\n\n @property({ type: Boolean })\n rendering = false;\n\n @property({ type: Number })\n get currentTimeMs(): number {\n return (\n this.targetTemporal?.playbackController?.currentTimeMs ?? Number.NaN\n );\n }\n set currentTimeMs(value: number) {\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.setCurrentTimeMs(value);\n }\n }\n\n #timegroupObserver = new MutationObserver((mutations) => {\n let shouldUpdate = false;\n const undefinedEFTags = new Set<string>();\n\n for (const mutation of mutations) {\n if (mutation.type === \"childList\") {\n const newTemporal = this.findRootTemporal();\n if (newTemporal !== this.targetTemporal) {\n this.targetTemporal = newTemporal;\n shouldUpdate = true;\n } else if (\n mutation.target instanceof Element &&\n isEFTemporal(mutation.target)\n ) {\n // Handle childList changes within existing temporal elements\n shouldUpdate = true;\n }\n\n // Collect ef-* tags from added nodes that haven't upgraded yet.\n // When React hydrates or TimelineRoot renders, the custom element\n // may be inserted before its class is defined, so isEFTemporal()\n // returns false. We need to retry after the element upgrades.\n if (!this.targetTemporal) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n this.#collectUndefinedEFTags(node, undefinedEFTags);\n }\n }\n }\n } else if (mutation.type === \"attributes\") {\n // Watch for attribute changes that might affect duration\n const durationAffectingAttributes = [\n \"duration\",\n \"mode\",\n \"trimstart\",\n \"trimend\",\n \"sourcein\",\n \"sourceout\",\n ];\n\n if (\n durationAffectingAttributes.includes(\n mutation.attributeName || \"\",\n ) ||\n (mutation.target instanceof Element &&\n isEFTemporal(mutation.target))\n ) {\n shouldUpdate = true;\n }\n }\n }\n\n if (undefinedEFTags.size > 0) {\n this.#retryTemporalDiscovery(undefinedEFTags);\n }\n\n if (shouldUpdate) {\n // Trigger an update to ensure reactive properties recalculate\n // Use a microtask to ensure DOM updates are complete\n queueMicrotask(() => {\n // Recalculate duration and endTime when temporal element changes\n this.updateDurationProperties();\n this.requestUpdate();\n // Also ensure the targetTemporal updates its computed properties\n if (this.targetTemporal) {\n (this.targetTemporal as any).requestUpdate();\n }\n });\n }\n });\n\n /**\n * Recursively collect ef-* tag names from an element tree that\n * have not yet been registered as custom elements.\n */\n #collectUndefinedEFTags(el: Element, tags: Set<string>): void {\n const tag = el.tagName.toLowerCase();\n if (tag.startsWith(\"ef-\") && !customElements.get(tag)) {\n tags.add(tag);\n }\n for (const child of el.children) {\n this.#collectUndefinedEFTags(child, tags);\n }\n }\n\n /**\n * Wait for unregistered ef-* custom elements to upgrade, then\n * retry findRootTemporal(). Mirrors the whenDefined pattern in play().\n */\n async #retryTemporalDiscovery(tags: Set<string>): Promise<void> {\n await Promise.all(\n [...tags].map((tag) => customElements.whenDefined(tag).catch(() => {})),\n );\n\n if (this.targetTemporal) return; // already found by another path\n\n const found = this.findRootTemporal();\n if (found) {\n this.targetTemporal = found;\n await (found as any).updateComplete;\n this.updateDurationProperties();\n this.requestUpdate();\n }\n }\n\n /**\n * Update duration properties when temporal element changes\n */\n updateDurationProperties(): void {\n const newDuration = this.targetTemporal?.durationMs ?? 0;\n const newEndTime = this.targetTemporal?.endTimeMs ?? 0;\n\n if (this.durationMs !== newDuration) {\n this.durationMs = newDuration;\n }\n\n if (this.endTimeMs !== newEndTime) {\n this.endTimeMs = newEndTime;\n }\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n\n // Create manual context providers for playback state\n this.#playingProvider = new ContextProvider(this, {\n context: playingContext,\n initialValue: this.playing,\n });\n this.#loopProvider = new ContextProvider(this, {\n context: loopContext,\n initialValue: this.loop,\n });\n this.#currentTimeMsProvider = new ContextProvider(this, {\n context: currentTimeContext,\n initialValue: this.currentTimeMs,\n });\n this.#targetTemporalProvider = new ContextProvider(this, {\n context: targetTemporalContext,\n initialValue: this.targetTemporal,\n });\n\n // Initialize targetTemporal to first root temporal element\n this.targetTemporal = this.findRootTemporal();\n // Initialize duration properties\n this.updateDurationProperties();\n\n this.#timegroupObserver.observe(this, {\n childList: true,\n subtree: true,\n attributes: true,\n });\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#timegroupObserver.disconnect();\n\n // Unsubscribe from controller\n if (this.#subscribedController) {\n this.#subscribedController.removeListener(this.#onControllerUpdate);\n this.#controllerSubscribed = false;\n this.#subscribedController = null;\n }\n\n this.pause();\n }\n\n updated(changedProperties: Map<string | number | symbol, unknown>) {\n super.updated?.(changedProperties);\n\n // Subscribe to controller when it becomes available or changes\n const currentController = this.#targetTemporal?.playbackController;\n if (\n currentController &&\n (!this.#controllerSubscribed ||\n this.#subscribedController !== currentController)\n ) {\n // Unsubscribe from old controller if it changed\n if (\n this.#subscribedController &&\n this.#subscribedController !== currentController\n ) {\n this.#subscribedController.removeListener(this.#onControllerUpdate);\n }\n currentController.addListener(this.#onControllerUpdate);\n this.#controllerSubscribed = true;\n this.#subscribedController = currentController;\n\n // Apply stored loop value when playbackController becomes available\n if (this.#loop) {\n currentController.setLoop(this.#loop);\n }\n\n // Trigger initial sync of context providers\n this.#playingProvider.setValue(this.playing);\n this.#loopProvider.setValue(this.loop);\n this.#currentTimeMsProvider.setValue(this.currentTimeMs);\n }\n }\n\n async play() {\n // If targetTemporal is not set, try to find it now\n // This handles cases where the DOM may not have been fully ready during connectedCallback\n if (!this.targetTemporal) {\n // Wait for any temporal custom elements to be defined\n const potentialTemporalTags = Array.from(this.children)\n .map((el) => el.tagName.toLowerCase())\n .filter((tag) => tag.startsWith(\"ef-\"));\n\n await Promise.all(\n potentialTemporalTags.map((tag) =>\n customElements.whenDefined(tag).catch(() => {}),\n ),\n );\n\n const foundTemporal = this.findRootTemporal();\n if (foundTemporal) {\n this.targetTemporal = foundTemporal;\n // Wait for it to initialize\n await (foundTemporal as any).updateComplete;\n } else {\n console.warn(\"No temporal element found to play\");\n return;\n }\n }\n\n // If playbackController doesn't exist yet, wait for it\n if (!this.targetTemporal.playbackController) {\n await (this.targetTemporal as any).updateComplete;\n // After waiting, check again\n if (!this.targetTemporal.playbackController) {\n console.warn(\"PlaybackController not available for temporal element\");\n return;\n }\n }\n\n this.targetTemporal.playbackController.play();\n }\n\n pause() {\n if (this.targetTemporal?.playbackController) {\n this.targetTemporal.playbackController.pause();\n }\n }\n }\n\n return ContextElement as Constructor<ContextMixinInterface> & T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAa,wBACX,cAA6C,OAAO,kBAAkB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AAc,CAAC;aAoMlC,SAAS;EAAE,MAAM;EAAQ,WAAW;EAAe,CAAC;aAQpD,SAAS;EAAE,MAAM;EAAS,SAAS;EAAM,CAAC;aAU1C,SAAS;EAAE,MAAM;EAAS,SAAS;EAAM,WAAW;EAAQ,CAAC;aAa7D,SAAS,EAAE,MAAM,SAAS,CAAC;aAG3B,SAAS,EAAE,MAAM,QAAQ,CAAC;AAmQ7B,QAAO"}
@@ -1,6 +1,6 @@
1
- import * as lit33 from "lit";
1
+ import * as lit32 from "lit";
2
2
  import { LitElement } from "lit";
3
- import * as lit_html31 from "lit-html";
3
+ import * as lit_html30 from "lit-html";
4
4
 
5
5
  //#region src/gui/EFOverlayItem.d.ts
6
6
  /**
@@ -23,7 +23,7 @@ interface OverlayItemPosition {
23
23
  * ensures transforms are applied before positions are read.
24
24
  */
25
25
  declare class EFOverlayItem extends LitElement {
26
- static styles: lit33.CSSResult[];
26
+ static styles: lit32.CSSResult[];
27
27
  elementId?: string;
28
28
  target?: HTMLElement | string;
29
29
  private currentPosition;
@@ -36,7 +36,7 @@ declare class EFOverlayItem extends LitElement {
36
36
  updatePosition(): void;
37
37
  connectedCallback(): void;
38
38
  disconnectedCallback(): void;
39
- render(): lit_html31.TemplateResult<1>;
39
+ render(): lit_html30.TemplateResult<1>;
40
40
  }
41
41
  declare global {
42
42
  interface HTMLElementTagNameMap {