@editframe/elements 0.42.0 → 0.42.1

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.
@@ -176,15 +176,12 @@ let EFText = class EFText$1 extends EFTemporal(LitElement) {
176
176
  if (fingerprint === this.#lastPropagatedAnimation) return;
177
177
  this.#lastPropagatedAnimation = fingerprint;
178
178
  const hasAnimation = animationName && animationName !== "none";
179
- const isLineMode = this.split === "line";
180
- for (const segment of segments) if (hasAnimation) {
181
- const isWhitespace = /^\s+$/.test(segment.segmentText || "");
182
- if (!isLineMode && !isWhitespace) segment.setAttribute("data-animated", "");
183
- for (const prop of animationPropsToPropagate) segment.style.setProperty(prop, computed.getPropertyValue(prop));
184
- } else {
185
- segment.removeAttribute("data-animated");
186
- for (const prop of animationPropsToPropagate) segment.style.removeProperty(prop);
179
+ for (const segment of segments) if (hasAnimation) for (const prop of animationPropsToPropagate) {
180
+ let value = computed.getPropertyValue(prop);
181
+ if (prop === "animation-fill-mode" && value === "none") value = "backwards";
182
+ segment.style.setProperty(prop, value);
187
183
  }
184
+ else for (const prop of animationPropsToPropagate) segment.style.removeProperty(prop);
188
185
  }
189
186
  getTextContent() {
190
187
  let text = "";
@@ -264,6 +261,7 @@ let EFText = class EFText$1 extends EFTemporal(LitElement) {
264
261
  segment.segmentEndMs = durationMs;
265
262
  segment.staggerOffsetMs = staggerOffset ?? 0;
266
263
  if (this.split === "line") segment.setAttribute("data-line-segment", "true");
264
+ if (/^\s+$/.test(segmentText)) segment.setAttribute("data-whitespace", "");
267
265
  segment.setAttribute("data-segment-created", "true");
268
266
  if (this.split === "char" && wordBoundaries) {
269
267
  const originalCharIndex = textStartOffset + charIndex;
@@ -296,6 +294,7 @@ let EFText = class EFText$1 extends EFTemporal(LitElement) {
296
294
  segment.segmentEndMs = durationMs;
297
295
  segment.staggerOffsetMs = staggerOffset ?? 0;
298
296
  if (this.split === "line") segment.setAttribute("data-line-segment", "true");
297
+ if (/^\s+$/.test(segmentText)) segment.setAttribute("data-whitespace", "");
299
298
  segment.setAttribute("data-segment-created", "true");
300
299
  if (this.split === "char" && wordBoundaries) {
301
300
  const originalCharIndex = textStartOffset + charIndex;
@@ -335,6 +334,10 @@ let EFText = class EFText$1 extends EFTemporal(LitElement) {
335
334
  if (templateToPreserve) this.appendChild(templateToPreserve);
336
335
  this.#lastPropagatedAnimation = "";
337
336
  this.propagateAnimationToSegments();
337
+ if (useTemplate) for (const segment of this.segments) {
338
+ const computedFill = window.getComputedStyle(segment).getPropertyValue("animation-fill-mode");
339
+ if (computedFill === "none" || computedFill === "") segment.style.setProperty("animation-fill-mode", "backwards");
340
+ }
338
341
  const segmentElements = this.segments;
339
342
  Promise.all(segmentElements.map((seg) => seg.updateComplete)).then(() => {
340
343
  updateAnimations(this.rootTimegroup || this);
@@ -1 +1 @@
1
- {"version":3,"file":"EFText.js","names":["EFText","textNodes: ChildNode[]","#segmentsInitialized","segments","#lastPropagatedAnimation","wordBoundaries: Map<number, number> | null","currentWordIndex: number | null","currentWordSpan: HTMLSpanElement | null","staggerOffset: number | undefined","wordIndexForStagger: number","result: string[]"],"sources":["../../src/elements/EFText.ts"],"sourcesContent":["import { css, html, LitElement, type PropertyValueMap } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { durationConverter } from \"./durationConverter.js\";\nimport { EFTemporal } from \"./EFTemporal.js\";\n\nimport { evaluateEasing } from \"./easingUtils.js\";\nimport type { EFTextSegment } from \"./EFTextSegment.js\";\nimport { updateAnimations } from \"./updateAnimations.js\";\nimport type { AnimatableElement } from \"./updateAnimations.js\";\n\nexport type SplitMode = \"line\" | \"word\" | \"char\";\n\n// Animation properties to propagate from ef-text to its segments.\n// animation-delay is intentionally excluded -- the stagger system manages delay per segment.\nconst animationPropsToPropagate = [\n \"animation-name\",\n \"animation-duration\",\n \"animation-timing-function\",\n \"animation-fill-mode\",\n \"animation-iteration-count\",\n \"animation-direction\",\n] as const;\n\n@customElement(\"ef-text\")\nexport class EFText extends EFTemporal(LitElement) {\n static styles = [\n css`\n :host {\n display: inline;\n }\n :host([split=\"line\"]) {\n display: inline-block;\n }\n `,\n ];\n\n @property({ type: String, reflect: true })\n split: SplitMode = \"word\";\n\n private validateSplit(value: string): SplitMode {\n if (value === \"line\" || value === \"word\" || value === \"char\") {\n return value as SplitMode;\n }\n console.warn(\n `Invalid split value \"${value}\". Must be \"line\", \"word\", or \"char\". Defaulting to \"word\".`,\n );\n return \"word\";\n }\n\n @property({\n type: Number,\n attribute: \"stagger\",\n converter: durationConverter,\n })\n staggerMs?: number;\n\n private validateStagger(value: number | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (value < 0) {\n console.warn(`Invalid stagger value ${value}ms. Must be >= 0. Using 0.`);\n return 0;\n }\n return value;\n }\n\n @property({ type: String, reflect: true })\n easing = \"linear\";\n\n private mutationObserver?: MutationObserver;\n private animationObserver?: MutationObserver;\n private lastTextContent = \"\";\n private _textContent: string | null = null; // null means not initialized, \"\" means explicitly empty\n private _templateElement: HTMLTemplateElement | null = null;\n private _segmentsReadyResolvers: Array<() => void> = [];\n #segmentsInitialized = false;\n #lastPropagatedAnimation = \"\";\n\n render() {\n return html`<slot></slot>`;\n }\n\n // Store text content so we can use it even after DOM is cleared\n set textContent(value: string | null) {\n const newValue = value || \"\";\n // Only update if value actually changed\n if (this._textContent !== newValue) {\n this._textContent = newValue;\n\n // Find template element if not already stored\n if (!this._templateElement && this.isConnected) {\n this._templateElement = this.querySelector(\"template\");\n }\n\n // Clear any existing text nodes\n const textNodes: ChildNode[] = [];\n for (const node of Array.from(this.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n textNodes.push(node as ChildNode);\n }\n }\n for (const node of textNodes) {\n node.remove();\n }\n // Add new text node if value is not empty\n if (newValue) {\n const textNode = document.createTextNode(newValue);\n this.appendChild(textNode);\n }\n if (this.isConnected) {\n this.emitContentChange(\"content\");\n this.splitText();\n }\n }\n }\n\n get textContent(): string {\n // If _textContent is null, it hasn't been initialized - read from DOM\n if (this._textContent === null) {\n return this.getTextContent();\n }\n // Otherwise use stored value (even if empty string)\n return this._textContent;\n }\n\n /**\n * Get all ef-text-segment elements directly\n * @public\n */\n get segments(): EFTextSegment[] {\n return Array.from(\n this.querySelectorAll(\"ef-text-segment[data-segment-created]\"),\n ) as EFTextSegment[];\n }\n\n /**\n * Returns a promise that resolves when segments are ready (created and connected)\n * Use this to wait for segments after setting textContent or other properties\n * @public\n */\n async whenSegmentsReady(): Promise<EFTextSegment[]> {\n // Wait for text element to be updated first\n await this.updateComplete;\n\n // If no text content, segments will be empty - return immediately\n // Use same logic as splitText to read text content\n const text =\n this._textContent !== null ? this._textContent : this.getTextContent();\n if (!text || text.trim().length === 0) {\n return [];\n }\n\n // If segments already initialized and exist, return immediately (no RAF waits)\n if (this.#segmentsInitialized && this.segments.length > 0) {\n await Promise.all(this.segments.map((seg) => seg.updateComplete));\n return this.segments;\n }\n\n // Check if segments are already in DOM (synchronous check - no RAF)\n let segments = this.segments;\n if (segments.length > 0) {\n // Segments exist, just wait for their Lit updates (no RAF)\n await Promise.all(segments.map((seg) => seg.updateComplete));\n this.#segmentsInitialized = true;\n return segments;\n }\n\n // Segments don't exist yet - use the promise-based mechanism (no RAF polling)\n // This waits for splitText() to complete and resolve the promise\n return new Promise<EFTextSegment[]>((resolve, reject) => {\n const timeout = setTimeout(() => {\n // Remove our resolver if we timeout\n const index = this._segmentsReadyResolvers.indexOf(resolveWithSegments);\n if (index > -1) {\n this._segmentsReadyResolvers.splice(index, 1);\n }\n reject(new Error(\"Timeout waiting for text segments to be created\"));\n }, 5000); // 5 second timeout\n\n const resolveWithSegments = () => {\n clearTimeout(timeout);\n // Wait for segment Lit updates\n const segments = this.segments;\n Promise.all(segments.map((seg) => seg.updateComplete)).then(() => {\n this.#segmentsInitialized = true;\n resolve(segments);\n });\n };\n\n this._segmentsReadyResolvers.push(resolveWithSegments);\n\n // Trigger splitText if it hasn't run yet\n // This handles the case where segments haven't been created at all\n if (segments.length === 0 && this.isConnected) {\n this.splitText();\n }\n });\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Find and store template element before any modifications\n this._templateElement = this.querySelector(\"template\");\n\n // Initialize _textContent from DOM if not already set (for declarative usage)\n if (this._textContent === null) {\n this._textContent = this.getTextContent();\n this.lastTextContent = this._textContent;\n }\n\n // Use RAF to ensure DOM is fully ready before splitting text\n // Callers that need segments immediately (e.g., render clones) should await whenSegmentsReady()\n requestAnimationFrame(() => {\n this.setupMutationObserver();\n this.setupAnimationObserver();\n this.splitText();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.mutationObserver?.disconnect();\n this.animationObserver?.disconnect();\n }\n\n protected updated(\n changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>,\n ): void {\n if (\n changedProperties.has(\"split\") ||\n changedProperties.has(\"staggerMs\") ||\n changedProperties.has(\"easing\") ||\n changedProperties.has(\"durationMs\")\n ) {\n this.emitContentChange(\"content\");\n this.splitText();\n }\n }\n\n private setupMutationObserver() {\n this.mutationObserver = new MutationObserver(() => {\n // Only react to changes that aren't from our own segment creation\n const currentText = this._textContent || this.getTextContent();\n if (currentText !== this.lastTextContent) {\n this._textContent = currentText;\n this.lastTextContent = currentText;\n this.splitText();\n }\n });\n\n this.mutationObserver.observe(this, {\n childList: true,\n characterData: true,\n subtree: true,\n });\n }\n\n private setupAnimationObserver() {\n this.animationObserver = new MutationObserver(() => {\n this.propagateAnimationToSegments();\n });\n\n this.animationObserver.observe(this, {\n attributes: true,\n attributeFilter: [\"class\", \"style\"],\n });\n }\n\n private propagateAnimationToSegments() {\n const segments = this.segments;\n if (segments.length === 0) return;\n\n const computed = window.getComputedStyle(this);\n const animationName = computed.animationName;\n\n // Build a fingerprint to avoid redundant work\n const fingerprint = animationPropsToPropagate\n .map((prop) => computed.getPropertyValue(prop))\n .join(\"|\");\n\n if (fingerprint === this.#lastPropagatedAnimation) return;\n this.#lastPropagatedAnimation = fingerprint;\n\n const hasAnimation = animationName && animationName !== \"none\";\n const isLineMode = this.split === \"line\";\n\n for (const segment of segments) {\n if (hasAnimation) {\n // Mark non-whitespace segments so shadow DOM rule promotes them to inline-block\n // for transform support. Using an attribute (not inline style) so it survives the\n // visibility system's removeProperty(\"display\") calls.\n // Whitespace-only segments must stay inline — inline-block creates a new block\n // formatting context that collapses the space to zero width.\n const isWhitespace = /^\\s+$/.test(segment.segmentText || \"\");\n if (!isLineMode && !isWhitespace) {\n segment.setAttribute(\"data-animated\", \"\");\n }\n for (const prop of animationPropsToPropagate) {\n segment.style.setProperty(prop, computed.getPropertyValue(prop));\n }\n } else {\n segment.removeAttribute(\"data-animated\");\n for (const prop of animationPropsToPropagate) {\n segment.style.removeProperty(prop);\n }\n }\n }\n }\n\n private getTextContent(): string {\n // Get text content, handling both text nodes and HTML content\n let text = \"\";\n for (const node of Array.from(this.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n text += node.textContent || \"\";\n } else if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n // Skip ef-text-segment elements (they're created by us)\n if (element.tagName === \"EF-TEXT-SEGMENT\") {\n continue;\n }\n // Skip template elements (they're templates, not content)\n if (element.tagName === \"TEMPLATE\") {\n continue;\n }\n text += element.textContent || \"\";\n }\n }\n return text;\n }\n\n private splitText() {\n // Validate split mode\n const validatedSplit = this.validateSplit(this.split);\n if (validatedSplit !== this.split) {\n this.split = validatedSplit;\n return; // Will trigger updated() which calls splitText() again\n }\n\n // Validate stagger\n const validatedStagger = this.validateStagger(this.staggerMs);\n if (validatedStagger !== this.staggerMs) {\n this.staggerMs = validatedStagger;\n return; // Will trigger updated() which calls splitText() again\n }\n\n // Read text content - use stored _textContent if set, otherwise read from DOM\n const text =\n this._textContent !== null ? this._textContent : this.getTextContent();\n const trimmedText = text.trim();\n const textStartOffset = text.indexOf(trimmedText);\n\n // GUARD: Check if segments are already correct before clearing/recreating\n // This prevents redundant splits from RAF callbacks, updated(), etc.\n if (\n this.#segmentsInitialized &&\n this.segments.length > 0 &&\n this.lastTextContent === text\n ) {\n return;\n }\n\n if (!text || trimmedText.length === 0) {\n // Clear segments if no text\n const existingSegments = Array.from(\n this.querySelectorAll(\"ef-text-segment\"),\n );\n for (const segment of existingSegments) {\n segment.remove();\n }\n // Clear text nodes\n const textNodes: ChildNode[] = [];\n for (const node of Array.from(this.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n textNodes.push(node as ChildNode);\n }\n }\n for (const node of textNodes) {\n node.remove();\n }\n this.lastTextContent = \"\";\n // Resolve any waiting promises\n this._segmentsReadyResolvers.forEach((resolve) => {\n resolve();\n });\n this._segmentsReadyResolvers = [];\n // Reset initialization flag when clearing segments\n this.#segmentsInitialized = false;\n return;\n }\n\n // Reset initialization flag when we're about to create new segments\n this.#segmentsInitialized = false;\n\n const segments = this.splitTextIntoSegments(text);\n const durationMs = this.durationMs || 1000; // Default 1 second if no duration\n\n // For character mode, detect word boundaries to wrap characters within words\n let wordBoundaries: Map<number, number> | null = null;\n if (this.split === \"char\") {\n wordBoundaries = this.detectWordBoundaries(text);\n }\n\n // Clear ALL child nodes (text nodes and segments) by replacing innerHTML\n // This ensures we don't have any leftover text nodes\n const fragment = document.createDocumentFragment();\n\n // Find template element if not already stored\n if (!this._templateElement) {\n this._templateElement = this.querySelector(\"template\");\n }\n\n // Get template content structure\n // If template exists, clone it; otherwise create default ef-text-segment\n const templateContent = this._templateElement?.content;\n const templateSegments = templateContent\n ? Array.from(templateContent.querySelectorAll(\"ef-text-segment\"))\n : [];\n\n // If no template segments found, we'll create a default one\n const useTemplate = templateSegments.length > 0;\n const segmentsPerTextSegment = useTemplate ? templateSegments.length : 1;\n\n // For character mode with word wrapping, track current word and wrap segments\n let currentWordIndex: number | null = null;\n let currentWordSpan: HTMLSpanElement | null = null;\n let charIndex = 0; // Track position in original text for character mode\n\n // For word splitting, count only word segments (not whitespace) for stagger calculation\n const wordOnlySegments =\n this.split === \"word\"\n ? segments.filter((seg) => !/^\\s+$/.test(seg))\n : segments;\n const wordSegmentCount = wordOnlySegments.length;\n\n // Track word index as we iterate (for word mode with duplicate words)\n // This ensures each occurrence of duplicate words gets a unique stagger index\n let wordStaggerIndex = 0;\n\n // Create new segments in a fragment first\n segments.forEach((segmentText, textIndex) => {\n // Calculate stagger offset if stagger is set\n let staggerOffset: number | undefined;\n if (this.staggerMs !== undefined) {\n // For word splitting, whitespace segments should inherit stagger from preceding word\n const isWhitespace = /^\\s+$/.test(segmentText);\n let wordIndexForStagger: number;\n\n if (this.split === \"word\" && isWhitespace) {\n // Whitespace inherits from the preceding word's index\n // Use the word stagger index (which is the index of the word before this whitespace)\n wordIndexForStagger = Math.max(0, wordStaggerIndex - 1);\n } else if (this.split === \"word\") {\n // For word mode, use the current word stagger index (incremented for each word encountered)\n // This ensures duplicate words get unique indices based on their position\n wordIndexForStagger = wordStaggerIndex;\n wordStaggerIndex++;\n } else {\n // For char/line mode, use the actual position in segments array\n wordIndexForStagger = textIndex;\n }\n\n // Apply easing to the stagger offset\n // Normalize index to 0-1 range (0 for first segment, 1 for last segment)\n const normalizedProgress =\n wordSegmentCount > 1\n ? wordIndexForStagger / (wordSegmentCount - 1)\n : 0;\n\n // Apply easing function to get eased progress\n const easedProgress = evaluateEasing(this.easing, normalizedProgress);\n\n // Calculate total stagger duration (last segment gets full stagger)\n const totalStaggerDuration = (wordSegmentCount - 1) * this.staggerMs;\n\n // Apply eased progress to total stagger duration\n staggerOffset = easedProgress * totalStaggerDuration;\n }\n\n if (useTemplate && templateContent) {\n // Clone template content for each text segment\n // This allows multiple ef-text-segment elements per character/word/line\n const clonedContent = templateContent.cloneNode(\n true,\n ) as DocumentFragment;\n const clonedSegments = Array.from(\n clonedContent.querySelectorAll(\"ef-text-segment\"),\n ) as EFTextSegment[];\n\n clonedSegments.forEach((segment, templateIndex) => {\n // Set properties - Lit will process these when element is connected\n segment.segmentText = segmentText;\n // Calculate segment index accounting for multiple segments per text segment\n segment.segmentIndex =\n textIndex * segmentsPerTextSegment + templateIndex;\n segment.segmentStartMs = 0;\n segment.segmentEndMs = durationMs;\n segment.staggerOffsetMs = staggerOffset ?? 0;\n\n // Set data attribute for line mode to enable block display\n if (this.split === \"line\") {\n segment.setAttribute(\"data-line-segment\", \"true\");\n }\n\n // Mark as created to avoid being picked up as template\n segment.setAttribute(\"data-segment-created\", \"true\");\n\n // For character mode with templates, also wrap in word spans\n if (this.split === \"char\" && wordBoundaries) {\n const originalCharIndex = textStartOffset + charIndex;\n const wordIndex = wordBoundaries.get(originalCharIndex);\n if (wordIndex !== undefined) {\n if (wordIndex !== currentWordIndex) {\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n }\n currentWordIndex = wordIndex;\n currentWordSpan = document.createElement(\"span\");\n currentWordSpan.style.whiteSpace = \"nowrap\";\n }\n if (currentWordSpan) {\n currentWordSpan.appendChild(segment);\n } else {\n fragment.appendChild(segment);\n }\n } else {\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n currentWordSpan = null;\n currentWordIndex = null;\n }\n fragment.appendChild(segment);\n }\n charIndex += segmentText.length;\n } else {\n fragment.appendChild(segment);\n }\n });\n } else {\n // No template - create default ef-text-segment\n const segment = document.createElement(\n \"ef-text-segment\",\n ) as EFTextSegment;\n\n segment.segmentText = segmentText;\n segment.segmentIndex = textIndex;\n segment.segmentStartMs = 0;\n segment.segmentEndMs = durationMs;\n segment.staggerOffsetMs = staggerOffset ?? 0;\n\n // Set data attribute for line mode to enable block display\n if (this.split === \"line\") {\n segment.setAttribute(\"data-line-segment\", \"true\");\n }\n\n // Mark as created to avoid being picked up as template\n segment.setAttribute(\"data-segment-created\", \"true\");\n\n // For character mode, wrap segments within words to prevent line breaks\n if (this.split === \"char\" && wordBoundaries) {\n // Map character index in trimmed text to original text position\n const originalCharIndex = textStartOffset + charIndex;\n const wordIndex = wordBoundaries.get(originalCharIndex);\n if (wordIndex !== undefined) {\n // Check if we're starting a new word\n if (wordIndex !== currentWordIndex) {\n // Close previous word span if it exists\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n }\n // Start new word span\n currentWordIndex = wordIndex;\n currentWordSpan = document.createElement(\"span\");\n currentWordSpan.style.whiteSpace = \"nowrap\";\n }\n // Append segment to current word span\n if (currentWordSpan) {\n currentWordSpan.appendChild(segment);\n } else {\n fragment.appendChild(segment);\n }\n } else {\n // Not part of a word (whitespace/punctuation) - append directly\n // Close current word span if it exists\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n currentWordSpan = null;\n currentWordIndex = null;\n }\n fragment.appendChild(segment);\n }\n // Update character index for next iteration (in trimmed text)\n charIndex += segmentText.length;\n } else {\n // Not character mode or no word boundaries - append directly\n fragment.appendChild(segment);\n }\n }\n });\n\n // Close any remaining word span\n if (this.split === \"char\" && currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n }\n\n // Ensure segments are connected to DOM before checking for animations\n // Append fragment first, then trigger updates\n\n // Replace all children with the fragment (this clears text nodes and old segments)\n // But preserve the template element if it exists\n const templateToPreserve = this._templateElement;\n while (this.firstChild) {\n const child = this.firstChild;\n // Don't remove the template element\n if (child === templateToPreserve) {\n // Skip template, but we need to move it after the fragment\n // So we'll remove it temporarily and re-add it after\n this.removeChild(child);\n continue;\n }\n this.removeChild(child);\n }\n this.appendChild(fragment);\n // Re-add template element if it existed\n if (templateToPreserve) {\n this.appendChild(templateToPreserve);\n }\n\n // Propagate animation properties from this element to newly created segments\n this.#lastPropagatedAnimation = \"\";\n this.propagateAnimationToSegments();\n\n // Segments will pause their own animations in connectedCallback\n // Lit will automatically update them when they're connected to the DOM\n // Ensure segments are updated after being connected\n const segmentElements = this.segments;\n Promise.all(segmentElements.map((seg) => seg.updateComplete)).then(() => {\n const rootTimegroup = this.rootTimegroup || this;\n updateAnimations(rootTimegroup as AnimatableElement);\n });\n\n this.lastTextContent = text;\n this._textContent = text;\n\n // Mark segments as initialized to prevent redundant splits\n this.#segmentsInitialized = true;\n\n // Resolve any waiting promises after segments are connected (synchronous)\n this._segmentsReadyResolvers.forEach((resolve) => {\n resolve();\n });\n this._segmentsReadyResolvers = [];\n }\n\n private detectWordBoundaries(text: string): Map<number, number> {\n // Create a map from character index to word index\n // Characters within the same word will have the same word index\n const boundaries = new Map<number, number>();\n const trimmedText = text.trim();\n if (!trimmedText) {\n return boundaries;\n }\n\n // Use Intl.Segmenter to detect word boundaries\n const segmenter = new Intl.Segmenter(undefined, {\n granularity: \"word\",\n });\n const segments = Array.from(segmenter.segment(trimmedText));\n\n // Find the offset of trimmedText within the original text\n const textStart = text.indexOf(trimmedText);\n\n let wordIndex = 0;\n for (const seg of segments) {\n if (seg.isWordLike) {\n // Map all character positions in this word to the same word index\n for (let i = 0; i < seg.segment.length; i++) {\n const charPos = textStart + seg.index + i;\n boundaries.set(charPos, wordIndex);\n }\n wordIndex++;\n }\n }\n\n return boundaries;\n }\n\n private splitTextIntoSegments(text: string): string[] {\n // Trim text before segmenting to remove leading/trailing whitespace\n const trimmedText = text.trim();\n if (!trimmedText) {\n return [];\n }\n\n switch (this.split) {\n case \"line\": {\n // Split on newlines and trim each line\n const lines = trimmedText.split(/\\r?\\n/);\n return lines\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n }\n case \"word\": {\n // Use Intl.Segmenter for locale-aware word segmentation\n const segmenter = new Intl.Segmenter(undefined, {\n granularity: \"word\",\n });\n const segments = Array.from(segmenter.segment(trimmedText));\n const result: string[] = [];\n\n for (const seg of segments) {\n if (seg.isWordLike) {\n // Word-like segment - add it\n result.push(seg.segment);\n } else if (/^\\s+$/.test(seg.segment)) {\n // Whitespace segment - add it as-is\n result.push(seg.segment);\n } else {\n // Punctuation segment - attach to preceding word if it exists\n if (result.length > 0) {\n const lastItem = result[result.length - 1];\n if (lastItem && !/^\\s+$/.test(lastItem)) {\n result[result.length - 1] = lastItem + seg.segment;\n } else {\n result.push(seg.segment);\n }\n } else {\n result.push(seg.segment);\n }\n }\n }\n\n return result;\n }\n case \"char\": {\n // Use Intl.Segmenter for grapheme-aware character segmentation\n const segmenter = new Intl.Segmenter(undefined, {\n granularity: \"grapheme\",\n });\n const segments = Array.from(segmenter.segment(trimmedText));\n return segments.map((seg) => seg.segment);\n }\n default:\n return [trimmedText];\n }\n }\n\n get intrinsicDurationMs(): number | undefined {\n // If explicit duration is set, use it\n if (this.hasExplicitDuration) {\n return undefined; // Let explicit duration take precedence\n }\n\n // If we have a parent timegroup that dictates duration (fixed) or inherits it (fit),\n // we should inherit from it instead of using our intrinsic duration.\n // For 'sequence' and 'contain' modes, the parent relies on our intrinsic duration,\n // so we must provide it.\n if (this.parentTimegroup) {\n const mode = this.parentTimegroup.mode;\n if (mode === \"fixed\" || mode === \"fit\") {\n return undefined;\n }\n }\n\n // Otherwise, calculate from content\n // Use _textContent if set, otherwise read from DOM\n const text =\n this._textContent !== null ? this._textContent : this.getTextContent();\n if (!text || text.trim().length === 0) {\n return 0;\n }\n\n // Use the same splitting logic as splitTextIntoSegments for consistency\n const segments = this.splitTextIntoSegments(text);\n // For word splitting, only count word segments (not whitespace) for intrinsic duration\n const segmentCount =\n this.split === \"word\"\n ? segments.filter((seg) => !/^\\s+$/.test(seg)).length || 1\n : segments.length || 1;\n\n return segmentCount * 1000;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-text\": EFText;\n }\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACD;AAGM,mBAAMA,iBAAe,WAAW,WAAW,CAAC;;;eAa9B;gBA6BV;yBAIiB;sBACY;0BACiB;iCACF,EAAE;;;gBAhDvC,CACd,GAAG;;;;;;;MAQJ;;CAKD,AAAQ,cAAc,OAA0B;AAC9C,MAAI,UAAU,UAAU,UAAU,UAAU,UAAU,OACpD,QAAO;AAET,UAAQ,KACN,wBAAwB,MAAM,6DAC/B;AACD,SAAO;;CAUT,AAAQ,gBAAgB,OAA+C;AACrE,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,QAAQ,GAAG;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S,UAAU,KAEH;;;YAvuBvB,SAAS;CAAE,MAAM;CAAQ,SAAS;CAAM,CAAC;YAazC,SAAS;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACZ,CAAC;YAYD,SAAS;CAAE,MAAM;CAAQ,SAAS;CAAM,CAAC;qBA1C3C,cAAc,UAAU"}
1
+ {"version":3,"file":"EFText.js","names":["EFText","textNodes: ChildNode[]","#segmentsInitialized","segments","#lastPropagatedAnimation","wordBoundaries: Map<number, number> | null","currentWordIndex: number | null","currentWordSpan: HTMLSpanElement | null","staggerOffset: number | undefined","wordIndexForStagger: number","result: string[]"],"sources":["../../src/elements/EFText.ts"],"sourcesContent":["import { css, html, LitElement, type PropertyValueMap } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { durationConverter } from \"./durationConverter.js\";\nimport { EFTemporal } from \"./EFTemporal.js\";\n\nimport { evaluateEasing } from \"./easingUtils.js\";\nimport type { EFTextSegment } from \"./EFTextSegment.js\";\nimport { updateAnimations } from \"./updateAnimations.js\";\nimport type { AnimatableElement } from \"./updateAnimations.js\";\n\nexport type SplitMode = \"line\" | \"word\" | \"char\";\n\n// Animation properties to propagate from ef-text to its segments.\n// animation-delay is intentionally excluded -- the stagger system manages delay per segment.\nconst animationPropsToPropagate = [\n \"animation-name\",\n \"animation-duration\",\n \"animation-timing-function\",\n \"animation-fill-mode\",\n \"animation-iteration-count\",\n \"animation-direction\",\n] as const;\n\n@customElement(\"ef-text\")\nexport class EFText extends EFTemporal(LitElement) {\n static styles = [\n css`\n :host {\n display: inline;\n }\n :host([split=\"line\"]) {\n display: inline-block;\n }\n `,\n ];\n\n @property({ type: String, reflect: true })\n split: SplitMode = \"word\";\n\n private validateSplit(value: string): SplitMode {\n if (value === \"line\" || value === \"word\" || value === \"char\") {\n return value as SplitMode;\n }\n console.warn(\n `Invalid split value \"${value}\". Must be \"line\", \"word\", or \"char\". Defaulting to \"word\".`,\n );\n return \"word\";\n }\n\n @property({\n type: Number,\n attribute: \"stagger\",\n converter: durationConverter,\n })\n staggerMs?: number;\n\n private validateStagger(value: number | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (value < 0) {\n console.warn(`Invalid stagger value ${value}ms. Must be >= 0. Using 0.`);\n return 0;\n }\n return value;\n }\n\n @property({ type: String, reflect: true })\n easing = \"linear\";\n\n private mutationObserver?: MutationObserver;\n private animationObserver?: MutationObserver;\n private lastTextContent = \"\";\n private _textContent: string | null = null; // null means not initialized, \"\" means explicitly empty\n private _templateElement: HTMLTemplateElement | null = null;\n private _segmentsReadyResolvers: Array<() => void> = [];\n #segmentsInitialized = false;\n #lastPropagatedAnimation = \"\";\n\n render() {\n return html`<slot></slot>`;\n }\n\n // Store text content so we can use it even after DOM is cleared\n set textContent(value: string | null) {\n const newValue = value || \"\";\n // Only update if value actually changed\n if (this._textContent !== newValue) {\n this._textContent = newValue;\n\n // Find template element if not already stored\n if (!this._templateElement && this.isConnected) {\n this._templateElement = this.querySelector(\"template\");\n }\n\n // Clear any existing text nodes\n const textNodes: ChildNode[] = [];\n for (const node of Array.from(this.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n textNodes.push(node as ChildNode);\n }\n }\n for (const node of textNodes) {\n node.remove();\n }\n // Add new text node if value is not empty\n if (newValue) {\n const textNode = document.createTextNode(newValue);\n this.appendChild(textNode);\n }\n if (this.isConnected) {\n this.emitContentChange(\"content\");\n this.splitText();\n }\n }\n }\n\n get textContent(): string {\n // If _textContent is null, it hasn't been initialized - read from DOM\n if (this._textContent === null) {\n return this.getTextContent();\n }\n // Otherwise use stored value (even if empty string)\n return this._textContent;\n }\n\n /**\n * Get all ef-text-segment elements directly\n * @public\n */\n get segments(): EFTextSegment[] {\n return Array.from(\n this.querySelectorAll(\"ef-text-segment[data-segment-created]\"),\n ) as EFTextSegment[];\n }\n\n /**\n * Returns a promise that resolves when segments are ready (created and connected)\n * Use this to wait for segments after setting textContent or other properties\n * @public\n */\n async whenSegmentsReady(): Promise<EFTextSegment[]> {\n // Wait for text element to be updated first\n await this.updateComplete;\n\n // If no text content, segments will be empty - return immediately\n // Use same logic as splitText to read text content\n const text =\n this._textContent !== null ? this._textContent : this.getTextContent();\n if (!text || text.trim().length === 0) {\n return [];\n }\n\n // If segments already initialized and exist, return immediately (no RAF waits)\n if (this.#segmentsInitialized && this.segments.length > 0) {\n await Promise.all(this.segments.map((seg) => seg.updateComplete));\n return this.segments;\n }\n\n // Check if segments are already in DOM (synchronous check - no RAF)\n let segments = this.segments;\n if (segments.length > 0) {\n // Segments exist, just wait for their Lit updates (no RAF)\n await Promise.all(segments.map((seg) => seg.updateComplete));\n this.#segmentsInitialized = true;\n return segments;\n }\n\n // Segments don't exist yet - use the promise-based mechanism (no RAF polling)\n // This waits for splitText() to complete and resolve the promise\n return new Promise<EFTextSegment[]>((resolve, reject) => {\n const timeout = setTimeout(() => {\n // Remove our resolver if we timeout\n const index = this._segmentsReadyResolvers.indexOf(resolveWithSegments);\n if (index > -1) {\n this._segmentsReadyResolvers.splice(index, 1);\n }\n reject(new Error(\"Timeout waiting for text segments to be created\"));\n }, 5000); // 5 second timeout\n\n const resolveWithSegments = () => {\n clearTimeout(timeout);\n // Wait for segment Lit updates\n const segments = this.segments;\n Promise.all(segments.map((seg) => seg.updateComplete)).then(() => {\n this.#segmentsInitialized = true;\n resolve(segments);\n });\n };\n\n this._segmentsReadyResolvers.push(resolveWithSegments);\n\n // Trigger splitText if it hasn't run yet\n // This handles the case where segments haven't been created at all\n if (segments.length === 0 && this.isConnected) {\n this.splitText();\n }\n });\n }\n\n connectedCallback() {\n super.connectedCallback();\n // Find and store template element before any modifications\n this._templateElement = this.querySelector(\"template\");\n\n // Initialize _textContent from DOM if not already set (for declarative usage)\n if (this._textContent === null) {\n this._textContent = this.getTextContent();\n this.lastTextContent = this._textContent;\n }\n\n // Use RAF to ensure DOM is fully ready before splitting text\n // Callers that need segments immediately (e.g., render clones) should await whenSegmentsReady()\n requestAnimationFrame(() => {\n this.setupMutationObserver();\n this.setupAnimationObserver();\n this.splitText();\n });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.mutationObserver?.disconnect();\n this.animationObserver?.disconnect();\n }\n\n protected updated(\n changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>,\n ): void {\n if (\n changedProperties.has(\"split\") ||\n changedProperties.has(\"staggerMs\") ||\n changedProperties.has(\"easing\") ||\n changedProperties.has(\"durationMs\")\n ) {\n this.emitContentChange(\"content\");\n this.splitText();\n }\n }\n\n private setupMutationObserver() {\n this.mutationObserver = new MutationObserver(() => {\n // Only react to changes that aren't from our own segment creation\n const currentText = this._textContent || this.getTextContent();\n if (currentText !== this.lastTextContent) {\n this._textContent = currentText;\n this.lastTextContent = currentText;\n this.splitText();\n }\n });\n\n this.mutationObserver.observe(this, {\n childList: true,\n characterData: true,\n subtree: true,\n });\n }\n\n private setupAnimationObserver() {\n this.animationObserver = new MutationObserver(() => {\n this.propagateAnimationToSegments();\n });\n\n this.animationObserver.observe(this, {\n attributes: true,\n attributeFilter: [\"class\", \"style\"],\n });\n }\n\n private propagateAnimationToSegments() {\n const segments = this.segments;\n if (segments.length === 0) return;\n\n const computed = window.getComputedStyle(this);\n const animationName = computed.animationName;\n\n // Build a fingerprint to avoid redundant work\n const fingerprint = animationPropsToPropagate\n .map((prop) => computed.getPropertyValue(prop))\n .join(\"|\");\n\n if (fingerprint === this.#lastPropagatedAnimation) return;\n this.#lastPropagatedAnimation = fingerprint;\n\n const hasAnimation = animationName && animationName !== \"none\";\n\n for (const segment of segments) {\n if (hasAnimation) {\n for (const prop of animationPropsToPropagate) {\n let value = computed.getPropertyValue(prop);\n if (prop === \"animation-fill-mode\" && value === \"none\") {\n value = \"backwards\";\n }\n segment.style.setProperty(prop, value);\n }\n } else {\n for (const prop of animationPropsToPropagate) {\n segment.style.removeProperty(prop);\n }\n }\n }\n }\n\n private getTextContent(): string {\n // Get text content, handling both text nodes and HTML content\n let text = \"\";\n for (const node of Array.from(this.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n text += node.textContent || \"\";\n } else if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node as HTMLElement;\n // Skip ef-text-segment elements (they're created by us)\n if (element.tagName === \"EF-TEXT-SEGMENT\") {\n continue;\n }\n // Skip template elements (they're templates, not content)\n if (element.tagName === \"TEMPLATE\") {\n continue;\n }\n text += element.textContent || \"\";\n }\n }\n return text;\n }\n\n private splitText() {\n // Validate split mode\n const validatedSplit = this.validateSplit(this.split);\n if (validatedSplit !== this.split) {\n this.split = validatedSplit;\n return; // Will trigger updated() which calls splitText() again\n }\n\n // Validate stagger\n const validatedStagger = this.validateStagger(this.staggerMs);\n if (validatedStagger !== this.staggerMs) {\n this.staggerMs = validatedStagger;\n return; // Will trigger updated() which calls splitText() again\n }\n\n // Read text content - use stored _textContent if set, otherwise read from DOM\n const text =\n this._textContent !== null ? this._textContent : this.getTextContent();\n const trimmedText = text.trim();\n const textStartOffset = text.indexOf(trimmedText);\n\n // GUARD: Check if segments are already correct before clearing/recreating\n // This prevents redundant splits from RAF callbacks, updated(), etc.\n if (\n this.#segmentsInitialized &&\n this.segments.length > 0 &&\n this.lastTextContent === text\n ) {\n return;\n }\n\n if (!text || trimmedText.length === 0) {\n // Clear segments if no text\n const existingSegments = Array.from(\n this.querySelectorAll(\"ef-text-segment\"),\n );\n for (const segment of existingSegments) {\n segment.remove();\n }\n // Clear text nodes\n const textNodes: ChildNode[] = [];\n for (const node of Array.from(this.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) {\n textNodes.push(node as ChildNode);\n }\n }\n for (const node of textNodes) {\n node.remove();\n }\n this.lastTextContent = \"\";\n // Resolve any waiting promises\n this._segmentsReadyResolvers.forEach((resolve) => {\n resolve();\n });\n this._segmentsReadyResolvers = [];\n // Reset initialization flag when clearing segments\n this.#segmentsInitialized = false;\n return;\n }\n\n // Reset initialization flag when we're about to create new segments\n this.#segmentsInitialized = false;\n\n const segments = this.splitTextIntoSegments(text);\n const durationMs = this.durationMs || 1000; // Default 1 second if no duration\n\n // For character mode, detect word boundaries to wrap characters within words\n let wordBoundaries: Map<number, number> | null = null;\n if (this.split === \"char\") {\n wordBoundaries = this.detectWordBoundaries(text);\n }\n\n // Clear ALL child nodes (text nodes and segments) by replacing innerHTML\n // This ensures we don't have any leftover text nodes\n const fragment = document.createDocumentFragment();\n\n // Find template element if not already stored\n if (!this._templateElement) {\n this._templateElement = this.querySelector(\"template\");\n }\n\n // Get template content structure\n // If template exists, clone it; otherwise create default ef-text-segment\n const templateContent = this._templateElement?.content;\n const templateSegments = templateContent\n ? Array.from(templateContent.querySelectorAll(\"ef-text-segment\"))\n : [];\n\n // If no template segments found, we'll create a default one\n const useTemplate = templateSegments.length > 0;\n const segmentsPerTextSegment = useTemplate ? templateSegments.length : 1;\n\n // For character mode with word wrapping, track current word and wrap segments\n let currentWordIndex: number | null = null;\n let currentWordSpan: HTMLSpanElement | null = null;\n let charIndex = 0; // Track position in original text for character mode\n\n // For word splitting, count only word segments (not whitespace) for stagger calculation\n const wordOnlySegments =\n this.split === \"word\"\n ? segments.filter((seg) => !/^\\s+$/.test(seg))\n : segments;\n const wordSegmentCount = wordOnlySegments.length;\n\n // Track word index as we iterate (for word mode with duplicate words)\n // This ensures each occurrence of duplicate words gets a unique stagger index\n let wordStaggerIndex = 0;\n\n // Create new segments in a fragment first\n segments.forEach((segmentText, textIndex) => {\n // Calculate stagger offset if stagger is set\n let staggerOffset: number | undefined;\n if (this.staggerMs !== undefined) {\n // For word splitting, whitespace segments should inherit stagger from preceding word\n const isWhitespace = /^\\s+$/.test(segmentText);\n let wordIndexForStagger: number;\n\n if (this.split === \"word\" && isWhitespace) {\n // Whitespace inherits from the preceding word's index\n // Use the word stagger index (which is the index of the word before this whitespace)\n wordIndexForStagger = Math.max(0, wordStaggerIndex - 1);\n } else if (this.split === \"word\") {\n // For word mode, use the current word stagger index (incremented for each word encountered)\n // This ensures duplicate words get unique indices based on their position\n wordIndexForStagger = wordStaggerIndex;\n wordStaggerIndex++;\n } else {\n // For char/line mode, use the actual position in segments array\n wordIndexForStagger = textIndex;\n }\n\n // Apply easing to the stagger offset\n // Normalize index to 0-1 range (0 for first segment, 1 for last segment)\n const normalizedProgress =\n wordSegmentCount > 1\n ? wordIndexForStagger / (wordSegmentCount - 1)\n : 0;\n\n // Apply easing function to get eased progress\n const easedProgress = evaluateEasing(this.easing, normalizedProgress);\n\n // Calculate total stagger duration (last segment gets full stagger)\n const totalStaggerDuration = (wordSegmentCount - 1) * this.staggerMs;\n\n // Apply eased progress to total stagger duration\n staggerOffset = easedProgress * totalStaggerDuration;\n }\n\n if (useTemplate && templateContent) {\n // Clone template content for each text segment\n // This allows multiple ef-text-segment elements per character/word/line\n const clonedContent = templateContent.cloneNode(\n true,\n ) as DocumentFragment;\n const clonedSegments = Array.from(\n clonedContent.querySelectorAll(\"ef-text-segment\"),\n ) as EFTextSegment[];\n\n clonedSegments.forEach((segment, templateIndex) => {\n // Set properties - Lit will process these when element is connected\n segment.segmentText = segmentText;\n // Calculate segment index accounting for multiple segments per text segment\n segment.segmentIndex =\n textIndex * segmentsPerTextSegment + templateIndex;\n segment.segmentStartMs = 0;\n segment.segmentEndMs = durationMs;\n segment.staggerOffsetMs = staggerOffset ?? 0;\n\n // Set data attribute for line mode to enable block display\n if (this.split === \"line\") {\n segment.setAttribute(\"data-line-segment\", \"true\");\n }\n\n if (/^\\s+$/.test(segmentText)) {\n segment.setAttribute(\"data-whitespace\", \"\");\n }\n\n // Mark as created to avoid being picked up as template\n segment.setAttribute(\"data-segment-created\", \"true\");\n\n // For character mode with templates, also wrap in word spans\n if (this.split === \"char\" && wordBoundaries) {\n const originalCharIndex = textStartOffset + charIndex;\n const wordIndex = wordBoundaries.get(originalCharIndex);\n if (wordIndex !== undefined) {\n if (wordIndex !== currentWordIndex) {\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n }\n currentWordIndex = wordIndex;\n currentWordSpan = document.createElement(\"span\");\n currentWordSpan.style.whiteSpace = \"nowrap\";\n }\n if (currentWordSpan) {\n currentWordSpan.appendChild(segment);\n } else {\n fragment.appendChild(segment);\n }\n } else {\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n currentWordSpan = null;\n currentWordIndex = null;\n }\n fragment.appendChild(segment);\n }\n charIndex += segmentText.length;\n } else {\n fragment.appendChild(segment);\n }\n });\n } else {\n // No template - create default ef-text-segment\n const segment = document.createElement(\n \"ef-text-segment\",\n ) as EFTextSegment;\n\n segment.segmentText = segmentText;\n segment.segmentIndex = textIndex;\n segment.segmentStartMs = 0;\n segment.segmentEndMs = durationMs;\n segment.staggerOffsetMs = staggerOffset ?? 0;\n\n // Set data attribute for line mode to enable block display\n if (this.split === \"line\") {\n segment.setAttribute(\"data-line-segment\", \"true\");\n }\n\n if (/^\\s+$/.test(segmentText)) {\n segment.setAttribute(\"data-whitespace\", \"\");\n }\n\n // Mark as created to avoid being picked up as template\n segment.setAttribute(\"data-segment-created\", \"true\");\n\n // For character mode, wrap segments within words to prevent line breaks\n if (this.split === \"char\" && wordBoundaries) {\n // Map character index in trimmed text to original text position\n const originalCharIndex = textStartOffset + charIndex;\n const wordIndex = wordBoundaries.get(originalCharIndex);\n if (wordIndex !== undefined) {\n // Check if we're starting a new word\n if (wordIndex !== currentWordIndex) {\n // Close previous word span if it exists\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n }\n // Start new word span\n currentWordIndex = wordIndex;\n currentWordSpan = document.createElement(\"span\");\n currentWordSpan.style.whiteSpace = \"nowrap\";\n }\n // Append segment to current word span\n if (currentWordSpan) {\n currentWordSpan.appendChild(segment);\n } else {\n fragment.appendChild(segment);\n }\n } else {\n // Not part of a word (whitespace/punctuation) - append directly\n // Close current word span if it exists\n if (currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n currentWordSpan = null;\n currentWordIndex = null;\n }\n fragment.appendChild(segment);\n }\n // Update character index for next iteration (in trimmed text)\n charIndex += segmentText.length;\n } else {\n // Not character mode or no word boundaries - append directly\n fragment.appendChild(segment);\n }\n }\n });\n\n // Close any remaining word span\n if (this.split === \"char\" && currentWordSpan) {\n fragment.appendChild(currentWordSpan);\n }\n\n // Ensure segments are connected to DOM before checking for animations\n // Append fragment first, then trigger updates\n\n // Replace all children with the fragment (this clears text nodes and old segments)\n // But preserve the template element if it exists\n const templateToPreserve = this._templateElement;\n while (this.firstChild) {\n const child = this.firstChild;\n // Don't remove the template element\n if (child === templateToPreserve) {\n // Skip template, but we need to move it after the fragment\n // So we'll remove it temporarily and re-add it after\n this.removeChild(child);\n continue;\n }\n this.removeChild(child);\n }\n this.appendChild(fragment);\n // Re-add template element if it existed\n if (templateToPreserve) {\n this.appendChild(templateToPreserve);\n }\n\n // Propagate animation properties from this element to newly created segments\n this.#lastPropagatedAnimation = \"\";\n this.propagateAnimationToSegments();\n\n // For template-path segments: their animation comes from a class, not from ef-text.\n // propagateAnimationToSegments() is a no-op when ef-text has no animation, but its\n // else-branch removes all animation inline styles — so we apply the fill-mode default\n // after propagation to avoid being cleared.\n if (useTemplate) {\n for (const segment of this.segments) {\n const computedFill = window\n .getComputedStyle(segment)\n .getPropertyValue(\"animation-fill-mode\");\n if (computedFill === \"none\" || computedFill === \"\") {\n segment.style.setProperty(\"animation-fill-mode\", \"backwards\");\n }\n }\n }\n\n // Segments will pause their own animations in connectedCallback\n // Lit will automatically update them when they're connected to the DOM\n // Ensure segments are updated after being connected\n const segmentElements = this.segments;\n Promise.all(segmentElements.map((seg) => seg.updateComplete)).then(() => {\n const rootTimegroup = this.rootTimegroup || this;\n updateAnimations(rootTimegroup as AnimatableElement);\n });\n\n this.lastTextContent = text;\n this._textContent = text;\n\n // Mark segments as initialized to prevent redundant splits\n this.#segmentsInitialized = true;\n\n // Resolve any waiting promises after segments are connected (synchronous)\n this._segmentsReadyResolvers.forEach((resolve) => {\n resolve();\n });\n this._segmentsReadyResolvers = [];\n }\n\n private detectWordBoundaries(text: string): Map<number, number> {\n // Create a map from character index to word index\n // Characters within the same word will have the same word index\n const boundaries = new Map<number, number>();\n const trimmedText = text.trim();\n if (!trimmedText) {\n return boundaries;\n }\n\n // Use Intl.Segmenter to detect word boundaries\n const segmenter = new Intl.Segmenter(undefined, {\n granularity: \"word\",\n });\n const segments = Array.from(segmenter.segment(trimmedText));\n\n // Find the offset of trimmedText within the original text\n const textStart = text.indexOf(trimmedText);\n\n let wordIndex = 0;\n for (const seg of segments) {\n if (seg.isWordLike) {\n // Map all character positions in this word to the same word index\n for (let i = 0; i < seg.segment.length; i++) {\n const charPos = textStart + seg.index + i;\n boundaries.set(charPos, wordIndex);\n }\n wordIndex++;\n }\n }\n\n return boundaries;\n }\n\n private splitTextIntoSegments(text: string): string[] {\n // Trim text before segmenting to remove leading/trailing whitespace\n const trimmedText = text.trim();\n if (!trimmedText) {\n return [];\n }\n\n switch (this.split) {\n case \"line\": {\n // Split on newlines and trim each line\n const lines = trimmedText.split(/\\r?\\n/);\n return lines\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n }\n case \"word\": {\n // Use Intl.Segmenter for locale-aware word segmentation\n const segmenter = new Intl.Segmenter(undefined, {\n granularity: \"word\",\n });\n const segments = Array.from(segmenter.segment(trimmedText));\n const result: string[] = [];\n\n for (const seg of segments) {\n if (seg.isWordLike) {\n // Word-like segment - add it\n result.push(seg.segment);\n } else if (/^\\s+$/.test(seg.segment)) {\n // Whitespace segment - add it as-is\n result.push(seg.segment);\n } else {\n // Punctuation segment - attach to preceding word if it exists\n if (result.length > 0) {\n const lastItem = result[result.length - 1];\n if (lastItem && !/^\\s+$/.test(lastItem)) {\n result[result.length - 1] = lastItem + seg.segment;\n } else {\n result.push(seg.segment);\n }\n } else {\n result.push(seg.segment);\n }\n }\n }\n\n return result;\n }\n case \"char\": {\n // Use Intl.Segmenter for grapheme-aware character segmentation\n const segmenter = new Intl.Segmenter(undefined, {\n granularity: \"grapheme\",\n });\n const segments = Array.from(segmenter.segment(trimmedText));\n return segments.map((seg) => seg.segment);\n }\n default:\n return [trimmedText];\n }\n }\n\n get intrinsicDurationMs(): number | undefined {\n // If explicit duration is set, use it\n if (this.hasExplicitDuration) {\n return undefined; // Let explicit duration take precedence\n }\n\n // If we have a parent timegroup that dictates duration (fixed) or inherits it (fit),\n // we should inherit from it instead of using our intrinsic duration.\n // For 'sequence' and 'contain' modes, the parent relies on our intrinsic duration,\n // so we must provide it.\n if (this.parentTimegroup) {\n const mode = this.parentTimegroup.mode;\n if (mode === \"fixed\" || mode === \"fit\") {\n return undefined;\n }\n }\n\n // Otherwise, calculate from content\n // Use _textContent if set, otherwise read from DOM\n const text =\n this._textContent !== null ? this._textContent : this.getTextContent();\n if (!text || text.trim().length === 0) {\n return 0;\n }\n\n // Use the same splitting logic as splitTextIntoSegments for consistency\n const segments = this.splitTextIntoSegments(text);\n // For word splitting, only count word segments (not whitespace) for intrinsic duration\n const segmentCount =\n this.split === \"word\"\n ? segments.filter((seg) => !/^\\s+$/.test(seg)).length || 1\n : segments.length || 1;\n\n return segmentCount * 1000;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-text\": EFText;\n }\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACD;AAGM,mBAAMA,iBAAe,WAAW,WAAW,CAAC;;;eAa9B;gBA6BV;yBAIiB;sBACY;0BACiB;iCACF,EAAE;;;gBAhDvC,CACd,GAAG;;;;;;;MAQJ;;CAKD,AAAQ,cAAc,OAA0B;AAC9C,MAAI,UAAU,UAAU,UAAU,UAAU,UAAU,OACpD,QAAO;AAET,UAAQ,KACN,wBAAwB,MAAM,6DAC/B;AACD,SAAO;;CAUT,AAAQ,gBAAgB,OAA+C;AACrE,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,QAAQ,GAAG;AACb,WAAQ,KAAK,yBAAyB,MAAM,4BAA4B;AACxE,UAAO;;AAET,SAAO;;CAYT,uBAAuB;CACvB,2BAA2B;CAE3B,SAAS;AACP,SAAO,IAAI;;CAIb,IAAI,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SAAS,QAAQ,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC,UAAU,IACvD,SAAS,UAAU,KAEH;;;YAvvBvB,SAAS;CAAE,MAAM;CAAQ,SAAS;CAAM,CAAC;YAazC,SAAS;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACZ,CAAC;YAYD,SAAS;CAAE,MAAM;CAAQ,SAAS;CAAM,CAAC;qBA1C3C,cAAc,UAAU"}
@@ -17,11 +17,11 @@ let EFTextSegment = class EFTextSegment$1 extends EFTemporal(LitElement) {
17
17
  static {
18
18
  this.styles = [css`
19
19
  :host {
20
- display: inline;
21
- }
22
- :host([data-animated]) {
23
20
  display: inline-block;
24
21
  }
22
+ :host([data-whitespace]) {
23
+ display: inline;
24
+ }
25
25
  :host([data-line-segment]) {
26
26
  display: block;
27
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"EFTextSegment.js","names":["EFTextSegment"],"sources":["../../src/elements/EFTextSegment.ts"],"sourcesContent":["import { css, html, LitElement } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { EFTemporal } from \"./EFTemporal.ts\";\nimport { EFText } from \"./EFText.js\";\n\n// Global registry for animation stylesheets shared across all text segments\nconst globalAnimationSheets = new Map<string, CSSStyleSheet>();\n\n@customElement(\"ef-text-segment\")\nexport class EFTextSegment extends EFTemporal(LitElement) {\n static styles = [\n css`\n :host {\n display: inline;\n }\n :host([data-animated]) {\n display: inline-block;\n }\n :host([data-line-segment]) {\n display: block;\n }\n :host([hidden]) {\n opacity: 0;\n pointer-events: none;\n }\n `,\n ];\n\n /**\n * Registers animation styles that should be shared across all text segments.\n * This is the correct way to inject animation styles for segments - not via innerHTML.\n *\n * @param id Unique identifier for this stylesheet (e.g., \"my-animations\")\n * @param cssText The CSS rules to inject\n *\n * @example\n * EFTextSegment.registerAnimations(\"bounceIn\", `\n * @keyframes bounceIn {\n * from { transform: scale(0); }\n * to { transform: scale(1); }\n * }\n * .bounce-in {\n * animation: bounceIn 0.5s ease-out;\n * }\n * `);\n */\n static registerAnimations(id: string, cssText: string): void {\n if (globalAnimationSheets.has(id)) {\n // Already registered\n return;\n }\n\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(cssText);\n globalAnimationSheets.set(id, sheet);\n\n // Apply to all existing instances\n document.querySelectorAll(\"ef-text-segment\").forEach((segment) => {\n if (segment.shadowRoot) {\n const adoptedSheets = segment.shadowRoot.adoptedStyleSheets;\n if (!adoptedSheets.includes(sheet)) {\n segment.shadowRoot.adoptedStyleSheets = [...adoptedSheets, sheet];\n }\n }\n });\n }\n\n /**\n * Unregisters previously registered animation styles.\n *\n * @param id The identifier of the stylesheet to remove\n */\n static unregisterAnimations(id: string): void {\n const sheet = globalAnimationSheets.get(id);\n if (!sheet) {\n return;\n }\n\n globalAnimationSheets.delete(id);\n\n // Remove from all existing instances\n document.querySelectorAll(\"ef-text-segment\").forEach((segment) => {\n if (segment.shadowRoot) {\n segment.shadowRoot.adoptedStyleSheets =\n segment.shadowRoot.adoptedStyleSheets.filter((s) => s !== sheet);\n }\n });\n }\n\n render() {\n // Set CSS variables in render() to ensure they're always set\n // This is necessary because Lit may clear inline styles during updates\n this.setCSSVariables();\n return html`${this.segmentText}`;\n }\n\n private setCSSVariables(): void {\n // Set deterministic --ef-seed value based on segment index\n const seed = (this.segmentIndex * 9007) % 233; // Prime numbers for better distribution\n const seedValue = seed / 233; // Normalize to 0-1 range\n this.style.setProperty(\"--ef-seed\", seedValue.toString());\n\n // Set stagger offset CSS variable\n // staggerOffsetMs is always set (defaults to 0), so we can always set the CSS variable\n const offsetMs = this.staggerOffsetMs ?? 0;\n this.style.setProperty(\"--ef-stagger-offset\", `${offsetMs}ms`);\n\n // Set index CSS variable\n this.style.setProperty(\"--ef-index\", this.segmentIndex.toString());\n }\n\n protected firstUpdated(): void {\n this.setCSSVariables();\n }\n\n protected updated(): void {\n this.setCSSVariables();\n }\n\n @property({ type: String, attribute: false })\n segmentText = \"\";\n\n @property({ type: Number, attribute: false })\n segmentIndex = 0;\n\n @property({ type: Number, attribute: false })\n staggerOffsetMs?: number;\n\n @property({ type: Number, attribute: false })\n segmentStartMs = 0;\n\n @property({ type: Number, attribute: false })\n segmentEndMs = 0;\n\n @property({ type: Boolean, reflect: true })\n hidden = false;\n\n get startTimeMs() {\n const parentText = this.closest(\"ef-text\") as EFText;\n const parentStartTime = parentText?.startTimeMs || 0;\n return parentStartTime + (this.segmentStartMs || 0);\n }\n\n get endTimeMs() {\n // Derive from parent's live durationMs rather than the snapshot stored in segmentEndMs.\n // This ensures segments track changes when the parent's duration updates\n // (e.g., a contain-mode timegroup whose duration changes after a video loads).\n const parentText = this.closest(\"ef-text\") as EFText;\n if (parentText) {\n return parentText.startTimeMs + parentText.durationMs;\n }\n return this.segmentEndMs || 0;\n }\n\n get durationMs(): number {\n const parentText = this.closest(\"ef-text\") as EFText;\n if (parentText) {\n return parentText.durationMs;\n }\n return this.segmentEndMs - this.segmentStartMs;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-text-segment\": EFTextSegment;\n }\n}\n"],"mappings":";;;;;;AAMA,MAAM,wCAAwB,IAAI,KAA4B;AAGvD,0BAAMA,wBAAsB,WAAW,WAAW,CAAC;;;qBA+G1C;sBAGC;wBAME;sBAGF;gBAGN;;;gBA7HO,CACd,GAAG;;;;;;;;;;;;;;MAeJ;;;;;;;;;;;;;;;;;;;;CAoBD,OAAO,mBAAmB,IAAY,SAAuB;AAC3D,MAAI,sBAAsB,IAAI,GAAG,CAE/B;EAGF,MAAM,QAAQ,IAAI,eAAe;AACjC,QAAM,YAAY,QAAQ;AAC1B,wBAAsB,IAAI,IAAI,MAAM;AAGpC,WAAS,iBAAiB,kBAAkB,CAAC,SAAS,YAAY;AAChE,OAAI,QAAQ,YAAY;IACtB,MAAM,gBAAgB,QAAQ,WAAW;AACzC,QAAI,CAAC,cAAc,SAAS,MAAM,CAChC,SAAQ,WAAW,qBAAqB,CAAC,GAAG,eAAe,MAAM;;IAGrE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S;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAG5C,SAAS;CAAE,MAAM;CAAS,SAAS;CAAM,CAAC;4BA9H5C,cAAc,kBAAkB"}
1
+ {"version":3,"file":"EFTextSegment.js","names":["EFTextSegment"],"sources":["../../src/elements/EFTextSegment.ts"],"sourcesContent":["import { css, html, LitElement } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { EFTemporal } from \"./EFTemporal.ts\";\nimport { EFText } from \"./EFText.js\";\n\n// Global registry for animation stylesheets shared across all text segments\nconst globalAnimationSheets = new Map<string, CSSStyleSheet>();\n\n@customElement(\"ef-text-segment\")\nexport class EFTextSegment extends EFTemporal(LitElement) {\n static styles = [\n css`\n :host {\n display: inline-block;\n }\n :host([data-whitespace]) {\n display: inline;\n }\n :host([data-line-segment]) {\n display: block;\n }\n :host([hidden]) {\n opacity: 0;\n pointer-events: none;\n }\n `,\n ];\n\n /**\n * Registers animation styles that should be shared across all text segments.\n * This is the correct way to inject animation styles for segments - not via innerHTML.\n *\n * @param id Unique identifier for this stylesheet (e.g., \"my-animations\")\n * @param cssText The CSS rules to inject\n *\n * @example\n * EFTextSegment.registerAnimations(\"bounceIn\", `\n * @keyframes bounceIn {\n * from { transform: scale(0); }\n * to { transform: scale(1); }\n * }\n * .bounce-in {\n * animation: bounceIn 0.5s ease-out;\n * }\n * `);\n */\n static registerAnimations(id: string, cssText: string): void {\n if (globalAnimationSheets.has(id)) {\n // Already registered\n return;\n }\n\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(cssText);\n globalAnimationSheets.set(id, sheet);\n\n // Apply to all existing instances\n document.querySelectorAll(\"ef-text-segment\").forEach((segment) => {\n if (segment.shadowRoot) {\n const adoptedSheets = segment.shadowRoot.adoptedStyleSheets;\n if (!adoptedSheets.includes(sheet)) {\n segment.shadowRoot.adoptedStyleSheets = [...adoptedSheets, sheet];\n }\n }\n });\n }\n\n /**\n * Unregisters previously registered animation styles.\n *\n * @param id The identifier of the stylesheet to remove\n */\n static unregisterAnimations(id: string): void {\n const sheet = globalAnimationSheets.get(id);\n if (!sheet) {\n return;\n }\n\n globalAnimationSheets.delete(id);\n\n // Remove from all existing instances\n document.querySelectorAll(\"ef-text-segment\").forEach((segment) => {\n if (segment.shadowRoot) {\n segment.shadowRoot.adoptedStyleSheets =\n segment.shadowRoot.adoptedStyleSheets.filter((s) => s !== sheet);\n }\n });\n }\n\n render() {\n // Set CSS variables in render() to ensure they're always set\n // This is necessary because Lit may clear inline styles during updates\n this.setCSSVariables();\n return html`${this.segmentText}`;\n }\n\n private setCSSVariables(): void {\n // Set deterministic --ef-seed value based on segment index\n const seed = (this.segmentIndex * 9007) % 233; // Prime numbers for better distribution\n const seedValue = seed / 233; // Normalize to 0-1 range\n this.style.setProperty(\"--ef-seed\", seedValue.toString());\n\n // Set stagger offset CSS variable\n // staggerOffsetMs is always set (defaults to 0), so we can always set the CSS variable\n const offsetMs = this.staggerOffsetMs ?? 0;\n this.style.setProperty(\"--ef-stagger-offset\", `${offsetMs}ms`);\n\n // Set index CSS variable\n this.style.setProperty(\"--ef-index\", this.segmentIndex.toString());\n }\n\n protected firstUpdated(): void {\n this.setCSSVariables();\n }\n\n protected updated(): void {\n this.setCSSVariables();\n }\n\n @property({ type: String, attribute: false })\n segmentText = \"\";\n\n @property({ type: Number, attribute: false })\n segmentIndex = 0;\n\n @property({ type: Number, attribute: false })\n staggerOffsetMs?: number;\n\n @property({ type: Number, attribute: false })\n segmentStartMs = 0;\n\n @property({ type: Number, attribute: false })\n segmentEndMs = 0;\n\n @property({ type: Boolean, reflect: true })\n hidden = false;\n\n get startTimeMs() {\n const parentText = this.closest(\"ef-text\") as EFText;\n const parentStartTime = parentText?.startTimeMs || 0;\n return parentStartTime + (this.segmentStartMs || 0);\n }\n\n get endTimeMs() {\n // Derive from parent's live durationMs rather than the snapshot stored in segmentEndMs.\n // This ensures segments track changes when the parent's duration updates\n // (e.g., a contain-mode timegroup whose duration changes after a video loads).\n const parentText = this.closest(\"ef-text\") as EFText;\n if (parentText) {\n return parentText.startTimeMs + parentText.durationMs;\n }\n return this.segmentEndMs || 0;\n }\n\n get durationMs(): number {\n const parentText = this.closest(\"ef-text\") as EFText;\n if (parentText) {\n return parentText.durationMs;\n }\n return this.segmentEndMs - this.segmentStartMs;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-text-segment\": EFTextSegment;\n }\n}\n"],"mappings":";;;;;;AAMA,MAAM,wCAAwB,IAAI,KAA4B;AAGvD,0BAAMA,wBAAsB,WAAW,WAAW,CAAC;;;qBA+G1C;sBAGC;wBAME;sBAGF;gBAGN;;;gBA7HO,CACd,GAAG;;;;;;;;;;;;;;MAeJ;;;;;;;;;;;;;;;;;;;;CAoBD,OAAO,mBAAmB,IAAY,SAAuB;AAC3D,MAAI,sBAAsB,IAAI,GAAG,CAE/B;EAGF,MAAM,QAAQ,IAAI,eAAe;AACjC,QAAM,YAAY,QAAQ;AAC1B,wBAAsB,IAAI,IAAI,MAAM;AAGpC,WAAS,iBAAiB,kBAAkB,CAAC,SAAS,YAAY;AAChE,OAAI,QAAQ,YAAY;IACtB,MAAM,gBAAgB,QAAQ,WAAW;AACzC,QAAI,CAAC,cAAc,SAAS,MAAM,CAChC,SAAQ,WAAW,qBAAqB,CAAC,GAAG,eAAe,MAAM;;IAGrE;;;;;;;CAQJ,OAAO,qBAAqB,IAAkB;EAC5C,MAAM,QAAQ,sBAAsB,IAAI,GAAG;AAC3C,MAAI,CAAC,MACH;AAGF,wBAAsB,OAAO,GAAG;AAGhC,WAAS,iBAAiB,kBAAkB,CAAC,SAAS,YAAY;AAChE,OAAI,QAAQ,WACV,SAAQ,WAAW,qBACjB,QAAQ,WAAW,mBAAmB,QAAQ,MAAM,MAAM,MAAM;IAEpE;;CAGJ,SAAS;AAGP,OAAK,iBAAiB;AACtB,SAAO,IAAI,GAAG,KAAK;;CAGrB,AAAQ,kBAAwB;EAG9B,MAAM,YADQ,KAAK,eAAe,OAAQ,MACjB;AACzB,OAAK,MAAM,YAAY,aAAa,UAAU,UAAU,CAAC;EAIzD,MAAM,WAAW,KAAK,mBAAmB;AACzC,OAAK,MAAM,YAAY,uBAAuB,GAAG,SAAS,IAAI;AAG9D,OAAK,MAAM,YAAY,cAAc,KAAK,aAAa,UAAU,CAAC;;CAGpE,AAAU,eAAqB;AAC7B,OAAK,iBAAiB;;CAGxB,AAAU,UAAgB;AACxB,OAAK,iBAAiB;;CAqBxB,IAAI,cAAc;AAGhB,UAFmB,KAAK,QAAQ,UAAU,EACN,eAAe,MACzB,KAAK,kBAAkB;;CAGnD,IAAI,YAAY;EAId,MAAM,aAAa,KAAK,QAAQ,UAAU;AAC1C,MAAI,WACF,QAAO,WAAW,cAAc,WAAW;AAE7C,SAAO,KAAK,gBAAgB;;CAG9B,IAAI,aAAqB;EACvB,MAAM,aAAa,KAAK,QAAQ,UAAU;AAC1C,MAAI,WACF,QAAO,WAAW;AAEpB,SAAO,KAAK,eAAe,KAAK;;;YAxCjC,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAG5C,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAG5C,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAG5C,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAG5C,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAG5C,SAAS;CAAE,MAAM;CAAS,SAAS;CAAM,CAAC;4BA9H5C,cAAc,kBAAkB"}
@@ -423,7 +423,7 @@ const validateAnimationFillMode = (animation, timing) => {
423
423
  if (fadePattern === "fade-out" && fill !== "forwards" && fill !== "both") warnings.push(`⚠️ Animation "${animationName}" modifies final state but lacks 'forwards' fill-mode.`, ` The element will snap back to its natural state after the animation completes.`, ` Fix: Add 'forwards' or 'both' to the animation.`, ` Example: animation: ${animationName} ${timing.duration}ms forwards;`);
424
424
  if (fadePattern === "both" && fill !== "both") warnings.push(`⚠️ Animation "${animationName}" modifies both initial and final state but doesn't use 'both' fill-mode.`, ` Fix: Use 'both' to apply initial and final states.`, ` Example: animation: ${animationName} ${timing.duration}ms both;`);
425
425
  } catch (e) {}
426
- if (warnings.length > 0 && typeof window !== "undefined" && window.__EDITFRAME_FILL_MODE_WARNINGS__) {
426
+ if (warnings.length > 0 && typeof window !== "undefined") {
427
427
  console.groupCollapsed("%c🎬 Editframe Animation Fill-Mode Warning", "color: #f59e0b; font-weight: bold");
428
428
  warnings.forEach((warning) => console.log(warning));
429
429
  console.log("\n📚 Learn more: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode");
@@ -1 +1 @@
1
- {"version":3,"file":"updateAnimations.js","names":["warnings: string[]","timeSource: 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,QA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SAAS;AAC/D,MAAI,CAAC,UAAU,EAAE,kBAAkB,SAAU;EAE7C,IAAIF,OAAuB;AAC3B,SAAO,MAAM;AACX,OAAI,YAAY,IAAI,KAAK,EAAE;IACzB,IAAI,QAAQ,gBAAgB,IAAI,KAA0B;AAC1D,QAAI,CAAC,OAAO;AACV,aAAQ,EAAE;AACV,qBAAgB,IAAI,MAA2B,MAAM;;AAEvD,UAAM,KAAK,UAAU;AACrB;;AAEF,UAAO,KAAK;;;AAOhB,4BACE,YAAY,SACZ,YAAY,MAAM,OAClB,cACD;AACD,MAAK,MAAM,WAAW,qBACpB,4BACE,QAAQ,SACR,QAAQ,MAAM,OACd,gBAAgB,IAAI,QAAQ,QAAQ,IAAI,EAAE,CAC3C;AAIH,kBAAiB,YAAY,SAAS,YAAY,MAAM;AACxD,MAAK,MAAM,WAAW,cACpB,kBAAiB,QAAQ,SAAS,QAAQ,MAAM;AAIlD,0BAAyB,QAAQ;AACjC,0BAAyB,QAAQ"}
1
+ {"version":3,"file":"updateAnimations.js","names":["warnings: string[]","timeSource: 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 (warnings.length > 0 && typeof window !== \"undefined\") {\n console.groupCollapsed(\n \"%c🎬 Editframe Animation Fill-Mode Warning\",\n \"color: #f59e0b; font-weight: bold\",\n );\n warnings.forEach((warning) => console.log(warning));\n console.log(\n \"\\n📚 Learn more: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode\",\n );\n console.groupEnd();\n }\n};\n\n/**\n * Prepares animation for manual control 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;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aAAY,IAAI,QAAQ;CACxB,MAAM,kCAAkB,IAAI,KAAqC;AACjE,MAAK,MAAM,aAAa,eAAe;EACrC,MAAM,SAAS,UAAU;EACzB,MAAM,SACJ,UAAU,kBAAkB,iBAAiB,OAAO,SAAS;AAC/D,MAAI,CAAC,UAAU,EAAE,kBAAkB,SAAU;EAE7C,IAAIF,OAAuB;AAC3B,SAAO,MAAM;AACX,OAAI,YAAY,IAAI,KAAK,EAAE;IACzB,IAAI,QAAQ,gBAAgB,IAAI,KAA0B;AAC1D,QAAI,CAAC,OAAO;AACV,aAAQ,EAAE;AACV,qBAAgB,IAAI,MAA2B,MAAM;;AAEvD,UAAM,KAAK,UAAU;AACrB;;AAEF,UAAO,KAAK;;;AAOhB,4BACE,YAAY,SACZ,YAAY,MAAM,OAClB,cACD;AACD,MAAK,MAAM,WAAW,qBACpB,4BACE,QAAQ,SACR,QAAQ,MAAM,OACd,gBAAgB,IAAI,QAAQ,QAAQ,IAAI,EAAE,CAC3C;AAIH,kBAAiB,YAAY,SAAS,YAAY,MAAM;AACxD,MAAK,MAAM,WAAW,cACpB,kBAAiB,QAAQ,SAAS,QAAQ,MAAM;AAIlD,0BAAyB,QAAQ;AACjC,0BAAyB,QAAQ"}
@@ -368,6 +368,13 @@ function ContextMixin(superClass) {
368
368
  return;
369
369
  }
370
370
  }
371
+ try {
372
+ const audioContext = new AudioContext({ latencyHint: "playback" });
373
+ audioContext.resume();
374
+ this.targetTemporal.playbackController.setPendingAudioContext(audioContext);
375
+ } catch (error) {
376
+ console.warn("Failed to create/resume AudioContext synchronously:", error);
377
+ }
371
378
  this.targetTemporal.playbackController.play();
372
379
  }
373
380
  pause() {
@@ -1 +1 @@
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,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;;AAGJ,QACE,CAAC,cAAc,IACf,KAAK,cACL,cAAc,KAAK,OAAO,SAAS,OAAO,EAC1C;KACA,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,KA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,MAAM;;EAG/C,QAAQ;AACN,OAAI,KAAK,gBAAgB,mBACvB,MAAK,eAAe,mBAAmB,OAAO;;;aA1mBjD,QAAQ;EAAE,SAAS;EAAwB,WAAW;EAAM,CAAC;aAG7D,QAAQ,EAAE,SAAS,cAAc,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;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
+ {"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 try {\n const audioContext = new AudioContext({ latencyHint: \"playback\" });\n audioContext.resume();\n this.targetTemporal.playbackController.setPendingAudioContext(\n audioContext,\n );\n } catch (error) {\n console.warn(\n \"Failed to create/resume AudioContext synchronously:\",\n error,\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,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;;AAGJ,QACE,CAAC,cAAc,IACf,KAAK,cACL,cAAc,KAAK,OAAO,SAAS,OAAO,EAC1C;KACA,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,C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AK,eAAe,mBAAmB,MAAM;;EAG/C,QAAQ;AACN,OAAI,KAAK,gBAAgB,mBACvB,MAAK,eAAe,mBAAmB,OAAO;;;aAvnBjD,QAAQ;EAAE,SAAS;EAAwB,WAAW;EAAM,CAAC;aAG7D,QAAQ,EAAE,SAAS,cAAc,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;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;AAgR7B,QAAO"}
@@ -40,6 +40,7 @@ var PlaybackController = class {
40
40
  #loopingPlayback = false;
41
41
  #playbackWrapTimeSeconds = 0;
42
42
  #seekAbortController = null;
43
+ #hasConnected = false;
43
44
  constructor(host) {
44
45
  this.#host = host;
45
46
  host.addController(this);
@@ -180,11 +181,13 @@ var PlaybackController = class {
180
181
  }
181
182
  #removed = false;
182
183
  hostConnected() {
184
+ const isReconnect = this.#hasConnected;
185
+ this.#hasConnected = true;
183
186
  requestAnimationFrame(() => {
184
187
  requestAnimationFrame(() => {
185
188
  if (this.#removed || this.#host.playbackController !== this) return;
186
- if (this.#playing) this.startPlayback();
187
- else this.#initializeTime();
189
+ if (this.#playing && isReconnect) this.startPlayback();
190
+ else if (!this.#playing) this.#initializeTime();
188
191
  });
189
192
  });
190
193
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PlaybackController.js","names":["#FPS","#host","#playingProvider","#playing","#loopProvider","#loop","#currentTimeMsProvider","#durationMsProvider","#currentTime","#processingPendingSeek","#pendingSeekTime","#seekInProgress","#runSeek","#seekAbortController","#notifyListeners","#removed","#initializeTime","#selfRenderSuspended","#selfRenderAbortController","#selfRenderPromise","#selfRenderDirty","#startSelfRender","#listeners","#pendingAudioContext","#playbackAudioContext","rawTimeMs: number","#playbackWrapTimeSeconds","#loopingPlayback","#MS_PER_FRAME","#updatePlaybackTime","#playbackAnimationFrameRequest","#syncPlayheadToAudioContext","#AUDIO_PLAYBACK_SLICE_MS"],"sources":["../../src/gui/PlaybackController.ts"],"sourcesContent":["import { ContextProvider } from \"@lit/context\";\nimport type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { currentTimeContext } from \"./currentTimeContext.js\";\nimport { durationContext } from \"./durationContext.js\";\nimport { loopContext, playingContext } from \"./playingContext.js\";\nimport {\n updateAnimations,\n type AnimatableElement,\n} from \"../elements/updateAnimations.js\";\nimport type {\n RenderFrameOptions,\n FrameRenderable,\n} from \"../preview/FrameController.js\";\n\ninterface PlaybackHost extends HTMLElement, ReactiveControllerHost {\n currentTimeMs: number;\n durationMs: number;\n endTimeMs: number;\n /** Centralized frame controller (present on EFTimegroup) */\n frameController?: {\n renderFrame(timeMs: number, options?: RenderFrameOptions): Promise<void>;\n abort(): void;\n };\n renderAudio?(fromMs: number, toMs: number): Promise<AudioBuffer>;\n waitForMediaDurations?(signal?: AbortSignal): Promise<void>;\n saveTimeToLocalStorage?(time: number): void;\n loadTimeFromLocalStorage?(): number | undefined;\n requestUpdate(property?: string): void;\n updateComplete: Promise<boolean>;\n playing: boolean;\n loop: boolean;\n play(): void;\n pause(): void;\n playbackController?: PlaybackController;\n parentTimegroup?: any;\n rootTimegroup?: any;\n}\n\nexport type PlaybackControllerUpdateEvent = {\n property: \"playing\" | \"loop\" | \"currentTimeMs\";\n value: boolean | number;\n};\n\n/**\n * Manages playback state and audio-driven timing for root temporal elements\n *\n * Created automatically when a temporal element becomes a root (no parent timegroup)\n * Provides playback contexts (playing, loop, currentTimeMs, durationMs) to descendants\n * Handles:\n * - Audio-driven playback with Web Audio API\n * - Seek and frame rendering throttling\n * - Time state management with pending seek handling\n * - Playback loop behavior\n *\n * Works with any temporal element (timegroups or standalone media) via PlaybackHost interface\n */\nexport class PlaybackController implements ReactiveController {\n #host: PlaybackHost;\n #playing = false;\n #loop = false;\n #listeners = new Set<(event: PlaybackControllerUpdateEvent) => void>();\n #playingProvider: ContextProvider<typeof playingContext>;\n #loopProvider: ContextProvider<typeof loopContext>;\n #currentTimeMsProvider: ContextProvider<typeof currentTimeContext>;\n #durationMsProvider: ContextProvider<typeof durationContext>;\n\n #FPS = 30;\n #MS_PER_FRAME = 1000 / this.#FPS;\n #playbackAudioContext: AudioContext | null = null;\n #playbackAnimationFrameRequest: number | null = null;\n #pendingAudioContext: AudioContext | null = null;\n #AUDIO_PLAYBACK_SLICE_MS = ((47 * 1024) / 48000) * 1000;\n\n #currentTime: number | undefined = undefined;\n #seekInProgress = false;\n #pendingSeekTime: number | undefined;\n #processingPendingSeek = false;\n #loopingPlayback = false; // Track if we're in a looping playback session\n #playbackWrapTimeSeconds = 0; // The AudioContext time when we wrapped\n\n #seekAbortController: AbortController | null = null;\n\n constructor(host: PlaybackHost) {\n this.#host = host;\n host.addController(this);\n\n this.#playingProvider = new ContextProvider(host, {\n context: playingContext,\n initialValue: this.#playing,\n });\n this.#loopProvider = new ContextProvider(host, {\n context: loopContext,\n initialValue: this.#loop,\n });\n this.#currentTimeMsProvider = new ContextProvider(host, {\n context: currentTimeContext,\n initialValue: host.currentTimeMs,\n });\n this.#durationMsProvider = new ContextProvider(host, {\n context: durationContext,\n initialValue: host.durationMs,\n });\n }\n\n get currentTime(): number {\n const rawTime = this.#currentTime ?? 0;\n // Quantize to frame boundaries based on host's fps\n const fps = (this.#host as any).fps ?? 30;\n if (!fps || fps <= 0) return rawTime;\n const frameDurationS = 1 / fps;\n const quantizedTime = Math.round(rawTime / frameDurationS) * frameDurationS;\n // Clamp to valid range after quantization to prevent exceeding duration\n const durationS = this.#host.durationMs / 1000;\n return Math.max(0, Math.min(quantizedTime, durationS));\n }\n\n set currentTime(time: number) {\n time = Math.max(0, Math.min(this.#host.durationMs / 1000, time));\n if (Number.isNaN(time)) {\n return;\n }\n if (time === this.#currentTime && !this.#processingPendingSeek) {\n return;\n }\n if (this.#pendingSeekTime === time) {\n return;\n }\n\n if (this.#seekInProgress) {\n this.#pendingSeekTime = time;\n this.#currentTime = time;\n return;\n }\n\n this.#currentTime = time;\n this.#seekInProgress = true;\n\n this.#runSeek(time).finally(async () => {\n // CRITICAL: Coordinate animations after seek completes\n // This ensures animations are positioned correctly, not playing naturally\n const { updateAnimations } =\n await import(\"../elements/updateAnimations.js\");\n updateAnimations(this.#host as any);\n\n if (\n this.#pendingSeekTime !== undefined &&\n this.#pendingSeekTime !== time\n ) {\n const pendingTime = this.#pendingSeekTime;\n this.#pendingSeekTime = undefined;\n this.#processingPendingSeek = true;\n try {\n this.currentTime = pendingTime;\n } finally {\n this.#processingPendingSeek = false;\n }\n } else {\n this.#pendingSeekTime = undefined;\n }\n });\n }\n\n async #runSeek(targetTime: number): Promise<number | undefined> {\n // Abort any in-flight seek\n this.#seekAbortController?.abort();\n this.#seekAbortController = new AbortController();\n const signal = this.#seekAbortController.signal;\n\n try {\n signal.throwIfAborted();\n\n await this.#host.waitForMediaDurations?.(signal);\n signal.throwIfAborted();\n\n const newTime = Math.max(\n 0,\n Math.min(targetTime, this.#host.durationMs / 1000),\n );\n this.#currentTime = newTime;\n this.#host.requestUpdate(\"currentTime\");\n this.#currentTimeMsProvider.setValue(this.currentTimeMs);\n this.#notifyListeners({\n property: \"currentTimeMs\",\n value: this.currentTimeMs,\n });\n\n signal.throwIfAborted();\n\n await this.runThrottledFrameTask();\n signal.throwIfAborted();\n\n // Save to localStorage for persistence (only if not restoring to avoid loops)\n const isRestoring =\n (this.#host as any).isRestoringFromLocalStorage?.() ?? false;\n if (!isRestoring) {\n this.#host.saveTimeToLocalStorage?.(newTime);\n } else {\n (this.#host as any).setRestoringFromLocalStorage?.(false);\n }\n this.#seekInProgress = false;\n return newTime;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n // Expected - don't log\n return undefined;\n }\n throw error;\n }\n }\n\n get playing(): boolean {\n return this.#playing;\n }\n\n setPlaying(value: boolean): void {\n if (this.#playing === value) return;\n this.#playing = value;\n this.#playingProvider.setValue(value);\n this.#host.requestUpdate(\"playing\");\n this.#notifyListeners({ property: \"playing\", value });\n\n if (value) {\n this.startPlayback();\n } else {\n this.stopPlayback();\n }\n }\n\n get loop(): boolean {\n return this.#loop;\n }\n\n setLoop(value: boolean): void {\n if (this.#loop === value) return;\n this.#loop = value;\n this.#loopProvider.setValue(value);\n this.#host.requestUpdate(\"loop\");\n this.#notifyListeners({ property: \"loop\", value });\n }\n\n get currentTimeMs(): number {\n return this.currentTime * 1000;\n }\n\n setCurrentTimeMs(value: number): void {\n this.currentTime = value / 1000;\n }\n\n // Update time during playback without triggering a seek\n // Used by #syncPlayheadToAudioContext to avoid frame drops\n #updatePlaybackTime(timeMs: number): void {\n // Clamp to valid range to prevent time exceeding duration\n const durationMs = this.#host.durationMs;\n const clampedTimeMs = Math.max(0, Math.min(timeMs, durationMs));\n const timeSec = clampedTimeMs / 1000;\n if (this.#currentTime === timeSec) {\n return;\n }\n this.#currentTime = timeSec;\n this.#host.requestUpdate(\"currentTime\");\n this.#currentTimeMsProvider.setValue(clampedTimeMs);\n this.#notifyListeners({\n property: \"currentTimeMs\",\n value: clampedTimeMs,\n });\n // Trigger frame rendering without the async seek mechanism\n this.runThrottledFrameTask();\n }\n\n play(): void {\n this.setPlaying(true);\n }\n\n pause(): void {\n this.setPlaying(false);\n }\n\n #removed = false;\n\n hostConnected(): void {\n // Defer all operations to avoid blocking during initialization\n // This prevents deadlocks when many timegroups are initializing simultaneously\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Check if this controller was removed before the RAF callback executed.\n // This happens when wrapWithWorkbench moves the element, causing disconnect/reconnect.\n if (this.#removed || this.#host.playbackController !== this) {\n return;\n }\n\n if (this.#playing) {\n this.startPlayback();\n } else {\n this.#initializeTime();\n }\n });\n });\n }\n\n async #initializeTime(): Promise<void> {\n try {\n const waitPromise = this.#host.waitForMediaDurations?.();\n if (waitPromise) {\n await waitPromise;\n }\n } catch (err) {\n const isAbortError =\n (err instanceof DOMException && err.name === \"AbortError\") ||\n (err instanceof Error &&\n (err.name === \"AbortError\" ||\n err.message.includes(\"signal is aborted\") ||\n err.message.includes(\"The user aborted a request\")));\n if (!isAbortError) {\n console.error(\"Error in PlaybackController hostConnected:\", err);\n }\n return;\n }\n\n if (this.#removed || this.#host.playbackController !== this) {\n return;\n }\n\n const maybeLoadedTime = this.#host.loadTimeFromLocalStorage?.();\n if (maybeLoadedTime !== undefined) {\n (this.#host as any).setRestoringFromLocalStorage?.(true);\n this.currentTime = maybeLoadedTime;\n } else if (this.#currentTime === undefined) {\n this.currentTime = 0;\n }\n }\n\n hostDisconnected(): void {\n this.pause();\n }\n\n hostUpdated(): void {\n this.#durationMsProvider.setValue(this.#host.durationMs);\n this.#currentTimeMsProvider.setValue(this.currentTimeMs);\n }\n\n #selfRenderAbortController?: AbortController;\n #selfRenderPromise?: Promise<void>;\n #selfRenderDirty = false;\n #selfRenderSuspended = false;\n\n suspendSelfRender(): void {\n this.#selfRenderSuspended = true;\n this.#selfRenderAbortController?.abort();\n this.#selfRenderAbortController = undefined;\n }\n\n resumeSelfRender(): void {\n this.#selfRenderSuspended = false;\n }\n\n /**\n * Run frame rendering via FrameController, or directly on the host if it\n * implements FrameRenderable (standalone media element without a Timegroup).\n */\n async runThrottledFrameTask(): Promise<void> {\n const timeMs = this.currentTimeMs;\n\n if (this.#host.frameController) {\n try {\n await this.#host.frameController.renderFrame(timeMs, {\n onAnimationsUpdate: (root: Element) => {\n updateAnimations(root as unknown as AnimatableElement);\n },\n });\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\")\n return;\n console.error(\"FrameController error:\", error);\n }\n return;\n }\n\n // Standalone FrameRenderable host (e.g. bare ef-video without a Timegroup)\n const host = this.#host as unknown as Partial<FrameRenderable>;\n if (!host.prepareFrame || !host.renderFrame) return;\n\n if (this.#selfRenderSuspended) return;\n\n // If a render is in-flight, mark dirty so we re-render after it\n // completes (source mapping may have changed due to trim drag).\n if (this.#selfRenderPromise) {\n this.#selfRenderDirty = true;\n return this.#selfRenderPromise;\n }\n\n return this.#startSelfRender(host, timeMs);\n }\n\n #startSelfRender(\n host: Partial<FrameRenderable>,\n timeMs: number,\n ): Promise<void> {\n this.#selfRenderAbortController?.abort();\n this.#selfRenderAbortController = new AbortController();\n const signal = this.#selfRenderAbortController.signal;\n this.#selfRenderDirty = false;\n\n this.#selfRenderPromise = (async () => {\n try {\n await host.prepareFrame!(timeMs, signal);\n signal.throwIfAborted();\n host.renderFrame!(timeMs);\n updateAnimations(this.#host as unknown as AnimatableElement);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\")\n return;\n if ((error as any)?.name === \"AbortError\") return;\n console.error(\"Standalone frame render error:\", error);\n } finally {\n this.#selfRenderPromise = undefined;\n // Re-render if source mapping changed while we were rendering\n if (this.#selfRenderDirty && !this.#selfRenderSuspended) {\n this.#startSelfRender(host, this.currentTimeMs);\n }\n }\n })();\n\n return this.#selfRenderPromise;\n }\n\n addListener(listener: (event: PlaybackControllerUpdateEvent) => void): void {\n this.#listeners.add(listener);\n }\n\n removeListener(\n listener: (event: PlaybackControllerUpdateEvent) => void,\n ): void {\n this.#listeners.delete(listener);\n }\n\n #notifyListeners(event: PlaybackControllerUpdateEvent): void {\n for (const listener of this.#listeners) {\n listener(event);\n }\n }\n\n remove(): void {\n this.#removed = true; // Mark as removed to abort any pending RAF callbacks\n this.stopPlayback();\n this.#listeners.clear();\n this.#host.removeController(this);\n }\n\n setPendingAudioContext(context: AudioContext): void {\n this.#pendingAudioContext = context;\n }\n\n #syncPlayheadToAudioContext(startMs: number) {\n const audioContextTime = this.#playbackAudioContext?.currentTime ?? 0;\n const endMs = this.#host.endTimeMs;\n\n // Calculate raw time based on audio context\n let rawTimeMs: number;\n if (\n this.#playbackWrapTimeSeconds > 0 &&\n audioContextTime >= this.#playbackWrapTimeSeconds\n ) {\n // After wrap: time since wrap, wrapped to duration\n const timeSinceWrap =\n (audioContextTime - this.#playbackWrapTimeSeconds) * 1000;\n rawTimeMs = timeSinceWrap % endMs;\n } else {\n // Before wrap or no wrap: normal calculation\n rawTimeMs = startMs + audioContextTime * 1000;\n\n // If looping and we've reached the end, wrap around\n if (this.#loopingPlayback && rawTimeMs >= endMs) {\n rawTimeMs = rawTimeMs % endMs;\n }\n }\n\n const nextTimeMs =\n Math.round(rawTimeMs / this.#MS_PER_FRAME) * this.#MS_PER_FRAME;\n\n // During playback, update time directly without triggering seek\n // This avoids frame drops at the loop boundary\n this.#updatePlaybackTime(nextTimeMs);\n\n // Only check for end if we haven't already handled looping\n if (!this.#loopingPlayback && nextTimeMs >= endMs) {\n this.maybeLoopPlayback();\n return;\n }\n\n this.#playbackAnimationFrameRequest = requestAnimationFrame(() => {\n this.#syncPlayheadToAudioContext(startMs);\n });\n }\n\n private async maybeLoopPlayback() {\n if (this.#loop) {\n // Loop enabled: reset to beginning and restart playback\n // We restart the audio system directly without changing #playing state\n // to keep the play button in sync\n this.setCurrentTimeMs(0);\n // Restart in next frame without awaiting to minimize gap\n requestAnimationFrame(() => {\n this.startPlayback();\n });\n } else {\n // No loop: reset to beginning and stop\n // This ensures play button works when clicked again\n this.setCurrentTimeMs(0);\n this.pause();\n }\n }\n\n private async stopPlayback() {\n if (this.#playbackAudioContext) {\n if (this.#playbackAudioContext.state !== \"closed\") {\n await this.#playbackAudioContext.close();\n }\n }\n if (this.#playbackAnimationFrameRequest) {\n cancelAnimationFrame(this.#playbackAnimationFrameRequest);\n }\n this.#playbackAudioContext = null;\n this.#playbackAnimationFrameRequest = null;\n this.#pendingAudioContext = null;\n }\n\n private async startPlayback() {\n // Guard against starting playback on a removed controller\n if (this.#removed) {\n return;\n }\n\n await this.stopPlayback();\n const host = this.#host;\n if (!host) {\n return;\n }\n\n if (host.waitForMediaDurations) {\n await host.waitForMediaDurations();\n }\n\n // Check again after async - controller could have been removed\n if (this.#removed) {\n return;\n }\n\n const currentMs = this.currentTimeMs;\n const fromMs = currentMs;\n const toMs = host.endTimeMs;\n\n if (fromMs >= toMs) {\n this.pause();\n return;\n }\n\n let bufferCount = 0;\n // Check for pre-resumed AudioContext from synchronous user interaction\n if (this.#pendingAudioContext) {\n this.#playbackAudioContext = this.#pendingAudioContext;\n this.#pendingAudioContext = null;\n } else {\n this.#playbackAudioContext = new AudioContext({\n latencyHint: \"playback\",\n });\n }\n this.#loopingPlayback = this.#loop; // Remember if we're in a looping session\n this.#playbackWrapTimeSeconds = 0; // Reset wrap time\n\n if (this.#playbackAnimationFrameRequest) {\n cancelAnimationFrame(this.#playbackAnimationFrameRequest);\n }\n this.#syncPlayheadToAudioContext(currentMs);\n const playbackContext = this.#playbackAudioContext;\n\n // Check if context is suspended (fallback for newly-created contexts)\n if (playbackContext.state === \"suspended\") {\n // Attempt to resume (may not work on mobile if user interaction context is lost)\n try {\n await playbackContext.resume();\n // Check state again after resume attempt\n if (playbackContext.state === \"suspended\") {\n console.warn(\n \"AudioContext is suspended and resume() failed. \" +\n \"On mobile devices, AudioContext.resume() must be called synchronously within a user interaction handler. \" +\n \"Media playback will not work until user has interacted with page.\",\n );\n this.setPlaying(false);\n return;\n }\n } catch (error) {\n console.warn(\n \"Failed to resume AudioContext:\",\n error,\n \"On mobile devices, AudioContext.resume() must be called synchronously within a user interaction handler.\",\n );\n this.setPlaying(false);\n return;\n }\n }\n await playbackContext.suspend();\n\n // Track the logical media time (what position in the media we're rendering)\n // vs the AudioContext schedule time (when to play it)\n let logicalTimeMs = currentMs;\n let audioContextTimeMs = 0; // Tracks the schedule position in the AudioContext timeline\n let hasWrapped = false;\n\n const fillBuffer = async () => {\n if (bufferCount > 2) {\n return;\n }\n const canFillBuffer = await queueBufferSource();\n if (canFillBuffer) {\n fillBuffer().catch(() => {});\n }\n };\n\n const queueBufferSource = async () => {\n // Check if we've already wrapped and aren't looping anymore\n if (hasWrapped && !this.#loopingPlayback) {\n return false;\n }\n\n const startMs = logicalTimeMs;\n const endMs = Math.min(\n logicalTimeMs + this.#AUDIO_PLAYBACK_SLICE_MS,\n toMs,\n );\n\n // Will this slice reach the end?\n const willReachEnd = endMs >= toMs;\n\n if (!host.renderAudio) {\n return false;\n }\n\n const audioBuffer = await host.renderAudio(startMs, endMs);\n bufferCount++;\n const source = playbackContext.createBufferSource();\n source.buffer = audioBuffer;\n source.connect(playbackContext.destination);\n // Schedule this buffer to play at the current audioContextTime position\n source.start(audioContextTimeMs / 1000);\n\n const sliceDurationMs = endMs - startMs;\n\n source.onended = () => {\n bufferCount--;\n\n if (willReachEnd) {\n if (!this.#loopingPlayback) {\n // Not looping, end playback\n this.maybeLoopPlayback();\n } else {\n // Looping: continue filling buffer after wrap\n fillBuffer().catch(() => {});\n }\n } else {\n // Continue filling buffer\n fillBuffer().catch(() => {});\n }\n };\n\n // Advance the AudioContext schedule time\n audioContextTimeMs += sliceDurationMs;\n\n // If this buffer reaches the end and we're looping, immediately queue the wraparound\n if (willReachEnd && this.#loopingPlayback) {\n // Mark that we've wrapped\n hasWrapped = true;\n // Store when we wrapped (relative to when playback started, which is time 0 in AudioContext)\n // This is the duration from start to end\n this.#playbackWrapTimeSeconds = (toMs - fromMs) / 1000;\n // Reset logical time to beginning\n logicalTimeMs = 0;\n // Continue buffering will happen in fillBuffer() call below\n } else {\n // Normal advance\n logicalTimeMs = endMs;\n }\n\n return true;\n };\n\n try {\n await fillBuffer();\n await playbackContext.resume();\n } catch (error) {\n // Ignore errors if AudioContext is closed or during test cleanup\n if (\n error instanceof Error &&\n (error.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,UAAU;AAElD,oBAAgB;SAIhB,iBAAgB;AAGlB,UAAO;;AAGT,MAAI;AACF,SAAM,YAAY;AAClB,SAAM,gBAAgB,QAAQ;WACvB,OAAO;AAEd,OACE,iBAAiB,UAChB,MAAM,SAAS,uBAAuB,MAAM,QAAQ,SAAS,SAAS,EAEvE;AAEF,SAAM"}
1
+ {"version":3,"file":"PlaybackController.js","names":["#FPS","#host","#playingProvider","#playing","#loopProvider","#loop","#currentTimeMsProvider","#durationMsProvider","#currentTime","#processingPendingSeek","#pendingSeekTime","#seekInProgress","#runSeek","#seekAbortController","#notifyListeners","#hasConnected","#removed","#initializeTime","#selfRenderSuspended","#selfRenderAbortController","#selfRenderPromise","#selfRenderDirty","#startSelfRender","#listeners","#pendingAudioContext","#playbackAudioContext","rawTimeMs: number","#playbackWrapTimeSeconds","#loopingPlayback","#MS_PER_FRAME","#updatePlaybackTime","#playbackAnimationFrameRequest","#syncPlayheadToAudioContext","#AUDIO_PLAYBACK_SLICE_MS"],"sources":["../../src/gui/PlaybackController.ts"],"sourcesContent":["import { ContextProvider } from \"@lit/context\";\nimport type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { currentTimeContext } from \"./currentTimeContext.js\";\nimport { durationContext } from \"./durationContext.js\";\nimport { loopContext, playingContext } from \"./playingContext.js\";\nimport {\n updateAnimations,\n type AnimatableElement,\n} from \"../elements/updateAnimations.js\";\nimport type {\n RenderFrameOptions,\n FrameRenderable,\n} from \"../preview/FrameController.js\";\n\ninterface PlaybackHost extends HTMLElement, ReactiveControllerHost {\n currentTimeMs: number;\n durationMs: number;\n endTimeMs: number;\n /** Centralized frame controller (present on EFTimegroup) */\n frameController?: {\n renderFrame(timeMs: number, options?: RenderFrameOptions): Promise<void>;\n abort(): void;\n };\n renderAudio?(fromMs: number, toMs: number): Promise<AudioBuffer>;\n waitForMediaDurations?(signal?: AbortSignal): Promise<void>;\n saveTimeToLocalStorage?(time: number): void;\n loadTimeFromLocalStorage?(): number | undefined;\n requestUpdate(property?: string): void;\n updateComplete: Promise<boolean>;\n playing: boolean;\n loop: boolean;\n play(): void;\n pause(): void;\n playbackController?: PlaybackController;\n parentTimegroup?: any;\n rootTimegroup?: any;\n}\n\nexport type PlaybackControllerUpdateEvent = {\n property: \"playing\" | \"loop\" | \"currentTimeMs\";\n value: boolean | number;\n};\n\n/**\n * Manages playback state and audio-driven timing for root temporal elements\n *\n * Created automatically when a temporal element becomes a root (no parent timegroup)\n * Provides playback contexts (playing, loop, currentTimeMs, durationMs) to descendants\n * Handles:\n * - Audio-driven playback with Web Audio API\n * - Seek and frame rendering throttling\n * - Time state management with pending seek handling\n * - Playback loop behavior\n *\n * Works with any temporal element (timegroups or standalone media) via PlaybackHost interface\n */\nexport class PlaybackController implements ReactiveController {\n #host: PlaybackHost;\n #playing = false;\n #loop = false;\n #listeners = new Set<(event: PlaybackControllerUpdateEvent) => void>();\n #playingProvider: ContextProvider<typeof playingContext>;\n #loopProvider: ContextProvider<typeof loopContext>;\n #currentTimeMsProvider: ContextProvider<typeof currentTimeContext>;\n #durationMsProvider: ContextProvider<typeof durationContext>;\n\n #FPS = 30;\n #MS_PER_FRAME = 1000 / this.#FPS;\n #playbackAudioContext: AudioContext | null = null;\n #playbackAnimationFrameRequest: number | null = null;\n #pendingAudioContext: AudioContext | null = null;\n #AUDIO_PLAYBACK_SLICE_MS = ((47 * 1024) / 48000) * 1000;\n\n #currentTime: number | undefined = undefined;\n #seekInProgress = false;\n #pendingSeekTime: number | undefined;\n #processingPendingSeek = false;\n #loopingPlayback = false; // Track if we're in a looping playback session\n #playbackWrapTimeSeconds = 0; // The AudioContext time when we wrapped\n\n #seekAbortController: AbortController | null = null;\n #hasConnected = false;\n\n constructor(host: PlaybackHost) {\n this.#host = host;\n host.addController(this);\n\n this.#playingProvider = new ContextProvider(host, {\n context: playingContext,\n initialValue: this.#playing,\n });\n this.#loopProvider = new ContextProvider(host, {\n context: loopContext,\n initialValue: this.#loop,\n });\n this.#currentTimeMsProvider = new ContextProvider(host, {\n context: currentTimeContext,\n initialValue: host.currentTimeMs,\n });\n this.#durationMsProvider = new ContextProvider(host, {\n context: durationContext,\n initialValue: host.durationMs,\n });\n }\n\n get currentTime(): number {\n const rawTime = this.#currentTime ?? 0;\n // Quantize to frame boundaries based on host's fps\n const fps = (this.#host as any).fps ?? 30;\n if (!fps || fps <= 0) return rawTime;\n const frameDurationS = 1 / fps;\n const quantizedTime = Math.round(rawTime / frameDurationS) * frameDurationS;\n // Clamp to valid range after quantization to prevent exceeding duration\n const durationS = this.#host.durationMs / 1000;\n return Math.max(0, Math.min(quantizedTime, durationS));\n }\n\n set currentTime(time: number) {\n time = Math.max(0, Math.min(this.#host.durationMs / 1000, time));\n if (Number.isNaN(time)) {\n return;\n }\n if (time === this.#currentTime && !this.#processingPendingSeek) {\n return;\n }\n if (this.#pendingSeekTime === time) {\n return;\n }\n\n if (this.#seekInProgress) {\n this.#pendingSeekTime = time;\n this.#currentTime = time;\n return;\n }\n\n this.#currentTime = time;\n this.#seekInProgress = true;\n\n this.#runSeek(time).finally(async () => {\n // CRITICAL: Coordinate animations after seek completes\n // This ensures animations are positioned correctly, not playing naturally\n const { updateAnimations } =\n await import(\"../elements/updateAnimations.js\");\n updateAnimations(this.#host as any);\n\n if (\n this.#pendingSeekTime !== undefined &&\n this.#pendingSeekTime !== time\n ) {\n const pendingTime = this.#pendingSeekTime;\n this.#pendingSeekTime = undefined;\n this.#processingPendingSeek = true;\n try {\n this.currentTime = pendingTime;\n } finally {\n this.#processingPendingSeek = false;\n }\n } else {\n this.#pendingSeekTime = undefined;\n }\n });\n }\n\n async #runSeek(targetTime: number): Promise<number | undefined> {\n // Abort any in-flight seek\n this.#seekAbortController?.abort();\n this.#seekAbortController = new AbortController();\n const signal = this.#seekAbortController.signal;\n\n try {\n signal.throwIfAborted();\n\n await this.#host.waitForMediaDurations?.(signal);\n signal.throwIfAborted();\n\n const newTime = Math.max(\n 0,\n Math.min(targetTime, this.#host.durationMs / 1000),\n );\n this.#currentTime = newTime;\n this.#host.requestUpdate(\"currentTime\");\n this.#currentTimeMsProvider.setValue(this.currentTimeMs);\n this.#notifyListeners({\n property: \"currentTimeMs\",\n value: this.currentTimeMs,\n });\n\n signal.throwIfAborted();\n\n await this.runThrottledFrameTask();\n signal.throwIfAborted();\n\n // Save to localStorage for persistence (only if not restoring to avoid loops)\n const isRestoring =\n (this.#host as any).isRestoringFromLocalStorage?.() ?? false;\n if (!isRestoring) {\n this.#host.saveTimeToLocalStorage?.(newTime);\n } else {\n (this.#host as any).setRestoringFromLocalStorage?.(false);\n }\n this.#seekInProgress = false;\n return newTime;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n // Expected - don't log\n return undefined;\n }\n throw error;\n }\n }\n\n get playing(): boolean {\n return this.#playing;\n }\n\n setPlaying(value: boolean): void {\n if (this.#playing === value) return;\n this.#playing = value;\n this.#playingProvider.setValue(value);\n this.#host.requestUpdate(\"playing\");\n this.#notifyListeners({ property: \"playing\", value });\n\n if (value) {\n this.startPlayback();\n } else {\n this.stopPlayback();\n }\n }\n\n get loop(): boolean {\n return this.#loop;\n }\n\n setLoop(value: boolean): void {\n if (this.#loop === value) return;\n this.#loop = value;\n this.#loopProvider.setValue(value);\n this.#host.requestUpdate(\"loop\");\n this.#notifyListeners({ property: \"loop\", value });\n }\n\n get currentTimeMs(): number {\n return this.currentTime * 1000;\n }\n\n setCurrentTimeMs(value: number): void {\n this.currentTime = value / 1000;\n }\n\n // Update time during playback without triggering a seek\n // Used by #syncPlayheadToAudioContext to avoid frame drops\n #updatePlaybackTime(timeMs: number): void {\n // Clamp to valid range to prevent time exceeding duration\n const durationMs = this.#host.durationMs;\n const clampedTimeMs = Math.max(0, Math.min(timeMs, durationMs));\n const timeSec = clampedTimeMs / 1000;\n if (this.#currentTime === timeSec) {\n return;\n }\n this.#currentTime = timeSec;\n this.#host.requestUpdate(\"currentTime\");\n this.#currentTimeMsProvider.setValue(clampedTimeMs);\n this.#notifyListeners({\n property: \"currentTimeMs\",\n value: clampedTimeMs,\n });\n // Trigger frame rendering without the async seek mechanism\n this.runThrottledFrameTask();\n }\n\n play(): void {\n this.setPlaying(true);\n }\n\n pause(): void {\n this.setPlaying(false);\n }\n\n #removed = false;\n\n hostConnected(): void {\n const isReconnect = this.#hasConnected;\n this.#hasConnected = true;\n // Defer all operations to avoid blocking during initialization\n // This prevents deadlocks when many timegroups are initializing simultaneously\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Check if this controller was removed before the RAF callback executed.\n // This happens when wrapWithWorkbench moves the element, causing disconnect/reconnect.\n if (this.#removed || this.#host.playbackController !== this) {\n return;\n }\n\n if (this.#playing && isReconnect) {\n this.startPlayback();\n } else if (!this.#playing) {\n this.#initializeTime();\n }\n });\n });\n }\n\n async #initializeTime(): Promise<void> {\n try {\n const waitPromise = this.#host.waitForMediaDurations?.();\n if (waitPromise) {\n await waitPromise;\n }\n } catch (err) {\n const isAbortError =\n (err instanceof DOMException && err.name === \"AbortError\") ||\n (err instanceof Error &&\n (err.name === \"AbortError\" ||\n err.message.includes(\"signal is aborted\") ||\n err.message.includes(\"The user aborted a request\")));\n if (!isAbortError) {\n console.error(\"Error in PlaybackController hostConnected:\", err);\n }\n return;\n }\n\n if (this.#removed || this.#host.playbackController !== this) {\n return;\n }\n\n const maybeLoadedTime = this.#host.loadTimeFromLocalStorage?.();\n if (maybeLoadedTime !== undefined) {\n (this.#host as any).setRestoringFromLocalStorage?.(true);\n this.currentTime = maybeLoadedTime;\n } else if (this.#currentTime === undefined) {\n this.currentTime = 0;\n }\n }\n\n hostDisconnected(): void {\n this.pause();\n }\n\n hostUpdated(): void {\n this.#durationMsProvider.setValue(this.#host.durationMs);\n this.#currentTimeMsProvider.setValue(this.currentTimeMs);\n }\n\n #selfRenderAbortController?: AbortController;\n #selfRenderPromise?: Promise<void>;\n #selfRenderDirty = false;\n #selfRenderSuspended = false;\n\n suspendSelfRender(): void {\n this.#selfRenderSuspended = true;\n this.#selfRenderAbortController?.abort();\n this.#selfRenderAbortController = undefined;\n }\n\n resumeSelfRender(): void {\n this.#selfRenderSuspended = false;\n }\n\n /**\n * Run frame rendering via FrameController, or directly on the host if it\n * implements FrameRenderable (standalone media element without a Timegroup).\n */\n async runThrottledFrameTask(): Promise<void> {\n const timeMs = this.currentTimeMs;\n\n if (this.#host.frameController) {\n try {\n await this.#host.frameController.renderFrame(timeMs, {\n onAnimationsUpdate: (root: Element) => {\n updateAnimations(root as unknown as AnimatableElement);\n },\n });\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\")\n return;\n console.error(\"FrameController error:\", error);\n }\n return;\n }\n\n // Standalone FrameRenderable host (e.g. bare ef-video without a Timegroup)\n const host = this.#host as unknown as Partial<FrameRenderable>;\n if (!host.prepareFrame || !host.renderFrame) return;\n\n if (this.#selfRenderSuspended) return;\n\n // If a render is in-flight, mark dirty so we re-render after it\n // completes (source mapping may have changed due to trim drag).\n if (this.#selfRenderPromise) {\n this.#selfRenderDirty = true;\n return this.#selfRenderPromise;\n }\n\n return this.#startSelfRender(host, timeMs);\n }\n\n #startSelfRender(\n host: Partial<FrameRenderable>,\n timeMs: number,\n ): Promise<void> {\n this.#selfRenderAbortController?.abort();\n this.#selfRenderAbortController = new AbortController();\n const signal = this.#selfRenderAbortController.signal;\n this.#selfRenderDirty = false;\n\n this.#selfRenderPromise = (async () => {\n try {\n await host.prepareFrame!(timeMs, signal);\n signal.throwIfAborted();\n host.renderFrame!(timeMs);\n updateAnimations(this.#host as unknown as AnimatableElement);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\")\n return;\n if ((error as any)?.name === \"AbortError\") return;\n console.error(\"Standalone frame render error:\", error);\n } finally {\n this.#selfRenderPromise = undefined;\n // Re-render if source mapping changed while we were rendering\n if (this.#selfRenderDirty && !this.#selfRenderSuspended) {\n this.#startSelfRender(host, this.currentTimeMs);\n }\n }\n })();\n\n return this.#selfRenderPromise;\n }\n\n addListener(listener: (event: PlaybackControllerUpdateEvent) => void): void {\n this.#listeners.add(listener);\n }\n\n removeListener(\n listener: (event: PlaybackControllerUpdateEvent) => void,\n ): void {\n this.#listeners.delete(listener);\n }\n\n #notifyListeners(event: PlaybackControllerUpdateEvent): void {\n for (const listener of this.#listeners) {\n listener(event);\n }\n }\n\n remove(): void {\n this.#removed = true; // Mark as removed to abort any pending RAF callbacks\n this.stopPlayback();\n this.#listeners.clear();\n this.#host.removeController(this);\n }\n\n setPendingAudioContext(context: AudioContext): void {\n this.#pendingAudioContext = context;\n }\n\n #syncPlayheadToAudioContext(startMs: number) {\n const audioContextTime = this.#playbackAudioContext?.currentTime ?? 0;\n const endMs = this.#host.endTimeMs;\n\n // Calculate raw time based on audio context\n let rawTimeMs: number;\n if (\n this.#playbackWrapTimeSeconds > 0 &&\n audioContextTime >= this.#playbackWrapTimeSeconds\n ) {\n // After wrap: time since wrap, wrapped to duration\n const timeSinceWrap =\n (audioContextTime - this.#playbackWrapTimeSeconds) * 1000;\n rawTimeMs = timeSinceWrap % endMs;\n } else {\n // Before wrap or no wrap: normal calculation\n rawTimeMs = startMs + audioContextTime * 1000;\n\n // If looping and we've reached the end, wrap around\n if (this.#loopingPlayback && rawTimeMs >= endMs) {\n rawTimeMs = rawTimeMs % endMs;\n }\n }\n\n const nextTimeMs =\n Math.round(rawTimeMs / this.#MS_PER_FRAME) * this.#MS_PER_FRAME;\n\n // During playback, update time directly without triggering seek\n // This avoids frame drops at the loop boundary\n this.#updatePlaybackTime(nextTimeMs);\n\n // Only check for end if we haven't already handled looping\n if (!this.#loopingPlayback && nextTimeMs >= endMs) {\n this.maybeLoopPlayback();\n return;\n }\n\n this.#playbackAnimationFrameRequest = requestAnimationFrame(() => {\n this.#syncPlayheadToAudioContext(startMs);\n });\n }\n\n private async maybeLoopPlayback() {\n if (this.#loop) {\n // Loop enabled: reset to beginning and restart playback\n // We restart the audio system directly without changing #playing state\n // to keep the play button in sync\n this.setCurrentTimeMs(0);\n // Restart in next frame without awaiting to minimize gap\n requestAnimationFrame(() => {\n this.startPlayback();\n });\n } else {\n // No loop: reset to beginning and stop\n // This ensures play button works when clicked again\n this.setCurrentTimeMs(0);\n this.pause();\n }\n }\n\n private async stopPlayback() {\n if (this.#playbackAudioContext) {\n if (this.#playbackAudioContext.state !== \"closed\") {\n await this.#playbackAudioContext.close();\n }\n }\n if (this.#playbackAnimationFrameRequest) {\n cancelAnimationFrame(this.#playbackAnimationFrameRequest);\n }\n this.#playbackAudioContext = null;\n this.#playbackAnimationFrameRequest = null;\n this.#pendingAudioContext = null;\n }\n\n private async startPlayback() {\n // Guard against starting playback on a removed controller\n if (this.#removed) {\n return;\n }\n\n await this.stopPlayback();\n const host = this.#host;\n if (!host) {\n return;\n }\n\n if (host.waitForMediaDurations) {\n await host.waitForMediaDurations();\n }\n\n // Check again after async - controller could have been removed\n if (this.#removed) {\n return;\n }\n\n const currentMs = this.currentTimeMs;\n const fromMs = currentMs;\n const toMs = host.endTimeMs;\n\n if (fromMs >= toMs) {\n this.pause();\n return;\n }\n\n let bufferCount = 0;\n // Check for pre-resumed AudioContext from synchronous user interaction\n if (this.#pendingAudioContext) {\n this.#playbackAudioContext = this.#pendingAudioContext;\n this.#pendingAudioContext = null;\n } else {\n this.#playbackAudioContext = new AudioContext({\n latencyHint: \"playback\",\n });\n }\n this.#loopingPlayback = this.#loop; // Remember if we're in a looping session\n this.#playbackWrapTimeSeconds = 0; // Reset wrap time\n\n if (this.#playbackAnimationFrameRequest) {\n cancelAnimationFrame(this.#playbackAnimationFrameRequest);\n }\n this.#syncPlayheadToAudioContext(currentMs);\n const playbackContext = this.#playbackAudioContext;\n\n // Check if context is suspended (fallback for newly-created contexts)\n if (playbackContext.state === \"suspended\") {\n // Attempt to resume (may not work on mobile if user interaction context is lost)\n try {\n await playbackContext.resume();\n // Check state again after resume attempt\n if (playbackContext.state === \"suspended\") {\n console.warn(\n \"AudioContext is suspended and resume() failed. \" +\n \"On mobile devices, AudioContext.resume() must be called synchronously within a user interaction handler. \" +\n \"Media playback will not work until user has interacted with page.\",\n );\n this.setPlaying(false);\n return;\n }\n } catch (error) {\n console.warn(\n \"Failed to resume AudioContext:\",\n error,\n \"On mobile devices, AudioContext.resume() must be called synchronously within a user interaction handler.\",\n );\n this.setPlaying(false);\n return;\n }\n }\n await playbackContext.suspend();\n\n // Track the logical media time (what position in the media we're rendering)\n // vs the AudioContext schedule time (when to play it)\n let logicalTimeMs = currentMs;\n let audioContextTimeMs = 0; // Tracks the schedule position in the AudioContext timeline\n let hasWrapped = false;\n\n const fillBuffer = async () => {\n if (bufferCount > 2) {\n return;\n }\n const canFillBuffer = await queueBufferSource();\n if (canFillBuffer) {\n fillBuffer().catch(() => {});\n }\n };\n\n const queueBufferSource = async () => {\n // Check if we've already wrapped and aren't looping anymore\n if (hasWrapped && !this.#loopingPlayback) {\n return false;\n }\n\n const startMs = logicalTimeMs;\n const endMs = Math.min(\n logicalTimeMs + this.#AUDIO_PLAYBACK_SLICE_MS,\n toMs,\n );\n\n // Will this slice reach the end?\n const willReachEnd = endMs >= toMs;\n\n if (!host.renderAudio) {\n return false;\n }\n\n const audioBuffer = await host.renderAudio(startMs, endMs);\n bufferCount++;\n const source = playbackContext.createBufferSource();\n source.buffer = audioBuffer;\n source.connect(playbackContext.destination);\n // Schedule this buffer to play at the current audioContextTime position\n source.start(audioContextTimeMs / 1000);\n\n const sliceDurationMs = endMs - startMs;\n\n source.onended = () => {\n bufferCount--;\n\n if (willReachEnd) {\n if (!this.#loopingPlayback) {\n // Not looping, end playback\n this.maybeLoopPlayback();\n } else {\n // Looping: continue filling buffer after wrap\n fillBuffer().catch(() => {});\n }\n } else {\n // Continue filling buffer\n fillBuffer().catch(() => {});\n }\n };\n\n // Advance the AudioContext schedule time\n audioContextTimeMs += sliceDurationMs;\n\n // If this buffer reaches the end and we're looping, immediately queue the wraparound\n if (willReachEnd && this.#loopingPlayback) {\n // Mark that we've wrapped\n hasWrapped = true;\n // Store when we wrapped (relative to when playback started, which is time 0 in AudioContext)\n // This is the duration from start to end\n this.#playbackWrapTimeSeconds = (toMs - fromMs) / 1000;\n // Reset logical time to beginning\n logicalTimeMs = 0;\n // Continue buffering will happen in fillBuffer() call below\n } else {\n // Normal advance\n logicalTimeMs = endMs;\n }\n\n return true;\n };\n\n try {\n await fillBuffer();\n await playbackContext.resume();\n } catch (error) {\n // Ignore errors if AudioContext is closed or during test cleanup\n if (\n error instanceof Error &&\n (error.name === \"InvalidStateError\" || error.message.includes(\"closed\"))\n ) {\n return;\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,qBAAb,MAA8D;CAC5D;CACA,WAAW;CACX,QAAQ;CACR,6BAAa,IAAI,KAAqD;CACtE;CACA;CACA;CACA;CAEA,OAAO;CACP,gBAAgB,MAAO,MAAKA;CAC5B,wBAA6C;CAC7C,iCAAgD;CAChD,uBAA4C;CAC5C,2BAA6B,KAAK,OAAQ,OAAS;CAEnD,eAAmC;CACnC,kBAAkB;CAClB;CACA,yBAAyB;CACzB,mBAAmB;CACnB,2BAA2B;CAE3B,uBAA+C;CAC/C,gBAAgB;CAEhB,YAAY,MAAoB;AAC9B,QAAKC,OAAQ;AACb,OAAK,cAAc,KAAK;AAExB,QAAKC,kBAAmB,IAAI,gBAAgB,MAAM;GAChD,SAAS;GACT,cAAc,MAAKC;GACpB,CAAC;AACF,QAAKC,eAAgB,IAAI,gBAAgB,MAAM;GAC7C,SAAS;GACT,cAAc,MAAKC;GACpB,CAAC;AACF,QAAKC,wBAAyB,IAAI,gBAAgB,MAAM;GACtD,SAAS;GACT,cAAc,KAAK;GACpB,CAAC;AACF,QAAKC,qBAAsB,IAAI,gBAAgB,MAAM;GACnD,SAAS;GACT,cAAc,KAAK;GACpB,CAAC;;CAGJ,IAAI,cAAsB;EACxB,MAAM,UAAU,MAAKC,eAAgB;EAErC,MAAM,MAAO,MAAKP,KAAc,OAAO;AACvC,MAAI,CAAC,OAAO,OAAO,EAAG,QAAO;EAC7B,MA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O,SAAS;AAChB,UAAO,QAAQ,gBAAgB,YAAY;AAE3C,UAAO,MAAM,qBAAqB,IAAK;GAEvC,MAAM,kBAAkB,QAAQ;AAEhC,UAAO,gBAAgB;AACrB;AAEA,QAAI,aACF,KAAI,CAAC,MAAKL,gBAER,MAAK,mBAAmB;QAGxB,aAAY,CAAC,YAAY,GAAG;QAI9B,aAAY,CAAC,YAAY,GAAG;;AAKhC,yBAAsB;AAGtB,OAAI,gBAAgB,MAAKA,iBAAkB;AAEzC,iBAAa;AAGb,UAAKD,2BAA4B,OAAO,UAAU;AAElD,oBAAgB;SAIhB,iBAAgB;AAGlB,UAAO;;AAGT,MAAI;AACF,SAAM,YAAY;AAClB,SAAM,gBAAgB,QAAQ;WACvB,OAAO;AAEd,OACE,iBAAiB,UAChB,MAAM,SAAS,uBAAuB,MAAM,QAAQ,SAAS,SAAS,EAEvE;AAEF,SAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@editframe/elements",
3
- "version": "0.42.0",
3
+ "version": "0.42.1",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -18,7 +18,7 @@
18
18
  "license": "UNLICENSED",
19
19
  "dependencies": {
20
20
  "@bramus/style-observer": "^1.3.0",
21
- "@editframe/assets": "0.42.0",
21
+ "@editframe/assets": "0.42.1",
22
22
  "@lit/context": "^1.1.6",
23
23
  "@opentelemetry/api": "^1.9.0",
24
24
  "@opentelemetry/context-zone": "^1.26.0",