@editframe/elements 0.45.2 → 0.45.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/DelayedLoadingState.js.map +1 -1
- package/dist/EF_FRAMEGEN.js.map +1 -1
- package/dist/EF_RENDERING.js.map +1 -1
- package/dist/canvas/EFCanvas.js +3 -3
- package/dist/canvas/EFCanvas.js.map +1 -1
- package/dist/canvas/EFCanvasItem.js.map +1 -1
- package/dist/canvas/api/CanvasAPI.js.map +1 -1
- package/dist/canvas/getElementBounds.js.map +1 -1
- package/dist/canvas/overlays/SelectionOverlay.js.map +1 -1
- package/dist/canvas/overlays/overlayState.js.map +1 -1
- package/dist/canvas/selection/SelectionController.js +25 -23
- package/dist/canvas/selection/SelectionController.js.map +1 -1
- package/dist/canvas/selection/SelectionModel.js.map +1 -1
- package/dist/canvas/selection/selectionContext.js.map +1 -1
- package/dist/elements/ContainerInfo.js.map +1 -1
- package/dist/elements/CrossUpdateController.js.map +1 -1
- package/dist/elements/EFAudio.js.map +1 -1
- package/dist/elements/EFCaptions.js.map +1 -1
- package/dist/elements/EFImage.js +1 -1
- package/dist/elements/EFImage.js.map +1 -1
- package/dist/elements/EFMedia/BufferedSeekingInput.js.map +1 -1
- package/dist/elements/EFMedia/CachedFetcher.js.map +1 -1
- package/dist/elements/EFMedia/MediaEngine.js.map +1 -1
- package/dist/elements/EFMedia/SegmentIndex.js.map +1 -1
- package/dist/elements/EFMedia/SegmentTransport.js.map +1 -1
- package/dist/elements/EFMedia/TimingModel.js.map +1 -1
- package/dist/elements/EFMedia/shared/AudioSpanUtils.js.map +1 -1
- package/dist/elements/EFMedia/shared/GlobalInputCache.js.map +1 -1
- package/dist/elements/EFMedia/shared/PrecisionUtils.js.map +1 -1
- package/dist/elements/EFMedia/shared/ThumbnailExtractor.js.map +1 -1
- package/dist/elements/EFMedia/videoTasks/MainVideoInputCache.js.map +1 -1
- package/dist/elements/EFMedia/videoTasks/ScrubInputCache.js.map +1 -1
- package/dist/elements/EFMedia.js.map +1 -1
- package/dist/elements/EFPanZoom.js +9 -8
- package/dist/elements/EFPanZoom.js.map +1 -1
- package/dist/elements/EFSourceMixin.js +1 -1
- package/dist/elements/EFSourceMixin.js.map +1 -1
- package/dist/elements/EFSurface.js.map +1 -1
- package/dist/elements/EFTemporal.js.map +1 -1
- package/dist/elements/EFText.d.ts +4 -4
- package/dist/elements/EFText.js.map +1 -1
- package/dist/elements/EFTextSegment.d.ts +4 -4
- package/dist/elements/EFTimegroup.js +7 -8
- package/dist/elements/EFTimegroup.js.map +1 -1
- package/dist/elements/EFVideo.d.ts +4 -4
- package/dist/elements/EFVideo.js.map +1 -1
- package/dist/elements/EFWaveform.d.ts +4 -4
- package/dist/elements/EFWaveform.js.map +1 -1
- package/dist/elements/ElementPositionInfo.js.map +1 -1
- package/dist/elements/FetchMixin.js.map +1 -1
- package/dist/elements/SampleBuffer.js.map +1 -1
- package/dist/elements/TargetController.js.map +1 -1
- package/dist/elements/TimegroupController.js.map +1 -1
- package/dist/elements/cloneFactoryRegistry.js.map +1 -1
- package/dist/elements/durationConverter.js.map +1 -1
- package/dist/elements/easingUtils.js.map +1 -1
- package/dist/elements/renderTemporalAudio.js.map +1 -1
- package/dist/elements/setupTemporalHierarchy.js.map +1 -1
- package/dist/elements/updateAnimations.js +1 -1
- package/dist/elements/updateAnimations.js.map +1 -1
- package/dist/getRenderInfo.js.map +1 -1
- package/dist/gui/ContextMixin.js.map +1 -1
- package/dist/gui/Controllable.js.map +1 -1
- package/dist/gui/EFActiveRootTemporal.d.ts +4 -4
- package/dist/gui/EFActiveRootTemporal.js.map +1 -1
- package/dist/gui/EFConfiguration.d.ts +4 -4
- package/dist/gui/EFControls.js.map +1 -1
- package/dist/gui/EFDial.d.ts +4 -4
- package/dist/gui/EFFilmstrip.d.ts +4 -4
- package/dist/gui/EFFilmstrip.js.map +1 -1
- package/dist/gui/EFFitScale.js.map +1 -1
- package/dist/gui/EFOverlayItem.d.ts +4 -4
- package/dist/gui/EFOverlayItem.js.map +1 -1
- package/dist/gui/EFOverlayLayer.d.ts +4 -4
- package/dist/gui/EFOverlayLayer.js.map +1 -1
- package/dist/gui/EFPause.d.ts +4 -4
- package/dist/gui/EFPlay.d.ts +4 -4
- package/dist/gui/EFPreview.d.ts +4 -4
- package/dist/gui/EFPreview.js.map +1 -1
- package/dist/gui/EFResizableBox.js.map +1 -1
- package/dist/gui/EFScrubber.d.ts +4 -4
- package/dist/gui/EFScrubber.js.map +1 -1
- package/dist/gui/EFTimeDisplay.d.ts +4 -4
- package/dist/gui/EFTimeDisplay.js.map +1 -1
- package/dist/gui/EFTimelineRuler.d.ts +4 -4
- package/dist/gui/EFTimelineRuler.js.map +1 -1
- package/dist/gui/EFToggleLoop.d.ts +4 -4
- package/dist/gui/EFTogglePlay.d.ts +4 -4
- package/dist/gui/EFTogglePlay.js.map +1 -1
- package/dist/gui/EFTransformHandles.js.map +1 -1
- package/dist/gui/EFWorkbench.d.ts +4 -4
- package/dist/gui/EFWorkbench.js.map +1 -1
- package/dist/gui/FitScaleHelpers.js.map +1 -1
- package/dist/gui/PlaybackController.js.map +1 -1
- package/dist/gui/TWMixin2.js.map +1 -1
- package/dist/gui/TargetOrContextMixin.js.map +1 -1
- package/dist/gui/currentTimeContext.js.map +1 -1
- package/dist/gui/efContext.js.map +1 -1
- package/dist/gui/fetchContext.js.map +1 -1
- package/dist/gui/hierarchy/EFHierarchy.d.ts +4 -4
- package/dist/gui/hierarchy/EFHierarchy.js.map +1 -1
- package/dist/gui/hierarchy/EFHierarchyItem.d.ts +2 -2
- package/dist/gui/hierarchy/EFHierarchyItem.js.map +1 -1
- package/dist/gui/hierarchy/hierarchyContext.js.map +1 -1
- package/dist/gui/panZoomTransformContext.js.map +1 -1
- package/dist/gui/previewSettingsContext.js.map +1 -1
- package/dist/gui/theme.js.map +1 -1
- package/dist/gui/timeline/EFTimeline.d.ts +2 -2
- package/dist/gui/timeline/EFTimeline.js +0 -1
- package/dist/gui/timeline/EFTimeline.js.map +1 -1
- package/dist/gui/timeline/EFTimelineRow.js.map +1 -1
- package/dist/gui/timeline/TrimHandles.d.ts +4 -4
- package/dist/gui/timeline/TrimHandles.js.map +1 -1
- package/dist/gui/timeline/flattenHierarchy.js.map +1 -1
- package/dist/gui/timeline/timelineStateContext.js.map +1 -1
- package/dist/gui/timeline/tracks/AudioTrack.js.map +1 -1
- package/dist/gui/timeline/tracks/CaptionsTrack.js.map +1 -1
- package/dist/gui/timeline/tracks/EFThumbnailStrip.js.map +1 -1
- package/dist/gui/timeline/tracks/ImageTrack.js.map +1 -1
- package/dist/gui/timeline/tracks/TextTrack.js.map +1 -1
- package/dist/gui/timeline/tracks/TimegroupTrack.js.map +1 -1
- package/dist/gui/timeline/tracks/TrackItem.js.map +1 -1
- package/dist/gui/timeline/tracks/VideoTrack.js.map +1 -1
- package/dist/gui/timeline/tracks/renderTrackChildren.js.map +1 -1
- package/dist/gui/timeline/tracks/waveformUtils.js.map +1 -1
- package/dist/gui/transformCalculations.js.map +1 -1
- package/dist/gui/transformUtils.js.map +1 -1
- package/dist/gui/tree/EFTree.d.ts +4 -4
- package/dist/gui/tree/EFTree.js.map +1 -1
- package/dist/gui/tree/EFTreeItem.d.ts +4 -4
- package/dist/gui/tree/EFTreeItem.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/otel/BridgeSpanExporter.js.map +1 -1
- package/dist/otel/setupBrowserTracing.js.map +1 -1
- package/dist/otel/tracingHelpers.js.map +1 -1
- package/dist/preview/AdaptiveResolutionTracker.js.map +1 -1
- package/dist/preview/FrameController.js.map +1 -1
- package/dist/preview/QualityUpgradeScheduler.js.map +1 -1
- package/dist/preview/RenderContext.js.map +1 -1
- package/dist/preview/RenderProfiler.js.map +1 -1
- package/dist/preview/RenderStats.js.map +1 -1
- package/dist/preview/encoding/canvasEncoder.js.map +1 -1
- package/dist/preview/encoding/mainThreadEncoder.js +1 -1
- package/dist/preview/encoding/mainThreadEncoder.js.map +1 -1
- package/dist/preview/previewSettings.js.map +1 -1
- package/dist/preview/previewTypes.js.map +1 -1
- package/dist/preview/renderElementToCanvas.js.map +1 -1
- package/dist/preview/renderTimegroupToCanvas.js +2 -44
- package/dist/preview/renderTimegroupToCanvas.js.map +1 -1
- package/dist/preview/renderTimegroupToVideo.js +2 -2
- package/dist/preview/renderTimegroupToVideo.js.map +1 -1
- package/dist/preview/renderVideoToVideo.js +2 -2
- package/dist/preview/renderVideoToVideo.js.map +1 -1
- package/dist/preview/renderers.js.map +1 -1
- package/dist/preview/rendering/ScaleConfig.js.map +1 -1
- package/dist/preview/rendering/loadImage.js.map +1 -1
- package/dist/preview/rendering/renderToImageNative.js.map +1 -1
- package/dist/preview/rendering/serializeTimelineDirect.js +1 -1
- package/dist/preview/rendering/serializeTimelineDirect.js.map +1 -1
- package/dist/preview/statsTrackingStrategy.js.map +1 -1
- package/dist/preview/workers/WorkerPool.js.map +1 -1
- package/dist/render/EFRenderAPI.js.map +1 -1
- package/dist/transcoding/cache/RequestDeduplicator.js.map +1 -1
- package/dist/utils/LRUCache.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SelectionOverlay.js","names":["SelectionOverlay","panZoom","current: Node | null","canvasWithMetadata: CanvasWithMetadata"],"sources":["../../../src/canvas/overlays/SelectionOverlay.ts"],"sourcesContent":["import { consume } from \"@lit/context\";\nimport { css, html, LitElement } from \"lit\";\nimport { customElement, property, state } from \"lit/decorators.js\";\nimport {\n selectionContext,\n type SelectionContext,\n} from \"../selection/selectionContext.js\";\nimport { panZoomTransformContext } from \"../../gui/panZoomTransformContext.js\";\nimport type { PanZoomTransform } from \"../../elements/EFPanZoom.js\";\nimport {\n type OverlayState,\n type CanvasWithMetadata,\n getOverlayTargets,\n calculateOverlayState,\n} from \"./overlayState.js\";\n\n/**\n * Selection overlay that renders unscaled selection indicators.\n * Uses fixed positioning to ensure 1:1 pixel ratio regardless of zoom level.\n */\n@customElement(\"ef-canvas-selection-overlay\")\nexport class SelectionOverlay extends LitElement {\n static styles = [\n css`\n :host {\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n pointer-events: none;\n z-index: 1000;\n }\n .box-select {\n position: absolute;\n border: 2px dashed rgb(59, 130, 246);\n background: rgba(59, 130, 246, 0.05);\n pointer-events: none;\n }\n .highlight-box {\n position: absolute;\n border: 2px solid rgb(148, 163, 184);\n background: rgba(148, 163, 184, 0.1);\n pointer-events: none;\n box-shadow: 0 0 0 2px rgba(148, 163, 184, 0.3);\n }\n `,\n ];\n\n createRenderRoot() {\n // Return this to render directly to the element (no shadow DOM)\n // This allows the overlay to use fixed positioning relative to viewport\n // Lit will inject styles as a <style> element when createRenderRoot returns this\n return this;\n }\n\n firstUpdated(\n changedProperties: Map<string | number | symbol, unknown>,\n ): void {\n super.firstUpdated?.(changedProperties);\n }\n\n @consume({ context: selectionContext, subscribe: true })\n selectionFromContext?: SelectionContext;\n\n @consume({ context: panZoomTransformContext, subscribe: true })\n panZoomTransformFromContext?: PanZoomTransform;\n\n /**\n * Selection context as fallback for when overlay is outside context providers (e.g., sibling of pan-zoom).\n */\n @property({ type: Object })\n selection?: SelectionContext;\n\n /**\n * Pan/zoom transform as fallback for when overlay is outside context providers (e.g., sibling of pan-zoom).\n */\n @property({ type: Object })\n panZoomTransform?: PanZoomTransform;\n\n @state()\n private canvasElement: HTMLElement | null = null;\n\n /**\n * Canvas element property - can be set directly when overlay is outside context providers.\n */\n @property({ type: Object })\n canvas?: HTMLElement;\n\n /**\n * Complete overlay state - calculated from targets using the abstraction layer.\n * This is the SINGLE source of truth for overlay bounds.\n */\n @state()\n private overlayState: OverlayState = {\n selection: null,\n boxSelect: null,\n highlight: null,\n };\n\n @state()\n private lastSelectionMode: string | null = null;\n\n /**\n * When true, the RAF loop skips all work. Used during playback to avoid\n * layout-thrashing getBoundingClientRect/getComputedStyle calls that\n * compete with the canvas render pipeline.\n */\n @property({ type: Boolean }) paused = false;\n\n private animationFrame?: number;\n private rafLoopActive = false;\n\n connectedCallback(): void {\n super.connectedCallback();\n // Apply styles directly since :host doesn't work in light DOM\n // These styles are critical for proper positioning relative to viewport\n this.style.position = \"fixed\";\n this.style.top = \"0\";\n this.style.left = \"0\";\n this.style.width = \"100vw\";\n this.style.height = \"100vh\";\n this.style.pointerEvents = \"none\";\n this.style.zIndex = \"1000\";\n // Add a data attribute for easier debugging\n this.setAttribute(\"data-selection-overlay\", \"true\");\n // Use requestAnimationFrame to ensure DOM is ready\n requestAnimationFrame(() => {\n // Use canvas property if provided, otherwise try to find it\n if (this.canvas) {\n this.canvasElement = this.canvas;\n } else {\n this.findCanvasElement();\n }\n // Always start RAF loop if we have a canvas element (needed for highlight updates)\n if (this.canvasElement) {\n this.startRafLoop();\n }\n });\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this.stopRafLoop();\n }\n\n /**\n * React to selection context changes to ensure box selection visual updates.\n * This is called whenever Lit detects a property change, including context updates.\n * Note: We don't call requestUpdate() here to avoid the Lit warning about scheduling\n * updates after an update completes. The RAF loop handles all updates.\n */\n updated(changedProperties: Map<string | number | symbol, unknown>): void {\n super.updated?.(changedProperties);\n // Check if selection mode changed (context updates might not show in changedProperties)\n const selection = this.effectiveSelection;\n const currentMode = selection?.selectionMode ?? null;\n if (currentMode !== this.lastSelectionMode) {\n this.lastSelectionMode = currentMode;\n }\n // Ensure RAF loop is running when box selecting (in case it stopped)\n if (currentMode === \"box-selecting\" && !this.rafLoopActive) {\n this.startRafLoop();\n }\n // Ensure RAF loop is running when canvas property is set (for highlight updates)\n if (changedProperties.has(\"canvas\") && this.canvas) {\n this.canvasElement = this.canvas;\n if (!this.rafLoopActive) {\n this.startRafLoop();\n }\n }\n // Start RAF loop if we have a canvas but loop isn't running\n if (this.canvasElement && !this.rafLoopActive) {\n this.startRafLoop();\n }\n // On unpause, force an immediate overlay update to sync stale state\n if (changedProperties.has(\"paused\") && !this.paused) {\n this.updateOverlayData();\n }\n }\n\n /**\n * Find the EFCanvas element.\n * Handles both cases:\n * 1. Overlay is inside EFCanvas's shadow DOM (old case)\n * 2. Overlay is a sibling of ef-pan-zoom (new case - outside transform)\n */\n private findCanvasElement(): void {\n // First, try to find ef-canvas as a sibling or descendant of ef-pan-zoom\n // (when overlay is outside the transform)\n // Since overlay is a sibling of ef-pan-zoom, we need to search in the parent\n const parent = this.parentElement;\n if (parent) {\n // Look for ef-pan-zoom sibling\n const panZoom = parent.querySelector(\"ef-pan-zoom\") as HTMLElement | null;\n if (panZoom) {\n // Look for ef-canvas inside ef-pan-zoom\n const canvas = panZoom.querySelector(\"ef-canvas\") as HTMLElement | null;\n if (canvas) {\n this.canvasElement = canvas;\n return;\n }\n }\n }\n\n // Also try closest in case overlay is inside pan-zoom somehow\n const panZoom = this.closest(\"ef-pan-zoom\") as HTMLElement | null;\n if (panZoom) {\n const canvas = panZoom.querySelector(\"ef-canvas\") as HTMLElement | null;\n if (canvas) {\n this.canvasElement = canvas;\n return;\n }\n }\n\n // Fallback: traverse up the DOM tree (for when overlay is inside canvas shadow DOM)\n let current: Node | null = this;\n while (current) {\n if (current instanceof ShadowRoot) {\n current = (current as ShadowRoot).host;\n } else if (current instanceof HTMLElement) {\n // Check if this is the EFCanvas element (case-insensitive check)\n if (\n current.tagName === \"EF-CANVAS\" ||\n current.tagName.toLowerCase() === \"ef-canvas\"\n ) {\n this.canvasElement = current;\n return;\n }\n // Check parent element or shadow root host\n const rootNode = current.getRootNode();\n if (rootNode instanceof ShadowRoot) {\n current = rootNode.host;\n } else {\n current = current.parentElement;\n }\n } else {\n const rootNode = (current as Node).getRootNode();\n if (rootNode instanceof ShadowRoot) {\n current = rootNode.host;\n } else {\n current = (current as Node).parentElement;\n }\n }\n }\n }\n\n /**\n * Start continuous RAF loop for smooth overlay updates.\n */\n private startRafLoop(): void {\n if (this.rafLoopActive) {\n return;\n }\n this.rafLoopActive = true;\n this.rafLoop();\n }\n\n /**\n * Stop RAF loop.\n */\n private stopRafLoop(): void {\n this.rafLoopActive = false;\n if (this.animationFrame) {\n cancelAnimationFrame(this.animationFrame);\n this.animationFrame = undefined;\n }\n }\n\n /**\n * Continuous RAF loop to update overlays every frame using Lit render cycle.\n * When paused, the loop keeps running (for quick resume) but skips all\n * expensive layout queries.\n */\n private rafLoop = (): void => {\n if (!this.rafLoopActive) {\n return;\n }\n\n // Skip all work when paused to avoid layout-thrashing during playback\n if (!this.paused) {\n this.updateOverlayData();\n }\n\n // Schedule next frame\n this.animationFrame = requestAnimationFrame(this.rafLoop);\n };\n\n /**\n * Get the effective selection context (from context or property).\n */\n private get effectiveSelection(): SelectionContext | undefined {\n return this.selectionFromContext ?? this.selection;\n }\n\n /**\n * Get the effective pan-zoom transform (from context or property).\n */\n private get effectivePanZoomTransform(): PanZoomTransform | undefined {\n return this.panZoomTransformFromContext ?? this.panZoomTransform;\n }\n\n /**\n * Update overlay data state using the abstraction layer.\n *\n * This method now uses the clean separation of:\n * - SEMANTICS: getOverlayTargets() determines WHAT should be shown\n * - MECHANISM: calculateOverlayState() determines HOW to show it\n */\n private updateOverlayData(): void {\n // Ensure canvas element reference is up-to-date\n if (this.canvas && this.canvas !== this.canvasElement) {\n this.canvasElement = this.canvas;\n }\n\n // Get canvas element - required for all overlay calculations\n const effectiveCanvas = this.canvasElement || this.canvas;\n if (!effectiveCanvas) {\n this.overlayState = { selection: null, boxSelect: null, highlight: null };\n return;\n }\n\n // Get canvas rect (try .canvas-content first for accurate positioning)\n let canvasRect = effectiveCanvas.getBoundingClientRect();\n if (effectiveCanvas.shadowRoot) {\n const canvasContent = effectiveCanvas.shadowRoot.querySelector(\n \".canvas-content\",\n ) as HTMLElement;\n if (canvasContent) {\n canvasRect = canvasContent.getBoundingClientRect();\n }\n }\n\n // Get pan-zoom element for box-select coordinate conversion\n const panZoomElement = effectiveCanvas.closest(\n \"ef-pan-zoom\",\n ) as HTMLElement | null;\n\n // Get highlighted element from canvas\n const canvas = effectiveCanvas as any;\n const highlightedElement = canvas?.highlightedElement as HTMLElement | null;\n\n // SEMANTICS: What should be shown?\n const targets = getOverlayTargets(\n this.effectiveSelection,\n highlightedElement,\n );\n\n // Adapt canvas to CanvasWithMetadata interface\n const canvasWithMetadata: CanvasWithMetadata = {\n getElementData: (id: string) => canvas?.getElementData?.(id),\n getElement: (id: string) => canvas?.elementRegistry?.get(id),\n querySelector: (selector: string) =>\n effectiveCanvas.querySelector(selector),\n shadowRoot: effectiveCanvas.shadowRoot,\n };\n\n // Read current transform directly from panzoom element (not stale property/context)\n // This ensures we always have the current scale/pan values\n const currentTransform = this.readCurrentTransform(panZoomElement);\n\n // MECHANISM: Calculate screen bounds\n this.overlayState = calculateOverlayState(\n targets,\n canvasWithMetadata,\n canvasRect,\n panZoomElement,\n currentTransform,\n );\n }\n\n /**\n * Read current transform directly from panzoom element.\n * This ensures we always have fresh values instead of stale property/context.\n */\n private readCurrentTransform(\n panZoomElement: HTMLElement | null,\n ): PanZoomTransform | undefined {\n // Try reading from panzoom element directly (most accurate)\n if (panZoomElement) {\n const pz = panZoomElement as any;\n if (\n typeof pz.x === \"number\" &&\n typeof pz.y === \"number\" &&\n typeof pz.scale === \"number\"\n ) {\n return { x: pz.x, y: pz.y, scale: pz.scale };\n }\n }\n\n // Fall back to context/property\n return this.effectivePanZoomTransform;\n }\n\n render() {\n // We only need canvasElement to render overlays\n const effectiveCanvas = this.canvasElement || this.canvas;\n if (!effectiveCanvas) {\n return html``;\n }\n\n // NOTE: Selection visualization is handled by EFTransformHandles (with rotation support).\n // This overlay only renders:\n // - box-select: marquee during drag-to-select\n // - highlight-box: hover indication for non-selected elements\n const { boxSelect, highlight } = this.overlayState;\n\n return html`\n ${\n boxSelect\n ? html`\n <div\n class=\"box-select\"\n style=\"left: ${boxSelect.x}px; top: ${boxSelect.y}px; width: ${boxSelect.width}px; height: ${boxSelect.height}px; position: absolute; border: 2px dashed rgb(59, 130, 246); background: rgba(59, 130, 246, 0.05); pointer-events: none;\"\n ></div>\n `\n : html``\n }\n ${\n highlight\n ? html`\n <div\n class=\"highlight-box\"\n style=\"left: ${highlight.x}px; top: ${highlight.y}px; width: ${highlight.width}px; height: ${highlight.height}px; position: absolute; border: 2px solid rgb(148, 163, 184); background: rgba(148, 163, 184, 0.1); pointer-events: none; box-shadow: 0 0 0 2px rgba(148, 163, 184, 0.3);\"\n ></div>\n `\n : html``\n }\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-canvas-selection-overlay\": SelectionOverlay;\n }\n}\n"],"mappings":";;;;;;;;;AAqBO,6BAAMA,2BAAyB,WAAW;;;uBA4DH;sBAaP;GACnC,WAAW;GACX,WAAW;GACX,WAAW;GACZ;2BAG0C;gBAOL;uBAGd;uBAmKM;AAC5B,OAAI,CAAC,KAAK,cACR;AAIF,OAAI,CAAC,KAAK,OACR,MAAK,mBAAmB;AAI1B,QAAK,iBAAiB,sBAAsB,KAAK,QAAQ;;;;gBAvQ3C,CACd,GAAG;;;;;;;;;;;;;;;;;;;;;;;MAwBJ;;CAED,mBAAmB;AAIjB,SAAO;;CAGT,aACE,mBACM;AACN,QAAM,eAAe,kBAAkB;;CAsDzC,oBAA0B;AACxB,QAAM,mBAAmB;AAGzB,OAAK,MAAM,WAAW;AACtB,OAAK,MAAM,MAAM;AACjB,OAAK,MAAM,OAAO;AAClB,OAAK,MAAM,QAAQ;AACnB,OAAK,MAAM,SAAS;AACpB,OAAK,MAAM,gBAAgB;AAC3B,OAAK,MAAM,SAAS;AAEpB,OAAK,aAAa,0BAA0B,OAAO;AAEnD,8BAA4B;AAE1B,OAAI,KAAK,OACP,MAAK,gBAAgB,KAAK;OAE1B,MAAK,mBAAmB;AAG1B,OAAI,KAAK,cACP,MAAK,cAAc;IAErB;;CAGJ,uBAA6B;AAC3B,QAAM,sBAAsB;AAC5B,OAAK,aAAa;;;;;;;;CASpB,QAAQ,mBAAiE;AACvE,QAAM,UAAU,kBAAkB;EAGlC,MAAM,cADY,KAAK,oBACQ,iBAAiB;AACh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;AAGP,MAAI,EADoB,KAAK,iBAAiB,KAAK,QAEjD,QAAO,IAAI;EAOb,MAAM,EAAE,WAAW,cAAc,KAAK;AAEtC,SAAO,IAAI;QAEP,YACI,IAAI;;;6BAGa,UAAU,EAAE,WAAW,UAAU,EAAE,aAAa,UAAU,MAAM,cAAc,UAAU,OAAO;;cAGhH,IAAI,GACT;QAEC,YACI,IAAI;;;6BAGa,UAAU,EAAE,WAAW,UAAU,EAAE,aAAa,UAAU,MAAM,cAAc,UAAU,OAAO;;cAGhH,IAAI,GACT;;;;YA7WJ,QAAQ;CAAE,SAAS;CAAkB,WAAW;CAAM,CAAC;YAGvD,QAAQ;CAAE,SAAS;CAAyB,WAAW;CAAM,CAAC;YAM9D,SAAS,EAAE,MAAM,QAAQ,CAAC;YAM1B,SAAS,EAAE,MAAM,QAAQ,CAAC;YAG1B,OAAO;YAMP,SAAS,EAAE,MAAM,QAAQ,CAAC;YAO1B,OAAO;YAOP,OAAO;YAQP,SAAS,EAAE,MAAM,SAAS,CAAC;+BAxF7B,cAAc,8BAA8B"}
|
|
1
|
+
{"version":3,"file":"SelectionOverlay.js","names":["SelectionOverlay","panZoom","current: Node | null","canvasWithMetadata: CanvasWithMetadata"],"sources":["../../../src/canvas/overlays/SelectionOverlay.ts"],"sourcesContent":["import { consume } from \"@lit/context\";\nimport { css, html, LitElement } from \"lit\";\nimport { customElement, property, state } from \"lit/decorators.js\";\nimport { selectionContext, type SelectionContext } from \"../selection/selectionContext.js\";\nimport { panZoomTransformContext } from \"../../gui/panZoomTransformContext.js\";\nimport type { PanZoomTransform } from \"../../elements/EFPanZoom.js\";\nimport {\n type OverlayState,\n type CanvasWithMetadata,\n getOverlayTargets,\n calculateOverlayState,\n} from \"./overlayState.js\";\n\n/**\n * Selection overlay that renders unscaled selection indicators.\n * Uses fixed positioning to ensure 1:1 pixel ratio regardless of zoom level.\n */\n@customElement(\"ef-canvas-selection-overlay\")\nexport class SelectionOverlay extends LitElement {\n static styles = [\n css`\n :host {\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n pointer-events: none;\n z-index: 1000;\n }\n .box-select {\n position: absolute;\n border: 2px dashed rgb(59, 130, 246);\n background: rgba(59, 130, 246, 0.05);\n pointer-events: none;\n }\n .highlight-box {\n position: absolute;\n border: 2px solid rgb(148, 163, 184);\n background: rgba(148, 163, 184, 0.1);\n pointer-events: none;\n box-shadow: 0 0 0 2px rgba(148, 163, 184, 0.3);\n }\n `,\n ];\n\n createRenderRoot() {\n // Return this to render directly to the element (no shadow DOM)\n // This allows the overlay to use fixed positioning relative to viewport\n // Lit will inject styles as a <style> element when createRenderRoot returns this\n return this;\n }\n\n firstUpdated(changedProperties: Map<string | number | symbol, unknown>): void {\n super.firstUpdated?.(changedProperties);\n }\n\n @consume({ context: selectionContext, subscribe: true })\n selectionFromContext?: SelectionContext;\n\n @consume({ context: panZoomTransformContext, subscribe: true })\n panZoomTransformFromContext?: PanZoomTransform;\n\n /**\n * Selection context as fallback for when overlay is outside context providers (e.g., sibling of pan-zoom).\n */\n @property({ type: Object })\n selection?: SelectionContext;\n\n /**\n * Pan/zoom transform as fallback for when overlay is outside context providers (e.g., sibling of pan-zoom).\n */\n @property({ type: Object })\n panZoomTransform?: PanZoomTransform;\n\n @state()\n private canvasElement: HTMLElement | null = null;\n\n /**\n * Canvas element property - can be set directly when overlay is outside context providers.\n */\n @property({ type: Object })\n canvas?: HTMLElement;\n\n /**\n * Complete overlay state - calculated from targets using the abstraction layer.\n * This is the SINGLE source of truth for overlay bounds.\n */\n @state()\n private overlayState: OverlayState = {\n selection: null,\n boxSelect: null,\n highlight: null,\n };\n\n @state()\n private lastSelectionMode: string | null = null;\n\n /**\n * When true, the RAF loop skips all work. Used during playback to avoid\n * layout-thrashing getBoundingClientRect/getComputedStyle calls that\n * compete with the canvas render pipeline.\n */\n @property({ type: Boolean }) paused = false;\n\n private animationFrame?: number;\n private rafLoopActive = false;\n\n connectedCallback(): void {\n super.connectedCallback();\n // Apply styles directly since :host doesn't work in light DOM\n // These styles are critical for proper positioning relative to viewport\n this.style.position = \"fixed\";\n this.style.top = \"0\";\n this.style.left = \"0\";\n this.style.width = \"100vw\";\n this.style.height = \"100vh\";\n this.style.pointerEvents = \"none\";\n this.style.zIndex = \"1000\";\n // Add a data attribute for easier debugging\n this.setAttribute(\"data-selection-overlay\", \"true\");\n // Use requestAnimationFrame to ensure DOM is ready\n requestAnimationFrame(() => {\n // Use canvas property if provided, otherwise try to find it\n if (this.canvas) {\n this.canvasElement = this.canvas;\n } else {\n this.findCanvasElement();\n }\n // Always start RAF loop if we have a canvas element (needed for highlight updates)\n if (this.canvasElement) {\n this.startRafLoop();\n }\n });\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n this.stopRafLoop();\n }\n\n /**\n * React to selection context changes to ensure box selection visual updates.\n * This is called whenever Lit detects a property change, including context updates.\n * Note: We don't call requestUpdate() here to avoid the Lit warning about scheduling\n * updates after an update completes. The RAF loop handles all updates.\n */\n updated(changedProperties: Map<string | number | symbol, unknown>): void {\n super.updated?.(changedProperties);\n // Check if selection mode changed (context updates might not show in changedProperties)\n const selection = this.effectiveSelection;\n const currentMode = selection?.selectionMode ?? null;\n if (currentMode !== this.lastSelectionMode) {\n this.lastSelectionMode = currentMode;\n }\n // Ensure RAF loop is running when box selecting (in case it stopped)\n if (currentMode === \"box-selecting\" && !this.rafLoopActive) {\n this.startRafLoop();\n }\n // Ensure RAF loop is running when canvas property is set (for highlight updates)\n if (changedProperties.has(\"canvas\") && this.canvas) {\n this.canvasElement = this.canvas;\n if (!this.rafLoopActive) {\n this.startRafLoop();\n }\n }\n // Start RAF loop if we have a canvas but loop isn't running\n if (this.canvasElement && !this.rafLoopActive) {\n this.startRafLoop();\n }\n // On unpause, force an immediate overlay update to sync stale state\n if (changedProperties.has(\"paused\") && !this.paused) {\n this.updateOverlayData();\n }\n }\n\n /**\n * Find the EFCanvas element.\n * Handles both cases:\n * 1. Overlay is inside EFCanvas's shadow DOM (old case)\n * 2. Overlay is a sibling of ef-pan-zoom (new case - outside transform)\n */\n private findCanvasElement(): void {\n // First, try to find ef-canvas as a sibling or descendant of ef-pan-zoom\n // (when overlay is outside the transform)\n // Since overlay is a sibling of ef-pan-zoom, we need to search in the parent\n const parent = this.parentElement;\n if (parent) {\n // Look for ef-pan-zoom sibling\n const panZoom = parent.querySelector(\"ef-pan-zoom\") as HTMLElement | null;\n if (panZoom) {\n // Look for ef-canvas inside ef-pan-zoom\n const canvas = panZoom.querySelector(\"ef-canvas\") as HTMLElement | null;\n if (canvas) {\n this.canvasElement = canvas;\n return;\n }\n }\n }\n\n // Also try closest in case overlay is inside pan-zoom somehow\n const panZoom = this.closest(\"ef-pan-zoom\") as HTMLElement | null;\n if (panZoom) {\n const canvas = panZoom.querySelector(\"ef-canvas\") as HTMLElement | null;\n if (canvas) {\n this.canvasElement = canvas;\n return;\n }\n }\n\n // Fallback: traverse up the DOM tree (for when overlay is inside canvas shadow DOM)\n // oxlint-disable-next-line no-this-alias -- legitimate DOM traversal starting at this element\n let current: Node | null = this;\n while (current) {\n if (current instanceof ShadowRoot) {\n current = (current as ShadowRoot).host;\n } else if (current instanceof HTMLElement) {\n // Check if this is the EFCanvas element (case-insensitive check)\n if (current.tagName === \"EF-CANVAS\" || current.tagName.toLowerCase() === \"ef-canvas\") {\n this.canvasElement = current;\n return;\n }\n // Check parent element or shadow root host\n const rootNode = current.getRootNode();\n if (rootNode instanceof ShadowRoot) {\n current = rootNode.host;\n } else {\n current = current.parentElement;\n }\n } else {\n const rootNode = (current as Node).getRootNode();\n if (rootNode instanceof ShadowRoot) {\n current = rootNode.host;\n } else {\n current = (current as Node).parentElement;\n }\n }\n }\n }\n\n /**\n * Start continuous RAF loop for smooth overlay updates.\n */\n private startRafLoop(): void {\n if (this.rafLoopActive) {\n return;\n }\n this.rafLoopActive = true;\n this.rafLoop();\n }\n\n /**\n * Stop RAF loop.\n */\n private stopRafLoop(): void {\n this.rafLoopActive = false;\n if (this.animationFrame) {\n cancelAnimationFrame(this.animationFrame);\n this.animationFrame = undefined;\n }\n }\n\n /**\n * Continuous RAF loop to update overlays every frame using Lit render cycle.\n * When paused, the loop keeps running (for quick resume) but skips all\n * expensive layout queries.\n */\n private rafLoop = (): void => {\n if (!this.rafLoopActive) {\n return;\n }\n\n // Skip all work when paused to avoid layout-thrashing during playback\n if (!this.paused) {\n this.updateOverlayData();\n }\n\n // Schedule next frame\n this.animationFrame = requestAnimationFrame(this.rafLoop);\n };\n\n /**\n * Get the effective selection context (from context or property).\n */\n private get effectiveSelection(): SelectionContext | undefined {\n return this.selectionFromContext ?? this.selection;\n }\n\n /**\n * Get the effective pan-zoom transform (from context or property).\n */\n private get effectivePanZoomTransform(): PanZoomTransform | undefined {\n return this.panZoomTransformFromContext ?? this.panZoomTransform;\n }\n\n /**\n * Update overlay data state using the abstraction layer.\n *\n * This method now uses the clean separation of:\n * - SEMANTICS: getOverlayTargets() determines WHAT should be shown\n * - MECHANISM: calculateOverlayState() determines HOW to show it\n */\n private updateOverlayData(): void {\n // Ensure canvas element reference is up-to-date\n if (this.canvas && this.canvas !== this.canvasElement) {\n this.canvasElement = this.canvas;\n }\n\n // Get canvas element - required for all overlay calculations\n const effectiveCanvas = this.canvasElement || this.canvas;\n if (!effectiveCanvas) {\n this.overlayState = { selection: null, boxSelect: null, highlight: null };\n return;\n }\n\n // Get canvas rect (try .canvas-content first for accurate positioning)\n let canvasRect = effectiveCanvas.getBoundingClientRect();\n if (effectiveCanvas.shadowRoot) {\n const canvasContent = effectiveCanvas.shadowRoot.querySelector(\n \".canvas-content\",\n ) as HTMLElement;\n if (canvasContent) {\n canvasRect = canvasContent.getBoundingClientRect();\n }\n }\n\n // Get pan-zoom element for box-select coordinate conversion\n const panZoomElement = effectiveCanvas.closest(\"ef-pan-zoom\") as HTMLElement | null;\n\n // Get highlighted element from canvas\n const canvas = effectiveCanvas as any;\n const highlightedElement = canvas?.highlightedElement as HTMLElement | null;\n\n // SEMANTICS: What should be shown?\n const targets = getOverlayTargets(this.effectiveSelection, highlightedElement);\n\n // Adapt canvas to CanvasWithMetadata interface\n const canvasWithMetadata: CanvasWithMetadata = {\n getElementData: (id: string) => canvas?.getElementData?.(id),\n getElement: (id: string) => canvas?.elementRegistry?.get(id),\n querySelector: (selector: string) => effectiveCanvas.querySelector(selector),\n shadowRoot: effectiveCanvas.shadowRoot,\n };\n\n // Read current transform directly from panzoom element (not stale property/context)\n // This ensures we always have the current scale/pan values\n const currentTransform = this.readCurrentTransform(panZoomElement);\n\n // MECHANISM: Calculate screen bounds\n this.overlayState = calculateOverlayState(\n targets,\n canvasWithMetadata,\n canvasRect,\n panZoomElement,\n currentTransform,\n );\n }\n\n /**\n * Read current transform directly from panzoom element.\n * This ensures we always have fresh values instead of stale property/context.\n */\n private readCurrentTransform(panZoomElement: HTMLElement | null): PanZoomTransform | undefined {\n // Try reading from panzoom element directly (most accurate)\n if (panZoomElement) {\n const pz = panZoomElement as any;\n if (typeof pz.x === \"number\" && typeof pz.y === \"number\" && typeof pz.scale === \"number\") {\n return { x: pz.x, y: pz.y, scale: pz.scale };\n }\n }\n\n // Fall back to context/property\n return this.effectivePanZoomTransform;\n }\n\n render() {\n // We only need canvasElement to render overlays\n const effectiveCanvas = this.canvasElement || this.canvas;\n if (!effectiveCanvas) {\n return html``;\n }\n\n // NOTE: Selection visualization is handled by EFTransformHandles (with rotation support).\n // This overlay only renders:\n // - box-select: marquee during drag-to-select\n // - highlight-box: hover indication for non-selected elements\n const { boxSelect, highlight } = this.overlayState;\n\n return html`\n ${\n boxSelect\n ? html`\n <div\n class=\"box-select\"\n style=\"left: ${boxSelect.x}px; top: ${boxSelect.y}px; width: ${boxSelect.width}px; height: ${boxSelect.height}px; position: absolute; border: 2px dashed rgb(59, 130, 246); background: rgba(59, 130, 246, 0.05); pointer-events: none;\"\n ></div>\n `\n : html``\n }\n ${\n highlight\n ? html`\n <div\n class=\"highlight-box\"\n style=\"left: ${highlight.x}px; top: ${highlight.y}px; width: ${highlight.width}px; height: ${highlight.height}px; position: absolute; border: 2px solid rgb(148, 163, 184); background: rgba(148, 163, 184, 0.1); pointer-events: none; box-shadow: 0 0 0 2px rgba(148, 163, 184, 0.3);\"\n ></div>\n `\n : html``\n }\n `;\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-canvas-selection-overlay\": SelectionOverlay;\n }\n}\n"],"mappings":";;;;;;;;;AAkBO,6BAAMA,2BAAyB,WAAW;;;uBA0DH;sBAaP;GACnC,WAAW;GACX,WAAW;GACX,WAAW;GACZ;2BAG0C;gBAOL;uBAGd;uBAiKM;AAC5B,OAAI,CAAC,KAAK,cACR;AAIF,OAAI,CAAC,KAAK,OACR,MAAK,mBAAmB;AAI1B,QAAK,iBAAiB,sBAAsB,KAAK,QAAQ;;;;gBAnQ3C,CACd,GAAG;;;;;;;;;;;;;;;;;;;;;;;MAwBJ;;CAED,mBAAmB;AAIjB,SAAO;;CAGT,aAAa,mBAAiE;AAC5E,QAAM,eAAe,kBAAkB;;CAsDzC,oBAA0B;AACxB,QAAM,mBAAmB;AAGzB,OAAK,MAAM,WAAW;AACtB,OAAK,MAAM,MAAM;AACjB,OAAK,MAAM,OAAO;AAClB,OAAK,MAAM,QAAQ;AACnB,OAAK,MAAM,SAAS;AACpB,OAAK,MAAM,gBAAgB;AAC3B,OAAK,MAAM,SAAS;AAEpB,OAAK,aAAa,0BAA0B,OAAO;AAEnD,8BAA4B;AAE1B,OAAI,KAAK,OACP,MAAK,gBAAgB,KAAK;OAE1B,MAAK,mBAAmB;AAG1B,OAAI,KAAK,cACP,MAAK,cAAc;IAErB;;CAGJ,uBAA6B;AAC3B,QAAM,sBAAsB;AAC5B,OAAK,aAAa;;;;;;;;CASpB,QAAQ,mBAAiE;AACvE,QAAM,UAAU,kBAAkB;EAGlC,MAAM,cADY,KAAK,oBACQ,iBAAiB;AAChD,MAAI,gBAAgB,KAAK,kBACvB,MAAK,oBAAoB;AAG3B,MAAI,gBAAgB,mBAA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AO,IAAI;EAOb,MAAM,EAAE,WAAW,cAAc,KAAK;AAEtC,SAAO,IAAI;QAEP,YACI,IAAI;;;6BAGa,UAAU,EAAE,WAAW,UAAU,EAAE,aAAa,UAAU,MAAM,cAAc,UAAU,OAAO;;cAGhH,IAAI,GACT;QAEC,YACI,IAAI;;;6BAGa,UAAU,EAAE,WAAW,UAAU,EAAE,aAAa,UAAU,MAAM,cAAc,UAAU,OAAO;;cAGhH,IAAI,GACT;;;;YA/VJ,QAAQ;CAAE,SAAS;CAAkB,WAAW;CAAM,CAAC;YAGvD,QAAQ;CAAE,SAAS;CAAyB,WAAW;CAAM,CAAC;YAM9D,SAAS,EAAE,MAAM,QAAQ,CAAC;YAM1B,SAAS,EAAE,MAAM,QAAQ,CAAC;YAG1B,OAAO;YAMP,SAAS,EAAE,MAAM,QAAQ,CAAC;YAO1B,OAAO;YAOP,OAAO;YAQP,SAAS,EAAE,MAAM,SAAS,CAAC;+BAtF7B,cAAc,8BAA8B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"overlayState.js","names":[],"sources":["../../../src/canvas/overlays/overlayState.ts"],"sourcesContent":["/**\n * Overlay State Management\n *\n * This module provides a clean separation between:\n * - SEMANTICS: What should be shown? (OverlayTargets)\n * - MECHANISM: How to calculate screen bounds (calculateOverlayState)\n *\n * INVARIANTS:\n * 1. Overlay is visible iff bounds are non-null with positive dimensions\n * 2. All bounds are in screen coordinates (relative to viewport origin)\n * 3. Only one element can be highlighted at a time\n *\n * COORDINATE SPACES:\n * - Canvas space: Logical coordinates, unaffected by zoom (used for element positioning)\n * - Screen space: Viewport coordinates (used for overlay positioning)\n */\n\nimport type { PanZoomTransform } from \"../../elements/EFPanZoom.js\";\nimport type { SelectionContext } from \"../selection/selectionContext.js\";\nimport { getElementBounds } from \"../getElementBounds.js\";\n\n// ============================================================================\n// TYPES: Core Concepts\n// ============================================================================\n\n/**\n * Screen-space bounding box for overlay positioning.\n * All values are in viewport coordinates (pixels from viewport origin).\n */\nexport interface ScreenBounds {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Canvas-space bounding box (from selection context).\n */\nexport interface CanvasBounds {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\n/**\n * The complete state of all overlays.\n * Each property is either a ScreenBounds or null.\n * An overlay is visible iff its bounds are non-null.\n */\nexport interface OverlayState {\n selection: ScreenBounds | null;\n boxSelect: ScreenBounds | null;\n highlight: ScreenBounds | null;\n}\n\n/**\n * SEMANTICS: What elements should have overlays?\n * This represents the \"what\" without the \"how\".\n */\nexport interface OverlayTargets {\n selectedIds: Set<string>;\n boxSelectBounds: CanvasBounds | null;\n highlightedElementId: string | null;\n}\n\n/**\n * Interface for canvas element data (metadata).\n */\nexport interface ElementMetadata {\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation?: number;\n}\n\n/**\n * Interface for canvas that provides element data.\n */\nexport interface CanvasWithMetadata {\n getElementData(elementId: string): ElementMetadata | undefined;\n getElement?(elementId: string): HTMLElement | undefined;\n querySelector(selector: string): HTMLElement | null;\n shadowRoot: ShadowRoot | null;\n}\n\n// ============================================================================\n// SEMANTICS: Extract what should be shown\n// ============================================================================\n\n/**\n * Extract overlay targets from selection context and highlighted element.\n * This is pure SEMANTICS - it determines WHAT should be shown.\n */\nexport function getOverlayTargets(\n selection: SelectionContext | undefined,\n highlightedElement: HTMLElement | null,\n): OverlayTargets {\n return {\n selectedIds: selection?.selectedIds\n ? new Set(selection.selectedIds)\n : new Set(),\n boxSelectBounds: selection?.boxSelectBounds ?? null,\n highlightedElementId:\n highlightedElement?.getAttribute(\"data-element-id\") ??\n highlightedElement?.id ??\n null,\n };\n}\n\n// ============================================================================\n// MECHANISM: Calculate screen bounds\n// ============================================================================\n\n/**\n * Calculate screen bounds for a single element.\n * This is the SINGLE SOURCE OF TRUTH for element → screen bounds conversion.\n *\n * Strategy:\n * 1. Try to use metadata (already in canvas coordinates)\n * 2. Fall back to DOM measurement if metadata unavailable\n *\n * @param elementId - The element's ID (data-element-id or id attribute)\n * @param canvas - Canvas element with getElementData method\n * @param canvasRect - Canvas content element's bounding rect\n * @param scale - Current zoom scale\n * @returns Screen bounds or null if element not found\n */\nexport function calculateElementScreenBounds(\n elementId: string,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n scale: number,\n): ScreenBounds | null {\n const metadata = canvas.getElementData(elementId);\n\n if (metadata && metadata.width > 0 && metadata.height > 0) {\n // Use metadata (already in canvas coordinates)\n return {\n x: canvasRect.left + metadata.x * scale,\n y: canvasRect.top + metadata.y * scale,\n width: metadata.width * scale,\n height: metadata.height * scale,\n };\n }\n\n // Fallback: find element and use DOM measurement\n const element = findElement(elementId, canvas);\n if (!element) return null;\n\n const bounds = getElementBounds(element);\n return {\n x: bounds.left,\n y: bounds.top,\n width: bounds.width,\n height: bounds.height,\n };\n}\n\n/**\n * Find an element by ID in the canvas (checks both light DOM and shadow DOM).\n */\nfunction findElement(\n elementId: string,\n canvas: CanvasWithMetadata,\n): HTMLElement | null {\n // Try canvas's getElement method first\n if (canvas.getElement) {\n const element = canvas.getElement(elementId);\n if (element) return element;\n }\n\n // Try shadow DOM\n if (canvas.shadowRoot) {\n const element = canvas.shadowRoot.querySelector(\n `[data-element-id=\"${elementId}\"]`,\n ) as HTMLElement | null;\n if (element) return element;\n }\n\n // Try light DOM\n return canvas.querySelector(\n `[data-element-id=\"${elementId}\"]`,\n ) as HTMLElement | null;\n}\n\n/**\n * Calculate the union of multiple bounds (bounding box that contains all).\n */\nexport function unionBounds(bounds: ScreenBounds[]): ScreenBounds | null {\n if (bounds.length === 0) return null;\n\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const b of bounds) {\n minX = Math.min(minX, b.x);\n minY = Math.min(minY, b.y);\n maxX = Math.max(maxX, b.x + b.width);\n maxY = Math.max(maxY, b.y + b.height);\n }\n\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY,\n };\n}\n\n/**\n * Calculate selection bounds for all selected elements.\n */\nexport function calculateSelectionBounds(\n selectedIds: Set<string>,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n scale: number,\n): ScreenBounds | null {\n if (selectedIds.size === 0) return null;\n\n const elementBounds = Array.from(selectedIds)\n .map((id) => calculateElementScreenBounds(id, canvas, canvasRect, scale))\n .filter((b): b is ScreenBounds => b !== null);\n\n return unionBounds(elementBounds);\n}\n\n/**\n * Calculate box-select bounds (convert canvas bounds to screen bounds).\n *\n * @param boxSelectBounds - Box selection bounds in canvas coordinates\n * @param panZoomElement - The pan-zoom element (for canvasToScreen conversion)\n * @param panZoomTransform - Current pan-zoom transform\n * @returns Screen bounds or null\n */\nexport function calculateBoxSelectBounds(\n boxSelectBounds: CanvasBounds | null,\n panZoomElement: HTMLElement | null,\n panZoomTransform: PanZoomTransform | undefined,\n): ScreenBounds | null {\n if (!boxSelectBounds || !panZoomElement || !panZoomTransform) {\n return null;\n }\n\n // Try to use EFPanZoom's canvasToScreen method if available\n const pz = panZoomElement as any;\n if (typeof pz.canvasToScreen === \"function\") {\n const topLeft = pz.canvasToScreen(\n boxSelectBounds.left,\n boxSelectBounds.top,\n );\n const bottomRight = pz.canvasToScreen(\n boxSelectBounds.right,\n boxSelectBounds.bottom,\n );\n\n return {\n x: topLeft.x,\n y: topLeft.y,\n width: bottomRight.x - topLeft.x,\n height: bottomRight.y - topLeft.y,\n };\n }\n\n // Fallback: manual calculation\n const panZoomRect = panZoomElement.getBoundingClientRect();\n const { scale, x, y } = panZoomTransform;\n\n const screenLeft = panZoomRect.left + boxSelectBounds.left * scale + x;\n const screenTop = panZoomRect.top + boxSelectBounds.top * scale + y;\n const screenRight = panZoomRect.left + boxSelectBounds.right * scale + x;\n const screenBottom = panZoomRect.top + boxSelectBounds.bottom * scale + y;\n\n return {\n x: screenLeft,\n y: screenTop,\n width: screenRight - screenLeft,\n height: screenBottom - screenTop,\n };\n}\n\n/**\n * Calculate highlight bounds for the highlighted element.\n */\nexport function calculateHighlightBounds(\n highlightedElementId: string | null,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n scale: number,\n): ScreenBounds | null {\n if (!highlightedElementId) return null;\n\n return calculateElementScreenBounds(\n highlightedElementId,\n canvas,\n canvasRect,\n scale,\n );\n}\n\n// ============================================================================\n// MAIN: Calculate complete overlay state\n// ============================================================================\n\n/**\n * Calculate the complete overlay state from targets.\n * This is the main entry point that combines semantics and mechanism.\n *\n * @param targets - What should be shown (from getOverlayTargets)\n * @param canvas - Canvas element with metadata\n * @param canvasRect - Canvas content bounding rect\n * @param panZoomElement - Pan-zoom element (for box-select conversion)\n * @param panZoomTransform - Current transform\n * @returns Complete overlay state\n */\nexport function calculateOverlayState(\n targets: OverlayTargets,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n panZoomElement: HTMLElement | null,\n panZoomTransform: PanZoomTransform | undefined,\n): OverlayState {\n const scale = panZoomTransform?.scale ?? 1;\n\n return {\n selection: calculateSelectionBounds(\n targets.selectedIds,\n canvas,\n canvasRect,\n scale,\n ),\n boxSelect: calculateBoxSelectBounds(\n targets.boxSelectBounds,\n panZoomElement,\n panZoomTransform,\n ),\n highlight: calculateHighlightBounds(\n targets.highlightedElementId,\n canvas,\n canvasRect,\n scale,\n ),\n };\n}\n\n// ============================================================================\n// INVARIANTS: Helper functions to check invariants\n// ============================================================================\n\n/**\n * INVARIANT: Overlay is visible iff bounds exist with positive dimensions.\n */\nexport function isOverlayVisible(bounds: ScreenBounds | null): boolean {\n return bounds !== null && bounds.width > 0 && bounds.height > 0;\n}\n\n/**\n * Check if overlay state has any visible overlays.\n */\nexport function hasVisibleOverlays(state: OverlayState): boolean {\n return (\n isOverlayVisible(state.selection) ||\n isOverlayVisible(state.boxSelect) ||\n isOverlayVisible(state.highlight)\n );\n}\n"],"mappings":";;;;;;;AAiGA,SAAgB,kBACd,WACA,oBACgB;AAChB,QAAO;EACL,aAAa,WAAW,cACpB,IAAI,IAAI,UAA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QAAQ,kBAAkB,SAAS;AAEzC,QAAO;EACL,WAAW,yBACT,QAAQ,aACR,QACA,YACA,MACD;EACD,WAAW,yBACT,QAAQ,iBACR,gBACA,iBACD;EACD,WAAW,yBACT,QAAQ,sBACR,QACA,YACA,MACD;EACF"}
|
|
1
|
+
{"version":3,"file":"overlayState.js","names":[],"sources":["../../../src/canvas/overlays/overlayState.ts"],"sourcesContent":["/**\n * Overlay State Management\n *\n * This module provides a clean separation between:\n * - SEMANTICS: What should be shown? (OverlayTargets)\n * - MECHANISM: How to calculate screen bounds (calculateOverlayState)\n *\n * INVARIANTS:\n * 1. Overlay is visible iff bounds are non-null with positive dimensions\n * 2. All bounds are in screen coordinates (relative to viewport origin)\n * 3. Only one element can be highlighted at a time\n *\n * COORDINATE SPACES:\n * - Canvas space: Logical coordinates, unaffected by zoom (used for element positioning)\n * - Screen space: Viewport coordinates (used for overlay positioning)\n */\n\nimport type { PanZoomTransform } from \"../../elements/EFPanZoom.js\";\nimport type { SelectionContext } from \"../selection/selectionContext.js\";\nimport { getElementBounds } from \"../getElementBounds.js\";\n\n// ============================================================================\n// TYPES: Core Concepts\n// ============================================================================\n\n/**\n * Screen-space bounding box for overlay positioning.\n * All values are in viewport coordinates (pixels from viewport origin).\n */\nexport interface ScreenBounds {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * Canvas-space bounding box (from selection context).\n */\nexport interface CanvasBounds {\n left: number;\n top: number;\n right: number;\n bottom: number;\n}\n\n/**\n * The complete state of all overlays.\n * Each property is either a ScreenBounds or null.\n * An overlay is visible iff its bounds are non-null.\n */\nexport interface OverlayState {\n selection: ScreenBounds | null;\n boxSelect: ScreenBounds | null;\n highlight: ScreenBounds | null;\n}\n\n/**\n * SEMANTICS: What elements should have overlays?\n * This represents the \"what\" without the \"how\".\n */\nexport interface OverlayTargets {\n selectedIds: Set<string>;\n boxSelectBounds: CanvasBounds | null;\n highlightedElementId: string | null;\n}\n\n/**\n * Interface for canvas element data (metadata).\n */\nexport interface ElementMetadata {\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation?: number;\n}\n\n/**\n * Interface for canvas that provides element data.\n */\nexport interface CanvasWithMetadata {\n getElementData(elementId: string): ElementMetadata | undefined;\n getElement?(elementId: string): HTMLElement | undefined;\n querySelector(selector: string): HTMLElement | null;\n shadowRoot: ShadowRoot | null;\n}\n\n// ============================================================================\n// SEMANTICS: Extract what should be shown\n// ============================================================================\n\n/**\n * Extract overlay targets from selection context and highlighted element.\n * This is pure SEMANTICS - it determines WHAT should be shown.\n */\nexport function getOverlayTargets(\n selection: SelectionContext | undefined,\n highlightedElement: HTMLElement | null,\n): OverlayTargets {\n return {\n selectedIds: selection?.selectedIds ? new Set(selection.selectedIds) : new Set(),\n boxSelectBounds: selection?.boxSelectBounds ?? null,\n highlightedElementId:\n highlightedElement?.getAttribute(\"data-element-id\") ?? highlightedElement?.id ?? null,\n };\n}\n\n// ============================================================================\n// MECHANISM: Calculate screen bounds\n// ============================================================================\n\n/**\n * Calculate screen bounds for a single element.\n * This is the SINGLE SOURCE OF TRUTH for element → screen bounds conversion.\n *\n * Strategy:\n * 1. Try to use metadata (already in canvas coordinates)\n * 2. Fall back to DOM measurement if metadata unavailable\n *\n * @param elementId - The element's ID (data-element-id or id attribute)\n * @param canvas - Canvas element with getElementData method\n * @param canvasRect - Canvas content element's bounding rect\n * @param scale - Current zoom scale\n * @returns Screen bounds or null if element not found\n */\nexport function calculateElementScreenBounds(\n elementId: string,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n scale: number,\n): ScreenBounds | null {\n const metadata = canvas.getElementData(elementId);\n\n if (metadata && metadata.width > 0 && metadata.height > 0) {\n // Use metadata (already in canvas coordinates)\n return {\n x: canvasRect.left + metadata.x * scale,\n y: canvasRect.top + metadata.y * scale,\n width: metadata.width * scale,\n height: metadata.height * scale,\n };\n }\n\n // Fallback: find element and use DOM measurement\n const element = findElement(elementId, canvas);\n if (!element) return null;\n\n const bounds = getElementBounds(element);\n return {\n x: bounds.left,\n y: bounds.top,\n width: bounds.width,\n height: bounds.height,\n };\n}\n\n/**\n * Find an element by ID in the canvas (checks both light DOM and shadow DOM).\n */\nfunction findElement(elementId: string, canvas: CanvasWithMetadata): HTMLElement | null {\n // Try canvas's getElement method first\n if (canvas.getElement) {\n const element = canvas.getElement(elementId);\n if (element) return element;\n }\n\n // Try shadow DOM\n if (canvas.shadowRoot) {\n const element = canvas.shadowRoot.querySelector(\n `[data-element-id=\"${elementId}\"]`,\n ) as HTMLElement | null;\n if (element) return element;\n }\n\n // Try light DOM\n return canvas.querySelector(`[data-element-id=\"${elementId}\"]`) as HTMLElement | null;\n}\n\n/**\n * Calculate the union of multiple bounds (bounding box that contains all).\n */\nexport function unionBounds(bounds: ScreenBounds[]): ScreenBounds | null {\n if (bounds.length === 0) return null;\n\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const b of bounds) {\n minX = Math.min(minX, b.x);\n minY = Math.min(minY, b.y);\n maxX = Math.max(maxX, b.x + b.width);\n maxY = Math.max(maxY, b.y + b.height);\n }\n\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY,\n };\n}\n\n/**\n * Calculate selection bounds for all selected elements.\n */\nexport function calculateSelectionBounds(\n selectedIds: Set<string>,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n scale: number,\n): ScreenBounds | null {\n if (selectedIds.size === 0) return null;\n\n const elementBounds = Array.from(selectedIds)\n .map((id) => calculateElementScreenBounds(id, canvas, canvasRect, scale))\n .filter((b): b is ScreenBounds => b !== null);\n\n return unionBounds(elementBounds);\n}\n\n/**\n * Calculate box-select bounds (convert canvas bounds to screen bounds).\n *\n * @param boxSelectBounds - Box selection bounds in canvas coordinates\n * @param panZoomElement - The pan-zoom element (for canvasToScreen conversion)\n * @param panZoomTransform - Current pan-zoom transform\n * @returns Screen bounds or null\n */\nexport function calculateBoxSelectBounds(\n boxSelectBounds: CanvasBounds | null,\n panZoomElement: HTMLElement | null,\n panZoomTransform: PanZoomTransform | undefined,\n): ScreenBounds | null {\n if (!boxSelectBounds || !panZoomElement || !panZoomTransform) {\n return null;\n }\n\n // Try to use EFPanZoom's canvasToScreen method if available\n const pz = panZoomElement as any;\n if (typeof pz.canvasToScreen === \"function\") {\n const topLeft = pz.canvasToScreen(boxSelectBounds.left, boxSelectBounds.top);\n const bottomRight = pz.canvasToScreen(boxSelectBounds.right, boxSelectBounds.bottom);\n\n return {\n x: topLeft.x,\n y: topLeft.y,\n width: bottomRight.x - topLeft.x,\n height: bottomRight.y - topLeft.y,\n };\n }\n\n // Fallback: manual calculation\n const panZoomRect = panZoomElement.getBoundingClientRect();\n const { scale, x, y } = panZoomTransform;\n\n const screenLeft = panZoomRect.left + boxSelectBounds.left * scale + x;\n const screenTop = panZoomRect.top + boxSelectBounds.top * scale + y;\n const screenRight = panZoomRect.left + boxSelectBounds.right * scale + x;\n const screenBottom = panZoomRect.top + boxSelectBounds.bottom * scale + y;\n\n return {\n x: screenLeft,\n y: screenTop,\n width: screenRight - screenLeft,\n height: screenBottom - screenTop,\n };\n}\n\n/**\n * Calculate highlight bounds for the highlighted element.\n */\nexport function calculateHighlightBounds(\n highlightedElementId: string | null,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n scale: number,\n): ScreenBounds | null {\n if (!highlightedElementId) return null;\n\n return calculateElementScreenBounds(highlightedElementId, canvas, canvasRect, scale);\n}\n\n// ============================================================================\n// MAIN: Calculate complete overlay state\n// ============================================================================\n\n/**\n * Calculate the complete overlay state from targets.\n * This is the main entry point that combines semantics and mechanism.\n *\n * @param targets - What should be shown (from getOverlayTargets)\n * @param canvas - Canvas element with metadata\n * @param canvasRect - Canvas content bounding rect\n * @param panZoomElement - Pan-zoom element (for box-select conversion)\n * @param panZoomTransform - Current transform\n * @returns Complete overlay state\n */\nexport function calculateOverlayState(\n targets: OverlayTargets,\n canvas: CanvasWithMetadata,\n canvasRect: DOMRect,\n panZoomElement: HTMLElement | null,\n panZoomTransform: PanZoomTransform | undefined,\n): OverlayState {\n const scale = panZoomTransform?.scale ?? 1;\n\n return {\n selection: calculateSelectionBounds(targets.selectedIds, canvas, canvasRect, scale),\n boxSelect: calculateBoxSelectBounds(targets.boxSelectBounds, panZoomElement, panZoomTransform),\n highlight: calculateHighlightBounds(targets.highlightedElementId, canvas, canvasRect, scale),\n };\n}\n\n// ============================================================================\n// INVARIANTS: Helper functions to check invariants\n// ============================================================================\n\n/**\n * INVARIANT: Overlay is visible iff bounds exist with positive dimensions.\n */\nexport function isOverlayVisible(bounds: ScreenBounds | null): boolean {\n return bounds !== null && bounds.width > 0 && bounds.height > 0;\n}\n\n/**\n * Check if overlay state has any visible overlays.\n */\nexport function hasVisibleOverlays(state: OverlayState): boolean {\n return (\n isOverlayVisible(state.selection) ||\n isOverlayVisible(state.boxSelect) ||\n isOverlayVisible(state.highlight)\n );\n}\n"],"mappings":";;;;;;;AAiGA,SAAgB,kBACd,WACA,oBACgB;AAChB,QAAO;EACL,aAAa,WAAW,cAAc,IAAI,IAAI,UAAU,YAAY,mBAAG,IAAI,KAAK;EAChF,iBAAiB,WAAW,mBAAmB;EAC/C,sBACE,oBAAoB,aAAa,kBAAkB,IAAI,oBAAoB,MAAM;EACpF;;;;;;;;;;;;;;;;AAqBH,SAAgB,6BACd,WACA,QACA,YACA,OACqB;CACrB,MAAM,WAAW,OAAO,eAAe,UAAU;AAEjD,KAAI,YAAY,SAAS,QAAQ,KAAK,SAAS,SAAS,EAEtD,QAAO;EACL,GAAG,WAAW,OAAO,SAAS,IAAI;EAClC,GAAG,WAAW,MAAM,SAAS,IAAI;EACjC,OAAO,SAAS,QAAQ;EACxB,QAAQ,SAAS,SAAS;EAC3B;CAIH,MAAM,UAAU,YAAY,WAAW,OAAO;AAC9C,KAAI,CAAC,QAAS,QAAO;CAErB,MAAM,SAAS,iBAAiB,QAAQ;AACxC,QAAO;EACL,GAAG,OAAO;EACV,GAAG,OAAO;EAC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AgB,OAAO,gBAAgB,OAAO;AAEpF,SAAO;GACL,GAAG,QAAQ;GACX,GAAG,QAAQ;GACX,OAAO,YAAY,IAAI,QAAQ;GAC/B,QAAQ,YAAY,IAAI,QAAQ;GACjC;;CAIH,MAAM,cAAc,eAAe,uBAAuB;CAC1D,MAAM,EAAE,OAAO,GAAG,MAAM;CAExB,MAAM,aAAa,YAAY,OAAO,gBAAgB,OAAO,QAAQ;CACrE,MAAM,YAAY,YAAY,MAAM,gBAAgB,MAAM,QAAQ;CAClE,MAAM,cAAc,YAAY,OAAO,gBAAgB,QAAQ,QAAQ;CACvE,MAAM,eAAe,YAAY,MAAM,gBAAgB,SAAS,QAAQ;AAExE,QAAO;EACL,GAAG;EACH,GAAG;EACH,OAAO,cAAc;EACrB,QAAQ,eAAe;EACxB;;;;;AAMH,SAAgB,yBACd,sBACA,QACA,YACA,OACqB;AACrB,KAAI,CAAC,qBAAsB,QAAO;AAElC,QAAO,6BAA6B,sBAAsB,QAAQ,YAAY,MAAM;;;;;;;;;;;;;AAkBtF,SAAgB,sBACd,SACA,QACA,YACA,gBACA,kBACc;CACd,MAAM,QAAQ,kBAAkB,SAAS;AAEzC,QAAO;EACL,WAAW,yBAAyB,QAAQ,aAAa,QAAQ,YAAY,MAAM;EACnF,WAAW,yBAAyB,QAAQ,iBAAiB,gBAAgB,iBAAiB;EAC9F,WAAW,yBAAyB,QAAQ,sBAAsB,QAAQ,YAAY,MAAM;EAC7F"}
|
|
@@ -34,63 +34,65 @@ var SelectionController = class {
|
|
|
34
34
|
* Create a proxy context that delegates to the selection model.
|
|
35
35
|
*/
|
|
36
36
|
createContextProxy() {
|
|
37
|
-
const
|
|
37
|
+
const selectionModel = this.selectionModel;
|
|
38
|
+
const getHost = () => this.host;
|
|
39
|
+
const getHitTestFn = () => this.hitTestFn;
|
|
38
40
|
return new Proxy({
|
|
39
41
|
select: (id) => {
|
|
40
|
-
|
|
42
|
+
selectionModel.select(id);
|
|
41
43
|
},
|
|
42
44
|
selectMultiple: (ids) => {
|
|
43
|
-
|
|
45
|
+
selectionModel.selectMultiple(ids);
|
|
44
46
|
},
|
|
45
47
|
addToSelection: (id) => {
|
|
46
|
-
|
|
48
|
+
selectionModel.addToSelection(id);
|
|
47
49
|
},
|
|
48
50
|
deselect: (id) => {
|
|
49
|
-
|
|
51
|
+
selectionModel.deselect(id);
|
|
50
52
|
},
|
|
51
53
|
toggle: (id) => {
|
|
52
|
-
|
|
54
|
+
selectionModel.toggle(id);
|
|
53
55
|
},
|
|
54
56
|
clear: () => {
|
|
55
|
-
|
|
57
|
+
selectionModel.clear();
|
|
56
58
|
},
|
|
57
59
|
startBoxSelect: (x, y) => {
|
|
58
|
-
|
|
59
|
-
queueMicrotask(() =>
|
|
60
|
+
selectionModel.startBoxSelect(x, y);
|
|
61
|
+
queueMicrotask(() => getHost().requestUpdate());
|
|
60
62
|
},
|
|
61
63
|
updateBoxSelect: (x, y) => {
|
|
62
|
-
|
|
63
|
-
queueMicrotask(() =>
|
|
64
|
+
selectionModel.updateBoxSelect(x, y);
|
|
65
|
+
queueMicrotask(() => getHost().requestUpdate());
|
|
64
66
|
},
|
|
65
67
|
endBoxSelect: (hitTest, addToSelection) => {
|
|
66
|
-
const fn = hitTest ||
|
|
67
|
-
if (fn)
|
|
68
|
+
const fn = hitTest || getHitTestFn();
|
|
69
|
+
if (fn) selectionModel.endBoxSelect(fn, addToSelection ?? false);
|
|
68
70
|
},
|
|
69
71
|
createGroup: (ids) => {
|
|
70
|
-
return
|
|
72
|
+
return selectionModel.createGroup(ids);
|
|
71
73
|
},
|
|
72
74
|
ungroup: (groupId) => {
|
|
73
|
-
|
|
75
|
+
selectionModel.ungroup(groupId);
|
|
74
76
|
},
|
|
75
77
|
selectGroup: (groupId) => {
|
|
76
|
-
|
|
78
|
+
selectionModel.selectGroup(groupId);
|
|
77
79
|
},
|
|
78
80
|
getGroupId: (elementId) => {
|
|
79
|
-
return
|
|
81
|
+
return selectionModel.getGroupId(elementId);
|
|
80
82
|
},
|
|
81
83
|
getGroupElements: (groupId) => {
|
|
82
|
-
return
|
|
84
|
+
return selectionModel.getGroupElements(groupId);
|
|
83
85
|
},
|
|
84
86
|
addEventListener: (type, listener) => {
|
|
85
|
-
|
|
87
|
+
selectionModel.addEventListener(type, listener);
|
|
86
88
|
},
|
|
87
89
|
removeEventListener: (type, listener) => {
|
|
88
|
-
|
|
90
|
+
selectionModel.removeEventListener(type, listener);
|
|
89
91
|
}
|
|
90
92
|
}, { get(target, prop) {
|
|
91
|
-
if (prop === "selectedIds") return
|
|
92
|
-
if (prop === "selectionMode") return
|
|
93
|
-
if (prop === "boxSelectBounds") return
|
|
93
|
+
if (prop === "selectedIds") return selectionModel.selectedIds;
|
|
94
|
+
if (prop === "selectionMode") return selectionModel.selectionMode;
|
|
95
|
+
if (prop === "boxSelectBounds") return selectionModel.boxSelectBounds;
|
|
94
96
|
return target[prop];
|
|
95
97
|
} });
|
|
96
98
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SelectionController.js","names":[],"sources":["../../../src/canvas/selection/SelectionController.ts"],"sourcesContent":["import type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { SelectionModel } from \"./SelectionModel.js\";\nimport type { SelectionContext } from \"./selectionContext.js\";\n\n/**\n * Reactive controller that bridges SelectionModel and Lit element lifecycle.\n * Provides selection context to child elements.\n */\nexport class SelectionController implements ReactiveController {\n private host: ReactiveControllerHost;\n private selectionModel: SelectionModel;\n private hitTestFn: ((bounds: DOMRect) => string[]) | null = null;\n selectionContext: SelectionContext;\n\n constructor(host: ReactiveControllerHost) {\n this.host = host;\n this.selectionModel = new SelectionModel();\n this.selectionContext = this.createContextProxy();\n host.addController(this);\n\n // Listen to selection change events from the model\n // Use queueMicrotask to defer the update and avoid Lit warning about\n // scheduling updates after update completed (change-in-update)\n this.selectionModel.addEventListener(\"selectionchange\", () => {\n queueMicrotask(() => this.host.requestUpdate());\n });\n }\n\n hostConnected(): void {\n // Context is provided via @provide decorator\n }\n\n hostDisconnected(): void {\n // Cleanup if needed\n }\n\n /**\n * Set the hit test function for box selection.\n */\n setHitTest(fn: (bounds: DOMRect) => string[]): void {\n this.hitTestFn = fn;\n }\n\n /**\n * Get the underlying selection model.\n */\n getModel(): SelectionModel {\n return this.selectionModel;\n }\n\n /**\n * Create a proxy context that delegates to the selection model.\n */\n private createContextProxy(): SelectionContext {\n const
|
|
1
|
+
{"version":3,"file":"SelectionController.js","names":[],"sources":["../../../src/canvas/selection/SelectionController.ts"],"sourcesContent":["import type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { SelectionModel } from \"./SelectionModel.js\";\nimport type { SelectionContext } from \"./selectionContext.js\";\n\n/**\n * Reactive controller that bridges SelectionModel and Lit element lifecycle.\n * Provides selection context to child elements.\n */\nexport class SelectionController implements ReactiveController {\n private host: ReactiveControllerHost;\n private selectionModel: SelectionModel;\n private hitTestFn: ((bounds: DOMRect) => string[]) | null = null;\n selectionContext: SelectionContext;\n\n constructor(host: ReactiveControllerHost) {\n this.host = host;\n this.selectionModel = new SelectionModel();\n this.selectionContext = this.createContextProxy();\n host.addController(this);\n\n // Listen to selection change events from the model\n // Use queueMicrotask to defer the update and avoid Lit warning about\n // scheduling updates after update completed (change-in-update)\n this.selectionModel.addEventListener(\"selectionchange\", () => {\n queueMicrotask(() => this.host.requestUpdate());\n });\n }\n\n hostConnected(): void {\n // Context is provided via @provide decorator\n }\n\n hostDisconnected(): void {\n // Cleanup if needed\n }\n\n /**\n * Set the hit test function for box selection.\n */\n setHitTest(fn: (bounds: DOMRect) => string[]): void {\n this.hitTestFn = fn;\n }\n\n /**\n * Get the underlying selection model.\n */\n getModel(): SelectionModel {\n return this.selectionModel;\n }\n\n /**\n * Create a proxy context that delegates to the selection model.\n */\n private createContextProxy(): SelectionContext {\n const selectionModel = this.selectionModel;\n const getHost = () => this.host;\n const getHitTestFn = () => this.hitTestFn;\n return new Proxy(\n {\n select: (id: string) => {\n selectionModel.select(id);\n // Event will trigger requestUpdate via event listener\n },\n selectMultiple: (ids: string[]) => {\n selectionModel.selectMultiple(ids);\n // Event will trigger requestUpdate via event listener\n },\n addToSelection: (id: string) => {\n selectionModel.addToSelection(id);\n // Event will trigger requestUpdate via event listener\n },\n deselect: (id: string) => {\n selectionModel.deselect(id);\n // Event will trigger requestUpdate via event listener\n },\n toggle: (id: string) => {\n selectionModel.toggle(id);\n // Event will trigger requestUpdate via event listener\n },\n clear: () => {\n selectionModel.clear();\n // Event will trigger requestUpdate via event listener\n },\n startBoxSelect: (x: number, y: number) => {\n selectionModel.startBoxSelect(x, y);\n queueMicrotask(() => getHost().requestUpdate());\n },\n updateBoxSelect: (x: number, y: number) => {\n selectionModel.updateBoxSelect(x, y);\n queueMicrotask(() => getHost().requestUpdate());\n },\n endBoxSelect: (hitTest: (bounds: DOMRect) => string[], addToSelection?: boolean) => {\n const fn = hitTest || getHitTestFn();\n if (fn) {\n selectionModel.endBoxSelect(fn, addToSelection ?? false);\n }\n // Event will trigger requestUpdate via event listener\n },\n createGroup: (ids: string[]) => {\n const groupId = selectionModel.createGroup(ids);\n return groupId;\n },\n ungroup: (groupId: string) => {\n selectionModel.ungroup(groupId);\n },\n selectGroup: (groupId: string) => {\n selectionModel.selectGroup(groupId);\n // Event will trigger requestUpdate via event listener\n },\n getGroupId: (elementId: string) => {\n return selectionModel.getGroupId(elementId);\n },\n getGroupElements: (groupId: string) => {\n return selectionModel.getGroupElements(groupId);\n },\n addEventListener: (type: \"selectionchange\", listener: (event: CustomEvent) => void) => {\n selectionModel.addEventListener(type, listener as EventListener);\n },\n removeEventListener: (type: \"selectionchange\", listener: (event: CustomEvent) => void) => {\n selectionModel.removeEventListener(type, listener as EventListener);\n },\n } as Omit<SelectionContext, \"selectedIds\" | \"selectionMode\" | \"boxSelectBounds\">,\n {\n get(target, prop) {\n if (prop === \"selectedIds\") {\n return selectionModel.selectedIds;\n }\n if (prop === \"selectionMode\") {\n return selectionModel.selectionMode;\n }\n if (prop === \"box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AAU,YAAoB;AAC5B,mBAAe,QAAQ,QAAQ;;GAEjC,cAAc,YAAoB;AAChC,mBAAe,YAAY,QAAQ;;GAGrC,aAAa,cAAsB;AACjC,WAAO,eAAe,WAAW,UAAU;;GAE7C,mBAAmB,YAAoB;AACrC,WAAO,eAAe,iBAAiB,QAAQ;;GAEjD,mBAAmB,MAAyB,aAA2C;AACrF,mBAAe,iBAAiB,MAAM,SAA0B;;GAElE,sBAAsB,MAAyB,aAA2C;AACxF,mBAAe,oBAAoB,MAAM,SAA0B;;GAEtE,EACD,EACE,IAAI,QAAQ,MAAM;AAChB,OAAI,SAAS,cACX,QAAO,eAAe;AAExB,OAAI,SAAS,gBACX,QAAO,eAAe;AAExB,OAAI,SAAS,kBACX,QAAO,eAAe;AAExB,UAAQ,OAAe;KAE1B,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SelectionModel.js","names":[],"sources":["../../../src/canvas/selection/SelectionModel.ts"],"sourcesContent":["import type { SelectionState } from \"../api/types.js\";\n\n/**\n * Create a DOMRect-like object. Polyfill for Node.js environments.\n */\nfunction createRect(\n x: number,\n y: number,\n width: number,\n height: number,\n): DOMRect {\n if (typeof DOMRect !== \"undefined\") {\n return new DOMRect(x, y, width, height);\n }\n // Polyfill for Node.js\n return {\n x,\n y,\n width,\n height,\n left: x,\n top: y,\n right: x + width,\n bottom: y + height,\n toJSON: () => ({ x, y, width, height }),\n } as DOMRect;\n}\n\n/**\n * Pure selection logic - semantics separate from mechanism.\n * Manages selection state and operations.\n */\nexport class SelectionModel extends EventTarget {\n private _selectedIds = new Set<string>();\n private _primaryId: string | null = null;\n private _selectionMode: SelectionState = \"none\";\n private _boxSelectStart: { x: number; y: number } | null = null;\n private _boxSelectCurrent: { x: number; y: number } | null = null;\n private _groups = new Map<string, Set<string>>();\n private _elementToGroup = new Map<string, string>();\n\n /**\n * Emit selectionchange event with current selection state.\n */\n private _emitSelectionChange(): void {\n // Convert Set to array with primary first\n const selectedIdsArray =\n this._primaryId && this._selectedIds.has(this._primaryId)\n ? [\n this._primaryId,\n ...Array.from(this._selectedIds).filter(\n (id) => id !== this._primaryId,\n ),\n ]\n : Array.from(this._selectedIds);\n\n this.dispatchEvent(\n new CustomEvent(\"selectionchange\", {\n detail: {\n selectedIds: selectedIdsArray,\n selectionMode: this._selectionMode,\n },\n bubbles: false,\n composed: false,\n }),\n );\n }\n\n /**\n * Get current selection state.\n */\n get selectedIds(): ReadonlySet<string> {\n return this._selectedIds;\n }\n\n /**\n * Get current selection mode.\n */\n get selectionMode(): SelectionState {\n return this._selectionMode;\n }\n\n /**\n * Get current box selection bounds, if active.\n */\n get boxSelectBounds(): DOMRect | null {\n if (!this._boxSelectStart || !this._boxSelectCurrent) {\n return null;\n }\n const left = Math.min(this._boxSelectStart.x, this._boxSelectCurrent.x);\n const top = Math.min(this._boxSelectStart.y, this._boxSelectCurrent.y);\n const right = Math.max(this._boxSelectStart.x, this._boxSelectCurrent.x);\n const bottom = Math.max(this._boxSelectStart.y, this._boxSelectCurrent.y);\n return createRect(left, top, right - left, bottom - top);\n }\n\n /**\n * Select a single element.\n */\n select(id: string): void {\n this._selectedIds.clear();\n this._selectedIds.add(id);\n this._primaryId = id;\n this._selectionMode = \"single\";\n this._emitSelectionChange();\n }\n\n /**\n * Select multiple elements.\n */\n selectMultiple(ids: string[]): void {\n this._selectedIds.clear();\n for (const id of ids) {\n this._selectedIds.add(id);\n }\n this._primaryId = ids.length > 0 ? (ids[0] ?? null) : null;\n this._selectionMode =\n ids.length === 0 ? \"none\" : ids.length === 1 ? \"single\" : \"multiple\";\n this._emitSelectionChange();\n }\n\n /**\n * Add element to selection (for multi-select).\n */\n addToSelection(id: string): void {\n this._selectedIds.add(id);\n if (!this._primaryId) {\n this._primaryId = id;\n }\n this._updateSelectionMode();\n this._emitSelectionChange();\n }\n\n /**\n * Remove element from selection.\n */\n deselect(id: string): void {\n this._selectedIds.delete(id);\n if (this._primaryId === id) {\n // Set primary to first remaining, or null if none\n const remaining = Array.from(this._selectedIds);\n this._primaryId = remaining.length > 0 ? (remaining[0] ?? null) : null;\n }\n this._updateSelectionMode();\n this._emitSelectionChange();\n }\n\n /**\n * Toggle element selection state.\n */\n toggle(id: string): void {\n if (this._selectedIds.has(id)) {\n this.deselect(id);\n } else {\n this.addToSelection(id);\n }\n }\n\n /**\n * Clear all selections.\n */\n clear(): void {\n this._selectedIds.clear();\n this._primaryId = null;\n this._selectionMode = \"none\";\n this._boxSelectStart = null;\n this._boxSelectCurrent = null;\n this._emitSelectionChange();\n }\n\n /**\n * Start box selection.\n */\n startBoxSelect(x: number, y: number): void {\n this._boxSelectStart = { x, y };\n this._boxSelectCurrent = { x, y };\n this._selectionMode = \"box-selecting\";\n }\n\n /**\n * Update box selection.\n */\n updateBoxSelect(x: number, y: number): void {\n if (this._selectionMode !== \"box-selecting\") {\n return;\n }\n this._boxSelectCurrent = { x, y };\n }\n\n /**\n * End box selection and select elements within bounds.\n * @param hitTest - Function to find elements within bounds\n * @param addToSelection - If true, add to existing selection; if false, replace selection\n */\n endBoxSelect(\n hitTest: (bounds: DOMRect) => string[],\n addToSelection = false,\n ): void {\n if (\n this._selectionMode !== \"box-selecting\" ||\n !this._boxSelectStart ||\n !this._boxSelectCurrent\n ) {\n return;\n }\n const bounds = this.boxSelectBounds;\n if (bounds) {\n const ids = hitTest(bounds);\n if (addToSelection) {\n // Add each element to selection\n for (const id of ids) {\n this.addToSelection(id);\n }\n } else {\n // Replace selection\n this.selectMultiple(ids);\n }\n }\n this._boxSelectStart = null;\n this._boxSelectCurrent = null;\n // Note: selectMultiple/addToSelection already emit events, so no need to emit again\n }\n\n /**\n * Create a group from selected elements.\n */\n createGroup(ids: string[]): string {\n if (ids.length === 0) {\n throw new Error(\"Cannot create group with no elements\");\n }\n const groupId = `group-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const groupSet = new Set(ids);\n this._groups.set(groupId, groupSet);\n for (const id of ids) {\n this._elementToGroup.set(id, groupId);\n }\n return groupId;\n }\n\n /**\n * Ungroup a group.\n */\n ungroup(groupId: string): void {\n const group = this._groups.get(groupId);\n if (!group) {\n return;\n }\n for (const id of group) {\n this._elementToGroup.delete(id);\n }\n this._groups.delete(groupId);\n }\n\n /**\n * Select all elements in a group.\n */\n selectGroup(groupId: string): void {\n const group = this._groups.get(groupId);\n if (!group) {\n return;\n }\n this.selectMultiple(Array.from(group));\n // Note: selectMultiple already emits event\n }\n\n /**\n * Get group ID for an element, if any.\n */\n getGroupId(elementId: string): string | undefined {\n return this._elementToGroup.get(elementId);\n }\n\n /**\n * Get all element IDs in a group.\n */\n getGroupElements(groupId: string): string[] {\n const group = this._groups.get(groupId);\n return group ? Array.from(group) : [];\n }\n\n /**\n * Update selection mode based on current selection count.\n */\n private _updateSelectionMode(): void {\n const count = this._selectedIds.size;\n if (count === 0) {\n this._selectionMode = \"none\";\n } else if (count === 1) {\n this._selectionMode = \"single\";\n } else {\n this._selectionMode = \"multiple\";\n }\n }\n}\n"],"mappings":";;;;AAKA,SAAS,WACP,GACA,GACA,OACA,QACS;AACT,KAAI,OAAO,YAAY,YACrB,QAAO,IAAI,QAAQ,GAAG,GAAG,OAAO,OAAO;AAGzC,QAAO;EACL;EACA;EACA;EACA;EACA,MAAM;EACN,KAAK;EACL,OAAO,IAAI;EACX,QAAQ,IAAI;EACZ,eAAe;GAAE;GAAG;GAAG;GAAO;GAAQ;EACvC;;;;;;AAOH,IAAa,iBAAb,cAAoC,YAAY;;;sCACvB,IAAI,KAAa;oBACJ;wBACK;yBACkB;2BACE;iCAC3C,IAAI,KAA0B;yCACtB,IAAI,KAAqB;;;;;CAKnD,AAAQ,uBAA6B;EAEnC,MAAM,mBACJ,KAAK,cAAc,KAAK,aAAa,IAAI,KAAK,WAAW,GACrD,CACE,KAAK,YACL,GAAG,MAAM,KAAK,KAAK,aAAa,CAAC,QAC9B,OAAO,OAAO,KAAK,WACrB,CACF,GACD,MAAM,KAAK,KAAK,aAAa;AAEnC,OAAK,c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AAK,gBAAgB,IAAI,IAAI,QAAQ;AAEvC,SAAO;;;;;CAMT,QAAQ,SAAuB;EAC7B,MAAM,QAAQ,KAAK,QAAQ,IAAI,QAAQ;AACvC,MAAI,CAAC,MACH;AAEF,OAAK,MAAM,MAAM,MACf,MAAK,gBAAgB,OAAO,GAAG;AAEjC,OAAK,QAAQ,OAAO,QAAQ;;;;;CAM9B,YAAY,SAAuB;EACjC,MAAM,QAAQ,KAAK,QAAQ,IAAI,QAAQ;AACvC,MAAI,CAAC,MACH;AAEF,OAAK,eAAe,MAAM,KAAK,MAAM,CAAC;;;;;CAOxC,WAAW,WAAuC;AAChD,SAAO,KAAK,gBAAgB,IAAI,UAAU;;;;;CAM5C,iBAAiB,SAA2B;EAC1C,MAAM,QAAQ,KAAK,QAAQ,IAAI,QAAQ;AACvC,SAAO,QAAQ,MAAM,KAAK,MAAM,GAAG,EAAE;;;;;CAMvC,AAAQ,uBAA6B;EACnC,MAAM,QAAQ,KAAK,aAAa;AAChC,MAAI,UAAU,EACZ,MAAK,iBAAiB;WACb,UAAU,EACnB,MAAK,iBAAiB;MAEtB,MAAK,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"SelectionModel.js","names":[],"sources":["../../../src/canvas/selection/SelectionModel.ts"],"sourcesContent":["import type { SelectionState } from \"../api/types.js\";\n\n/**\n * Create a DOMRect-like object. Polyfill for Node.js environments.\n */\nfunction createRect(x: number, y: number, width: number, height: number): DOMRect {\n if (typeof DOMRect !== \"undefined\") {\n return new DOMRect(x, y, width, height);\n }\n // Polyfill for Node.js\n return {\n x,\n y,\n width,\n height,\n left: x,\n top: y,\n right: x + width,\n bottom: y + height,\n toJSON: () => ({ x, y, width, height }),\n } as DOMRect;\n}\n\n/**\n * Pure selection logic - semantics separate from mechanism.\n * Manages selection state and operations.\n */\nexport class SelectionModel extends EventTarget {\n private _selectedIds = new Set<string>();\n private _primaryId: string | null = null;\n private _selectionMode: SelectionState = \"none\";\n private _boxSelectStart: { x: number; y: number } | null = null;\n private _boxSelectCurrent: { x: number; y: number } | null = null;\n private _groups = new Map<string, Set<string>>();\n private _elementToGroup = new Map<string, string>();\n\n /**\n * Emit selectionchange event with current selection state.\n */\n private _emitSelectionChange(): void {\n // Convert Set to array with primary first\n const selectedIdsArray =\n this._primaryId && this._selectedIds.has(this._primaryId)\n ? [this._primaryId, ...Array.from(this._selectedIds).filter((id) => id !== this._primaryId)]\n : Array.from(this._selectedIds);\n\n this.dispatchEvent(\n new CustomEvent(\"selectionchange\", {\n detail: {\n selectedIds: selectedIdsArray,\n selectionMode: this._selectionMode,\n },\n bubbles: false,\n composed: false,\n }),\n );\n }\n\n /**\n * Get current selection state.\n */\n get selectedIds(): ReadonlySet<string> {\n return this._selectedIds;\n }\n\n /**\n * Get current selection mode.\n */\n get selectionMode(): SelectionState {\n return this._selectionMode;\n }\n\n /**\n * Get current box selection bounds, if active.\n */\n get boxSelectBounds(): DOMRect | null {\n if (!this._boxSelectStart || !this._boxSelectCurrent) {\n return null;\n }\n const left = Math.min(this._boxSelectStart.x, this._boxSelectCurrent.x);\n const top = Math.min(this._boxSelectStart.y, this._boxSelectCurrent.y);\n const right = Math.max(this._boxSelectStart.x, this._boxSelectCurrent.x);\n const bottom = Math.max(this._boxSelectStart.y, this._boxSelectCurrent.y);\n return createRect(left, top, right - left, bottom - top);\n }\n\n /**\n * Select a single element.\n */\n select(id: string): void {\n this._selectedIds.clear();\n this._selectedIds.add(id);\n this._primaryId = id;\n this._selectionMode = \"single\";\n this._emitSelectionChange();\n }\n\n /**\n * Select multiple elements.\n */\n selectMultiple(ids: string[]): void {\n this._selectedIds.clear();\n for (const id of ids) {\n this._selectedIds.add(id);\n }\n this._primaryId = ids.length > 0 ? (ids[0] ?? null) : null;\n this._selectionMode = ids.length === 0 ? \"none\" : ids.length === 1 ? \"single\" : \"multiple\";\n this._emitSelectionChange();\n }\n\n /**\n * Add element to selection (for multi-select).\n */\n addToSelection(id: string): void {\n this._selectedIds.add(id);\n if (!this._primaryId) {\n this._primaryId = id;\n }\n this._updateSelectionMode();\n this._emitSelectionChange();\n }\n\n /**\n * Remove element from selection.\n */\n deselect(id: string): void {\n this._selectedIds.delete(id);\n if (this._primaryId === id) {\n // Set primary to first remaining, or null if none\n const remaining = Array.from(this._selectedIds);\n this._primaryId = remaining.length > 0 ? (remaining[0] ?? null) : null;\n }\n this._updateSelectionMode();\n this._emitSelectionChange();\n }\n\n /**\n * Toggle element selection state.\n */\n toggle(id: string): void {\n if (this._selectedIds.has(id)) {\n this.deselect(id);\n } else {\n this.addToSelection(id);\n }\n }\n\n /**\n * Clear all selections.\n */\n clear(): void {\n this._selectedIds.clear();\n this._primaryId = null;\n this._selectionMode = \"none\";\n this._boxSelectStart = null;\n this._boxSelectCurrent = null;\n this._emitSelectionChange();\n }\n\n /**\n * Start box selection.\n */\n startBoxSelect(x: number, y: number): void {\n this._boxSelectStart = { x, y };\n this._boxSelectCurrent = { x, y };\n this._selectionMode = \"box-selecting\";\n }\n\n /**\n * Update box selection.\n */\n updateBoxSelect(x: number, y: number): void {\n if (this._selectionMode !== \"box-selecting\") {\n return;\n }\n this._boxSelectCurrent = { x, y };\n }\n\n /**\n * End box selection and select elements within bounds.\n * @param hitTest - Function to find elements within bounds\n * @param addToSelection - If true, add to existing selection; if false, replace selection\n */\n endBoxSelect(hitTest: (bounds: DOMRect) => string[], addToSelection = false): void {\n if (\n this._selectionMode !== \"box-selecting\" ||\n !this._boxSelectStart ||\n !this._boxSelectCurrent\n ) {\n return;\n }\n const bounds = this.boxSelectBounds;\n if (bounds) {\n const ids = hitTest(bounds);\n if (addToSelection) {\n // Add each element to selection\n for (const id of ids) {\n this.addToSelection(id);\n }\n } else {\n // Replace selection\n this.selectMultiple(ids);\n }\n }\n this._boxSelectStart = null;\n this._boxSelectCurrent = null;\n // Note: selectMultiple/addToSelection already emit events, so no need to emit again\n }\n\n /**\n * Create a group from selected elements.\n */\n createGroup(ids: string[]): string {\n if (ids.length === 0) {\n throw new Error(\"Cannot create group with no elements\");\n }\n const groupId = `group-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n const groupSet = new Set(ids);\n this._groups.set(groupId, groupSet);\n for (const id of ids) {\n this._elementToGroup.set(id, groupId);\n }\n return groupId;\n }\n\n /**\n * Ungroup a group.\n */\n ungroup(groupId: string): void {\n const group = this._groups.get(groupId);\n if (!group) {\n return;\n }\n for (const id of group) {\n this._elementToGroup.delete(id);\n }\n this._groups.delete(groupId);\n }\n\n /**\n * Select all elements in a group.\n */\n selectGroup(groupId: string): void {\n const group = this._groups.get(groupId);\n if (!group) {\n return;\n }\n this.selectMultiple(Array.from(group));\n // Note: selectMultiple already emits event\n }\n\n /**\n * Get group ID for an element, if any.\n */\n getGroupId(elementId: string): string | undefined {\n return this._elementToGroup.get(elementId);\n }\n\n /**\n * Get all element IDs in a group.\n */\n getGroupElements(groupId: string): string[] {\n const group = this._groups.get(groupId);\n return group ? Array.from(group) : [];\n }\n\n /**\n * Update selection mode based on current selection count.\n */\n private _updateSelectionMode(): void {\n const count = this._selectedIds.size;\n if (count === 0) {\n this._selectionMode = \"none\";\n } else if (count === 1) {\n this._selectionMode = \"single\";\n } else {\n this._selectionMode = \"multiple\";\n }\n }\n}\n"],"mappings":";;;;AAKA,SAAS,WAAW,GAAW,GAAW,OAAe,QAAyB;AAChF,KAAI,OAAO,YAAY,YACrB,QAAO,IAAI,QAAQ,GAAG,GAAG,OAAO,OAAO;AAGzC,QAAO;EACL;EACA;EACA;EACA;EACA,MAAM;EACN,KAAK;EACL,OAAO,IAAI;EACX,QAAQ,IAAI;EACZ,eAAe;GAAE;GAAG;GAAG;GAAO;GAAQ;EACvC;;;;;;AAOH,IAAa,iBAAb,cAAoC,YAAY;;;sCACvB,IAAI,KAAa;oBACJ;wBACK;yBACkB;2BACE;iCAC3C,IAAI,KAA0B;yCACtB,IAAI,KAAqB;;;;;CAKnD,AAAQ,uBAA6B;EAEnC,MAAM,mBACJ,KAAK,cAAc,KAAK,aAAa,IAAI,KAAK,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K,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,GAAG,EAAE;EACjF,MAAM,WAAW,IAAI,IAAI,IAAI;AAC7B,OAAK,QAAQ,IAAI,SAAS,SAAS;AACnC,OAAK,MAAM,MAAM,IACf,MAAK,gBAAgB,IAAI,IAAI,QAAQ;AAEvC,SAAO;;;;;CAMT,QAAQ,SAAuB;EAC7B,MAAM,QAAQ,KAAK,QAAQ,IAAI,QAAQ;AACvC,MAAI,CAAC,MACH;AAEF,OAAK,MAAM,MAAM,MACf,MAAK,gBAAgB,OAAO,GAAG;AAEjC,OAAK,QAAQ,OAAO,QAAQ;;;;;CAM9B,YAAY,SAAuB;EACjC,MAAM,QAAQ,KAAK,QAAQ,IAAI,QAAQ;AACvC,MAAI,CAAC,MACH;AAEF,OAAK,eAAe,MAAM,KAAK,MAAM,CAAC;;;;;CAOxC,WAAW,WAAuC;AAChD,SAAO,KAAK,gBAAgB,IAAI,UAAU;;;;;CAM5C,iBAAiB,SAA2B;EAC1C,MAAM,QAAQ,KAAK,QAAQ,IAAI,QAAQ;AACvC,SAAO,QAAQ,MAAM,KAAK,MAAM,GAAG,EAAE;;;;;CAMvC,AAAQ,uBAA6B;EACnC,MAAM,QAAQ,KAAK,aAAa;AAChC,MAAI,UAAU,EACZ,MAAK,iBAAiB;WACb,UAAU,EACnB,MAAK,iBAAiB;MAEtB,MAAK,iBAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectionContext.js","names":[],"sources":["../../../src/canvas/selection/selectionContext.ts"],"sourcesContent":["import { createContext } from \"@lit/context\";\nimport type { SelectionState } from \"../api/types.js\";\n\n/**\n * Selection context interface for Lit context.\n */\nexport interface SelectionContext {\n selectedIds: ReadonlySet<string>;\n selectionMode: SelectionState;\n boxSelectBounds: DOMRect | null;\n select: (id: string) => void;\n selectMultiple: (ids: string[]) => void;\n addToSelection: (id: string) => void;\n deselect: (id: string) => void;\n toggle: (id: string) => void;\n clear: () => void;\n startBoxSelect: (x: number, y: number) => void;\n updateBoxSelect: (x: number, y: number) => void;\n endBoxSelect: (
|
|
1
|
+
{"version":3,"file":"selectionContext.js","names":[],"sources":["../../../src/canvas/selection/selectionContext.ts"],"sourcesContent":["import { createContext } from \"@lit/context\";\nimport type { SelectionState } from \"../api/types.js\";\n\n/**\n * Selection context interface for Lit context.\n */\nexport interface SelectionContext {\n selectedIds: ReadonlySet<string>;\n selectionMode: SelectionState;\n boxSelectBounds: DOMRect | null;\n select: (id: string) => void;\n selectMultiple: (ids: string[]) => void;\n addToSelection: (id: string) => void;\n deselect: (id: string) => void;\n toggle: (id: string) => void;\n clear: () => void;\n startBoxSelect: (x: number, y: number) => void;\n updateBoxSelect: (x: number, y: number) => void;\n endBoxSelect: (hitTest: (bounds: DOMRect) => string[], addToSelection?: boolean) => void;\n createGroup: (ids: string[]) => string;\n ungroup: (groupId: string) => void;\n selectGroup: (groupId: string) => void;\n getGroupId: (elementId: string) => string | undefined;\n getGroupElements: (groupId: string) => string[];\n addEventListener: (type: \"selectionchange\", listener: (event: CustomEvent) => void) => void;\n removeEventListener: (type: \"selectionchange\", listener: (event: CustomEvent) => void) => void;\n}\n\n/**\n * Lit context for selection state.\n * Provided by EFCanvas, consumed by child elements.\n */\nexport const selectionContext = createContext<SelectionContext>(Symbol(\"selectionContext\"));\n"],"mappings":";;;;;;;AAgCA,MAAa,mBAAmB,cAAgC,OAAO,mBAAmB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ContainerInfo.js","names":["displayMode: \"flex\" | \"grid\" | \"block\" | null"],"sources":["../../src/elements/ContainerInfo.ts"],"sourcesContent":["/**\n * Container information interface for elements that can contain children.\n * Provides information about container capabilities and display mode.\n */\n\nexport interface ContainerInfo {\n /**\n * Whether this element is a container that can contain children.\n */\n isContainer: boolean;\n\n /**\n * The display mode of the container.\n * \"flex\" | \"grid\" | \"block\" | null\n */\n displayMode: \"flex\" | \"grid\" | \"block\" | null;\n\n /**\n * Whether this container can contain children.\n * This may differ from isContainer if the container is not configured to accept children.\n */\n canContainChildren: boolean;\n}\n\n/**\n * Helper function to get container info from any HTMLElement.\n * Reads computed styles to determine display mode.\n */\nexport function getContainerInfoFromElement(
|
|
1
|
+
{"version":3,"file":"ContainerInfo.js","names":["displayMode: \"flex\" | \"grid\" | \"block\" | null"],"sources":["../../src/elements/ContainerInfo.ts"],"sourcesContent":["/**\n * Container information interface for elements that can contain children.\n * Provides information about container capabilities and display mode.\n */\n\nexport interface ContainerInfo {\n /**\n * Whether this element is a container that can contain children.\n */\n isContainer: boolean;\n\n /**\n * The display mode of the container.\n * \"flex\" | \"grid\" | \"block\" | null\n */\n displayMode: \"flex\" | \"grid\" | \"block\" | null;\n\n /**\n * Whether this container can contain children.\n * This may differ from isContainer if the container is not configured to accept children.\n */\n canContainChildren: boolean;\n}\n\n/**\n * Helper function to get container info from any HTMLElement.\n * Reads computed styles to determine display mode.\n */\nexport function getContainerInfoFromElement(element: HTMLElement | null): ContainerInfo {\n if (!element) {\n return {\n isContainer: false,\n displayMode: null,\n canContainChildren: false,\n };\n }\n\n const computedStyle = window.getComputedStyle(element);\n const display = computedStyle.display;\n\n // Determine if it's a container (grid or flex)\n const isGrid = display === \"grid\" || display === \"inline-grid\";\n const isFlex = display === \"flex\" || display === \"inline-flex\";\n const isBlock = display === \"block\" || display === \"inline-block\";\n\n const isContainer = isGrid || isFlex || isBlock;\n\n let displayMode: \"flex\" | \"grid\" | \"block\" | null = null;\n if (isFlex) {\n displayMode = \"flex\";\n } else if (isGrid) {\n displayMode = \"grid\";\n } else if (isBlock) {\n displayMode = \"block\";\n }\n\n return {\n isContainer,\n displayMode,\n canContainChildren: isContainer,\n };\n}\n"],"mappings":";;;;;AA4BA,SAAgB,4BAA4B,SAA4C;AACtF,KAAI,CAAC,QACH,QAAO;EACL,aAAa;EACb,aAAa;EACb,oBAAoB;EACrB;CAIH,MAAM,UADgB,OAAO,iBAAiB,QAAQ,CACxB;CAG9B,MAAM,SAAS,YAAY,UAAU,YAAY;CACjD,MAAM,SAAS,YAAY,UAAU,YAAY;CACjD,MAAM,UAAU,YAAY,WAAW,YAAY;CAEnD,MAAM,cAAc,UAAU,UAAU;CAExC,IAAIA,cAAgD;AACpD,KAAI,OACF,eAAc;UACL,OACT,eAAc;UACL,QACT,eAAc;AAGhB,QAAO;EACL;EACA;EACA,oBAAoB;EACrB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CrossUpdateController.js","names":["host: ReactiveControllerHost","target: LitElement"],"sources":["../../src/elements/CrossUpdateController.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"CrossUpdateController.js","names":["host: ReactiveControllerHost","target: LitElement"],"sources":["../../src/elements/CrossUpdateController.ts"],"sourcesContent":["import type { LitElement, ReactiveController, ReactiveControllerHost } from \"lit\";\n\nexport class CrossUpdateController implements ReactiveController {\n constructor(\n private host: ReactiveControllerHost,\n private target: LitElement,\n ) {\n this.host.addController(this);\n }\n\n hostUpdate(): void {\n this.target.requestUpdate();\n }\n\n remove(): void {\n this.host.removeController(this);\n }\n}\n"],"mappings":";AAEA,IAAa,wBAAb,MAAiE;CAC/D,YACE,AAAQA,MACR,AAAQC,QACR;EAFQ;EACA;AAER,OAAK,KAAK,cAAc,KAAK;;CAG/B,aAAmB;AACjB,OAAK,OAAO,eAAe;;CAG7B,SAAe;AACb,OAAK,KAAK,iBAAiB,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EFAudio.js","names":["EFAudio","#mediaEngineLoaded"],"sources":["../../src/elements/EFAudio.ts"],"sourcesContent":["import { html } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { createRef, ref } from \"lit/directives/ref.js\";\nimport { TWMixin } from \"../gui/TWMixin.js\";\nimport {\n type FrameRenderable,\n type FrameState,\n PRIORITY_AUDIO,\n} from \"../preview/FrameController.js\";\nimport { EFMedia } from \"./EFMedia.js\";\n\n@customElement(\"ef-audio\")\nexport class EFAudio extends TWMixin(EFMedia) implements FrameRenderable {\n /**\n * EFAudio only requires audio tracks - skip video track validation\n * to avoid unnecessary network requests to transcoding service.\n */\n override get requiredTracks(): \"audio\" | \"video\" | \"both\" {\n return \"audio\";\n }\n\n /**\n * Audio volume level (0.0 to 1.0)\n * @domAttribute \"volume\"\n */\n @property({ type: Number, attribute: \"volume\", reflect: true })\n volume = 1.0;\n\n audioElementRef = createRef<HTMLAudioElement>();\n\n #mediaEngineLoaded = false;\n\n protected updated(changedProperties: Map<PropertyKey, unknown>): void {\n super.updated(changedProperties);\n\n // Sync volume property to HTMLAudioElement whenever it changes or element is first rendered\n if (this.audioElementRef.value) {\n if (changedProperties.has(\"volume\") || changedProperties.size === 0) {\n this.audioElementRef.value.volume = this.volume;\n }\n }\n }\n\n render() {\n return html`<audio ${ref(this.audioElementRef)}></audio>`;\n }\n\n // ============================================================================\n // FrameRenderable Implementation\n // ============================================================================\n\n /**\n * Query readiness state for a given time.\n * @implements FrameRenderable\n */\n getFrameState(_timeMs: number): FrameState {\n // Check if media engine is loaded\n const isReady
|
|
1
|
+
{"version":3,"file":"EFAudio.js","names":["EFAudio","#mediaEngineLoaded"],"sources":["../../src/elements/EFAudio.ts"],"sourcesContent":["import { html } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport { createRef, ref } from \"lit/directives/ref.js\";\nimport { TWMixin } from \"../gui/TWMixin.js\";\nimport {\n type FrameRenderable,\n type FrameState,\n PRIORITY_AUDIO,\n} from \"../preview/FrameController.js\";\nimport { EFMedia } from \"./EFMedia.js\";\n\n@customElement(\"ef-audio\")\nexport class EFAudio extends TWMixin(EFMedia) implements FrameRenderable {\n /**\n * EFAudio only requires audio tracks - skip video track validation\n * to avoid unnecessary network requests to transcoding service.\n */\n override get requiredTracks(): \"audio\" | \"video\" | \"both\" {\n return \"audio\";\n }\n\n /**\n * Audio volume level (0.0 to 1.0)\n * @domAttribute \"volume\"\n */\n @property({ type: Number, attribute: \"volume\", reflect: true })\n volume = 1.0;\n\n audioElementRef = createRef<HTMLAudioElement>();\n\n #mediaEngineLoaded = false;\n\n protected updated(changedProperties: Map<PropertyKey, unknown>): void {\n super.updated(changedProperties);\n\n // Sync volume property to HTMLAudioElement whenever it changes or element is first rendered\n if (this.audioElementRef.value) {\n if (changedProperties.has(\"volume\") || changedProperties.size === 0) {\n this.audioElementRef.value.volume = this.volume;\n }\n }\n }\n\n render() {\n return html`<audio ${ref(this.audioElementRef)}></audio>`;\n }\n\n // ============================================================================\n // FrameRenderable Implementation\n // ============================================================================\n\n /**\n * Query readiness state for a given time.\n * @implements FrameRenderable\n */\n getFrameState(_timeMs: number): FrameState {\n // Check if media engine is loaded\n const isReady = this.#mediaEngineLoaded && this.mediaEngineTask.status === 2; // COMPLETE\n\n return {\n needsPreparation: !isReady,\n isReady,\n priority: PRIORITY_AUDIO,\n };\n }\n\n /**\n * Async preparation - waits for media engine to load.\n * @implements FrameRenderable\n */\n async prepareFrame(_timeMs: number, signal: AbortSignal): Promise<void> {\n // Just ensure media engine is loaded\n const mediaEngine = await this.getMediaEngine(signal);\n this.#mediaEngineLoaded = !!mediaEngine;\n signal.throwIfAborted();\n }\n\n /**\n * Synchronous render - audio plays via HTMLAudioElement, no explicit render needed.\n * @implements FrameRenderable\n */\n renderFrame(_timeMs: number): void {\n // Audio playback is handled by the browser's HTMLAudioElement\n // No explicit rendering action needed\n }\n\n // ============================================================================\n // End FrameRenderable Implementation\n // ============================================================================\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-audio\": EFAudio;\n }\n}\n"],"mappings":";;;;;;;;;AAYO,oBAAMA,kBAAgB,QAAQ,QAAQ,CAA4B;;;gBAc9D;yBAES,WAA6B;;;;;;CAX/C,IAAa,iBAA6C;AACxD,SAAO;;CAYT,qBAAqB;CAErB,AAAU,QAAQ,mBAAoD;AACpE,QAAM,QAAQ,kBAAkB;AAGhC,MAAI,KAAK,gBAAgB,OACvB;OAAI,kBAAkB,IAAI,SAAS,IAAI,kBAAkB,SAAS,EAChE,MAAK,gBAAgB,MAAM,SAAS,KAAK;;;CAK/C,SAAS;AACP,SAAO,IAAI,UAAU,IAAI,KAAK,gBAAgB,CAAC;;;;;;CAWjD,cAAc,SAA6B;EAEzC,MAAM,UAAU,MAAKC,qBAAsB,KAAK,gBAAgB,WAAW;AAE3E,SAAO;GACL,kBAAkB,CAAC;GACnB;GACA,UAAU;GACX;;;;;;CAOH,MAAM,aAAa,SAAiB,QAAoC;AAGtE,QAAKA,oBAAqB,CAAC,CADP,MAAM,KAAK,eAAe,OAAO;AAErD,SAAO,gBAAgB;;;;;;CAOzB,YAAY,SAAuB;;YAxDlC,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAU,SAAS;CAAM,CAAC;sBAdhE,cAAc,WAAW"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EFCaptions.js","names":["EFCaptionsActiveWord","#wordText","#wordIndex","EFCaptionsSegment","#segmentText","EFCaptionsBeforeActiveWord","EFCaptionsAfterActiveWord","EFCaptions","#captionsDataLoaded","#captionsDataValue","#captionsDataPromise","#doLoadCaptionsData","#findElementById","#transcriptionData","#loadTranscriptionFragment","#rootTimegroupUpdateController","#cachedIntrinsicDurationMs","captionsData: Caption | null","result: number"],"sources":["../../src/elements/EFCaptions.ts"],"sourcesContent":["import { css, html, LitElement, type PropertyValueMap } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport type { ReactiveController } from \"lit\";\nimport type { GetISOBMFFFileTranscriptionResult } from \"../../../api/src/index.js\";\nimport {\n type FrameRenderable,\n type FrameState,\n PRIORITY_CAPTIONS,\n} from \"../preview/FrameController.js\";\nimport { AsyncValue } from \"./EFMedia.js\";\nimport { CrossUpdateController } from \"./CrossUpdateController.js\";\nimport { EFAudio } from \"./EFAudio.js\";\nimport { EFSourceMixin } from \"./EFSourceMixin.js\";\nimport { EFTemporal, flushStartTimeMsCache } from \"./EFTemporal.js\";\nimport { flushSequenceDurationCache, EFTimegroup } from \"./EFTimegroup.js\";\nimport { EFVideo } from \"./EFVideo.js\";\nimport { FetchMixin } from \"./FetchMixin.js\";\n\nexport interface WordSegment {\n text: string;\n start: number;\n end: number;\n}\n\nexport interface Segment {\n start: number;\n end: number;\n text: string;\n}\n\nexport interface Caption {\n segments: Segment[];\n word_segments: WordSegment[];\n}\n\nconst stopWords = new Set([\"\", \".\", \"!\", \"?\", \",\"]);\n\n/**\n * Caption active word element - displays the currently spoken word.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-active-word\")\nexport class EFCaptionsActiveWord extends LitElement {\n #wordText = \"\";\n #wordIndex = 0;\n\n set wordText(text: string) {\n this.#wordText = text;\n // Hide element if no content or only stop words\n if (!text || stopWords.has(text)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n // Add trailing space to maintain consistent spacing with surrounding words\n this.textContent = text + \" \";\n }\n }\n\n get wordText(): string {\n return this.#wordText;\n }\n\n set wordIndex(index: number) {\n this.#wordIndex = index;\n // Set deterministic --ef-word-seed value based on word index\n const seed = (index * 9007) % 233; // Prime numbers for better distribution\n const seedValue = seed / 233; // Normalize to 0-1 range\n this.style.setProperty(\"--ef-word-seed\", seedValue.toString());\n }\n\n get wordIndex(): number {\n return this.#wordIndex;\n }\n}\n\n/**\n * Caption segment element - displays a full caption segment.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-segment\")\nexport class EFCaptionsSegment extends LitElement {\n #segmentText = \"\";\n\n set segmentText(text: string) {\n this.#segmentText = text;\n // Hide element if no content or only stop words\n if (!text || stopWords.has(text)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n this.textContent = text;\n }\n }\n\n get segmentText(): string {\n return this.#segmentText;\n }\n}\n\n/**\n * Caption before-active-word element - displays words before the current word.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-before-active-word\")\nexport class EFCaptionsBeforeActiveWord extends EFCaptionsSegment {\n set segmentText(text: string) {\n // Check if there's an active word by looking for sibling active word element\n const activeWord = this.closest(\"ef-captions\")?.querySelector(\n \"ef-captions-active-word\",\n ) as EFCaptionsActiveWord;\n const hasActiveWord = activeWord?.wordText;\n\n // Add trailing space if there's an active word coming after us\n const finalText = text && hasActiveWord ? text + \" \" : text;\n\n // Hide element if no content or only stop words\n if (!finalText || stopWords.has(finalText)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n this.textContent = finalText;\n }\n }\n}\n\n/**\n * Caption after-active-word element - displays words after the current word.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-after-active-word\")\nexport class EFCaptionsAfterActiveWord extends EFCaptionsSegment {\n set segmentText(text: string) {\n // No leading space - active word will add trailing space\n const finalText = text;\n\n // Hide element if no content or only stop words\n if (!finalText || stopWords.has(finalText)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n this.textContent = finalText;\n }\n }\n}\n\n@customElement(\"ef-captions\")\nexport class EFCaptions\n extends EFSourceMixin(EFTemporal(FetchMixin(LitElement)), {\n assetType: \"caption_files\",\n })\n implements FrameRenderable\n{\n static styles = [\n css`\n :host {\n display: block;\n white-space: normal;\n line-height: 1;\n gap: 0;\n }\n ::slotted(*) {\n display: inline;\n margin: 0;\n padding: 0;\n }\n `,\n ];\n\n @property({ type: String, attribute: \"target\", reflect: true })\n targetSelector = \"\";\n\n set target(value: string) {\n this.targetSelector = value;\n }\n\n @property({ attribute: \"word-style\" })\n wordStyle = \"\";\n\n /**\n * URL or path to a JSON file containing custom captions data.\n * The JSON should conform to the Caption interface with 'segments' and 'word_segments' arrays.\n */\n @property({ type: String, attribute: \"captions-src\", reflect: true })\n captionsSrc = \"\";\n\n /**\n * Direct captions data object. Takes priority over captions-src and captions-script.\n * Should conform to the Caption interface with 'segments' and 'word_segments' arrays.\n */\n @property({ type: Object, attribute: false })\n captionsData: Caption | null = null;\n\n /**\n * ID of a <script> element containing JSON captions data.\n * The script's textContent should be valid JSON conforming to the Caption interface.\n */\n @property({ type: String, attribute: \"captions-script\", reflect: true })\n captionsScript = \"\";\n\n activeWordContainers = this.getElementsByTagName(\"ef-captions-active-word\");\n segmentContainers = this.getElementsByTagName(\"ef-captions-segment\");\n beforeActiveWordContainers = this.getElementsByTagName(\n \"ef-captions-before-active-word\",\n );\n afterActiveWordContainers = this.getElementsByTagName(\n \"ef-captions-after-active-word\",\n );\n\n // Cache for intrinsicDurationMs to avoid expensive O(n) recalculation every frame\n #cachedIntrinsicDurationMs: number | undefined | null = null; // null = not computed, undefined = no duration\n\n render() {\n return html`<slot></slot>`;\n }\n\n transcriptionsPath() {\n if (!this.targetElement) {\n return null;\n }\n const fileId = this.targetElement.fileId ?? this.targetElement.assetId;\n if (fileId) {\n return `${this.apiHost}/api/v1/files/${fileId}/transcription`;\n }\n return null;\n }\n\n captionsPath() {\n if (!this.targetElement) {\n return null;\n }\n const fileId = this.targetElement.fileId ?? this.targetElement.assetId;\n if (fileId) {\n return `${this.apiHost}/api/v1/files/${fileId}`;\n }\n const targetSrc = this.targetElement.src;\n // Normalize the path: remove leading slash and any double slashes\n let normalizedSrc = targetSrc.startsWith(\"/\")\n ? targetSrc.slice(1)\n : targetSrc;\n normalizedSrc = normalizedSrc.replace(/^\\/+/, \"\");\n // Use production API format for local files\n return `/api/v1/assets/captions?src=${encodeURIComponent(normalizedSrc)}`;\n }\n\n // ============================================================================\n // Captions Data Loading - async methods instead of Tasks\n // ============================================================================\n\n #captionsDataLoaded = false;\n #captionsDataPromise: Promise<Caption | null> | null = null;\n #captionsDataValue: Caption | null = null;\n #transcriptionData: GetISOBMFFFileTranscriptionResult | null = null;\n\n /**\n * AsyncValue wrapper for backwards compatibility\n */\n unifiedCaptionsDataTask = new AsyncValue<Caption | null>();\n\n override shouldAutoReady(): boolean {\n return false;\n }\n\n /**\n * Load captions data from all possible sources\n */\n async loadCaptionsData(signal?: AbortSignal): Promise<Caption | null> {\n // Return cached if already loaded\n if (this.#captionsDataLoaded && this.#captionsDataValue) {\n this.setContentReadyState(\"ready\");\n return this.#captionsDataValue;\n }\n\n // Return in-flight promise\n if (this.#captionsDataPromise) {\n return this.#captionsDataPromise;\n }\n\n this.unifiedCaptionsDataTask.startPending();\n this.setContentReadyState(\"loading\");\n this.#captionsDataPromise = this.#doLoadCaptionsData(signal);\n\n try {\n this.#captionsDataValue = await this.#captionsDataPromise;\n this.#captionsDataLoaded = true;\n if (this.#captionsDataValue) {\n this.unifiedCaptionsDataTask.setValue(this.#captionsDataValue);\n }\n this.setContentReadyState(\"ready\");\n return this.#captionsDataValue;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n console.error(\"Failed to load captions data:\", error);\n this.setContentReadyState(\"error\");\n return null;\n } finally {\n this.#captionsDataPromise = null;\n }\n }\n\n async #doLoadCaptionsData(signal?: AbortSignal): Promise<Caption | null> {\n // Priority 1: Direct captionsData property\n if (this.captionsData) {\n return this.captionsData;\n }\n\n // Priority 2: Script element reference\n if (this.captionsScript) {\n const scriptElement = this.#findElementById(this.captionsScript);\n if (scriptElement?.textContent) {\n try {\n return JSON.parse(scriptElement.textContent) as Caption;\n } catch (error) {\n console.error(\n `Failed to parse captions from script #${this.captionsScript}:`,\n error,\n );\n }\n }\n }\n\n // Priority 3: External captions file\n if (this.captionsSrc) {\n try {\n const response = await this.fetch(this.captionsSrc, { signal });\n return (await response.json()) as Caption;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n console.error(\n `Failed to load captions from ${this.captionsSrc}:`,\n error,\n );\n }\n }\n\n // Priority 4: Transcription from target element\n if (this.targetElement && !this.hasCustomCaptionsData) {\n const transcriptionPath = this.transcriptionsPath();\n if (transcriptionPath) {\n try {\n const response = await this.fetch(transcriptionPath, { signal });\n this.#transcriptionData =\n (await response.json()) as GetISOBMFFFileTranscriptionResult;\n signal?.throwIfAborted();\n\n // Load fragment for current time\n if (this.#transcriptionData) {\n return this.#loadTranscriptionFragment(signal);\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n // Transcription not available - not an error\n }\n }\n }\n\n return null;\n }\n\n async #loadTranscriptionFragment(\n signal?: AbortSignal,\n ): Promise<Caption | null> {\n if (!this.#transcriptionData) return null;\n\n const fragmentIndex = Math.floor(\n this.ownCurrentTimeMs / this.#transcriptionData.work_slice_ms,\n );\n const fragmentPath = `${this.apiHost}/api/v1/transcriptions/${this.#transcriptionData.id}/fragments/${fragmentIndex}`;\n\n try {\n const response = await this.fetch(fragmentPath, { signal });\n return (await response.json()) as Caption;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n console.error(\"Failed to load transcription fragment:\", error);\n return null;\n }\n }\n\n // ============================================================================\n // FrameRenderable Implementation\n // ============================================================================\n\n /**\n * Query readiness state for a given time.\n * @implements FrameRenderable\n */\n getFrameState(_timeMs: number): FrameState {\n // Check if captions data is loaded\n const hasData =\n this.#captionsDataLoaded && this.#captionsDataValue !== null;\n\n return {\n needsPreparation: !hasData,\n isReady: hasData,\n priority: PRIORITY_CAPTIONS,\n };\n }\n\n /**\n * Async preparation - waits for captions data to load.\n * @implements FrameRenderable\n */\n async prepareFrame(_timeMs: number, signal: AbortSignal): Promise<void> {\n await this.loadCaptionsData(signal);\n signal.throwIfAborted();\n }\n\n /**\n * Synchronous render - updates caption text containers.\n * Sets textContent directly on child elements (light DOM).\n * @implements FrameRenderable\n */\n renderFrame(_timeMs: number): void {\n // Update text containers by setting properties\n // Child elements update their textContent directly (light DOM)\n this.updateTextContainers();\n }\n\n // ============================================================================\n // End FrameRenderable Implementation\n // ============================================================================\n\n #rootTimegroupUpdateController?: ReactiveController;\n\n connectedCallback() {\n super.connectedCallback();\n\n // Start loading captions data\n this.loadCaptionsData().catch(() => {});\n\n // Try to get target element safely\n const target = this.targetSelector\n ? this.#findElementById(this.targetSelector)\n : null;\n if (target && (target instanceof EFAudio || target instanceof EFVideo)) {\n new CrossUpdateController(target, this);\n }\n // For standalone captions with custom data, ensure proper timeline sync\n else if (this.hasCustomCaptionsData && this.rootTimegroup) {\n new CrossUpdateController(this.rootTimegroup, this);\n }\n\n // Ensure captions update when root timegroup's currentTimeMs changes\n if (this.rootTimegroup) {\n this.#rootTimegroupUpdateController = {\n hostUpdated: () => {\n Promise.resolve().then(() => {\n this.updateTextContainers();\n });\n },\n hostDisconnected: () => {\n this.#rootTimegroupUpdateController = undefined;\n },\n };\n this.rootTimegroup.addController(this.#rootTimegroupUpdateController);\n }\n\n // Prevent display:none from being set on the parent caption element.\n // IMPORTANT: This only applies to the parent <ef-captions> element, NOT to\n // caption child elements (<ef-captions-segment>, <ef-captions-active-word>, etc.).\n // Child elements MUST respect display:none for proper temporal visibility\n // in video rendering. Video export relies on display:none to hide elements\n // outside their time range.\n const observer = new MutationObserver(() => {\n if (this.style.display === \"none\") {\n this.style.removeProperty(\"display\");\n this.style.opacity = \"0\";\n this.style.pointerEvents = \"none\";\n } else if (!this.style.display || this.style.display === \"\") {\n this.style.removeProperty(\"opacity\");\n this.style.removeProperty(\"pointer-events\");\n }\n });\n observer.observe(this, { attributes: true, attributeFilter: [\"style\"] });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this.#rootTimegroupUpdateController && this.rootTimegroup) {\n this.rootTimegroup.removeController(this.#rootTimegroupUpdateController);\n this.#rootTimegroupUpdateController = undefined;\n }\n }\n\n protected updated(\n changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>,\n ): void {\n // Set up root timegroup controller if rootTimegroup is now available\n if (this.rootTimegroup && !this.#rootTimegroupUpdateController) {\n this.#rootTimegroupUpdateController = {\n hostUpdated: () => {\n Promise.resolve().then(() => {\n this.updateTextContainers();\n });\n },\n hostDisconnected: () => {\n this.#rootTimegroupUpdateController = undefined;\n },\n };\n this.rootTimegroup.addController(this.#rootTimegroupUpdateController);\n }\n\n // Clean up controller if rootTimegroup changed\n if (\n changedProperties.has(\"rootTimegroup\") &&\n this.#rootTimegroupUpdateController\n ) {\n const oldRootTimegroup = changedProperties.get(\"rootTimegroup\") as\n | EFTimegroup\n | undefined;\n if (oldRootTimegroup && oldRootTimegroup !== this.rootTimegroup) {\n oldRootTimegroup.removeController(this.#rootTimegroupUpdateController);\n this.#rootTimegroupUpdateController = undefined;\n }\n }\n\n this.updateTextContainers();\n\n // Force duration recalculation when custom captions data changes\n if (\n changedProperties.has(\"captionsData\") ||\n changedProperties.has(\"captionsSrc\") ||\n changedProperties.has(\"captionsScript\")\n ) {\n this.emitContentChange(\"source\");\n this.#cachedIntrinsicDurationMs = null;\n this.#captionsDataLoaded = false;\n this.#captionsDataValue = null;\n this.loadCaptionsData().catch(() => {});\n\n this.requestUpdate(\"intrinsicDurationMs\");\n\n flushSequenceDurationCache();\n flushStartTimeMsCache();\n\n if (this.parentTimegroup) {\n this.parentTimegroup.requestUpdate(\"durationMs\");\n this.parentTimegroup.requestUpdate(\"currentTime\");\n }\n }\n\n // Update captions when timeline position changes\n if (changedProperties.has(\"ownCurrentTimeMs\")) {\n this.updateTextContainers();\n }\n }\n\n updateTextContainers() {\n const captionsData = this.#captionsDataValue;\n if (!captionsData) {\n return;\n }\n\n // For captions with custom data, try to use the video's source time\n let currentTimeMs = this.ownCurrentTimeMs;\n if (this.hasCustomCaptionsData && this.parentTimegroup) {\n const videoElement = Array.from(this.parentTimegroup.children).find(\n (child): child is EFVideo => child instanceof EFVideo,\n );\n if (videoElement) {\n const sourceInMs = videoElement.sourceInMs ?? 0;\n currentTimeMs = videoElement.currentSourceTimeMs - sourceInMs;\n currentTimeMs = Math.max(0, Math.min(currentTimeMs, this.durationMs));\n }\n }\n\n const currentTimeSec = currentTimeMs / 1000;\n\n // Find the current word from word_segments\n const currentWord = captionsData.word_segments.find(\n (word) => currentTimeSec >= word.start && currentTimeSec < word.end,\n );\n\n // Find the current segment\n const currentSegment = captionsData.segments.find(\n (segment) =>\n currentTimeSec >= segment.start && currentTimeSec < segment.end,\n );\n\n for (const wordContainer of this.activeWordContainers) {\n if (currentWord) {\n const wordIndex = captionsData.word_segments.findIndex(\n (w) =>\n w.start === currentWord.start &&\n w.end === currentWord.end &&\n w.text === currentWord.text,\n );\n wordContainer.wordIndex = wordIndex >= 0 ? wordIndex : 0;\n wordContainer.wordText = currentWord.text; // Sets textContent directly\n } else {\n wordContainer.wordText = \"\"; // Hides element\n }\n }\n\n for (const segmentContainer of this.segmentContainers) {\n if (currentSegment) {\n segmentContainer.segmentText = currentSegment.text; // Sets textContent directly\n } else {\n segmentContainer.segmentText = \"\"; // Hides element\n }\n }\n\n // Process context for both word and segment cases\n if (currentWord && currentSegment) {\n const segmentWords = captionsData.word_segments.filter(\n (word) =>\n word.start >= currentSegment.start && word.end <= currentSegment.end,\n );\n\n const currentWordIndex = segmentWords.findIndex(\n (word) =>\n word.start === currentWord.start && word.end === currentWord.end,\n );\n\n if (currentWordIndex !== -1) {\n const beforeWords = segmentWords\n .slice(0, currentWordIndex)\n .map((w) => w.text.trim())\n .join(\" \");\n\n const afterWords = segmentWords\n .slice(currentWordIndex + 1)\n .map((w) => w.text.trim())\n .join(\" \");\n\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = beforeWords; // Sets textContent directly\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = afterWords; // Sets textContent directly\n }\n }\n } else if (currentSegment) {\n const segmentWords = captionsData.word_segments.filter(\n (word) =>\n word.start >= currentSegment.start && word.end <= currentSegment.end,\n );\n\n const firstWord = segmentWords[0];\n const isBeforeFirstWord = firstWord && currentTimeSec < firstWord.start;\n\n if (isBeforeFirstWord) {\n const allWords = segmentWords.map((w) => w.text.trim()).join(\" \");\n\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = allWords; // Sets textContent directly\n }\n } else {\n const allCompletedWords = segmentWords\n .map((w) => w.text.trim())\n .join(\" \");\n\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = allCompletedWords; // Sets textContent directly\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n }\n } else {\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n }\n }\n\n get targetElement() {\n const target = this.targetSelector\n ? this.#findElementById(this.targetSelector)\n : null;\n if (target instanceof EFAudio || target instanceof EFVideo) {\n return target;\n }\n if (this.hasCustomCaptionsData) {\n return null;\n }\n return null;\n }\n\n get hasCustomCaptionsData(): boolean {\n return !!(this.captionsData || this.captionsSrc || this.captionsScript);\n }\n\n /**\n * Find element by ID, searching within clone scope first to avoid cross-boundary references.\n * @private\n */\n #findElementById(id: string): Element | null {\n // Search within nearest timegroup or configuration container first\n const container = this.closest(\"ef-timegroup, ef-configuration\");\n if (container) {\n const result = container.querySelector(`#${CSS.escape(id)}`);\n if (result) return result;\n }\n\n // Fall back to document-wide search\n return document.getElementById(id);\n }\n\n get intrinsicDurationMs(): number | undefined {\n if (this.#cachedIntrinsicDurationMs !== null) {\n return this.#cachedIntrinsicDurationMs;\n }\n\n let captionsData: Caption | null = null;\n\n if (this.captionsData) {\n captionsData = this.captionsData;\n } else if (this.captionsScript) {\n const scriptElement = this.#findElementById(this.captionsScript);\n if (scriptElement?.textContent) {\n try {\n captionsData = JSON.parse(scriptElement.textContent) as Caption;\n } catch {\n // Invalid JSON\n }\n }\n } else if (this.#captionsDataValue) {\n captionsData = this.#captionsDataValue;\n }\n\n if (!captionsData) {\n if (!this.captionsData && !this.captionsScript && !this.captionsSrc) {\n this.#cachedIntrinsicDurationMs = undefined;\n }\n return undefined;\n }\n\n let result: number;\n if (\n captionsData.segments.length === 0 &&\n captionsData.word_segments.length === 0\n ) {\n result = 0;\n } else {\n const maxSegmentEnd =\n captionsData.segments.length > 0\n ? captionsData.segments.reduce(\n (max, s) => (s.end > max ? s.end : max),\n 0,\n )\n : 0;\n const maxWordEnd =\n captionsData.word_segments.length > 0\n ? captionsData.word_segments.reduce(\n (max, w) => (w.end > max ? w.end : max),\n 0,\n )\n : 0;\n\n result = Math.max(maxSegmentEnd, maxWordEnd) * 1000;\n }\n\n this.#cachedIntrinsicDurationMs = result;\n return result;\n }\n\n get hasOwnDuration(): boolean {\n return !!(\n this.captionsData ||\n this.captionsScript ||\n this.#captionsDataValue\n );\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-captions\": EFCaptions;\n \"ef-captions-active-word\": EFCaptionsActiveWord;\n \"ef-captions-segment\": EFCaptionsSegment;\n \"ef-captions-before-active-word\": EFCaptionsBeforeActiveWord;\n \"ef-captions-after-active-word\": EFCaptionsAfterActiveWord;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmCA,MAAM,YAAY,IAAI,IAAI;CAAC;CAAI;CAAK;CAAK;CAAK;CAAI,CAAC;AAO5C,iCAAMA,+BAA6B,WAAW;CACnD,YAAY;CACZ,aAAa;CAEb,IAAI,SAAS,MAAc;AACzB,QAAKC,WAAY;AAEjB,MAAI,CAAC,QAAQ,UAAU,IAAI,KAAK,EAAE;AAChC,QAAK,SAAS;AACd,QAAK,cAAc;SACd;AACL,QAAK,SAAS;AAEd,QAAK,cAAc,OAAO;;;CAI9B,IAAI,WAAmB;AACrB,SAAO,MAAKA;;CAGd,IAAI,UAAU,OAAe;AAC3B,QAAKC,YAAa;EAGlB,MAAM,YADQ,QAAQ,OAAQ,MACL;AACzB,OAAK,MAAM,YAAY,kBAAkB,UAAU,UAAU,CAAC;;CAGhE,IAAI,YAAoB;AACtB,SAAO,MAAKA;;;mCA/Bf,cAAc,0BAA0B;AAwClC,8BAAMC,4BAA0B,WAAW;CAChD,eAAe;CAEf,IAAI,YAAY,MAAc;AAC5B,QAAKC,cAAe;AAEpB,MAAI,CAAC,QAAQ,UAAU,IAAI,KAAK,EAAE;AAChC,QAAK,SAAS;AAC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AAC,KAAK,kBAAkB,CAAC,KAAK,YACtD,OAAKO,4BAA6B;AAEpC;;EAGF,IAAIE;AACJ,MACE,aAAa,SAAS,WAAW,KACjC,aAAa,cAAc,WAAW,EAEtC,UAAS;OACJ;GACL,MAAM,gBACJ,aAAa,SAAS,SAAS,IAC3B,aAAa,SAAS,QACnB,KAAK,MAAO,EAAE,MAAM,MAAM,EAAE,MAAM,KACnC,EACD,GACD;GACN,MAAM,aACJ,aAAa,cAAc,SAAS,IAChC,aAAa,cAAc,QACxB,KAAK,MAAO,EAAE,MAAM,MAAM,EAAE,MAAM,KACnC,EACD,GACD;AAEN,YAAS,KAAK,IAAI,eAAe,WAAW,GAAG;;AAGjD,QAAKF,4BAA6B;AAClC,SAAO;;CAGT,IAAI,iBAA0B;AAC5B,SAAO,CAAC,EACN,KAAK,gBACL,KAAK,kBACL,MAAKP;;;YAnmBR,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAU,SAAS;CAAM,CAAC;YAO9D,SAAS,EAAE,WAAW,cAAc,CAAC;YAOrC,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAgB,SAAS;CAAM,CAAC;YAOpE,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAO5C,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAmB,SAAS;CAAM,CAAC;yBAnDzE,cAAc,cAAc"}
|
|
1
|
+
{"version":3,"file":"EFCaptions.js","names":["EFCaptionsActiveWord","#wordText","#wordIndex","EFCaptionsSegment","#segmentText","EFCaptionsBeforeActiveWord","EFCaptionsAfterActiveWord","EFCaptions","#captionsDataLoaded","#captionsDataValue","#captionsDataPromise","#doLoadCaptionsData","#findElementById","#transcriptionData","#loadTranscriptionFragment","#rootTimegroupUpdateController","#cachedIntrinsicDurationMs","captionsData: Caption | null","result: number"],"sources":["../../src/elements/EFCaptions.ts"],"sourcesContent":["import { css, html, LitElement, type PropertyValueMap } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\nimport type { ReactiveController } from \"lit\";\nimport type { GetISOBMFFFileTranscriptionResult } from \"../../../api/src/index.js\";\nimport {\n type FrameRenderable,\n type FrameState,\n PRIORITY_CAPTIONS,\n} from \"../preview/FrameController.js\";\nimport { AsyncValue } from \"./EFMedia.js\";\nimport { CrossUpdateController } from \"./CrossUpdateController.js\";\nimport { EFAudio } from \"./EFAudio.js\";\nimport { EFSourceMixin } from \"./EFSourceMixin.js\";\nimport { EFTemporal, flushStartTimeMsCache } from \"./EFTemporal.js\";\nimport { flushSequenceDurationCache, EFTimegroup } from \"./EFTimegroup.js\";\nimport { EFVideo } from \"./EFVideo.js\";\nimport { FetchMixin } from \"./FetchMixin.js\";\n\nexport interface WordSegment {\n text: string;\n start: number;\n end: number;\n}\n\nexport interface Segment {\n start: number;\n end: number;\n text: string;\n}\n\nexport interface Caption {\n segments: Segment[];\n word_segments: WordSegment[];\n}\n\nconst stopWords = new Set([\"\", \".\", \"!\", \"?\", \",\"]);\n\n/**\n * Caption active word element - displays the currently spoken word.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-active-word\")\nexport class EFCaptionsActiveWord extends LitElement {\n #wordText = \"\";\n #wordIndex = 0;\n\n set wordText(text: string) {\n this.#wordText = text;\n // Hide element if no content or only stop words\n if (!text || stopWords.has(text)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n // Add trailing space to maintain consistent spacing with surrounding words\n this.textContent = text + \" \";\n }\n }\n\n get wordText(): string {\n return this.#wordText;\n }\n\n set wordIndex(index: number) {\n this.#wordIndex = index;\n // Set deterministic --ef-word-seed value based on word index\n const seed = (index * 9007) % 233; // Prime numbers for better distribution\n const seedValue = seed / 233; // Normalize to 0-1 range\n this.style.setProperty(\"--ef-word-seed\", seedValue.toString());\n }\n\n get wordIndex(): number {\n return this.#wordIndex;\n }\n}\n\n/**\n * Caption segment element - displays a full caption segment.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-segment\")\nexport class EFCaptionsSegment extends LitElement {\n #segmentText = \"\";\n\n set segmentText(text: string) {\n this.#segmentText = text;\n // Hide element if no content or only stop words\n if (!text || stopWords.has(text)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n this.textContent = text;\n }\n }\n\n get segmentText(): string {\n return this.#segmentText;\n }\n}\n\n/**\n * Caption before-active-word element - displays words before the current word.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-before-active-word\")\nexport class EFCaptionsBeforeActiveWord extends EFCaptionsSegment {\n set segmentText(text: string) {\n // Check if there's an active word by looking for sibling active word element\n const activeWord = this.closest(\"ef-captions\")?.querySelector(\n \"ef-captions-active-word\",\n ) as EFCaptionsActiveWord;\n const hasActiveWord = activeWord?.wordText;\n\n // Add trailing space if there's an active word coming after us\n const finalText = text && hasActiveWord ? text + \" \" : text;\n\n // Hide element if no content or only stop words\n if (!finalText || stopWords.has(finalText)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n this.textContent = finalText;\n }\n }\n}\n\n/**\n * Caption after-active-word element - displays words after the current word.\n * Uses light DOM for simplicity - parent sets textContent directly.\n */\n@customElement(\"ef-captions-after-active-word\")\nexport class EFCaptionsAfterActiveWord extends EFCaptionsSegment {\n set segmentText(text: string) {\n // No leading space - active word will add trailing space\n const finalText = text;\n\n // Hide element if no content or only stop words\n if (!finalText || stopWords.has(finalText)) {\n this.hidden = true;\n this.textContent = \"\";\n } else {\n this.hidden = false;\n this.textContent = finalText;\n }\n }\n}\n\n@customElement(\"ef-captions\")\nexport class EFCaptions\n extends EFSourceMixin(EFTemporal(FetchMixin(LitElement)), {\n assetType: \"caption_files\",\n })\n implements FrameRenderable\n{\n static styles = [\n css`\n :host {\n display: block;\n white-space: normal;\n line-height: 1;\n gap: 0;\n }\n ::slotted(*) {\n display: inline;\n margin: 0;\n padding: 0;\n }\n `,\n ];\n\n @property({ type: String, attribute: \"target\", reflect: true })\n targetSelector = \"\";\n\n set target(value: string) {\n this.targetSelector = value;\n }\n\n @property({ attribute: \"word-style\" })\n wordStyle = \"\";\n\n /**\n * URL or path to a JSON file containing custom captions data.\n * The JSON should conform to the Caption interface with 'segments' and 'word_segments' arrays.\n */\n @property({ type: String, attribute: \"captions-src\", reflect: true })\n captionsSrc = \"\";\n\n /**\n * Direct captions data object. Takes priority over captions-src and captions-script.\n * Should conform to the Caption interface with 'segments' and 'word_segments' arrays.\n */\n @property({ type: Object, attribute: false })\n captionsData: Caption | null = null;\n\n /**\n * ID of a <script> element containing JSON captions data.\n * The script's textContent should be valid JSON conforming to the Caption interface.\n */\n @property({ type: String, attribute: \"captions-script\", reflect: true })\n captionsScript = \"\";\n\n activeWordContainers = this.getElementsByTagName(\"ef-captions-active-word\");\n segmentContainers = this.getElementsByTagName(\"ef-captions-segment\");\n beforeActiveWordContainers = this.getElementsByTagName(\"ef-captions-before-active-word\");\n afterActiveWordContainers = this.getElementsByTagName(\"ef-captions-after-active-word\");\n\n // Cache for intrinsicDurationMs to avoid expensive O(n) recalculation every frame\n #cachedIntrinsicDurationMs: number | undefined | null = null; // null = not computed, undefined = no duration\n\n render() {\n return html`<slot></slot>`;\n }\n\n transcriptionsPath() {\n if (!this.targetElement) {\n return null;\n }\n const fileId = this.targetElement.fileId ?? this.targetElement.assetId;\n if (fileId) {\n return `${this.apiHost}/api/v1/files/${fileId}/transcription`;\n }\n return null;\n }\n\n captionsPath() {\n if (!this.targetElement) {\n return null;\n }\n const fileId = this.targetElement.fileId ?? this.targetElement.assetId;\n if (fileId) {\n return `${this.apiHost}/api/v1/files/${fileId}`;\n }\n const targetSrc = this.targetElement.src;\n // Normalize the path: remove leading slash and any double slashes\n let normalizedSrc = targetSrc.startsWith(\"/\") ? targetSrc.slice(1) : targetSrc;\n normalizedSrc = normalizedSrc.replace(/^\\/+/, \"\");\n // Use production API format for local files\n return `/api/v1/assets/captions?src=${encodeURIComponent(normalizedSrc)}`;\n }\n\n // ============================================================================\n // Captions Data Loading - async methods instead of Tasks\n // ============================================================================\n\n #captionsDataLoaded = false;\n #captionsDataPromise: Promise<Caption | null> | null = null;\n #captionsDataValue: Caption | null = null;\n #transcriptionData: GetISOBMFFFileTranscriptionResult | null = null;\n\n /**\n * AsyncValue wrapper for backwards compatibility\n */\n unifiedCaptionsDataTask = new AsyncValue<Caption | null>();\n\n override shouldAutoReady(): boolean {\n return false;\n }\n\n /**\n * Load captions data from all possible sources\n */\n async loadCaptionsData(signal?: AbortSignal): Promise<Caption | null> {\n // Return cached if already loaded\n if (this.#captionsDataLoaded && this.#captionsDataValue) {\n this.setContentReadyState(\"ready\");\n return this.#captionsDataValue;\n }\n\n // Return in-flight promise\n if (this.#captionsDataPromise) {\n return this.#captionsDataPromise;\n }\n\n this.unifiedCaptionsDataTask.startPending();\n this.setContentReadyState(\"loading\");\n this.#captionsDataPromise = this.#doLoadCaptionsData(signal);\n\n try {\n this.#captionsDataValue = await this.#captionsDataPromise;\n this.#captionsDataLoaded = true;\n if (this.#captionsDataValue) {\n this.unifiedCaptionsDataTask.setValue(this.#captionsDataValue);\n }\n this.setContentReadyState(\"ready\");\n return this.#captionsDataValue;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n console.error(\"Failed to load captions data:\", error);\n this.setContentReadyState(\"error\");\n return null;\n } finally {\n this.#captionsDataPromise = null;\n }\n }\n\n async #doLoadCaptionsData(signal?: AbortSignal): Promise<Caption | null> {\n // Priority 1: Direct captionsData property\n if (this.captionsData) {\n return this.captionsData;\n }\n\n // Priority 2: Script element reference\n if (this.captionsScript) {\n const scriptElement = this.#findElementById(this.captionsScript);\n if (scriptElement?.textContent) {\n try {\n return JSON.parse(scriptElement.textContent) as Caption;\n } catch (error) {\n console.error(`Failed to parse captions from script #${this.captionsScript}:`, error);\n }\n }\n }\n\n // Priority 3: External captions file\n if (this.captionsSrc) {\n try {\n const response = await this.fetch(this.captionsSrc, { signal });\n return (await response.json()) as Caption;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n console.error(`Failed to load captions from ${this.captionsSrc}:`, error);\n }\n }\n\n // Priority 4: Transcription from target element\n if (this.targetElement && !this.hasCustomCaptionsData) {\n const transcriptionPath = this.transcriptionsPath();\n if (transcriptionPath) {\n try {\n const response = await this.fetch(transcriptionPath, { signal });\n this.#transcriptionData = (await response.json()) as GetISOBMFFFileTranscriptionResult;\n signal?.throwIfAborted();\n\n // Load fragment for current time\n if (this.#transcriptionData) {\n return this.#loadTranscriptionFragment(signal);\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n // Transcription not available - not an error\n }\n }\n }\n\n return null;\n }\n\n async #loadTranscriptionFragment(signal?: AbortSignal): Promise<Caption | null> {\n if (!this.#transcriptionData) return null;\n\n const fragmentIndex = Math.floor(this.ownCurrentTimeMs / this.#transcriptionData.work_slice_ms);\n const fragmentPath = `${this.apiHost}/api/v1/transcriptions/${this.#transcriptionData.id}/fragments/${fragmentIndex}`;\n\n try {\n const response = await this.fetch(fragmentPath, { signal });\n return (await response.json()) as Caption;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw error;\n }\n console.error(\"Failed to load transcription fragment:\", error);\n return null;\n }\n }\n\n // ============================================================================\n // FrameRenderable Implementation\n // ============================================================================\n\n /**\n * Query readiness state for a given time.\n * @implements FrameRenderable\n */\n getFrameState(_timeMs: number): FrameState {\n // Check if captions data is loaded\n const hasData = this.#captionsDataLoaded && this.#captionsDataValue !== null;\n\n return {\n needsPreparation: !hasData,\n isReady: hasData,\n priority: PRIORITY_CAPTIONS,\n };\n }\n\n /**\n * Async preparation - waits for captions data to load.\n * @implements FrameRenderable\n */\n async prepareFrame(_timeMs: number, signal: AbortSignal): Promise<void> {\n await this.loadCaptionsData(signal);\n signal.throwIfAborted();\n }\n\n /**\n * Synchronous render - updates caption text containers.\n * Sets textContent directly on child elements (light DOM).\n * @implements FrameRenderable\n */\n renderFrame(_timeMs: number): void {\n // Update text containers by setting properties\n // Child elements update their textContent directly (light DOM)\n this.updateTextContainers();\n }\n\n // ============================================================================\n // End FrameRenderable Implementation\n // ============================================================================\n\n #rootTimegroupUpdateController?: ReactiveController;\n\n connectedCallback() {\n super.connectedCallback();\n\n // Start loading captions data\n this.loadCaptionsData().catch(() => {});\n\n // Try to get target element safely\n const target = this.targetSelector ? this.#findElementById(this.targetSelector) : null;\n if (target && (target instanceof EFAudio || target instanceof EFVideo)) {\n new CrossUpdateController(target, this);\n }\n // For standalone captions with custom data, ensure proper timeline sync\n else if (this.hasCustomCaptionsData && this.rootTimegroup) {\n new CrossUpdateController(this.rootTimegroup, this);\n }\n\n // Ensure captions update when root timegroup's currentTimeMs changes\n if (this.rootTimegroup) {\n this.#rootTimegroupUpdateController = {\n hostUpdated: () => {\n Promise.resolve().then(() => {\n this.updateTextContainers();\n });\n },\n hostDisconnected: () => {\n this.#rootTimegroupUpdateController = undefined;\n },\n };\n this.rootTimegroup.addController(this.#rootTimegroupUpdateController);\n }\n\n // Prevent display:none from being set on the parent caption element.\n // IMPORTANT: This only applies to the parent <ef-captions> element, NOT to\n // caption child elements (<ef-captions-segment>, <ef-captions-active-word>, etc.).\n // Child elements MUST respect display:none for proper temporal visibility\n // in video rendering. Video export relies on display:none to hide elements\n // outside their time range.\n const observer = new MutationObserver(() => {\n if (this.style.display === \"none\") {\n this.style.removeProperty(\"display\");\n this.style.opacity = \"0\";\n this.style.pointerEvents = \"none\";\n } else if (!this.style.display || this.style.display === \"\") {\n this.style.removeProperty(\"opacity\");\n this.style.removeProperty(\"pointer-events\");\n }\n });\n observer.observe(this, { attributes: true, attributeFilter: [\"style\"] });\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n if (this.#rootTimegroupUpdateController && this.rootTimegroup) {\n this.rootTimegroup.removeController(this.#rootTimegroupUpdateController);\n this.#rootTimegroupUpdateController = undefined;\n }\n }\n\n protected updated(changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>): void {\n // Set up root timegroup controller if rootTimegroup is now available\n if (this.rootTimegroup && !this.#rootTimegroupUpdateController) {\n this.#rootTimegroupUpdateController = {\n hostUpdated: () => {\n Promise.resolve().then(() => {\n this.updateTextContainers();\n });\n },\n hostDisconnected: () => {\n this.#rootTimegroupUpdateController = undefined;\n },\n };\n this.rootTimegroup.addController(this.#rootTimegroupUpdateController);\n }\n\n // Clean up controller if rootTimegroup changed\n if (changedProperties.has(\"rootTimegroup\") && this.#rootTimegroupUpdateController) {\n const oldRootTimegroup = changedProperties.get(\"rootTimegroup\") as EFTimegroup | undefined;\n if (oldRootTimegroup && oldRootTimegroup !== this.rootTimegroup) {\n oldRootTimegroup.removeController(this.#rootTimegroupUpdateController);\n this.#rootTimegroupUpdateController = undefined;\n }\n }\n\n this.updateTextContainers();\n\n // Force duration recalculation when custom captions data changes\n if (\n changedProperties.has(\"captionsData\") ||\n changedProperties.has(\"captionsSrc\") ||\n changedProperties.has(\"captionsScript\")\n ) {\n this.emitContentChange(\"source\");\n this.#cachedIntrinsicDurationMs = null;\n this.#captionsDataLoaded = false;\n this.#captionsDataValue = null;\n this.loadCaptionsData().catch(() => {});\n\n this.requestUpdate(\"intrinsicDurationMs\");\n\n flushSequenceDurationCache();\n flushStartTimeMsCache();\n\n if (this.parentTimegroup) {\n this.parentTimegroup.requestUpdate(\"durationMs\");\n this.parentTimegroup.requestUpdate(\"currentTime\");\n }\n }\n\n // Update captions when timeline position changes\n if (changedProperties.has(\"ownCurrentTimeMs\")) {\n this.updateTextContainers();\n }\n }\n\n updateTextContainers() {\n const captionsData = this.#captionsDataValue;\n if (!captionsData) {\n return;\n }\n\n // For captions with custom data, try to use the video's source time\n let currentTimeMs = this.ownCurrentTimeMs;\n if (this.hasCustomCaptionsData && this.parentTimegroup) {\n const videoElement = Array.from(this.parentTimegroup.children).find(\n (child): child is EFVideo => child instanceof EFVideo,\n );\n if (videoElement) {\n const sourceInMs = videoElement.sourceInMs ?? 0;\n currentTimeMs = videoElement.currentSourceTimeMs - sourceInMs;\n currentTimeMs = Math.max(0, Math.min(currentTimeMs, this.durationMs));\n }\n }\n\n const currentTimeSec = currentTimeMs / 1000;\n\n // Find the current word from word_segments\n const currentWord = captionsData.word_segments.find(\n (word) => currentTimeSec >= word.start && currentTimeSec < word.end,\n );\n\n // Find the current segment\n const currentSegment = captionsData.segments.find(\n (segment) => currentTimeSec >= segment.start && currentTimeSec < segment.end,\n );\n\n for (const wordContainer of this.activeWordContainers) {\n if (currentWord) {\n const wordIndex = captionsData.word_segments.findIndex(\n (w) =>\n w.start === currentWord.start &&\n w.end === currentWord.end &&\n w.text === currentWord.text,\n );\n wordContainer.wordIndex = wordIndex >= 0 ? wordIndex : 0;\n wordContainer.wordText = currentWord.text; // Sets textContent directly\n } else {\n wordContainer.wordText = \"\"; // Hides element\n }\n }\n\n for (const segmentContainer of this.segmentContainers) {\n if (currentSegment) {\n segmentContainer.segmentText = currentSegment.text; // Sets textContent directly\n } else {\n segmentContainer.segmentText = \"\"; // Hides element\n }\n }\n\n // Process context for both word and segment cases\n if (currentWord && currentSegment) {\n const segmentWords = captionsData.word_segments.filter(\n (word) => word.start >= currentSegment.start && word.end <= currentSegment.end,\n );\n\n const currentWordIndex = segmentWords.findIndex(\n (word) => word.start === currentWord.start && word.end === currentWord.end,\n );\n\n if (currentWordIndex !== -1) {\n const beforeWords = segmentWords\n .slice(0, currentWordIndex)\n .map((w) => w.text.trim())\n .join(\" \");\n\n const afterWords = segmentWords\n .slice(currentWordIndex + 1)\n .map((w) => w.text.trim())\n .join(\" \");\n\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = beforeWords; // Sets textContent directly\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = afterWords; // Sets textContent directly\n }\n }\n } else if (currentSegment) {\n const segmentWords = captionsData.word_segments.filter(\n (word) => word.start >= currentSegment.start && word.end <= currentSegment.end,\n );\n\n const firstWord = segmentWords[0];\n const isBeforeFirstWord = firstWord && currentTimeSec < firstWord.start;\n\n if (isBeforeFirstWord) {\n const allWords = segmentWords.map((w) => w.text.trim()).join(\" \");\n\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = allWords; // Sets textContent directly\n }\n } else {\n const allCompletedWords = segmentWords.map((w) => w.text.trim()).join(\" \");\n\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = allCompletedWords; // Sets textContent directly\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n }\n } else {\n for (const container of this.beforeActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n\n for (const container of this.afterActiveWordContainers) {\n container.segmentText = \"\"; // Hides element\n }\n }\n }\n\n get targetElement() {\n const target = this.targetSelector ? this.#findElementById(this.targetSelector) : null;\n if (target instanceof EFAudio || target instanceof EFVideo) {\n return target;\n }\n if (this.hasCustomCaptionsData) {\n return null;\n }\n return null;\n }\n\n get hasCustomCaptionsData(): boolean {\n return !!(this.captionsData || this.captionsSrc || this.captionsScript);\n }\n\n /**\n * Find element by ID, searching within clone scope first to avoid cross-boundary references.\n * @private\n */\n #findElementById(id: string): Element | null {\n // Search within nearest timegroup or configuration container first\n const container = this.closest(\"ef-timegroup, ef-configuration\");\n if (container) {\n const result = container.querySelector(`#${CSS.escape(id)}`);\n if (result) return result;\n }\n\n // Fall back to document-wide search\n return document.getElementById(id);\n }\n\n get intrinsicDurationMs(): number | undefined {\n if (this.#cachedIntrinsicDurationMs !== null) {\n return this.#cachedIntrinsicDurationMs;\n }\n\n let captionsData: Caption | null = null;\n\n if (this.captionsData) {\n captionsData = this.captionsData;\n } else if (this.captionsScript) {\n const scriptElement = this.#findElementById(this.captionsScript);\n if (scriptElement?.textContent) {\n try {\n captionsData = JSON.parse(scriptElement.textContent) as Caption;\n } catch {\n // Invalid JSON\n }\n }\n } else if (this.#captionsDataValue) {\n captionsData = this.#captionsDataValue;\n }\n\n if (!captionsData) {\n if (!this.captionsData && !this.captionsScript && !this.captionsSrc) {\n this.#cachedIntrinsicDurationMs = undefined;\n }\n return undefined;\n }\n\n let result: number;\n if (captionsData.segments.length === 0 && captionsData.word_segments.length === 0) {\n result = 0;\n } else {\n const maxSegmentEnd =\n captionsData.segments.length > 0\n ? captionsData.segments.reduce((max, s) => (s.end > max ? s.end : max), 0)\n : 0;\n const maxWordEnd =\n captionsData.word_segments.length > 0\n ? captionsData.word_segments.reduce((max, w) => (w.end > max ? w.end : max), 0)\n : 0;\n\n result = Math.max(maxSegmentEnd, maxWordEnd) * 1000;\n }\n\n this.#cachedIntrinsicDurationMs = result;\n return result;\n }\n\n get hasOwnDuration(): boolean {\n return !!(this.captionsData || this.captionsScript || this.#captionsDataValue);\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"ef-captions\": EFCaptions;\n \"ef-captions-active-word\": EFCaptionsActiveWord;\n \"ef-captions-segment\": EFCaptionsSegment;\n \"ef-captions-before-active-word\": EFCaptionsBeforeActiveWord;\n \"ef-captions-after-active-word\": EFCaptionsAfterActiveWord;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmCA,MAAM,YAAY,IAAI,IAAI;CAAC;CAAI;CAAK;CAAK;CAAK;CAAI,CAAC;AAO5C,iCAAMA,+BAA6B,WAAW;CACnD,YAAY;CACZ,aAAa;CAEb,IAAI,SAAS,MAAc;AACzB,QAAKC,WAAY;AAEjB,MAAI,CAAC,QAAQ,UAAU,IAAI,KAAK,EAAE;AAChC,QAAK,SAAS;AACd,QAAK,cAAc;SACd;AACL,QAAK,SAAS;AAEd,QAAK,cAAc,OAAO;;;CAI9B,IAAI,WAAmB;AACrB,SAAO,MAAKA;;CAGd,IAAI,UAAU,OAAe;AAC3B,QAAKC,YAAa;EAGlB,MAAM,YADQ,QAAQ,OAAQ,MACL;AACzB,OAAK,MAAM,YAAY,kBAAkB,UAAU,UAAU,CAAC;;CAGhE,IAAI,YAAoB;AACtB,SAAO,MAAKA;;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gB;GAC9B,MAAM,gBAAgB,MAAKL,gBAAiB,KAAK,eAAe;AAChE,OAAI,eAAe,YACjB,KAAI;AACF,mBAAe,KAAK,MAAM,cAAc,YAAY;WAC9C;aAID,MAAKH,kBACd,gBAAe,MAAKA;AAGtB,MAAI,CAAC,cAAc;AACjB,OAAI,CAAC,KAAK,gBAAgB,CAAC,KAAK,kBAAkB,CAAC,KAAK,YACtD,OAAKO,4BAA6B;AAEpC;;EAGF,IAAIE;AACJ,MAAI,aAAa,SAAS,WAAW,KAAK,aAAa,cAAc,WAAW,EAC9E,UAAS;OACJ;GACL,MAAM,gBACJ,aAAa,SAAS,SAAS,IAC3B,aAAa,SAAS,QAAQ,KAAK,MAAO,EAAE,MAAM,MAAM,EAAE,MAAM,KAAM,EAAE,GACxE;GACN,MAAM,aACJ,aAAa,cAAc,SAAS,IAChC,aAAa,cAAc,QAAQ,KAAK,MAAO,EAAE,MAAM,MAAM,EAAE,MAAM,KAAM,EAAE,GAC7E;AAEN,YAAS,KAAK,IAAI,eAAe,WAAW,GAAG;;AAGjD,QAAKF,4BAA6B;AAClC,SAAO;;CAGT,IAAI,iBAA0B;AAC5B,SAAO,CAAC,EAAE,KAAK,gBAAgB,KAAK,kBAAkB,MAAKP;;;YApjB5D,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAU,SAAS;CAAM,CAAC;YAO9D,SAAS,EAAE,WAAW,cAAc,CAAC;YAOrC,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAgB,SAAS;CAAM,CAAC;YAOpE,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAO,CAAC;YAO5C,SAAS;CAAE,MAAM;CAAQ,WAAW;CAAmB,SAAS;CAAM,CAAC;yBAnDzE,cAAc,cAAc"}
|
package/dist/elements/EFImage.js
CHANGED
|
@@ -223,7 +223,7 @@ let EFImage = class EFImage$1 extends EFTemporal(EFSourceMixin(FetchMixin(LitEle
|
|
|
223
223
|
this.canvasRef.value.height = canvasHeight;
|
|
224
224
|
try {
|
|
225
225
|
await image.decode();
|
|
226
|
-
} catch (
|
|
226
|
+
} catch (_decodeError) {}
|
|
227
227
|
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
|
|
228
228
|
try {
|
|
229
229
|
ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
|