@aceshooting/lyra-ui 30.9.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +236 -339
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +5 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +13 -7
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-json-viewer.md +17 -0
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-prompt-input.md +1 -1
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +1 -0
- package/llms/peers.md +2 -2
- package/llms/shared/forms-and-accessibility.md +21 -4
- package/llms/shared.md +21 -4
- package/package.json +21 -20
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{finiteRange}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{styles}from"./pan-zoom.styles.js";import{LYRA_DEFAULT_zoomControls,LYRA_DEFAULT_zoomableFrameLabel}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_resetZoom,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";class LyraPanZoom extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="viewport"][role="group"]')),this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._fit="actual",this.src="",this.alt="",this.accessibleLabel=null,this.onViewportFocus=event=>{relayNativeEvent(this,event)},this.onViewportBlur=event=>{relayNativeEvent(this,event)},this.onViewportKeyDown=event=>{event.altKey||event.ctrlKey||event.metaKey||keyEventOwnedByInnerControl(event,{container:this})||(event.key==="+"||event.key==="="?(event.preventDefault(),this.zoomIn()):event.key==="-"||event.key==="_"?(event.preventDefault(),this.zoomOut()):event.key==="0"&&(event.preventDefault(),this.resetZoom()))}}static{this.defaultStrings={...super.defaultStrings,pdfViewerCurrentZoom:LYRA_DEFAULT_pdfViewerCurrentZoom,resetZoom:LYRA_DEFAULT_resetZoom,zoomControls:LYRA_DEFAULT_zoomControls,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut,zoomableFrameLabel:LYRA_DEFAULT_zoomableFrameLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value,"actual"),this.requestUpdate("fit",old)}get safeMinZoom(){return finiteRange(this.minZoom,.5,.01,1e3)}get safeMaxZoom(){return finiteRange(this.maxZoom,4,this.safeMinZoom,1e3)}get safeZoomStep(){return finiteRange(this.zoomStep,.25,.01,1e3)}get safeZoom(){return normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom)}setZoom(value,quantize=!0){const min=this.safeMinZoom,max=this.safeMaxZoom,step=this.safeZoomStep,stepped=quantize?Math.round(value/step)*step:value,next=Math.min(max,Math.max(min,Math.round(stepped*100)/100));next!==this.zoom&&(this.zoom=next,this.emit("lr-zoom-change",{zoom:next}))}zoomIn(){this.setZoom(this.safeZoom+this.safeZoomStep)}zoomOut(){this.setZoom(this.safeZoom-this.safeZoomStep)}resetZoom(){this.setZoom(1,!1)}resetView(){this.resetZoom(),this.viewportEl?.scrollTo({left:0,top:0})}get viewportEl(){return this.renderRoot
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{finiteRange}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{styles}from"./pan-zoom.styles.js";import{LYRA_DEFAULT_zoomControls,LYRA_DEFAULT_zoomableFrameLabel}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_resetZoom,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";class LyraPanZoom extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="viewport"][role="group"]')),this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._fit="actual",this.src="",this.alt="",this.accessibleLabel=null,this.onViewportFocus=event=>{relayNativeEvent(this,event)},this.onViewportBlur=event=>{relayNativeEvent(this,event)},this.onViewportKeyDown=event=>{event.altKey||event.ctrlKey||event.metaKey||keyEventOwnedByInnerControl(event,{container:this})||(event.key==="+"||event.key==="="?(event.preventDefault(),this.zoomIn()):event.key==="-"||event.key==="_"?(event.preventDefault(),this.zoomOut()):event.key==="0"&&(event.preventDefault(),this.resetZoom()))}}static{this.defaultStrings={...super.defaultStrings,pdfViewerCurrentZoom:LYRA_DEFAULT_pdfViewerCurrentZoom,resetZoom:LYRA_DEFAULT_resetZoom,zoomControls:LYRA_DEFAULT_zoomControls,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut,zoomableFrameLabel:LYRA_DEFAULT_zoomableFrameLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value,"actual"),this.requestUpdate("fit",old)}get safeMinZoom(){return finiteRange(this.minZoom,.5,.01,1e3)}get safeMaxZoom(){return finiteRange(this.maxZoom,4,this.safeMinZoom,1e3)}get safeZoomStep(){return finiteRange(this.zoomStep,.25,.01,1e3)}get safeZoom(){return normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom)}setZoom(value,quantize=!0){const min=this.safeMinZoom,max=this.safeMaxZoom,step=this.safeZoomStep,stepped=quantize?Math.round(value/step)*step:value,next=Math.min(max,Math.max(min,Math.round(stepped*100)/100));next!==this.zoom&&(this.zoom=next,this.emit("lr-zoom-change",{zoom:next}))}zoomIn(){this.setZoom(this.safeZoom+this.safeZoomStep)}zoomOut(){this.setZoom(this.safeZoom-this.safeZoomStep)}resetZoom(){this.setZoom(1,!1)}resetView(){this.resetZoom(),this.viewportEl?.scrollTo({left:0,top:0})}get viewportEl(){return this.renderRoot?.querySelector('[part="viewport"]')??null}focus(options){this.viewportEl?.focus(options)}blur(){this.viewportEl?.blur()}click(){this.viewportEl?.click()}render(){const zoom=this.safeZoom,min=this.safeMinZoom,max=this.safeMaxZoom,viewportLabel=hostAriaLabel(this)??this.localize("zoomableFrameLabel"),safeSrc=safeMediaSrc(this.src);return html`<div part="base">
|
|
2
2
|
<div
|
|
3
3
|
part="viewport"
|
|
4
4
|
role="group"
|
|
@@ -87,9 +87,9 @@ protected static readonly knownUnobservedAttributes:readonly string[];static get
|
|
|
87
87
|
/** Flat media by default. Equirectangular rendering also requires engine="webgl".*/
|
|
88
88
|
get projection():LyraMediaProjection;set projection(value:LyraMediaProjection);private _engine;
|
|
89
89
|
/** Preferred panorama renderer; the builtin flat view never downloads a companion.*/
|
|
90
|
-
get engine():Engine3dPreference;set engine(value:Engine3dPreference);private _panoramaCamera;
|
|
90
|
+
get engine():Engine3dPreference;set engine(value:Engine3dPreference);private _panoramaCamera;private panoramaCameraRevision;
|
|
91
91
|
/** Camera yaw/pitch in radians and vertical fieldOfView in degrees (20–100). Authored writes are silent.*/
|
|
92
|
-
get panoramaCamera():LyraPanoramaCamera;set panoramaCamera(value:LyraPanoramaCamera);private _hotspots;private hotspotSource;
|
|
92
|
+
get panoramaCamera():LyraPanoramaCamera;set panoramaCamera(value:LyraPanoramaCamera);private _hotspots;private hotspotSource;private hotspotRevision;
|
|
93
93
|
/** Bounded clone-owned hotspot snapshot. First valid unique ID wins; reassign after changes.
|
|
94
94
|
* Angles are radians, pitch is within ±π/2, and invalid rows are omitted. */
|
|
95
95
|
get hotspots():readonly LyraPanoramaHotspot[];set hotspots(value:readonly LyraPanoramaHotspot[]);private get panoramaEnabled();private synchronizingCurrentTime;private currentTimeFromMedia;requestUpdate(name?:PropertyKey,oldValue?:unknown,options?:Parameters<LyraElement['requestUpdate']>[2]):void;
|
|
@@ -155,4 +155,4 @@ togglePlay():void;
|
|
|
155
155
|
/** Requests fullscreen for the wrapper so custom overlays remain visible.*/
|
|
156
156
|
requestFullscreen():Promise<void>;
|
|
157
157
|
/** Exits document fullscreen and preserves the platform promise/rejection.*/
|
|
158
|
-
exitFullscreen():Promise<void>;private onNativeMediaEvent;private onTimelineInput;private onVolumeInput;private onRateChange;private onPosterPlay;private canRenderFullscreen;private canRenderPictureInPicture;private onFullscreenButton;private onFullscreenChange;private onPictureInPictureChange;private togglePictureInPicture;private pauseForVisibility;private configureVisibilityObserver;private unbindCaptionTracks;private bindCaptionTracks;private syncActiveCaption;private onCaptionChange;private loadThumbnails;private onTimelinePointerMove;private onTimelinePointerLeave;private renderIcon;private renderDecorativeIconLayer;private renderPlaySlots;private renderVolumeSlots;private renderFullscreenSlots;private renderThumbnail;private renderControls;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-video':LyraVideo;}}
|
|
158
|
+
exitFullscreen():Promise<void>;private onNativeMediaEvent;private onTimelineInput;private onVolumeInput;private onRateChange;private onPosterPlay;private canRenderFullscreen;private canRenderPictureInPicture;private onFullscreenButton;private onFullscreenChange;private get isPictureInPicture();private onPictureInPictureChange;private togglePictureInPicture;private pauseForVisibility;private configureVisibilityObserver;private unbindCaptionTracks;private bindCaptionTracks;private syncActiveCaption;private onCaptionChange;private loadThumbnails;private onTimelinePointerMove;private onTimelinePointerLeave;private renderIcon;private renderDecorativeIconLayer;private renderPlaySlots;private renderVolumeSlots;private renderFullscreenSlots;private renderThumbnail;private renderControls;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-video':LyraVideo;}}
|
|
@@ -2,7 +2,7 @@ import{__decorate}from"tslib";import{panoramaStyles}from"../../../internal/media
|
|
|
2
2
|
`,`
|
|
3
3
|
`).replaceAll("\r",`
|
|
4
4
|
`);for(const block of normalized.split(/\n{2,}/u)){if(cues.length>=MAX_THUMBNAIL_CUES)break;const lines=block.split(`
|
|
5
|
-
`).map(line=>line.trim()).filter(Boolean),timingIndex=lines.findIndex(line=>line.includes("-->"));if(timingIndex<0||!lines[timingIndex+1])continue;const match=/^(\S+)\s+-->\s+(\S+)/u.exec(lines[timingIndex]);if(!match)continue;const start=parseVttTime(match[1]),end=parseVttTime(match[2]),thumbnail=parseThumbnailUrl(lines[timingIndex+1],sourceUrl,URLCtor);start===null||end===null||end<=start||!thumbnail||cues.push({start,end,...thumbnail})}return cues}function unsupportedPromise(host,message){const DOMExceptionConstructor=host.ownerDocument.defaultView?.DOMException??DOMException;return Promise.reject(new DOMExceptionConstructor(message,"NotSupportedError"))}class LyraVideo extends LyraElement{constructor(){super(...arguments),this.panoramaRevision=0,this.panorama=new PanoramaController(this,{changed:()=>this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaState",void 0,{hasChanged:()=>!0}),"panorama-state"),updated:async()=>(await Promise.resolve(),this.updateComplete),localize:key=>this.localize(key),direction:()=>this.effectiveDirection,fallback:detail=>this.emit("lr-engine-fallback",detail),pick:detail=>this.emit("lr-panorama-hotspot-select",detail),camera:camera=>{const old=this._panoramaCamera;this._panoramaCamera=camera,this.requestUpdate("panoramaCamera",old),this.emit("lr-panorama-camera-change",{camera})}}),this._projection="flat",this._engine="builtin",this._panoramaCamera=PANORAMA_DEFAULT_CAMERA,this._hotspots=Object.freeze([]),this.hotspotSource=this._hotspots,this.synchronizingCurrentTime=!1,this.currentTimeFromMedia=!1,this.autoplay=!1,this.autoplayMuted=!1,this.autoplayOnVisible=!1,this.controls="standard",this.currentTime=0,this.duration=0,this.iconLibrary="system",this.loop=!1,this.muted=!1,this.isPlaying=!1,this.poster="",this.preload="metadata",this.src="",this.thumbnails="",this.title="",this.volume=1,this.playbackRate=1,this.posterVisible=!0,this.captionText="",this.captionTracks=[],this.fullscreen=!1,this.pictureInPicture=!1,this.thumbnailCues=[],this.thumbnailPosition=50,this.panoramaVideoReady=!1,this.onPanoramaMediaReady=()=>{this.panoramaVideoReady=!0,this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaMedia",void 0,{hasChanged:()=>!0}),"panorama-media")},this.onPanoramaMediaReset=()=>{this.panoramaVideoReady=!1,this.panoramaRevision++,this.panorama.invalidate(),this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaMedia",void 0,{hasChanged:()=>!0}),"panorama-media")},this.mediaController=new NativeMediaController(this,{selectedTrackMode:"hidden",relayEvents:NATIVE_MEDIA_RELAY_EVENTS.filter(type=>type!=="timeupdate"),onEvent:event=>this.onNativeMediaEvent(event)}),this.pendingNativeEcho={timeupdate:!1,muted:!1},this.thumbnailGeneration=0,this.visibilityPaused=!1,this.captionListeners=[],this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.mediaRef=element=>{const video=element?.localName==="video"?element:void 0;this.mediaController.attach(video),video&&(this.mediaController.volume=finiteRange(this.volume,1,0,1),this.autoplayMuted&&!this.muted?this.forceAutoplayMuted():this.mediaController.muted=this.muted,this.mediaController.playbackRate=this.playbackRate)},this.onSourceSlotChange=()=>this.syncSources(),this.onTimelineInput=event=>{const input=event.currentTarget;this.seek(Number(input.value))},this.onVolumeInput=event=>{this.setVolume(Number(event.currentTarget.value))},this.onRateChange=event=>{this.setPlaybackRate(Number(event.currentTarget.value))},this.onPosterPlay=()=>{this.play().catch(()=>{})},this.onFullscreenButton=()=>{(this.fullscreen?this.exitFullscreen():this.requestFullscreen()).catch(()=>{})},this.onFullscreenChange=()=>{this.fullscreen=this.ownerDocument.fullscreenElement===this.wrapperEl},this.onPictureInPictureChange=()=>{const documentRef=this.ownerDocument;this.pictureInPicture=documentRef.pictureInPictureElement===this.videoEl},this.togglePictureInPicture=()=>{const video=this.videoEl,documentRef=this.ownerDocument;if(!video||!canRequestPictureInPicture(video))return;(documentRef.pictureInPictureElement===video?documentRef.exitPictureInPicture?.():video.requestPictureInPicture().then(()=>{}))?.catch(()=>{})},this.onCaptionChange=event=>{const selected=Number(event.currentTarget.value);this.captionTracks.forEach(({track},index)=>{track.mode=index===selected?"hidden":"disabled"}),this.syncActiveCaption()},this.onTimelinePointerMove=event=>{const rect=event.currentTarget.getBoundingClientRect();if(rect.width<=0||this.duration<=0){this.activeThumbnail=void 0;return}const ratio=finiteRange((event.clientX-rect.left)/rect.width,0,0,1),time=ratio*this.duration;this.activeThumbnail=this.thumbnailCues.find(cue=>time>=cue.start&&time<cue.end),this.thumbnailPosition=ratio*100},this.onTimelinePointerLeave=()=>{this.activeThumbnail=void 0}}static{this.defaultStrings={...super.defaultStrings,avPlayerPlaybackRate:LYRA_DEFAULT_avPlayerPlaybackRate,avPlayerPosition:LYRA_DEFAULT_avPlayerPosition,avPlayerRateOption:LYRA_DEFAULT_avPlayerRateOption,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,duration:LYRA_DEFAULT_duration,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,model:LYRA_DEFAULT_model,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationLabel:LYRA_DEFAULT_paginationLabel,panoramaHotspotsLabel:LYRA_DEFAULT_panoramaHotspotsLabel,panoramaInstructions:LYRA_DEFAULT_panoramaInstructions,pause:LYRA_DEFAULT_pause,play:LYRA_DEFAULT_play,playbackPosition:LYRA_DEFAULT_playbackPosition,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,videoCaptions:LYRA_DEFAULT_videoCaptions,videoCaptionsOff:LYRA_DEFAULT_videoCaptionsOff,videoEnterFullscreen:LYRA_DEFAULT_videoEnterFullscreen,videoExitFullscreen:LYRA_DEFAULT_videoExitFullscreen,videoExitPictureInPicture:LYRA_DEFAULT_videoExitPictureInPicture,videoMute:LYRA_DEFAULT_videoMute,videoPictureInPicture:LYRA_DEFAULT_videoPictureInPicture,videoPlayerLabel:LYRA_DEFAULT_videoPlayerLabel,videoUnmute:LYRA_DEFAULT_videoUnmute,videoVolume:LYRA_DEFAULT_videoVolume}}static{this.styles=[LyraElement.styles,panoramaStyles,styles,srOnly]}static{this.knownUnobservedAttributes=["playing"]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"currenttime","current-time"])]}get projection(){return this._projection}set projection(value){const next=PANORAMA_PROJECTION.normalize(value),old=this._projection;next!==old&&(this._projection=next,this.panorama?.invalidate(),this.requestUpdate("projection",old))}get engine(){return this._engine}set engine(value){const next=ENGINE_3D_PREFERENCE.normalize(value),old=this._engine;next!==old&&(this._engine=next,this.panorama?.invalidate(),this.requestUpdate("engine",old))}get panoramaCamera(){return this._panoramaCamera}set panoramaCamera(value){const next=normalizePanoramaCamera(value),old=this._panoramaCamera;next.yaw===old.yaw&&next.pitch===old.pitch&&next.fieldOfView===old.fieldOfView||(this._panoramaCamera=next,this.requestUpdate("panoramaCamera",old))}get hotspots(){return this._hotspots}set hotspots(value){if(value===this.hotspotSource||value===this._hotspots)return;const old=this._hotspots;this.hotspotSource=value,this._hotspots=snapshotPanoramaHotspots(value,this.ownerDocument?.defaultView??null),this.panorama?.invalidate(),this.requestUpdate("hotspots",old)}get panoramaEnabled(){return this.projection==="equirectangular"&&this.engine==="webgl"}requestUpdate(name,oldValue,options){name==="currentTime"&&(this.currentTimeFromMedia=this.synchronizingCurrentTime),name==="src"&&this.panorama&&!Object.is(this.src,oldValue)&&(this.panoramaVideoReady=!1,this.panoramaRevision++,this.panorama.invalidate()),super.requestUpdate(name,oldValue,options)}get playing(){return this.isPlaying}updated(changed){super.updated(changed);const video=this.videoEl;this.panorama.update(this.panoramaEnabled,this.panoramaVideoReady&&video&&(video.readyState>=2||this.panorama.ready||this.panorama.notice?.reason==="context-lost")?video:null,this.panoramaRevision,this.hotspots,this.panoramaCamera,this.renderRoot.querySelector('[part="panorama-engine"]'))}adoptedCallback(){super.adoptedCallback(),this.panorama.adopted(),super.requestUpdate("panoramaAdopted",void 0,{hasChanged:()=>!0})}attributeChangedCallback(name,oldValue,newValue){if(name==="currenttime"||name==="current-time"){oldValue!==newValue&&(this.currentTime=finiteRange(Number(newValue??0),0,0));return}super.attributeChangedCallback(name,oldValue,newValue)}get videoEl(){const media=this.mediaController.element;return media?.localName==="video"?media:void 0}get playControl(){return this.renderRoot.querySelector('[part="poster-play-button"], [data-control="play"]')}focus(options){this.playControl?.focus(options)}blur(){this.playControl?.blur()}click(){this.playControl?.click()}connectedCallback(){super.connectedCallback(),super.requestUpdate("panoramaReconnect",void 0,{hasChanged:()=>!0}),this.mediaController.reconnect();const doc=this.listenerDocument=this.ownerDocument;doc.addEventListener("fullscreenchange",this.onFullscreenChange),doc.addEventListener("enterpictureinpicture",this.onPictureInPictureChange,!0),doc.addEventListener("leavepictureinpicture",this.onPictureInPictureChange,!0),this.hasUpdated&&(this.scheduleAfterUpdate(()=>this.bindCaptionTracks(),"video-caption-reconnect"),this.scheduleAfterUpdate(()=>this.configureVisibilityObserver(),"video-visibility-reconnect"),this.thumbnails&&this.scheduleAfterUpdate(()=>{this.loadThumbnails()},"video-thumbnails-reconnect"))}firstUpdated(changed){super.firstUpdated(changed),this.syncSources(),this.configureVisibilityObserver(),this.loadThumbnails()}disconnectedCallback(){this.panorama.disconnect(),this.mediaController.disconnect(),this.thumbnailGeneration+=1,this.thumbnailAbort?.abort(),this.thumbnailAbort=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.unbindCaptionTracks(),this.captionTracks.length&&(this.captionTracks=[]),this.captionText&&(this.captionText=""),this.activeThumbnail&&(this.activeThumbnail=void 0),this.isPlaying&&(this.isPlaying=!1),this.fullscreen&&(this.fullscreen=!1),this.pictureInPicture&&(this.pictureInPicture=!1);const doc=this.listenerDocument;doc?.removeEventListener("fullscreenchange",this.onFullscreenChange),doc?.removeEventListener("enterpictureinpicture",this.onPictureInPictureChange,!0),doc?.removeEventListener("leavepictureinpicture",this.onPictureInPictureChange,!0),super.disconnectedCallback()}willUpdate(changed){if(super.willUpdate(changed),changed.has("controls")&&(this.controls=safeControls(this.controls)),changed.has("preload")&&(this.preload=safePreload(this.preload)),changed.has("volume")){const next=finiteRange(this.volume,this.mediaController.volume,0,1);Object.is(next,this.volume)||(this.volume=next),this.mediaController.volume=next}if(changed.has("isPlaying")&&this.toggleAttribute("playing",this.isPlaying),changed.has("muted")&&(this.mediaController.muted=this.muted),changed.has("autoplayMuted")&&this.autoplayMuted&&this.forceAutoplayMuted(),changed.has("currentTime")&&!this.currentTimeFromMedia){const max=this.mediaController.duration>0?this.mediaController.duration:Number.POSITIVE_INFINITY,next=finiteRange(this.currentTime,0,0,max);Object.is(next,this.currentTime)||(this.currentTime=next),next!==this.mediaController.currentTime&&(this.mediaController.currentTime=next)}if(changed.has("duration")){const next=finiteRange(this.duration,0,0);Object.is(next,this.duration)||(this.duration=next)}changed.has("src")&&(this.visibilityPaused=!1,this.posterVisible=!0,this.hasUpdated&&(this.isPlaying=!1,this.duration=0,this.currentTime=0,this.scheduleAfterUpdate(()=>this.syncSources(),"video-sources"))),changed.has("thumbnails")&&this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.loadThumbnails()},"video-thumbnails"),changed.has("autoplayOnVisible")&&this.hasUpdated&&this.scheduleAfterUpdate(()=>this.configureVisibilityObserver(),"video-visibility")}forceAutoplayMuted(){this.pendingNativeEcho.muted=!0,this.mediaController.muted=!0}sourceSignature(){const nodes=[...this.children].filter(child=>child.localName==="source"||child.localName==="track").map(child=>({tag:child.localName,src:child.getAttribute("src"),type:child.getAttribute("type"),media:child.getAttribute("media"),kind:child.getAttribute("kind"),srclang:child.getAttribute("srclang"),label:child.getAttribute("label"),default:child.hasAttribute("default")}));return JSON.stringify({src:this.src,nodes})}syncSources(force=!1){if(!this.videoEl)return;const signature=this.sourceSignature();!force&&signature===this.lastSourceSignature||(this.lastSourceSignature=signature,this.onPanoramaMediaReset(),this.visibilityPaused=!1,this.unbindCaptionTracks(),this.captionTracks.length&&(this.captionTracks=[]),this.captionText&&(this.captionText=""),this.mediaController.setSources({src:this.src,nodes:this.children}),this.mediaController.currentTime=this.currentTime)}getVideoElement(){return this.videoEl}getState(){const video=this.videoEl;return{playing:!!(video&&!video.paused&&!video.ended),currentTime:this.mediaController.currentTime,duration:this.mediaController.duration,volume:this.mediaController.volume,muted:this.mediaController.muted,playbackRate:this.mediaController.playbackRate}}play(){return this.mediaController.play()}pause(){this.visibilityPaused=!1,this.mediaController.pause()}load(){this.visibilityPaused=!1,this.currentTime=0,this.syncSources(!0)}unloadMedia(){const native=this.videoEl;!native||!native.hasAttribute("src")&&![...native.children].some(child=>child.localName==="source"||child.localName==="track")||(this.visibilityPaused=!1,this.onPanoramaMediaReset(),this.mediaController.unload(),this.currentTime=0,this.lastSourceSignature=void 0,this.unbindCaptionTracks(),this.captionTracks=[],this.captionText="")}captureMediaPreferences(native=this.videoEl){return this.mediaController.captureUserPreferences(native)}applyMediaPreferences(preferences){this.mediaController.applyUserPreferences(preferences);const state2=this.getState();this.volume=state2.volume,this.muted=state2.muted,this.playbackRate=state2.playbackRate}seek(time){const max=this.mediaController.duration>0?this.mediaController.duration:Number.POSITIVE_INFINITY,next=finiteRange(time,0,0,max);this.mediaController.currentTime=next,this.synchronizeCurrentTime(),this.pendingNativeEcho.timeupdate=!0,this.dispatchHostTimeupdate()}synchronizeCurrentTime(){this.synchronizingCurrentTime=!0;try{this.currentTime=this.mediaController.currentTime}finally{this.synchronizingCurrentTime=!1}}dispatchHostTimeupdate(){const EventConstructor=this.ownerDocument.defaultView?.Event??Event;this.dispatchEvent(new EventConstructor("timeupdate"))}setPlaybackRate(rate){const next=finiteRange(rate,1,MIN_NATIVE_PLAYBACK_RATE,MAX_NATIVE_PLAYBACK_RATE);this.playbackRate=next,this.mediaController.playbackRate=next}rateSelectOptions(){const rates=PLAYBACK_RATES;return rates.includes(this.playbackRate)?rates:[...rates,this.playbackRate].sort((a,b)=>a-b)}renderRateOptions(){const format=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:2});return this.rateSelectOptions().map(rate=>html`<option value=${String(rate)} ?selected=${rate===this.playbackRate}>${this.localize("avPlayerRateOption",void 0,{rate:format.format(rate)})}</option>`)}setVolume(volume){const next=finiteRange(volume,this.mediaController.volume,0,1);this.volume=next,this.mediaController.volume=next}toggleMute(){const next=!this.mediaController.muted;this.muted=next,this.mediaController.muted=next}togglePlay(){this.videoEl?.paused??!0?this.play().catch(()=>{}):this.pause()}requestFullscreen(){return canRequestFullscreen(this.wrapperEl)?this.wrapperEl.requestFullscreen():unsupportedPromise(this,"Fullscreen is unavailable for this video.")}exitFullscreen(){return canExitFullscreen(this.ownerDocument)?this.ownerDocument.exitFullscreen():unsupportedPromise(this,"Fullscreen exit is unavailable for this video.")}onNativeMediaEvent(event){if(this.videoEl)switch(event.type){case"loadedmetadata":case"durationchange":this.duration=this.mediaController.duration,this.synchronizeCurrentTime(),this.bindCaptionTracks();break;case"play":this.isPlaying=!0,this.posterVisible=!1;break;case"pause":case"ended":this.isPlaying=!1;break;case"error":this.isPlaying=!1,this.duration=0,this.currentTime=0;break;case"timeupdate":this.synchronizeCurrentTime(),this.pendingNativeEcho.timeupdate?this.pendingNativeEcho.timeupdate=!1:this.dispatchHostTimeupdate();break;case"seeked":this.synchronizeCurrentTime(),this.pendingNativeEcho.timeupdate=!1;break;case"volumechange":this.volume=this.mediaController.volume,this.pendingNativeEcho.muted?this.pendingNativeEcho.muted=!1:this.muted=this.mediaController.muted;break;case"ratechange":this.playbackRate=this.mediaController.playbackRate;break}}canRenderFullscreen(){return typeof this.ownerDocument.defaultView?.HTMLElement.prototype.requestFullscreen=="function"&&this.ownerDocument.fullscreenEnabled!==!1}canRenderPictureInPicture(){const ownerWindow=this.ownerDocument.defaultView,documentRef=this.ownerDocument;return this.controls==="full"&&typeof ownerWindow?.HTMLVideoElement.prototype.requestPictureInPicture=="function"&&documentRef.pictureInPictureEnabled!==!1}pauseForVisibility(){this.visibilityPaused=!0,this.mediaController.pause()}configureVisibilityObserver(){const visibilityOwnedPause=this.visibilityPaused;this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0;const ownerWindow=this.ownerDocument.defaultView,IntersectionObserverCtor=ownerWindow?.IntersectionObserver;if(!this.autoplayOnVisible||!IntersectionObserverCtor){visibilityOwnedPause&&(this.visibilityPaused=!1,this.mediaController.play().catch(()=>{}));return}this.visibilityPaused=visibilityOwnedPause;let observer;observer=new IntersectionObserverCtor(entries=>{if(!observer||!this.isConnected||this.intersectionObserver!==observer||this.ownerDocument.defaultView!==ownerWindow)return;const visible=entries[0]?.isIntersecting??!0,video=this.videoEl;if(video){if(!visible){video.paused||this.pauseForVisibility();return}this.visibilityPaused&&(this.visibilityPaused=!1,this.mediaController.play().catch(()=>{}))}}),this.intersectionObserver=observer,observer.observe(this)}unbindCaptionTracks(){for(const{track,listener}of this.captionListeners)track.removeEventListener("cuechange",listener);this.captionListeners=[]}bindCaptionTracks(){this.unbindCaptionTracks();const selectable=Array.from(this.videoEl?.textTracks??[]).filter(track=>track.kind==="captions"||track.kind==="subtitles");for(const track of selectable)track.mode==="showing"&&(track.mode="hidden");this.captionTracks=selectable.map(track=>({track,label:track.label||track.language||this.localize("videoCaptions"),language:track.language}));for(const track of selectable){const listener=()=>this.syncActiveCaption();track.addEventListener("cuechange",listener),this.captionListeners.push({track,listener})}this.syncActiveCaption()}syncActiveCaption(){const lines=[];for(const{track}of this.captionTracks)if(!(track.mode!=="hidden"||!track.activeCues))for(let index=0;index<track.activeCues.length;index+=1){const cue=track.activeCues[index];cue&&typeof cue.text=="string"&&lines.push(cue.text)}this.captionText=lines.join(`
|
|
5
|
+
`).map(line=>line.trim()).filter(Boolean),timingIndex=lines.findIndex(line=>line.includes("-->"));if(timingIndex<0||!lines[timingIndex+1])continue;const match=/^(\S+)\s+-->\s+(\S+)/u.exec(lines[timingIndex]);if(!match)continue;const start=parseVttTime(match[1]),end=parseVttTime(match[2]),thumbnail=parseThumbnailUrl(lines[timingIndex+1],sourceUrl,URLCtor);start===null||end===null||end<=start||!thumbnail||cues.push({start,end,...thumbnail})}return cues}function unsupportedPromise(host,message){const DOMExceptionConstructor=host.ownerDocument.defaultView?.DOMException??DOMException;return Promise.reject(new DOMExceptionConstructor(message,"NotSupportedError"))}class LyraVideo extends LyraElement{constructor(){super(...arguments),this.panoramaRevision=0,this.panorama=new PanoramaController(this,{changed:()=>this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaState",void 0,{hasChanged:()=>!0}),"panorama-state"),updated:async()=>(await Promise.resolve(),this.updateComplete),localize:key=>this.localize(key),direction:()=>this.effectiveDirection,fallback:detail=>this.emit("lr-engine-fallback",detail),pick:detail=>this.emit("lr-panorama-hotspot-select",detail),camera:camera=>{const old=this._panoramaCamera;this._panoramaCamera=camera,this.requestUpdate("panoramaCamera",old),this.emit("lr-panorama-camera-change",{camera})}}),this._projection="flat",this._engine="builtin",this._panoramaCamera=PANORAMA_DEFAULT_CAMERA,this.panoramaCameraRevision=0,this._hotspots=Object.freeze([]),this.hotspotSource=this._hotspots,this.hotspotRevision=0,this.synchronizingCurrentTime=!1,this.currentTimeFromMedia=!1,this.autoplay=!1,this.autoplayMuted=!1,this.autoplayOnVisible=!1,this.controls="standard",this.currentTime=0,this.duration=0,this.iconLibrary="system",this.loop=!1,this.muted=!1,this.isPlaying=!1,this.poster="",this.preload="metadata",this.src="",this.thumbnails="",this.title="",this.volume=1,this.playbackRate=1,this.posterVisible=!0,this.captionText="",this.captionTracks=[],this.fullscreen=!1,this.pictureInPicture=!1,this.thumbnailCues=[],this.thumbnailPosition=50,this.panoramaVideoReady=!1,this.onPanoramaMediaReady=()=>{this.panoramaVideoReady=!0,this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaMedia",void 0,{hasChanged:()=>!0}),"panorama-media")},this.onPanoramaMediaReset=()=>{this.panoramaVideoReady=!1,this.panoramaRevision++,this.panorama.invalidate(),this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaMedia",void 0,{hasChanged:()=>!0}),"panorama-media")},this.mediaController=new NativeMediaController(this,{selectedTrackMode:"hidden",relayEvents:NATIVE_MEDIA_RELAY_EVENTS.filter(type=>type!=="timeupdate"),onEvent:event=>this.onNativeMediaEvent(event)}),this.pendingNativeEcho={timeupdate:!1,muted:!1},this.thumbnailGeneration=0,this.visibilityPaused=!1,this.captionListeners=[],this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.mediaRef=element=>{const video=element?.localName==="video"?element:void 0;this.mediaController.attach(video),video&&(this.mediaController.volume=finiteRange(this.volume,1,0,1),this.autoplayMuted&&!this.muted?this.forceAutoplayMuted():this.mediaController.muted=this.muted,this.mediaController.playbackRate=this.playbackRate)},this.onSourceSlotChange=()=>this.syncSources(),this.onTimelineInput=event=>{const input=event.currentTarget;this.seek(Number(input.value))},this.onVolumeInput=event=>{this.setVolume(Number(event.currentTarget.value))},this.onRateChange=event=>{this.setPlaybackRate(Number(event.currentTarget.value))},this.onPosterPlay=()=>{this.play().catch(()=>{})},this.onFullscreenButton=()=>{(this.fullscreen?this.exitFullscreen():this.requestFullscreen()).catch(()=>{})},this.onFullscreenChange=()=>{this.fullscreen=!!this.wrapperEl&&this.shadowRoot?.fullscreenElement===this.wrapperEl},this.onPictureInPictureChange=()=>{this.pictureInPicture=this.isConnected&&this.isPictureInPicture},this.togglePictureInPicture=()=>{const video=this.videoEl,documentRef=this.ownerDocument;if(!video||!canRequestPictureInPicture(video))return;(this.isPictureInPicture?documentRef.exitPictureInPicture?.():video.requestPictureInPicture().then(()=>{}))?.catch(()=>{})},this.onCaptionChange=event=>{const selected=Number(event.currentTarget.value);this.captionTracks.forEach(({track},index)=>{track.mode=index===selected?"hidden":"disabled"}),this.syncActiveCaption()},this.onTimelinePointerMove=event=>{const rect=event.currentTarget.getBoundingClientRect();if(rect.width<=0||this.duration<=0){this.activeThumbnail=void 0;return}const ratio=finiteRange((event.clientX-rect.left)/rect.width,0,0,1),time=ratio*this.duration;this.activeThumbnail=this.thumbnailCues.find(cue=>time>=cue.start&&time<cue.end),this.thumbnailPosition=ratio*100},this.onTimelinePointerLeave=()=>{this.activeThumbnail=void 0}}static{this.defaultStrings={...super.defaultStrings,avPlayerPlaybackRate:LYRA_DEFAULT_avPlayerPlaybackRate,avPlayerPosition:LYRA_DEFAULT_avPlayerPosition,avPlayerRateOption:LYRA_DEFAULT_avPlayerRateOption,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,duration:LYRA_DEFAULT_duration,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,model:LYRA_DEFAULT_model,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationLabel:LYRA_DEFAULT_paginationLabel,panoramaHotspotsLabel:LYRA_DEFAULT_panoramaHotspotsLabel,panoramaInstructions:LYRA_DEFAULT_panoramaInstructions,pause:LYRA_DEFAULT_pause,play:LYRA_DEFAULT_play,playbackPosition:LYRA_DEFAULT_playbackPosition,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,videoCaptions:LYRA_DEFAULT_videoCaptions,videoCaptionsOff:LYRA_DEFAULT_videoCaptionsOff,videoEnterFullscreen:LYRA_DEFAULT_videoEnterFullscreen,videoExitFullscreen:LYRA_DEFAULT_videoExitFullscreen,videoExitPictureInPicture:LYRA_DEFAULT_videoExitPictureInPicture,videoMute:LYRA_DEFAULT_videoMute,videoPictureInPicture:LYRA_DEFAULT_videoPictureInPicture,videoPlayerLabel:LYRA_DEFAULT_videoPlayerLabel,videoUnmute:LYRA_DEFAULT_videoUnmute,videoVolume:LYRA_DEFAULT_videoVolume}}static{this.styles=[LyraElement.styles,panoramaStyles,styles,srOnly]}static{this.knownUnobservedAttributes=["playing"]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"currenttime","current-time"])]}get projection(){return this._projection}set projection(value){const next=PANORAMA_PROJECTION.normalize(value),old=this._projection;next!==old&&(this._projection=next,this.panorama?.invalidate(),this.requestUpdate("projection",old))}get engine(){return this._engine}set engine(value){const next=ENGINE_3D_PREFERENCE.normalize(value),old=this._engine;next!==old&&(this._engine=next,this.panorama?.invalidate(),this.requestUpdate("engine",old))}get panoramaCamera(){return this._panoramaCamera}set panoramaCamera(value){const revision=++this.panoramaCameraRevision,next=normalizePanoramaCamera(value),old=this._panoramaCamera;revision===this.panoramaCameraRevision&&(next.yaw===old.yaw&&next.pitch===old.pitch&&next.fieldOfView===old.fieldOfView||(this._panoramaCamera=next,this.requestUpdate("panoramaCamera",old)))}get hotspots(){return this._hotspots}set hotspots(value){if(value===this.hotspotSource||value===this._hotspots)return;const old=this._hotspots;this.hotspotSource=value;const revision=++this.hotspotRevision,next=snapshotPanoramaHotspots(value,this.ownerDocument?.defaultView??null);revision===this.hotspotRevision&&(this._hotspots=next,this.panorama?.invalidate(),this.requestUpdate("hotspots",old))}get panoramaEnabled(){return this.projection==="equirectangular"&&this.engine==="webgl"}requestUpdate(name,oldValue,options){name==="currentTime"&&(this.currentTimeFromMedia=this.synchronizingCurrentTime),name==="src"&&this.panorama&&!Object.is(this.src,oldValue)&&(this.panoramaVideoReady=!1,this.panoramaRevision++,this.panorama.invalidate()),super.requestUpdate(name,oldValue,options)}get playing(){return this.isPlaying}updated(changed){super.updated(changed);const video=this.videoEl;this.panorama.update(this.panoramaEnabled,this.panoramaVideoReady&&video&&(video.readyState>=2||this.panorama.ready||this.panorama.notice?.reason==="context-lost")?video:null,this.panoramaRevision,this.hotspots,this.panoramaCamera,this.renderRoot.querySelector('[part="panorama-engine"]'))}adoptedCallback(){super.adoptedCallback(),this.panorama.adopted(),super.requestUpdate("panoramaAdopted",void 0,{hasChanged:()=>!0})}attributeChangedCallback(name,oldValue,newValue){if(name==="currenttime"||name==="current-time"){oldValue!==newValue&&(this.currentTime=finiteRange(Number(newValue??0),0,0));return}super.attributeChangedCallback(name,oldValue,newValue)}get videoEl(){const media=this.mediaController.element;return media?.localName==="video"?media:void 0}get playControl(){return this.renderRoot?.querySelector('[part="poster-play-button"], [data-control="play"]')??null}focus(options){this.playControl?.focus(options)}blur(){this.playControl?.blur()}click(){this.playControl?.click()}connectedCallback(){super.connectedCallback(),super.requestUpdate("panoramaReconnect",void 0,{hasChanged:()=>!0}),this.mediaController.reconnect(),(this.listenerDocument=this.ownerDocument).addEventListener("fullscreenchange",this.onFullscreenChange),this.hasUpdated&&(this.scheduleAfterUpdate(()=>this.bindCaptionTracks(),"video-caption-reconnect"),this.scheduleAfterUpdate(()=>this.configureVisibilityObserver(),"video-visibility-reconnect"),this.thumbnails&&this.scheduleAfterUpdate(()=>{this.loadThumbnails()},"video-thumbnails-reconnect"))}firstUpdated(changed){super.firstUpdated(changed),this.syncSources(),this.configureVisibilityObserver(),this.loadThumbnails()}disconnectedCallback(){this.panorama.disconnect(),this.mediaController.disconnect(),this.thumbnailGeneration+=1,this.thumbnailAbort?.abort(),this.thumbnailAbort=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.unbindCaptionTracks(),this.captionTracks.length&&(this.captionTracks=[]),this.captionText&&(this.captionText=""),this.activeThumbnail&&(this.activeThumbnail=void 0),this.isPlaying&&(this.isPlaying=!1),this.fullscreen&&(this.fullscreen=!1),this.pictureInPicture&&(this.pictureInPicture=!1),this.listenerDocument?.removeEventListener("fullscreenchange",this.onFullscreenChange),super.disconnectedCallback()}willUpdate(changed){if(super.willUpdate(changed),changed.has("controls")&&(this.controls=safeControls(this.controls)),changed.has("preload")&&(this.preload=safePreload(this.preload)),changed.has("volume")){const next=finiteRange(this.volume,this.mediaController.volume,0,1);Object.is(next,this.volume)||(this.volume=next),this.mediaController.volume=next}if(changed.has("isPlaying")&&this.toggleAttribute("playing",this.isPlaying),changed.has("muted")&&(this.mediaController.muted=this.muted),changed.has("autoplayMuted")&&this.autoplayMuted&&this.forceAutoplayMuted(),changed.has("currentTime")&&!this.currentTimeFromMedia){const max=this.mediaController.duration>0?this.mediaController.duration:Number.POSITIVE_INFINITY,next=finiteRange(this.currentTime,0,0,max);Object.is(next,this.currentTime)||(this.currentTime=next),next!==this.mediaController.currentTime&&(this.mediaController.currentTime=next)}if(changed.has("duration")){const next=finiteRange(this.duration,0,0);Object.is(next,this.duration)||(this.duration=next)}changed.has("src")&&(this.visibilityPaused=!1,this.posterVisible=!0,this.hasUpdated&&(this.isPlaying=!1,this.duration=0,this.currentTime=0,this.scheduleAfterUpdate(()=>this.syncSources(),"video-sources"))),changed.has("thumbnails")&&this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.loadThumbnails()},"video-thumbnails"),changed.has("autoplayOnVisible")&&this.hasUpdated&&this.scheduleAfterUpdate(()=>this.configureVisibilityObserver(),"video-visibility")}forceAutoplayMuted(){this.pendingNativeEcho.muted=!0,this.mediaController.muted=!0}sourceSignature(){const nodes=[...this.children].filter(child=>child.localName==="source"||child.localName==="track").map(child=>({tag:child.localName,src:child.getAttribute("src"),type:child.getAttribute("type"),media:child.getAttribute("media"),kind:child.getAttribute("kind"),srclang:child.getAttribute("srclang"),label:child.getAttribute("label"),default:child.hasAttribute("default")}));return JSON.stringify({src:this.src,nodes})}syncSources(force=!1){if(!this.videoEl)return;const signature=this.sourceSignature();!force&&signature===this.lastSourceSignature||(this.lastSourceSignature=signature,this.onPanoramaMediaReset(),this.visibilityPaused=!1,this.unbindCaptionTracks(),this.captionTracks.length&&(this.captionTracks=[]),this.captionText&&(this.captionText=""),this.mediaController.setSources({src:this.src,nodes:this.children}),this.mediaController.currentTime=this.currentTime)}getVideoElement(){return this.videoEl}getState(){const video=this.videoEl;return{playing:!!(video&&!video.paused&&!video.ended),currentTime:this.mediaController.currentTime,duration:this.mediaController.duration,volume:this.mediaController.volume,muted:this.mediaController.muted,playbackRate:this.mediaController.playbackRate}}play(){return this.mediaController.play()}pause(){this.visibilityPaused=!1,this.mediaController.pause()}load(){this.visibilityPaused=!1,this.currentTime=0,this.syncSources(!0)}unloadMedia(){const native=this.videoEl;!native||!native.hasAttribute("src")&&![...native.children].some(child=>child.localName==="source"||child.localName==="track")||(this.visibilityPaused=!1,this.onPanoramaMediaReset(),this.mediaController.unload(),this.currentTime=0,this.lastSourceSignature=void 0,this.unbindCaptionTracks(),this.captionTracks=[],this.captionText="")}captureMediaPreferences(native=this.videoEl){return this.mediaController.captureUserPreferences(native)}applyMediaPreferences(preferences){this.mediaController.applyUserPreferences(preferences);const state2=this.getState();this.volume=state2.volume,this.muted=state2.muted,this.playbackRate=state2.playbackRate}seek(time){const max=this.mediaController.duration>0?this.mediaController.duration:Number.POSITIVE_INFINITY,next=finiteRange(time,0,0,max);this.mediaController.currentTime=next,this.synchronizeCurrentTime(),this.pendingNativeEcho.timeupdate=!0,this.dispatchHostTimeupdate()}synchronizeCurrentTime(){this.synchronizingCurrentTime=!0;try{this.currentTime=this.mediaController.currentTime}finally{this.synchronizingCurrentTime=!1}}dispatchHostTimeupdate(){const EventConstructor=this.ownerDocument.defaultView?.Event??Event;this.dispatchEvent(new EventConstructor("timeupdate"))}setPlaybackRate(rate){const next=finiteRange(rate,1,MIN_NATIVE_PLAYBACK_RATE,MAX_NATIVE_PLAYBACK_RATE);this.playbackRate=next,this.mediaController.playbackRate=next}rateSelectOptions(){const rates=PLAYBACK_RATES;return rates.includes(this.playbackRate)?rates:[...rates,this.playbackRate].sort((a,b)=>a-b)}renderRateOptions(){const format=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:2});return this.rateSelectOptions().map(rate=>html`<option value=${String(rate)} ?selected=${rate===this.playbackRate}>${this.localize("avPlayerRateOption",void 0,{rate:format.format(rate)})}</option>`)}setVolume(volume){const next=finiteRange(volume,this.mediaController.volume,0,1);this.volume=next,this.mediaController.volume=next}toggleMute(){const next=!this.mediaController.muted;this.muted=next,this.mediaController.muted=next}togglePlay(){this.videoEl?.paused??!0?this.play().catch(()=>{}):this.pause()}requestFullscreen(){return canRequestFullscreen(this.wrapperEl)?this.wrapperEl.requestFullscreen():unsupportedPromise(this,"Fullscreen is unavailable for this video.")}exitFullscreen(){return canExitFullscreen(this.ownerDocument)?this.ownerDocument.exitFullscreen():unsupportedPromise(this,"Fullscreen exit is unavailable for this video.")}onNativeMediaEvent(event){if(this.videoEl)switch(event.type){case"loadedmetadata":case"durationchange":this.duration=this.mediaController.duration,this.synchronizeCurrentTime(),this.bindCaptionTracks();break;case"play":this.isPlaying=!0,this.posterVisible=!1;break;case"pause":case"ended":this.isPlaying=!1;break;case"error":this.isPlaying=!1,this.duration=0,this.currentTime=0;break;case"timeupdate":this.synchronizeCurrentTime(),this.pendingNativeEcho.timeupdate?this.pendingNativeEcho.timeupdate=!1:this.dispatchHostTimeupdate();break;case"seeked":this.synchronizeCurrentTime(),this.pendingNativeEcho.timeupdate=!1;break;case"volumechange":this.volume=this.mediaController.volume,this.pendingNativeEcho.muted?this.pendingNativeEcho.muted=!1:this.muted=this.mediaController.muted;break;case"ratechange":this.playbackRate=this.mediaController.playbackRate;break}}canRenderFullscreen(){return typeof this.ownerDocument.defaultView?.HTMLElement.prototype.requestFullscreen=="function"&&this.ownerDocument.fullscreenEnabled!==!1}canRenderPictureInPicture(){const ownerWindow=this.ownerDocument.defaultView,documentRef=this.ownerDocument;return this.controls==="full"&&typeof ownerWindow?.HTMLVideoElement.prototype.requestPictureInPicture=="function"&&documentRef.pictureInPictureEnabled!==!1}get isPictureInPicture(){return!!this.videoEl&&this.shadowRoot?.pictureInPictureElement===this.videoEl}pauseForVisibility(){this.visibilityPaused=!0,this.mediaController.pause()}configureVisibilityObserver(){const visibilityOwnedPause=this.visibilityPaused;this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0;const ownerWindow=this.ownerDocument.defaultView,IntersectionObserverCtor=ownerWindow?.IntersectionObserver;if(!this.autoplayOnVisible||!IntersectionObserverCtor){visibilityOwnedPause&&(this.visibilityPaused=!1,this.mediaController.play().catch(()=>{}));return}this.visibilityPaused=visibilityOwnedPause;let observer;observer=new IntersectionObserverCtor(entries=>{if(!observer||!this.isConnected||this.intersectionObserver!==observer||this.ownerDocument.defaultView!==ownerWindow)return;const visible=entries[0]?.isIntersecting??!0,video=this.videoEl;if(video){if(!visible){video.paused||this.pauseForVisibility();return}this.visibilityPaused&&(this.visibilityPaused=!1,this.mediaController.play().catch(()=>{}))}}),this.intersectionObserver=observer,observer.observe(this)}unbindCaptionTracks(){for(const{track,listener}of this.captionListeners)track.removeEventListener("cuechange",listener);this.captionListeners=[]}bindCaptionTracks(){this.unbindCaptionTracks();const selectable=Array.from(this.videoEl?.textTracks??[]).filter(track=>track.kind==="captions"||track.kind==="subtitles");for(const track of selectable)track.mode==="showing"&&(track.mode="hidden");this.captionTracks=selectable.map(track=>({track,label:track.label||track.language||this.localize("videoCaptions"),language:track.language}));for(const track of selectable){const listener=()=>this.syncActiveCaption();track.addEventListener("cuechange",listener),this.captionListeners.push({track,listener})}this.syncActiveCaption()}syncActiveCaption(){const lines=[];for(const{track}of this.captionTracks)if(!(track.mode!=="hidden"||!track.activeCues))for(let index=0;index<track.activeCues.length;index+=1){const cue=track.activeCues[index];cue&&typeof cue.text=="string"&&lines.push(cue.text)}this.captionText=lines.join(`
|
|
6
6
|
`)}async loadThumbnails(){const generation=++this.thumbnailGeneration;this.thumbnailAbort?.abort(),this.thumbnailAbort=void 0,this.thumbnailCues.length&&(this.thumbnailCues=[]),this.activeThumbnail&&(this.activeThumbnail=void 0);const fetchTarget=resolveOwnerFetchTarget(this,this.thumbnails),AbortControllerCtor=fetchTarget?.view.AbortController;if(!fetchTarget||!AbortControllerCtor)return;const controller=new AbortControllerCtor;this.thumbnailAbort=controller;try{const response=await fetchTarget.view.fetch(fetchTarget.url,{signal:controller.signal});if(generation!==this.thumbnailGeneration||!this.isConnected||this.ownerDocument.defaultView!==fetchTarget.view||!response.ok)return;const text=await readResponseText(response,MAX_THUMBNAIL_BYTES);if(generation!==this.thumbnailGeneration||!this.isConnected||this.ownerDocument.defaultView!==fetchTarget.view)return;this.thumbnailCues=parseThumbnailVtt(text,fetchTarget.url,fetchTarget.view.URL)}catch{if(generation!==this.thumbnailGeneration||!this.isConnected)return;this.thumbnailCues=[],this.activeThumbnail=void 0}finally{generation===this.thumbnailGeneration&&(this.thumbnailAbort=void 0)}}renderIcon(name,path){return html`<lr-icon library=${this.iconLibrary} name=${name} aria-hidden="true">
|
|
7
7
|
<path d=${path}></path>
|
|
8
8
|
</lr-icon>`}renderDecorativeIconLayer(content){return html`<span class="control-icon-layer" aria-hidden="true" inert>${content}</span>`}renderPlaySlots(){return html`
|
|
@@ -157,6 +157,8 @@ import{__decorate}from"tslib";import{panoramaStyles}from"../../../internal/media
|
|
|
157
157
|
@loadeddata=${this.onPanoramaMediaReady}
|
|
158
158
|
@emptied=${this.onPanoramaMediaReset}
|
|
159
159
|
@error=${this.onPanoramaMediaReset}
|
|
160
|
+
@enterpictureinpicture=${this.onPictureInPictureChange}
|
|
161
|
+
@leavepictureinpicture=${this.onPictureInPictureChange}
|
|
160
162
|
playsinline
|
|
161
163
|
?autoplay=${this.autoplay||this.autoplayMuted}
|
|
162
164
|
?loop=${this.loop}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatMediaTime}from"../../../internal/media-time.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{finiteRange}from"../../../internal/numbers.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{tag}from"../../../internal/prefix.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./video-playlist.styles.js";import{LYRA_DEFAULT_videoPlaylistLabel,LYRA_DEFAULT_videoPlaylistUntitled}from"../../../internal/default-strings/media.generated.js";function safeControls(value){return value==="none"||value==="standard"?value:"full"}function safeRepeat(value){return value==="one"||value==="all"?value:"none"}function sameVideos(left,right){return left.length===right.length&&left.every((video,index)=>video===right[index])}function sourceSnapshot(src,type,media){return{src,type,media}}function trackSnapshot(src,kind,srclang,label,isDefault){return{src,kind,srclang,label,default:isDefault}}class LyraVideoPlaylist extends LyraElement{constructor(){super(...arguments),this.controls="full",this.iconLibrary="system",this.withoutAutoAdvance=!1,this.repeat="none",this.items=[],this.playlistVideos=[],this.liveChildrenReady=!1,this.activeIndex=-1,this.navigationIndex=-1,this.listeners=new Map,this.lastKnownPlaying=new WeakMap,this.nativeVideos=new WeakMap,this.needsReload=new WeakSet,this.ownedVideoState=new WeakMap,this.preferences={},this.activationGeneration=0,this.reconcileGeneration=0,this.onSlotChange=()=>this.reconcileChildren(),this.onItemFocus=event=>{relayNativeEvent(this,event)},this.onItemBlur=event=>{relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,videoPlaylistLabel:LYRA_DEFAULT_videoPlaylistLabel,videoPlaylistUntitled:LYRA_DEFAULT_videoPlaylistUntitled}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-video-change"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.observeChildren(),this.hasUpdated?this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile"):this.seedFirstRenderState(()=>{this.directVideos().length>0&&this.reconcileChildren()})}disconnectedCallback(){this.activationGeneration+=1,this.reconcileGeneration+=1,this.pendingPlay=void 0,this.mutationObserver?.disconnect(),this.mutationObserver=void 0;for(const video of this.playlistVideos)this.unbindVideo(video),video.hidden=!0,this.pauseAndUnload(video);super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),changed.has("controls")&&(this.controls=safeControls(this.controls)),changed.has("repeat")&&(this.repeat=safeRepeat(this.repeat)),(changed.has("controls")||changed.has("iconLibrary"))&&this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile")}observeChildren(){this.mutationObserver?.disconnect(),this.mutationObserver=void 0;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.mutationObserver=new MutationObserverCtor(()=>{this.scheduleAfterUpdate(()=>{this.reconcileChildren(),this.requestUpdate()},"video-playlist-reconcile")}),this.mutationObserver.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["default","inert","kind","label","media","poster","src","srclang","title","type"]}))}directVideos(){const videoTag=tag("video");return[...this.children].filter(child=>child.localName===videoTag)}isEnabled(video){return!video.inert}nearestEnabledIndex(videos,preferred){if(!videos.length)return-1;const start=Math.min(Math.max(preferred,0),videos.length-1);for(let index=start;index<videos.length;index+=1)if(this.isEnabled(videos[index]))return index;for(let index=start-1;index>=0;index-=1)if(this.isEnabled(videos[index]))return index;return-1}reconcileChildren(){if(!this.isConnected)return;const previousVideos=this.playlistVideos,previousActive=this.activeVideo,previousIndex=this.activeIndex,previousNavigation=previousVideos[this.navigationIndex],navigationHadFocus=shadowFocusTarget(this)?.getAttribute("part")==="playlist-item",videos=this.directVideos(),videoSet=new Set(videos);(videos.length>0||this.liveChildrenReady)&&(this.liveChildrenReady=!0);let active=previousActive&&videoSet.has(previousActive)&&this.isEnabled(previousActive)?previousActive:void 0,nextIndex=active?videos.indexOf(active):this.nearestEnabledIndex(videos,previousIndex);!active&&nextIndex>=0&&(active=videos[nextIndex]),active||(nextIndex=-1);const activeChanged=active!==previousActive,outgoingWasRemoved=!!(previousActive&&!videoSet.has(previousActive)),resumePlayback=activeChanged&&previousActive?outgoingWasRemoved?this.lastKnownPlaying.get(previousActive)??previousActive.getState().playing:previousActive.getState().playing:!1,outgoingPreferences=activeChanged&&previousActive?outgoingWasRemoved?this.capturePreferences(previousActive,this.nativeVideos.get(previousActive)):this.capturePreferences(previousActive):void 0;for(const video of previousVideos)videoSet.has(video)||this.releaseVideo(video);for(const video of videos)this.claimVideo(video),this.bindVideo(video);activeChanged&&previousActive?(this.preferences=outgoingPreferences??{},outgoingWasRemoved||this.pauseAndUnload(previousActive),this.activationGeneration+=1):activeChanged&&(this.activationGeneration+=1),this.activeVideo=active,this.activeIndex=nextIndex,sameVideos(previousVideos,videos)||(this.playlistVideos=videos);for(const video of videos){video.controls!==this.controls&&(video.controls=this.controls),video.iconLibrary!==this.iconLibrary&&(video.iconLibrary=this.iconLibrary);const isActive=video===active;video.hidden=!isActive,isActive||this.pauseAndUnload(video)}active?(activeChanged||this.needsReload.has(active))&&this.activateVideo(active,resumePlayback,this.activationGeneration):this.pendingPlay=void 0;const keptNavigation=previousNavigation&&videoSet.has(previousNavigation)&&this.isEnabled(previousNavigation)?videos.indexOf(previousNavigation):-1;this.navigationIndex=keptNavigation>=0?keptNavigation:nextIndex,navigationHadFocus&&keptNavigation<0&&this.navigationIndex>=0&&this.focusItem(this.navigationIndex),activeChanged&&previousActive&&this.emitChange(previousIndex,nextIndex,active??null),this.scheduleChildrenReady(videos)}scheduleChildrenReady(videos){const reconcileGeneration=++this.reconcileGeneration;Promise.all(videos.map(video=>video.updateComplete)).then(()=>{if(!this.isConnected||reconcileGeneration!==this.reconcileGeneration)return;for(const video of this.playlistVideos)this.rememberNativeVideo(video);for(const video of this.playlistVideos)video!==this.activeVideo&&this.pauseAndUnload(video);const active=this.activeVideo;if(!active||!this.needsReload.has(active))return;const shouldPlay=this.pendingPlay?.video===active&&this.pendingPlay.generation===this.activationGeneration;this.activateVideo(active,shouldPlay,this.activationGeneration)})}bindVideo(video){if(this.listeners.has(video))return;const listeners={ended:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1),this.handleCompletion(video)},error:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},loadedmetadata:()=>{this.rememberNativeVideo(video),this.handleLoadedMetadata(video)},pause:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},play:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!0),video!==this.activeVideo&&this.pauseAndUnload(video)}};this.lastKnownPlaying.set(video,video.getState().playing),this.rememberNativeVideo(video),this.listeners.set(video,listeners),video.addEventListener("ended",listeners.ended),video.addEventListener("error",listeners.error),video.addEventListener("loadedmetadata",listeners.loadedmetadata),video.addEventListener("pause",listeners.pause),video.addEventListener("play",listeners.play)}unbindVideo(video){const listeners=this.listeners.get(video);listeners&&(video.removeEventListener("ended",listeners.ended),video.removeEventListener("error",listeners.error),video.removeEventListener("loadedmetadata",listeners.loadedmetadata),video.removeEventListener("pause",listeners.pause),video.removeEventListener("play",listeners.play),this.listeners.delete(video))}claimVideo(video){this.ownedVideoState.has(video)||this.ownedVideoState.set(video,{controls:video.controls,iconLibrary:video.iconLibrary,hidden:!!video.hidden})}releaseVideo(video){const authored=this.ownedVideoState.get(video);this.unbindVideo(video),this.pauseAndUnload(video),authored&&(video.controls=authored.controls,video.iconLibrary=authored.iconLibrary,video.hidden=authored.hidden,this.ownedVideoState.delete(video),video.isConnected&&video.load())}rememberNativeVideo(video){const native=video.getVideoElement();native&&this.nativeVideos.set(video,native)}pauseAndUnload(video){video.pause(),video.hidden=!0,this.needsReload.add(video),video.unloadMedia()}activateVideo(video,shouldPlay,generation){if(video.hidden=!1,!video.getVideoElement()){this.needsReload.add(video),shouldPlay&&(this.pendingPlay={video,generation});return}if(this.rememberNativeVideo(video),video.load(),this.needsReload.delete(video),this.applyPreferences(video,this.preferences),!shouldPlay){this.pendingPlay?.video===video&&(this.pendingPlay=void 0);return}this.pendingPlay=void 0,video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}capturePreferences(video,native=video.getVideoElement()){return video.captureMediaPreferences(native)}applyPreferences(video,preferences){video.applyMediaPreferences(preferences)}handleLoadedMetadata(video){video===this.activeVideo&&(this.applyPreferences(video,this.preferences),this.requestUpdate())}handleCompletion(video){if(video!==this.activeVideo||this.withoutAutoAdvance)return;if(this.repeat==="one"){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo});return}const nextIndex=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);if(nextIndex>this.activeIndex){this.switchTo(nextIndex,!0);return}if(this.repeat==="all"){const first=this.nearestEnabledIndex(this.playlistVideos,0);if(first>=0&&first!==this.activeIndex)this.switchTo(first,!0);else if(first===this.activeIndex){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}}}snapshotVideo(video){const sources=[],directSrc=video.src.trim();directSrc&&sources.push(sourceSnapshot(directSrc,"",""));const tracks=[];for(const child of video.children)if(child.localName==="source"){const src=child.getAttribute("src")?.trim()??"";src&&sources.push(sourceSnapshot(src,child.getAttribute("type")??"",child.getAttribute("media")??""))}else if(child.localName==="track"){const src=child.getAttribute("src")?.trim()??"";src&&tracks.push(trackSnapshot(src,child.getAttribute("kind")??"",child.getAttribute("srclang")??"",child.getAttribute("label")??"",child.hasAttribute("default")))}return{title:video.title,poster:video.poster,sources,tracks}}emitChange(previousIndex,currentIndex,video){this.emit("lr-video-change",{previousIndex,currentIndex,video:video?this.snapshotVideo(video):null})}switchTo(index,forcePlay=!1){const incoming=this.playlistVideos[index];if(!incoming||!this.isEnabled(incoming))return;const previousIndex=this.activeIndex,outgoing=this.activeVideo;if(incoming===outgoing){if(this.navigationIndex=index,this.requestUpdate(),forcePlay){const generation=this.activationGeneration;incoming.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}this.emitChange(previousIndex,index,incoming);return}const wasPlaying=forcePlay||!!outgoing?.getState().playing;outgoing&&(this.preferences=this.capturePreferences(outgoing),this.pauseAndUnload(outgoing)),this.activationGeneration+=1,this.activeVideo=incoming,this.activeIndex=index,this.navigationIndex=index;for(const video of this.playlistVideos){const isActive=video===incoming;video.hidden=!isActive,!isActive&&video!==outgoing&&this.pauseAndUnload(video)}this.activateVideo(incoming,wasPlaying,this.activationGeneration),this.requestUpdate(),this.emitChange(previousIndex,index,incoming)}goTo(index){!Number.isFinite(index)||!Number.isInteger(index)||index<0||index>=this.playlistVideos.length||this.switchTo(index)}next(){const index=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);index>this.activeIndex&&this.switchTo(index)}previous(){for(let index=this.activeIndex-1;index>=0;index-=1)if(this.isEnabled(this.playlistVideos[index])){this.switchTo(index);return}}onItemClick(event){const button=event.currentTarget,index=Number(button.dataset.index);Number.isInteger(index)&&(this.navigationIndex=index,this.goTo(index))}enabledIndices(){const result=[];for(let index=0;index<this.playlistVideos.length;index+=1)this.isEnabled(this.playlistVideos[index])&&result.push(index);return result}moveNavigation(from,direction){const enabled=this.enabledIndices(),position=enabled.indexOf(from);if(position<0)return;const next=enabled[position+direction];next!==void 0&&this.focusItem(next)}get navigationItem(){const rows=[...this.renderRoot.querySelectorAll('[part~="playlist-item"]')];return rows.find(row=>!row.disabled&&row.getAttribute("aria-current")==="true")??rows.find(row=>!row.disabled)??null}focus(options){this.navigationItem?.focus(options)}blur(){this.navigationItem?.blur()}click(){this.navigationItem?.click()}focusItem(index){this.isEnabled(this.playlistVideos[index])&&(this.navigationIndex=index,this.requestUpdate(),this.updateComplete.then(()=>{this.navigationIndex===index&&this.shadowRoot?.querySelector(`[data-index="${index}"]`)?.focus()}))}onItemKeyDown(event){const button=event.currentTarget,index=Number(button.dataset.index);if(!Number.isInteger(index)||button.disabled)return;const forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";if(event.key==="Enter"||event.key===" ")event.preventDefault(),this.navigationIndex=index,this.goTo(index);else if(event.key==="ArrowDown"||event.key===forward)event.preventDefault(),this.moveNavigation(index,1);else if(event.key==="ArrowUp"||event.key===backward)event.preventDefault(),this.moveNavigation(index,-1);else if(event.key==="Home"){event.preventDefault();const first=this.enabledIndices()[0];first!==void 0&&this.focusItem(first)}else if(event.key==="End"){event.preventDefault();const enabled=this.enabledIndices(),last=enabled[enabled.length-1];last!==void 0&&this.focusItem(last)}}itemTitle(value,index){const title=typeof value=="string"?value.trim():"";if(title)return title;const position=getNumberFormat(this.effectiveLocale).format(index+1);return this.localize("videoPlaylistUntitled",void 0,{position})}renderItem(item,index,current,disabled){const title=this.itemTitle(item.title,index),poster=safeMediaSrc(typeof item.poster=="string"?item.poster:""),duration=finiteRange(typeof item.duration=="number"?item.duration:0,0,0),durationId=`playlist-duration-${index}`;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatMediaTime}from"../../../internal/media-time.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{finiteRange}from"../../../internal/numbers.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{tag}from"../../../internal/prefix.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./video-playlist.styles.js";import{LYRA_DEFAULT_videoPlaylistLabel,LYRA_DEFAULT_videoPlaylistUntitled}from"../../../internal/default-strings/media.generated.js";function safeControls(value){return value==="none"||value==="standard"?value:"full"}function safeRepeat(value){return value==="one"||value==="all"?value:"none"}function sameVideos(left,right){return left.length===right.length&&left.every((video,index)=>video===right[index])}function sourceSnapshot(src,type,media){return{src,type,media}}function trackSnapshot(src,kind,srclang,label,isDefault){return{src,kind,srclang,label,default:isDefault}}class LyraVideoPlaylist extends LyraElement{constructor(){super(...arguments),this.controls="full",this.iconLibrary="system",this.withoutAutoAdvance=!1,this.repeat="none",this.items=[],this.playlistVideos=[],this.liveChildrenReady=!1,this.activeIndex=-1,this.navigationIndex=-1,this.listeners=new Map,this.lastKnownPlaying=new WeakMap,this.nativeVideos=new WeakMap,this.needsReload=new WeakSet,this.ownedVideoState=new WeakMap,this.preferences={},this.activationGeneration=0,this.reconcileGeneration=0,this.onSlotChange=()=>this.reconcileChildren(),this.onItemFocus=event=>{relayNativeEvent(this,event)},this.onItemBlur=event=>{relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,videoPlaylistLabel:LYRA_DEFAULT_videoPlaylistLabel,videoPlaylistUntitled:LYRA_DEFAULT_videoPlaylistUntitled}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-video-change"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.observeChildren(),this.hasUpdated?this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile"):this.seedFirstRenderState(()=>{this.directVideos().length>0&&this.reconcileChildren()})}disconnectedCallback(){this.activationGeneration+=1,this.reconcileGeneration+=1,this.pendingPlay=void 0,this.mutationObserver?.disconnect(),this.mutationObserver=void 0;for(const video of this.playlistVideos)this.unbindVideo(video),video.hidden=!0,this.pauseAndUnload(video);super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),changed.has("controls")&&(this.controls=safeControls(this.controls)),changed.has("repeat")&&(this.repeat=safeRepeat(this.repeat)),(changed.has("controls")||changed.has("iconLibrary"))&&this.scheduleAfterUpdate(()=>this.reconcileChildren(),"video-playlist-reconcile")}observeChildren(){this.mutationObserver?.disconnect(),this.mutationObserver=void 0;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.mutationObserver=new MutationObserverCtor(()=>{this.scheduleAfterUpdate(()=>{this.reconcileChildren(),this.requestUpdate()},"video-playlist-reconcile")}),this.mutationObserver.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["default","inert","kind","label","media","poster","src","srclang","title","type"]}))}directVideos(){const videoTag=tag("video");return[...this.children].filter(child=>child.localName===videoTag)}isEnabled(video){return!video.inert}nearestEnabledIndex(videos,preferred){if(!videos.length)return-1;const start=Math.min(Math.max(preferred,0),videos.length-1);for(let index=start;index<videos.length;index+=1)if(this.isEnabled(videos[index]))return index;for(let index=start-1;index>=0;index-=1)if(this.isEnabled(videos[index]))return index;return-1}reconcileChildren(){if(!this.isConnected)return;const previousVideos=this.playlistVideos,previousActive=this.activeVideo,previousIndex=this.activeIndex,previousNavigation=previousVideos[this.navigationIndex],navigationHadFocus=shadowFocusTarget(this)?.getAttribute("part")==="playlist-item",videos=this.directVideos(),videoSet=new Set(videos);(videos.length>0||this.liveChildrenReady)&&(this.liveChildrenReady=!0);let active=previousActive&&videoSet.has(previousActive)&&this.isEnabled(previousActive)?previousActive:void 0,nextIndex=active?videos.indexOf(active):this.nearestEnabledIndex(videos,previousIndex);!active&&nextIndex>=0&&(active=videos[nextIndex]),active||(nextIndex=-1);const activeChanged=active!==previousActive,outgoingWasRemoved=!!(previousActive&&!videoSet.has(previousActive)),resumePlayback=activeChanged&&previousActive?outgoingWasRemoved?this.lastKnownPlaying.get(previousActive)??previousActive.getState().playing:previousActive.getState().playing:!1,outgoingPreferences=activeChanged&&previousActive?outgoingWasRemoved?this.capturePreferences(previousActive,this.nativeVideos.get(previousActive)):this.capturePreferences(previousActive):void 0;for(const video of previousVideos)videoSet.has(video)||this.releaseVideo(video);for(const video of videos)this.claimVideo(video),this.bindVideo(video);activeChanged&&previousActive?(this.preferences=outgoingPreferences??{},outgoingWasRemoved||this.pauseAndUnload(previousActive),this.activationGeneration+=1):activeChanged&&(this.activationGeneration+=1),this.activeVideo=active,this.activeIndex=nextIndex,sameVideos(previousVideos,videos)||(this.playlistVideos=videos);for(const video of videos){video.controls!==this.controls&&(video.controls=this.controls),video.iconLibrary!==this.iconLibrary&&(video.iconLibrary=this.iconLibrary);const isActive=video===active;video.hidden=!isActive,isActive||this.pauseAndUnload(video)}active?(activeChanged||this.needsReload.has(active))&&this.activateVideo(active,resumePlayback,this.activationGeneration):this.pendingPlay=void 0;const keptNavigation=previousNavigation&&videoSet.has(previousNavigation)&&this.isEnabled(previousNavigation)?videos.indexOf(previousNavigation):-1;this.navigationIndex=keptNavigation>=0?keptNavigation:nextIndex,navigationHadFocus&&keptNavigation<0&&this.navigationIndex>=0&&this.focusItem(this.navigationIndex),activeChanged&&previousActive&&this.emitChange(previousIndex,nextIndex,active??null),this.scheduleChildrenReady(videos)}scheduleChildrenReady(videos){const reconcileGeneration=++this.reconcileGeneration;Promise.all(videos.map(video=>video.updateComplete)).then(()=>{if(!this.isConnected||reconcileGeneration!==this.reconcileGeneration)return;for(const video of this.playlistVideos)this.rememberNativeVideo(video);for(const video of this.playlistVideos)video!==this.activeVideo&&this.pauseAndUnload(video);const active=this.activeVideo;if(!active||!this.needsReload.has(active))return;const shouldPlay=this.pendingPlay?.video===active&&this.pendingPlay.generation===this.activationGeneration;this.activateVideo(active,shouldPlay,this.activationGeneration)})}bindVideo(video){if(this.listeners.has(video))return;const listeners={ended:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1),this.handleCompletion(video)},error:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},loadedmetadata:()=>{this.rememberNativeVideo(video),this.handleLoadedMetadata(video)},pause:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!1)},play:()=>{this.rememberNativeVideo(video),this.lastKnownPlaying.set(video,!0),video!==this.activeVideo&&this.pauseAndUnload(video)}};this.lastKnownPlaying.set(video,video.getState().playing),this.rememberNativeVideo(video),this.listeners.set(video,listeners),video.addEventListener("ended",listeners.ended),video.addEventListener("error",listeners.error),video.addEventListener("loadedmetadata",listeners.loadedmetadata),video.addEventListener("pause",listeners.pause),video.addEventListener("play",listeners.play)}unbindVideo(video){const listeners=this.listeners.get(video);listeners&&(video.removeEventListener("ended",listeners.ended),video.removeEventListener("error",listeners.error),video.removeEventListener("loadedmetadata",listeners.loadedmetadata),video.removeEventListener("pause",listeners.pause),video.removeEventListener("play",listeners.play),this.listeners.delete(video))}claimVideo(video){this.ownedVideoState.has(video)||this.ownedVideoState.set(video,{controls:video.controls,iconLibrary:video.iconLibrary,hidden:!!video.hidden})}releaseVideo(video){const authored=this.ownedVideoState.get(video);this.unbindVideo(video),this.pauseAndUnload(video),authored&&(video.controls=authored.controls,video.iconLibrary=authored.iconLibrary,video.hidden=authored.hidden,this.ownedVideoState.delete(video),video.isConnected&&video.load())}rememberNativeVideo(video){const native=video.getVideoElement();native&&this.nativeVideos.set(video,native)}pauseAndUnload(video){video.pause(),video.hidden=!0,this.needsReload.add(video),video.unloadMedia()}activateVideo(video,shouldPlay,generation){if(video.hidden=!1,!video.getVideoElement()){this.needsReload.add(video),shouldPlay&&(this.pendingPlay={video,generation});return}if(this.rememberNativeVideo(video),video.load(),this.needsReload.delete(video),this.applyPreferences(video,this.preferences),!shouldPlay){this.pendingPlay?.video===video&&(this.pendingPlay=void 0);return}this.pendingPlay=void 0,video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}capturePreferences(video,native=video.getVideoElement()){return video.captureMediaPreferences(native)}applyPreferences(video,preferences){video.applyMediaPreferences(preferences)}handleLoadedMetadata(video){video===this.activeVideo&&(this.applyPreferences(video,this.preferences),this.requestUpdate())}handleCompletion(video){if(video!==this.activeVideo||this.withoutAutoAdvance)return;if(this.repeat==="one"){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo});return}const nextIndex=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);if(nextIndex>this.activeIndex){this.switchTo(nextIndex,!0);return}if(this.repeat==="all"){const first=this.nearestEnabledIndex(this.playlistVideos,0);if(first>=0&&first!==this.activeIndex)this.switchTo(first,!0);else if(first===this.activeIndex){video.seek(0);const generation=this.activationGeneration;video.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}}}snapshotVideo(video){const sources=[],directSrc=video.src.trim();directSrc&&sources.push(sourceSnapshot(directSrc,"",""));const tracks=[];for(const child of video.children)if(child.localName==="source"){const src=child.getAttribute("src")?.trim()??"";src&&sources.push(sourceSnapshot(src,child.getAttribute("type")??"",child.getAttribute("media")??""))}else if(child.localName==="track"){const src=child.getAttribute("src")?.trim()??"";src&&tracks.push(trackSnapshot(src,child.getAttribute("kind")??"",child.getAttribute("srclang")??"",child.getAttribute("label")??"",child.hasAttribute("default")))}return{title:video.title,poster:video.poster,sources,tracks}}emitChange(previousIndex,currentIndex,video){this.emit("lr-video-change",{previousIndex,currentIndex,video:video?this.snapshotVideo(video):null})}switchTo(index,forcePlay=!1){const incoming=this.playlistVideos[index];if(!incoming||!this.isEnabled(incoming))return;const previousIndex=this.activeIndex,outgoing=this.activeVideo;if(incoming===outgoing){if(this.navigationIndex=index,this.requestUpdate(),forcePlay){const generation=this.activationGeneration;incoming.play().catch(()=>{generation!==this.activationGeneration||this.activeVideo})}this.emitChange(previousIndex,index,incoming);return}const wasPlaying=forcePlay||!!outgoing?.getState().playing;outgoing&&(this.preferences=this.capturePreferences(outgoing),this.pauseAndUnload(outgoing)),this.activationGeneration+=1,this.activeVideo=incoming,this.activeIndex=index,this.navigationIndex=index;for(const video of this.playlistVideos){const isActive=video===incoming;video.hidden=!isActive,!isActive&&video!==outgoing&&this.pauseAndUnload(video)}this.activateVideo(incoming,wasPlaying,this.activationGeneration),this.requestUpdate(),this.emitChange(previousIndex,index,incoming)}goTo(index){!Number.isFinite(index)||!Number.isInteger(index)||index<0||index>=this.playlistVideos.length||this.switchTo(index)}next(){const index=this.nearestEnabledIndex(this.playlistVideos,this.activeIndex+1);index>this.activeIndex&&this.switchTo(index)}previous(){for(let index=this.activeIndex-1;index>=0;index-=1)if(this.isEnabled(this.playlistVideos[index])){this.switchTo(index);return}}onItemClick(event){const button=event.currentTarget,index=Number(button.dataset.index);Number.isInteger(index)&&(this.navigationIndex=index,this.goTo(index))}enabledIndices(){const result=[];for(let index=0;index<this.playlistVideos.length;index+=1)this.isEnabled(this.playlistVideos[index])&&result.push(index);return result}moveNavigation(from,direction){const enabled=this.enabledIndices(),position=enabled.indexOf(from);if(position<0)return;const next=enabled[position+direction];next!==void 0&&this.focusItem(next)}get navigationItem(){const rows=[...this.renderRoot?.querySelectorAll('[part~="playlist-item"]')??[]];return rows.find(row=>!row.disabled&&row.getAttribute("aria-current")==="true")??rows.find(row=>!row.disabled)??null}focus(options){this.navigationItem?.focus(options)}blur(){this.navigationItem?.blur()}click(){this.navigationItem?.click()}focusItem(index){this.isEnabled(this.playlistVideos[index])&&(this.navigationIndex=index,this.requestUpdate(),this.updateComplete.then(()=>{this.navigationIndex===index&&this.shadowRoot?.querySelector(`[data-index="${index}"]`)?.focus()}))}onItemKeyDown(event){const button=event.currentTarget,index=Number(button.dataset.index);if(!Number.isInteger(index)||button.disabled)return;const forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";if(event.key==="Enter"||event.key===" ")event.preventDefault(),this.navigationIndex=index,this.goTo(index);else if(event.key==="ArrowDown"||event.key===forward)event.preventDefault(),this.moveNavigation(index,1);else if(event.key==="ArrowUp"||event.key===backward)event.preventDefault(),this.moveNavigation(index,-1);else if(event.key==="Home"){event.preventDefault();const first=this.enabledIndices()[0];first!==void 0&&this.focusItem(first)}else if(event.key==="End"){event.preventDefault();const enabled=this.enabledIndices(),last=enabled[enabled.length-1];last!==void 0&&this.focusItem(last)}}itemTitle(value,index){const title=typeof value=="string"?value.trim():"";if(title)return title;const position=getNumberFormat(this.effectiveLocale).format(index+1);return this.localize("videoPlaylistUntitled",void 0,{position})}renderItem(item,index,current,disabled){const title=this.itemTitle(item.title,index),poster=safeMediaSrc(typeof item.poster=="string"?item.poster:""),duration=finiteRange(typeof item.duration=="number"?item.duration:0,0,0),durationId=`playlist-duration-${index}`;return html`
|
|
2
2
|
<li>
|
|
3
3
|
<button
|
|
4
4
|
type="button"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{applyComposedFocusRepair,captureComposedFocusRepair,nearestExternalFocusTarget}from"../../../internal/focus-navigation.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{literalSetConverter}from"../../../internal/converters.js";import{semanticVariantConverter}from"../../../internal/semantic-variant.js";import{variants}from"../../../internal/variants.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./chip.styles.js";import{LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const CHIP_SIZE=literalSetConverter(["3xs","2xs","xs","s","m","l","xl","small","medium","large"],"m"),CHIP_VARIANT=semanticVariantConverter("neutral");function sourceParent(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root?root.host:null}function isClosedSourceDetailsBranch(details,branch){return details.localName!=="details"||details.hasAttribute("open")||branch===null?!1:Array.from(details.children).find(child=>child.localName==="summary")!==branch}function isSourceLabelAvailable(node){const target=node.nodeType===1?node:sourceParent(node);if(!target?.isConnected)return!1;let branch=target,current=sourceParent(target);if(isAccessibilitySubtreeExcluded(target))return!1;for(;current;){if(isAccessibilitySubtreeExcluded(current)||isClosedSourceDetailsBranch(current,branch))return!1;branch=current,current=sourceParent(current)}return!0}class LyraChip extends LyraElement{constructor(){super(...arguments),this._size="m",this._variant="neutral",this.removable=!1,this.disabled=!1,this.pill=!1,this.selected=!1,this.toggleable=!1,this.wrap=!1,this.slotPresence=new SlotPresenceController(this),this.cachedLabelText="",this.labelTextObserver=new AccessibleTextController(this,[""],()=>{this.syncHostActionRole(),this.updateBrowserDerivedState(()=>this.recomputeLabelText())},["slot","role"],!1),this.labelObservationReady=!1,this.managedActionGroupRole=!1,this.onLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||this.tracksActionLabel&&(this.labelTextObserver.bind(),this.updateBrowserDerivedState(()=>this.recomputeLabelText()))},this.onRemoveClick=()=>{if(this.disabled)return;const repair=captureComposedFocusRepair(this,()=>nearestExternalFocusTarget(this));this.emit("lr-remove",{value:this.value}),repair&&(!this.isConnected||!this.removable)&&applyComposedFocusRepair(repair)},this.onToggleClick=()=>{if(this.disabled)return;const selected=!this.selected;this.emit("lr-chip-toggle-request",{value:this.value,selected},{cancelable:!0}).defaultPrevented||(this.selected=selected,this.emit("lr-chip-change",{value:this.value,selected}))}}static{this.defaultStrings={...super.defaultStrings,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,variants,styles]}get size(){return this._size}set size(next){const normalized=CHIP_SIZE.normalizeReflected(this,"size",next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get variant(){return this._variant}set variant(next){const normalized=CHIP_VARIANT.normalizeReflected(this,"variant",next),old=this._variant;old!==normalized&&(this._variant=normalized,this.requestUpdate("variant",old))}get withRemove(){return this.removable}set withRemove(next){this.removable=!!next}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated&&(this.labelObservationReady=!0),this.syncLabelObservation();const sampleBrowserState=()=>{this.tracksActionLabel&&this.recomputeLabelText(!0,!0)};this.hasUpdated?(sampleBrowserState(),this.ownerDocument.defaultView?.queueMicrotask(()=>{this.isConnected&&this.tracksActionLabel&&this.recomputeLabelText()})):this.seedFirstRenderState(sampleBrowserState)}get tracksActionLabel(){return this.toggleable||this.removable}syncLabelObservation(){this.labelObservationReady&&this.labelTextObserver.setEnabled(this.tracksActionLabel)}scheduleInitialLabelObservation(){if(this.labelObservationReady||this.pendingInitialLabelObservation||!this.isConnected)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;const pending={};this.pendingInitialLabelObservation=pending,ownerWindow.queueMicrotask(()=>{this.pendingInitialLabelObservation!==pending||!this.isConnected||this.ownerDocument!==ownerDocument||(this.pendingInitialLabelObservation=void 0,this.labelObservationReady=!0,this.syncLabelObservation(),this.tracksActionLabel&&this.updateBrowserDerivedState(()=>this.recomputeLabelText()))})}disconnectedCallback(){this.pendingInitialLabelObservation=void 0,this.removeEventListener("slotchange",this.onLabelSlotChange),this.releaseHostActionRole(),this.pendingControlFocusRepair=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted()}computeLabelText(preferLightDom=!1){const slot=this.renderRoot?.querySelector("slot:not([name])"),lightDomNodes=this.childNodes,assigned=slot?.assignedNodes({flatten:!0})??[],direct=Array.from(lightDomNodes??[]).filter(node=>node.nodeType!==1||(node.getAttribute("slot")??"")==="");return(!preferLightDom&&assigned.length>0?assigned:direct).map(node=>composedAccessibilityText(node,{ancestorBoundary:this,isSubtreeExcluded:element=>element.getRootNode()===this.renderRoot&&element.getAttribute("part")?.split(/\s+/).includes("label")?!1:isAccessibilitySubtreeExcluded(element),requireRendered:preferLightDom?!1:node.nodeType!==1||node.localName!=="slot",shouldPruneNode:candidate=>!this.contains(candidate)&&!isSourceLabelAvailable(candidate),ignoreInheritedVisibility:!0})).join(" ").replace(/\s+/g," ").trim()}recomputeLabelText(request=!0,preferLightDom=!1){const next=this.computeLabelText(preferLightDom);next!==this.cachedLabelText&&(this.cachedLabelText=next,request&&this.requestUpdate())}get accessibleToggleLabel(){return this.cachedLabelText||this.localize("select")}get accessibleRemoveLabel(){const text=this.cachedLabelText;return text?this.localize("removeWithContext",void 0,{label:text}):this.localize("remove")}get primaryControl(){return this.renderRoot
|
|
1
|
+
import{__decorate}from"tslib";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{applyComposedFocusRepair,captureComposedFocusRepair,nearestExternalFocusTarget}from"../../../internal/focus-navigation.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{literalSetConverter}from"../../../internal/converters.js";import{semanticVariantConverter}from"../../../internal/semantic-variant.js";import{variants}from"../../../internal/variants.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./chip.styles.js";import{LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const CHIP_SIZE=literalSetConverter(["3xs","2xs","xs","s","m","l","xl","small","medium","large"],"m"),CHIP_VARIANT=semanticVariantConverter("neutral");function sourceParent(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root?root.host:null}function isClosedSourceDetailsBranch(details,branch){return details.localName!=="details"||details.hasAttribute("open")||branch===null?!1:Array.from(details.children).find(child=>child.localName==="summary")!==branch}function isSourceLabelAvailable(node){const target=node.nodeType===1?node:sourceParent(node);if(!target?.isConnected)return!1;let branch=target,current=sourceParent(target);if(isAccessibilitySubtreeExcluded(target))return!1;for(;current;){if(isAccessibilitySubtreeExcluded(current)||isClosedSourceDetailsBranch(current,branch))return!1;branch=current,current=sourceParent(current)}return!0}class LyraChip extends LyraElement{constructor(){super(...arguments),this._size="m",this._variant="neutral",this.removable=!1,this.disabled=!1,this.pill=!1,this.selected=!1,this.toggleable=!1,this.wrap=!1,this.slotPresence=new SlotPresenceController(this),this.cachedLabelText="",this.labelTextObserver=new AccessibleTextController(this,[""],()=>{this.syncHostActionRole(),this.updateBrowserDerivedState(()=>this.recomputeLabelText())},["slot","role"],!1),this.labelObservationReady=!1,this.managedActionGroupRole=!1,this.onLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||this.tracksActionLabel&&(this.labelTextObserver.bind(),this.updateBrowserDerivedState(()=>this.recomputeLabelText()))},this.onRemoveClick=()=>{if(this.disabled)return;const repair=captureComposedFocusRepair(this,()=>nearestExternalFocusTarget(this));this.emit("lr-remove",{value:this.value}),repair&&(!this.isConnected||!this.removable)&&applyComposedFocusRepair(repair)},this.onToggleClick=()=>{if(this.disabled)return;const selected=!this.selected;this.emit("lr-chip-toggle-request",{value:this.value,selected},{cancelable:!0}).defaultPrevented||(this.selected=selected,this.emit("lr-chip-change",{value:this.value,selected}))}}static{this.defaultStrings={...super.defaultStrings,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,variants,styles]}get size(){return this._size}set size(next){const normalized=CHIP_SIZE.normalizeReflected(this,"size",next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get variant(){return this._variant}set variant(next){const normalized=CHIP_VARIANT.normalizeReflected(this,"variant",next),old=this._variant;old!==normalized&&(this._variant=normalized,this.requestUpdate("variant",old))}get withRemove(){return this.removable}set withRemove(next){this.removable=!!next}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated&&(this.labelObservationReady=!0),this.syncLabelObservation();const sampleBrowserState=()=>{this.tracksActionLabel&&this.recomputeLabelText(!0,!0)};this.hasUpdated?(sampleBrowserState(),this.ownerDocument.defaultView?.queueMicrotask(()=>{this.isConnected&&this.tracksActionLabel&&this.recomputeLabelText()})):this.seedFirstRenderState(sampleBrowserState)}get tracksActionLabel(){return this.toggleable||this.removable}syncLabelObservation(){this.labelObservationReady&&this.labelTextObserver.setEnabled(this.tracksActionLabel)}scheduleInitialLabelObservation(){if(this.labelObservationReady||this.pendingInitialLabelObservation||!this.isConnected)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;const pending={};this.pendingInitialLabelObservation=pending,ownerWindow.queueMicrotask(()=>{this.pendingInitialLabelObservation!==pending||!this.isConnected||this.ownerDocument!==ownerDocument||(this.pendingInitialLabelObservation=void 0,this.labelObservationReady=!0,this.syncLabelObservation(),this.tracksActionLabel&&this.updateBrowserDerivedState(()=>this.recomputeLabelText()))})}disconnectedCallback(){this.pendingInitialLabelObservation=void 0,this.removeEventListener("slotchange",this.onLabelSlotChange),this.releaseHostActionRole(),this.pendingControlFocusRepair=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted()}computeLabelText(preferLightDom=!1){const slot=this.renderRoot?.querySelector("slot:not([name])"),lightDomNodes=this.childNodes,assigned=slot?.assignedNodes({flatten:!0})??[],direct=Array.from(lightDomNodes??[]).filter(node=>node.nodeType!==1||(node.getAttribute("slot")??"")==="");return(!preferLightDom&&assigned.length>0?assigned:direct).map(node=>composedAccessibilityText(node,{ancestorBoundary:this,isSubtreeExcluded:element=>element.getRootNode()===this.renderRoot&&element.getAttribute("part")?.split(/\s+/).includes("label")?!1:isAccessibilitySubtreeExcluded(element),requireRendered:preferLightDom?!1:node.nodeType!==1||node.localName!=="slot",shouldPruneNode:candidate=>!this.contains(candidate)&&!isSourceLabelAvailable(candidate),ignoreInheritedVisibility:!0})).join(" ").replace(/\s+/g," ").trim()}recomputeLabelText(request=!0,preferLightDom=!1){const next=this.computeLabelText(preferLightDom);next!==this.cachedLabelText&&(this.cachedLabelText=next,request&&this.requestUpdate())}get accessibleToggleLabel(){return this.cachedLabelText||this.localize("select")}get accessibleRemoveLabel(){const text=this.cachedLabelText;return text?this.localize("removeWithContext",void 0,{label:text}):this.localize("remove")}get primaryControl(){return this.renderRoot?.querySelector(this.removable?'[part="remove-button"]':'[part="toggle-button"]')??null}focus(options){this.primaryControl?.focus(options)}blur(){this.primaryControl?.blur()}click(){const control=this.primaryControl;control?control.click():super.click()}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated&&changed.size>0&&[...changed.keys()].every(key=>key==="selected"||key==="disabled")&&this.labelTextObserver.preserveBindingForNextUpdate(),changed.has("removable")&&!this.removable&&this.removeAttribute("with-remove"),(changed.has("removable")||changed.has("toggleable"))&&(this.syncLabelObservation(),this.hasUpdated&&(this.tracksActionLabel?this.recomputeLabelText(!1):this.cachedLabelText="")),this.pendingControlFocusRepair)return;const oldRemovable=changed.get("removable")??this.removable,oldToggleable=changed.get("toggleable")??this.toggleable,oldDisabled=changed.get("disabled")??this.disabled,oldMode=oldRemovable?"remove":oldToggleable?"toggle":"passive",newMode=this.removable?"remove":this.toggleable?"toggle":"passive";oldMode===newMode&&!(oldDisabled===!1&&this.disabled)||(this.pendingControlFocusRepair=captureComposedFocusRepair(this,()=>nearestExternalFocusTarget(this)??this.renderRoot.querySelector('[part="remove-button"], [part="toggle-button"]'))??void 0)}updated(changed){super.updated(changed),this.scheduleInitialLabelObservation(),this.syncHostActionRole();const repair=this.pendingControlFocusRepair;if(this.pendingControlFocusRepair=void 0,!repair)return;const replacement=this.disabled?null:this.primaryControl;applyComposedFocusRepair(repair,replacement??repair.candidate)}syncHostActionRole(){const needsGroup=this.tracksActionLabel&&this.hasAttribute("aria-label");needsGroup&&!this.hasAttribute("role")?(this.setAttribute("role","group"),this.managedActionGroupRole=!0):needsGroup||this.releaseHostActionRole()}releaseHostActionRole(){this.managedActionGroupRole&&this.getAttribute("role")==="group"&&this.removeAttribute("role"),this.managedActionGroupRole=!1}render(){const toggleMode=this.toggleable&&!this.removable,pressed=this.selected&&!this.removable;return html`
|
|
2
2
|
<span part="base">
|
|
3
3
|
${renderInertPresentation(html`<slot name="start"></slot>`,{part:"start",hidden:!this.slotPresence.has("start")})}
|
|
4
4
|
${renderInertPresentation(html`<slot @slotchange=${this.onLabelSlotChange}></slot>`,{part:"label",presentation:toggleMode})}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property,query,state}from"lit/decorators.js";import{html as staticHtml,unsafeStatic}from"lit/static-html.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{tag}from"../../../internal/prefix.js";import{LyraPopover}from"./popover.class.js";import{styles}from"./dropdown.styles.js";const menuTag=unsafeStatic(tag("menu"));class LyraDropdown extends LyraPopover{static{this.styles=[LyraPopover.styles,styles]}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}constructor(){super(),this.distance=0,this.placement="bottom-start",this.size="m",this.stayOpenOnSelect=!1,this.onContentSlotChange=event=>{this.collectConsumerMenuFromSlot(event.target)},this.popupRole="menu"}get popupRole(){return"menu"}set popupRole(_next){super.popupRole!=="menu"&&(super.popupRole="menu")}attributeChangedCallback(name,oldValue,newValue){if(name==="popup-role"&&newValue!==null&&newValue!=="menu"){this.setAttribute("popup-role","menu");return}super.attributeChangedCallback(name,oldValue,newValue)}get defaultDistance(){return 0}get defaultPositioningStrategy(){return"absolute"}onPositioningStrategyChanged(previous,next){const wasHoisted=previous==="fixed";wasHoisted!==(next==="fixed")&&this.requestUpdate("hoist",wasHoisted)}get positioningSync(){return this.sync}get animationNamespace(){return"dropdown"}get popupSurfaceRole(){}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-transition-fast"]}get popupPartNames(){return["popup","dialog","popup-popup","base","base__popup","panel"].join(" ")}get arrowPartNames(){return"arrow popup-arrow"}isInsideLightDismissBoundary(path){return super.isInsideLightDismissBoundary(path)||!!(this.containingElement&&path.includes(this.containingElement))}onPopupPositioned(){if(super.onPopupPositioned(),this.openedByInteraction)return;const menu=this.menuEngine;if(!menu?.dropdownOpen)return;menu.shadowRoot?.querySelector("slot:not([name])")?.assignedElements({flatten:!0}).find(element=>element.tabIndex===0)?.focus()}get menuEngine(){return this.consumerMenu??this.renderRoot.querySelector('[part~="menu"]')??void 0}configureMenu(menu){!this.isConnected||!menu||(menu===this.consumerMenu&&!this.consumerMenuSnapshot&&(this.consumerMenuSnapshot={dropdownOwner:menu.dropdownOwner,dropdownContained:menu.dropdownContained,dropdownRendersMenuRole:menu.dropdownRendersMenuRole,dropdownStayOpenOnSelect:menu.dropdownStayOpenOnSelect,dropdownSize:menu.dropdownSize,dropdownLabel:menu.dropdownLabel,dropdownOpen:menu.dropdownOpen}),menu.dropdownOwner=this,menu.dropdownContained=!0,menu.dropdownRendersMenuRole=!0,menu.dropdownStayOpenOnSelect=this.stayOpenOnSelect,menu.dropdownSize=this.size,menu.dropdownLabel=this.effectivePopupLabel,menu.dropdownOpen=this.open)}connectedCallback(){super.connectedCallback(),this.updateComplete.then(()=>{this.
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property,query,state}from"lit/decorators.js";import{html as staticHtml,unsafeStatic}from"lit/static-html.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{tag}from"../../../internal/prefix.js";import{LyraPopover}from"./popover.class.js";import{styles}from"./dropdown.styles.js";const menuTag=unsafeStatic(tag("menu"));class LyraDropdown extends LyraPopover{static{this.styles=[LyraPopover.styles,styles]}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}constructor(){super(),this.distance=0,this.placement="bottom-start",this.size="m",this.stayOpenOnSelect=!1,this.onContentSlotChange=event=>{this.collectConsumerMenuFromSlot(event.target)},this.popupRole="menu"}get popupRole(){return"menu"}set popupRole(_next){super.popupRole!=="menu"&&(super.popupRole="menu")}attributeChangedCallback(name,oldValue,newValue){if(name==="popup-role"&&newValue!==null&&newValue!=="menu"){this.setAttribute("popup-role","menu");return}super.attributeChangedCallback(name,oldValue,newValue)}get defaultDistance(){return 0}get defaultPositioningStrategy(){return"absolute"}onPositioningStrategyChanged(previous,next){const wasHoisted=previous==="fixed";wasHoisted!==(next==="fixed")&&this.requestUpdate("hoist",wasHoisted)}get positioningSync(){return this.sync}get animationNamespace(){return"dropdown"}get popupSurfaceRole(){}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-transition-fast"]}get popupPartNames(){return["popup","dialog","popup-popup","base","base__popup","panel"].join(" ")}get arrowPartNames(){return"arrow popup-arrow"}isInsideLightDismissBoundary(path){return super.isInsideLightDismissBoundary(path)||!!(this.containingElement&&path.includes(this.containingElement))}onPopupPositioned(){if(super.onPopupPositioned(),this.openedByInteraction)return;const menu=this.menuEngine;if(!menu?.dropdownOpen)return;menu.shadowRoot?.querySelector("slot:not([name])")?.assignedElements({flatten:!0}).find(element=>element.tabIndex===0)?.focus()}get menuEngine(){return this.consumerMenu??this.renderRoot.querySelector('[part~="menu"]')??void 0}configureMenu(menu){!this.isConnected||!menu||(menu===this.consumerMenu&&!this.consumerMenuSnapshot&&(this.consumerMenuSnapshot={dropdownOwner:menu.dropdownOwner,dropdownContained:menu.dropdownContained,dropdownRendersMenuRole:menu.dropdownRendersMenuRole,dropdownStayOpenOnSelect:menu.dropdownStayOpenOnSelect,dropdownSize:menu.dropdownSize,dropdownLabel:menu.dropdownLabel,dropdownOpen:menu.dropdownOpen}),menu.dropdownOwner=this,menu.dropdownContained=!0,menu.dropdownRendersMenuRole=!0,menu.dropdownStayOpenOnSelect=this.stayOpenOnSelect,menu.dropdownSize=this.size,menu.dropdownLabel=this.effectivePopupLabel,menu.dropdownOpen=this.open)}connectedCallback(){super.connectedCallback(),this.updateComplete.then(()=>{this.contentSlot&&this.collectConsumerMenuFromSlot(this.contentSlot)})}releaseConsumerMenu(menu){if(!menu)return;const snapshot=menu===this.consumerMenu?this.consumerMenuSnapshot:void 0;menu.dropdownOpen=!1,menu.dropdownOwner=snapshot?.dropdownOwner??null,menu.dropdownContained=snapshot?.dropdownContained??!1,menu.dropdownRendersMenuRole=snapshot?.dropdownRendersMenuRole??!1,menu.dropdownStayOpenOnSelect=snapshot?.dropdownStayOpenOnSelect??!1,menu.dropdownSize=snapshot?.dropdownSize,menu.dropdownLabel=snapshot?.dropdownLabel,snapshot&&(menu.dropdownOpen=snapshot.dropdownOpen),menu===this.consumerMenu&&(this.consumerMenuSnapshot=void 0)}collectConsumerMenuFromSlot(slot){if(!this.isConnected||slot!==this.contentSlot)return;const next=slot.assignedElements({flatten:!0}).find(element=>element.localName===tag("menu"));next!==this.consumerMenu&&(this.releaseConsumerMenu(this.consumerMenu),this.consumerMenu=next),this.configureMenu(next??this.menuEngine)}onTriggerKeyDown(event){if(this.disabled||this.open)return;let focus;if(event.key==="ArrowDown"?focus="first":event.key==="ArrowUp"&&(focus="last"),!focus)return;event.preventDefault();const menu=this.menuEngine;this.configureMenu(menu),menu?menu.focusContained(focus):this.show()}reposition(){this.positionPopup()}focusOnTrigger(options){this.renderRoot.querySelector('slot[name="trigger"]')?.assignedElements({flatten:!0})[0]?.focus(options)}getMenu(){return this.menuEngine??null}updated(changed){super.updated(changed),this.configureMenu(this.menuEngine),this.open&&changed.has("sync")&&this.reposition()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.contentSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.collectConsumerMenuFromSlot(s))})}disconnectedCallback(){this.releaseConsumerMenu(this.consumerMenu),super.disconnectedCallback()}renderPopupContent(){return this.consumerMenu?html`<slot @slotchange=${this.onContentSlotChange}></slot>`:staticHtml`
|
|
2
2
|
<${menuTag}
|
|
3
3
|
part="menu"
|
|
4
4
|
.dropdownOwner=${this}
|
|
@@ -186,7 +186,11 @@ withoutArrow:boolean;
|
|
|
186
186
|
/** Where the arrow sits along the popup's edge. `anchor` tracks the anchor's centre.*/
|
|
187
187
|
arrowPlacement:LyraArrowPlacement;
|
|
188
188
|
/** Keeps the arrow this far from the popup's corners, in pixels.*/
|
|
189
|
-
arrowPadding:number;
|
|
189
|
+
arrowPadding:number;
|
|
190
|
+
/** Plain-text tooltip content, painted when the active content slot carries nothing of its own.
|
|
191
|
+
* Whitespace-only text there (template indentation around a `slot="trigger"` element) counts as
|
|
192
|
+
* nothing, so this text still paints and describes the trigger. */
|
|
193
|
+
content:string;accessibleLabel:string;private triggerElement?;private slottedTriggerElement?;private namedTriggerMode;private interactiveContent;private blankContentAssignment;private resolvedSide;private anchorPositioned;private popupHidden;private positionedAnchor?;private positioningDirection?;private directionChanged;private readonly anchorIdentity;private triggerAria?;private accessibleTriggerAria?;private virtualAnchor?;private returnFocusTo?;private cleanup?;private placementPending;private readonly delayTimer;private restoreFocusOnClose;private suppressTriggerFocusOpen;private openedByPointer;private overlayHandle?;private readonly tooltipId;private readonly descriptionId;private descriptionProxy?;private focusDescribesTrigger;private contentObserver?;private contentSnapshot?;private triggerSyncGeneration;private stopLabelReferenceIdentityObservation?;private readonly contentSlotListeners;private shadowContentScanFrame?;private shadowContentScanView?;private shadowContentScanAttempts;private transitionToken;private transitionAnimation?;private readonly transitionGate;private get rendersArrow();private get activeContentSlot();private syncNamedTriggerMode;private get triggerKeywords();private get isManual();private opensOn;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private syncAnchorIdentityObservation;private resolveInteractionTrigger;private syncInteractionTrigger;private activateTooltipOverlay;private shouldRestoreFocusAfterEscape;private get requiresOverlayManager();
|
|
190
194
|
/**
|
|
191
195
|
* Opens the tooltip anchored to an arbitrary rectangle instead of any DOM anchor -- for
|
|
192
196
|
* anchoring to a graph node, a canvas pixel, a chart datum, or any other non-DOM location.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{imageMapImageFor}from"../../../internal/dom-guards.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{parseCssTimeToken}from"../../../internal/css-motion-time.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{subscribeInheritedAttributes}from"../../../internal/inherited-attribute-hub.js";import{accessibleTextRecordsMatter,bindAccessibleTextObserver,labelReferenceRecordsMatter,composedAccessibilityTextResult}from"../../../internal/accessibility-visibility.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,OverlayAnchorIdentity,OverlayDelayTimer,OverlayTransitionGate,resolveOverlayAnchor,resolveOverlayInteractionTrigger,settleOverlayTransition}from"./overlay-shared.js";import{tooltipStyles}from"./overlay.styles.js";import{LYRA_DEFAULT_popover}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_SHOW_DELAY=150,DEFAULT_HIDE_DELAY=0,DEFAULT_DISTANCE=8,MAX_SHADOW_CONTENT_SCAN_FRAMES=4;function safelyComposedContains(container,candidate){try{return candidate?.nodeType===1&&composedContains(container,candidate)}catch{return!1}}const TOOLTIP_POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraTooltip extends LyraElement{constructor(){super(...arguments),this._open=!1,this.trigger="hover focus",this.manual=!1,this.showDelay=150,this.hideDelay=0,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.disabled=!1,this.topLayer=!1,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.content="",this.accessibleLabel="",this.namedTriggerMode=!0,this.interactiveContent=!1,this.resolvedSide="top",this.anchorPositioned=!1,this.popupHidden=!0,this.directionChanged=!1,this.anchorIdentity=new OverlayAnchorIdentity,this.placementPending=!1,this.delayTimer=new OverlayDelayTimer,this.restoreFocusOnClose=!1,this.suppressTriggerFocusOpen=!1,this.openedByPointer=!1,this.tooltipId=nextId("tooltip"),this.descriptionId=nextId("tooltip-description"),this.focusDescribesTrigger=!1,this.triggerSyncGeneration=0,this.contentSlotListeners=new Set,this.shadowContentScanAttempts=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.onTriggerSlotChange=event=>{this.syncNamedTriggerMode();const slot=event.target;this.slottedTriggerElement=slot.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()},this.onEnter=event=>{if(!this.disabled){if(event.type==="focusin"){if(this.updateInteractiveContent(),this.opensOn("focus")&&(this.focusDescribesTrigger=!0),this.contentSnapshot&&this.bindContentObservation(this.contentSnapshot),this.syncTriggerA11y(),this.suppressTriggerFocusOpen||!this.opensOn("focus")||!isKeyboardFocusEvent(event))return}else{if(this.syncTriggerA11y(),!this.opensOn("hover"))return;this.openedByPointer=!0}this.requestTransition(!0)}},this.onLeave=event=>{if(event.type==="focusout"?!this.opensOn("focus"):!this.opensOn("hover"))return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&this.triggerElement&&composedContains(this.triggerElement,next)||(event.type==="focusout"&&(this.focusDescribesTrigger=!1,this.contentSnapshot&&this.bindContentObservation(this.contentSnapshot),this.syncTriggerA11y()),!(this.interactiveContent&&this.isPopupTarget(next))&&this.requestTransition(!1))},this.onTriggerClick=()=>{this.disabled||this.opensOn("click")&&(this.syncTriggerA11y(),this._open?this.hide():this.show())},this.onPopupEnter=()=>{!this.interactiveContent||this.isManual||(this.cancelPendingTransition(),this.show())},this.onPopupLeave=event=>{if(!this.interactiveContent||this.isManual)return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&(this.triggerElement&&composedContains(this.triggerElement,next)||this.isPopupTarget(next))||this.requestTransition(!1)},this.onContentSlotChange=event=>{event.target?.localName==="slot"&&this.updateInteractiveContent()}}static{this.defaultStrings={...super.defaultStrings,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,tooltipStyles]}get open(){return this._open}set open(next){const normalized=!!next;if(normalized||this.cancelPendingTransition(),normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=TOOLTIP_POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}get rendersArrow(){return!this.withoutArrow}get activeContentSlot(){const selector=this.namedTriggerMode?'[part~="body"] slot:not([name])':'[part~="body"] slot[name="content"]';return(this.renderRoot??this.shadowRoot)?.querySelector(selector)??null}syncNamedTriggerMode(schedule=!0){const children=Array.from(this.children),hasNamedTrigger=children.some(child=>child.getAttribute("slot")==="trigger"),hasShoelaceContent=(this.content??"").length>0||children.some(child=>child.getAttribute("slot")==="content"),next=hasNamedTrigger||!hasShoelaceContent;if(next===this.namedTriggerMode)return;const old=this.namedTriggerMode;this.namedTriggerMode=next,schedule&&this.hasUpdated&&this.requestUpdate("namedTriggerMode",old)}get triggerKeywords(){return new Set(String(this.trigger??"").trim().split(/\s+/).filter(Boolean))}get isManual(){const keywords=this.triggerKeywords;return this.manual||keywords.size===0||keywords.has("manual")}opensOn(keyword){return!this.isManual&&this.triggerKeywords.has(keyword)}willUpdate(changed){super.willUpdate(changed);const direction=this.effectiveDirection;this.directionChanged=direction!==this.positioningDirection,this.positioningDirection=direction,this.syncNamedTriggerMode(!1),(changed.has("manual")||changed.has("trigger"))&&this.isManual&&this.cancelPendingTransition(),(changed.has("manual")||changed.has("trigger"))&&this.focusDescribesTrigger&&!this.opensOn("focus")&&(this.focusDescribesTrigger=!1,this.syncTriggerA11y()),changed.has("disabled")&&this.disabled&&(this.cancelPendingTransition(),this.focusDescribesTrigger&&(this.focusDescribesTrigger=!1,this.syncTriggerA11y()),this._open&&(this.hasUpdated?this.hide():this.applyOpenState(!1))),this.anchorIdentity.lostAnchorProperty(changed,this.anchor)&&this.open&&!this.resolveAnchor()&&this.forceClose(),changed.has("showDelay")&&this.delayTimer.pendingDirection==="show"&&this.requestTransition(!0),changed.has("hideDelay")&&this.delayTimer.pendingDirection==="hide"&&this.requestTransition(!1),changed.has("for")&&this.syncInteractionTrigger(),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),changed.has("open")&&this.open&&(this.popupHidden=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){if(super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),this.directionChanged||changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("interactiveContent")){if(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.position(),changed.has("open"))if(this.open)this.updateInteractiveContent(),this.isConnected&&this.requiresOverlayManager&&this.activateTooltipOverlay();else{this.positionedAnchor=void 0;const restoreFocus=this.restoreFocusOnClose;this.suppressTriggerFocusOpen=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.suppressTriggerFocusOpen=!1}this.overlayHandle=void 0,this.restoreFocusOnClose=!1,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger(),this.contentSnapshot&&this.bindContentObservation(this.contentSnapshot)}else changed.has("interactiveContent")&&this.open&&this.isConnected&&this.activateTooltipOverlay();this.syncTriggerA11y()}(changed.has("content")||changed.has("accessibleLabel"))&&this.updateDescriptionProxy()}connectedCallback(){super.connectedCallback();const triggerSyncGeneration=++this.triggerSyncGeneration,triggerSyncDocument=this.ownerDocument;this.syncAnchorIdentityObservation(),this.ensureDescriptionProxy(),this.contentObserver?.disconnect();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.contentObserver=MutationObserverCtor?new MutationObserverCtor((records,observer)=>{accessibleTextRecordsMatter(observer,records)&&(this.syncNamedTriggerMode(),this.updateInteractiveContent())}):void 0,this.updateInteractiveContent(),this.syncInteractionTrigger(),this.updateComplete.then(()=>{if(triggerSyncGeneration!==this.triggerSyncGeneration||!this.isConnected||this.ownerDocument!==triggerSyncDocument)return;const slot=this.renderRoot.querySelector('[part="trigger"] > slot');this.slottedTriggerElement=slot?.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()}),this.hasUpdated&&this.open&&(this.popupHidden=!1,this.position(),this.requiresOverlayManager&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateTooltipOverlay()))}disconnectedCallback(){this.triggerSyncGeneration++,this.anchorIdentity.stop(),this.cancelPendingTransition(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.suspend(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.releaseTriggerA11y(),this.focusDescribesTrigger=!1,this.triggerElement=void 0,this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.cancelShadowContentScan(),this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.popupHidden=!0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.triggerSyncGeneration++,this.anchorIdentity.stop(),this.cancelPendingTransition(),this.cancelShadowContentScan(),this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.anchorIdentity.stop();const directAnchor=this.open?this.anchor??void 0:void 0;this.anchorIdentity.observe(this,directAnchor,this.for,()=>this.anchor,directAnchorRemoved=>{if((this.resolveInteractionTrigger()!==this.triggerElement||this.open||this.focusDescribesTrigger)&&this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose();return}nextAnchor!==this.positionedAnchor&&this.position()})}resolveInteractionTrigger(){return resolveOverlayInteractionTrigger(this,this.virtualAnchor,this.slottedTriggerElement,this.for)}syncInteractionTrigger(){const next=this.resolveInteractionTrigger();this.adoptTrigger(next)}activateTooltipOverlay(){if(!this.isConnected)return;const restoreFocusTarget=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(restoreFocusTarget);return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide({restoreFocus:this.shouldRestoreFocusAfterEscape()})},restoreFocusTo:restoreFocusTarget}),this.overlayHandle.focusAutofocus()}shouldRestoreFocusAfterEscape(){if(this.virtualAnchor)return this.returnFocusTo!==void 0;const active=deepActiveElementIn(this.ownerDocument);return safelyComposedContains(this,active)}get requiresOverlayManager(){return this.open}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.activateTooltipOverlay(),this.position();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}show(){return this.cancelPendingTransition(),this.disabled||this._open?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emit("lr-show",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show")})}hide(options){return this.cancelPendingTransition(),this._open?this.transitionGate.request(!1,()=>{if(this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return options?.restoreFocus&&(this.restoreFocusOnClose=!0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")}):Promise.resolve()}forceClose(){return this.cancelPendingTransition(),this._open?(this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}applyOpenState(next){const old=this._open;this._open=next,next||(this.cancelShadowContentScan(),this.placementPending=!1),next||(this.openedByPointer=!1),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}async settleTransition(event){const token=++this.transitionToken,showing=event==="lr-after-show";return settleOverlayTransition({showing,updateComplete:()=>this.updateComplete,isCurrent:()=>this.transitionToken===token,readyToShow:async()=>{const positioned=await waitForDeferredPlacement(()=>this.cleanup);return this.transitionToken!==token||!this.open?!1:positioned?this.anchorPositioned&&!this.placementPending:(await this.forceClose(),!1)},animate:async()=>{if(!this.isConnected)return;const popup=this.renderRoot.querySelector('[part~="popup"]'),animation=popup?animateRegistered(this,popup,`tooltip.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:["--lr-transition-fast","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken===token&&this.cancelTransitionAnimation()},afterHide:()=>{this.removeAttribute("data-closing"),this.popupHidden=!0},settled:()=>{this.emit(event)}})}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.triggerElement})}position(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1,this.placementPending=!1;return}if(anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.open&&anchor&&popup){const arrowPadding=Math.max(0,finiteNumber(this.arrowPadding,0));this.placementPending=!0,this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),offset:finiteNumber(this.distance,DEFAULT_DISTANCE),skidding:finiteNumber(this.skidding,0),arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding,onPlaced:({placement,arrow})=>{this.placementPending=!1,this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding,rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-tooltip-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}}syncTriggerA11y(){const trigger=this.triggerElement??null,proxy=this.open||this.focusDescribesTrigger?this.descriptionProxy:void 0,contribution={descriptions:proxy?[proxy]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.triggerElement?resolveAccessibleTrigger(this.triggerElement):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}requestTransition(next){if(this.cancelPendingTransition(),this.disabled)return;const delay=this.interactionDelay(next);if(delay<=0){next?this.show():this.hide();return}const view=this.ownerDocument.defaultView;view&&this.delayTimer.schedule(view,delay,next?"show":"hide",()=>{next?this.show():this.hide()})}interactionDelay(showing){const value=showing?this.showDelay:this.hideDelay,fallback=showing?DEFAULT_SHOW_DELAY:DEFAULT_HIDE_DELAY,attribute=showing?"show-delay":"hide-delay";if(this.hasAttribute(attribute)||value!==fallback)return finiteDuration(value,fallback);const property2=showing?"--show-delay":"--hide-delay",raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(property2).trim()??"",token=parseCssTimeToken(raw);return token&&!token.rest?finiteDuration(token.ms,fallback):fallback}cancelPendingTransition(){this.delayTimer.cancel()}bindTrigger(trigger){trigger.addEventListener("mouseenter",this.onEnter),trigger.addEventListener("mouseleave",this.onLeave),trigger.addEventListener("focusin",this.onEnter),trigger.addEventListener("focusout",this.onLeave),trigger.addEventListener("click",this.onTriggerClick)}unbindTrigger(trigger){trigger.removeEventListener("mouseenter",this.onEnter),trigger.removeEventListener("mouseleave",this.onLeave),trigger.removeEventListener("focusin",this.onEnter),trigger.removeEventListener("focusout",this.onLeave),trigger.removeEventListener("click",this.onTriggerClick),this.focusDescribesTrigger=!1}isTriggerHeld(trigger){try{if(trigger.matches(":hover"))return!0}catch{}const active=deepActiveElementIn(trigger.ownerDocument);return safelyComposedContains(trigger,active)}adoptTrigger(next){if(next===this.triggerElement){this.syncTriggerA11y();return}const hadTrigger=this.triggerElement!==void 0;if(this.cancelPendingTransition(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.triggerElement=next,!this.triggerElement){this.syncTriggerA11y(),hadTrigger&&this.open&&!this.resolveAnchor()&&this.forceClose();return}this.bindTrigger(this.triggerElement),this.syncTriggerA11y(),hadTrigger&&this._open&&this.openedByPointer&&!this.isTriggerHeld(this.triggerElement)&&this.forceClose(),this.open&&this.position(),this.open&&this.interactiveContent&&this.activateTooltipOverlay()}isPopupTarget(target){if(target===null||target.nodeType!==1)return!1;const element=target,slot=this.activeContentSlot;return this.renderRoot.querySelector('[part~="popup"]')?.contains(element)===!0||slot?.assignedElements({flatten:!0}).some(root=>composedContains(root,element))===!0}clearContentSlotListeners(){for(const slot of this.contentSlotListeners)slot.removeEventListener("slotchange",this.onContentSlotChange);this.contentSlotListeners.clear()}syncContentSlotListeners(slots){const activeSlot=this.activeContentSlot;for(const slot of this.contentSlotListeners)slots.has(slot)&&slot!==activeSlot||(slot.removeEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.delete(slot));for(const slot of slots)slot===activeSlot||this.contentSlotListeners.has(slot)||(slot.addEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.add(slot))}inspectContent(){const snapshot={actionable:!1,assigned:!1,awaitingShadowRoot:!1,labelReferenceRoots:new Set,labelReferenceIds:new Set,referencedElements:new Set,text:"",externalRoots:new Set,shadowRoots:new Set,forwardingSlots:new Set,composedAncestors:new Set},activeSlot=this.activeContentSlot;if(!activeSlot)return snapshot;const renderRoot=this.renderRoot??this.shadowRoot;snapshot.assigned=activeSlot.assignedNodes().length>0;const popup=renderRoot?.querySelector('[part~="popup"]'),bypassClosedVisibility=popup?.hasAttribute("data-hidden")===!0||this.placementPending,previousVisibility=popup?.style.getPropertyValue("visibility")??"",previousVisibilityPriority=popup?.style.getPropertyPriority("visibility")??"",previousHidden=popup?.hidden??!1;if(popup&&bypassClosedVisibility){const hostVisibility=this.ownerDocument.defaultView?.getComputedStyle(this).visibility??"visible";popup.style.setProperty("visibility",hostVisibility),popup.hidden=!1}try{const visitedContentElements=new Set,elementStates=new Map,accessibilityText=composedAccessibilityTextResult(activeSlot,{shouldPruneNode:node=>{if(node.getRootNode()!==renderRoot&&!this.contains(node)&&snapshot.externalRoots.add(node),node.nodeType!==1)return!1;const element=node;return visitedContentElements.add(element),element.localName==="slot"&&snapshot.forwardingSlots.add(element),element.shadowRoot?snapshot.shadowRoots.add(element.shadowRoot):element.localName.includes("-")&&(snapshot.awaitingShadowRoot=!0),!1},onElementState:(element,state2)=>elementStates.set(element,state2)});for(const element of elementStates.keys())!visitedContentElements.has(element)&&element!==this&&snapshot.composedAncestors.add(element);for(const element of visitedContentElements){const imageMapElement=element.localName==="map"||element.localName==="area";if(imageMapElement){const image=imageMapImageFor(element);image&&snapshot.externalRoots.add(image)}if(!isActionableElement(element))continue;const state2=imageMapElement?void 0:elementStates.get(element);if(state2?.subtreeExcluded??isAccessibilitySubtreeExcluded(element))continue;(state2?.visibilityHidden??isAccessibilityVisibilityHidden(element))||(snapshot.actionable=!0)}snapshot.text=accessibilityText.text.replace(/\s+/g," ").trim();for(const root of accessibilityText.labelReferenceRoots)snapshot.labelReferenceRoots.add(root);for(const id of accessibilityText.labelReferenceIds)snapshot.labelReferenceIds.add(id);for(const reference of accessibilityText.referencedElements)snapshot.referencedElements.add(reference),snapshot.externalRoots.add(reference)}finally{popup&&bypassClosedVisibility&&(previousVisibility?popup.style.setProperty("visibility",previousVisibility,previousVisibilityPriority):popup.style.removeProperty("visibility"),popup.hidden=previousHidden)}return snapshot}observeContentNode(node){if(this.contentObserver){if(node.nodeType===3){this.contentObserver.observe(node,{characterData:!0});return}node.nodeType!==1&&node.nodeType!==11||this.contentObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","aria-labelledby","alt","class","contenteditable","hidden","href","inert","name","open","role","slot","style","tabindex","usemap"],childList:!0,characterData:!0,subtree:!0})}}bindContentObservation(snapshot){if(this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.isConnected&&snapshot.labelReferenceRoots.size>0){const Observer=this.ownerDocument.defaultView?.MutationObserver,cleanups=[...snapshot.labelReferenceRoots].map(root=>subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:records=>{labelReferenceRecordsMatter(records,snapshot.labelReferenceIds,snapshot.referencedElements)&&this.updateInteractiveContent()}}));this.stopLabelReferenceIdentityObservation=()=>{for(const cleanup of cleanups)cleanup?.()}}if(!this.contentObserver)return;const pendingRecords=this.contentObserver.takeRecords(),pendingMatter=pendingRecords.length>0&&accessibleTextRecordsMatter(this.contentObserver,pendingRecords),observer=this.contentObserver;bindAccessibleTextObserver(observer,this),pendingMatter&&queueMicrotask(()=>{this.isConnected&&this.contentObserver===observer&&this.updateInteractiveContent()}),this.observeContentNode(this);for(const root of snapshot.externalRoots)this.observeContentNode(root);for(const root of snapshot.shadowRoots)this.observeContentNode(root)}updateInteractiveContent(fromShadowContentScan=!1){fromShadowContentScan||(this.shadowContentScanAttempts=0);const snapshot=this.inspectContent();this.contentSnapshot=snapshot,this.interactiveContent=snapshot.actionable,this.syncContentSlotListeners(snapshot.forwardingSlots),this.bindContentObservation(snapshot),this.scheduleShadowContentScan(snapshot.awaitingShadowRoot),this.updateDescriptionProxy(snapshot.text,snapshot.assigned)}scheduleShadowContentScan(awaitingShadowRoot){if(this.cancelShadowContentScan(!1),!awaitingShadowRoot||!this.open||!this.isConnected||this.shadowContentScanAttempts>=MAX_SHADOW_CONTENT_SCAN_FRAMES)return;const view=this.ownerDocument.defaultView;view&&(this.shadowContentScanView=view,this.shadowContentScanFrame=view.requestAnimationFrame(()=>{this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,this.shadowContentScanAttempts++,this.updateInteractiveContent(!0)}))}cancelShadowContentScan(resetAttempts=!0){this.shadowContentScanFrame!==void 0&&this.shadowContentScanView?.cancelAnimationFrame(this.shadowContentScanFrame),this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,resetAttempts&&(this.shadowContentScanAttempts=0)}ensureDescriptionProxy(){this.descriptionProxy||(this.descriptionProxy=this.ownerDocument.createElement("span"),this.descriptionProxy.id=this.descriptionId,this.descriptionProxy.slot="__lr-tooltip-description",this.descriptionProxy.hidden=!0,this.descriptionProxy.dataset.lyraTooltipDescription=""),this.updateDescriptionProxy()}updateDescriptionProxy(contentText,assigned){if(!this.descriptionProxy)return;this.descriptionProxy.parentNode!==this&&this.append(this.descriptionProxy);const hostLabel=this.getAttribute("aria-label"),snapshot=contentText===void 0||assigned===void 0?this.inspectContent():void 0,visibleContent=contentText??snapshot?.text??"",hasAssignment=assigned??snapshot?.assigned??!1,description=hostLabel!==null?hostLabel.trim():(this.accessibleLabel||visibleContent||(hasAssignment?"":this.content)).trim();this.descriptionProxy.textContent!==description&&(this.descriptionProxy.textContent=description)}render(){const hostLabel=this.getAttribute("aria-label"),propertyLabel=this.accessibleLabel??"",hasExplicitLabel=hostLabel!==null||propertyLabel.length>0,label=hostLabel!==null?hostLabel:propertyLabel,popupLabel=this.interactiveContent?hasExplicitLabel?label:this.localize("popover"):hasExplicitLabel?label:nothing;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{imageMapImageFor}from"../../../internal/dom-guards.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{parseCssTimeToken}from"../../../internal/css-motion-time.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{subscribeInheritedAttributes}from"../../../internal/inherited-attribute-hub.js";import{accessibleTextRecordsMatter,bindAccessibleTextObserver,labelReferenceRecordsMatter,composedAccessibilityTextResult}from"../../../internal/accessibility-visibility.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,OverlayAnchorIdentity,OverlayDelayTimer,OverlayTransitionGate,resolveOverlayAnchor,resolveOverlayInteractionTrigger,settleOverlayTransition}from"./overlay-shared.js";import{tooltipStyles}from"./overlay.styles.js";import{LYRA_DEFAULT_popover}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_SHOW_DELAY=150,DEFAULT_HIDE_DELAY=0,DEFAULT_DISTANCE=8,MAX_SHADOW_CONTENT_SCAN_FRAMES=4;function safelyComposedContains(container,candidate){try{return candidate?.nodeType===1&&composedContains(container,candidate)}catch{return!1}}const TOOLTIP_POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]),BLANK_TEXT=/^[ \t\n\f\r]*$/;function isBlankText(node){return node.nodeType===Node.TEXT_NODE&&BLANK_TEXT.test(node.textContent??"")}class LyraTooltip extends LyraElement{constructor(){super(...arguments),this._open=!1,this.trigger="hover focus",this.manual=!1,this.showDelay=150,this.hideDelay=0,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.disabled=!1,this.topLayer=!1,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.content="",this.accessibleLabel="",this.namedTriggerMode=!0,this.interactiveContent=!1,this.blankContentAssignment=!1,this.resolvedSide="top",this.anchorPositioned=!1,this.popupHidden=!0,this.directionChanged=!1,this.anchorIdentity=new OverlayAnchorIdentity,this.placementPending=!1,this.delayTimer=new OverlayDelayTimer,this.restoreFocusOnClose=!1,this.suppressTriggerFocusOpen=!1,this.openedByPointer=!1,this.tooltipId=nextId("tooltip"),this.descriptionId=nextId("tooltip-description"),this.focusDescribesTrigger=!1,this.triggerSyncGeneration=0,this.contentSlotListeners=new Set,this.shadowContentScanAttempts=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.onTriggerSlotChange=event=>{this.syncNamedTriggerMode();const slot=event.target;this.slottedTriggerElement=slot.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()},this.onEnter=event=>{if(!this.disabled){if(event.type==="focusin"){if(this.updateInteractiveContent(),this.opensOn("focus")&&(this.focusDescribesTrigger=!0),this.contentSnapshot&&this.bindContentObservation(this.contentSnapshot),this.syncTriggerA11y(),this.suppressTriggerFocusOpen||!this.opensOn("focus")||!isKeyboardFocusEvent(event))return}else{if(this.syncTriggerA11y(),!this.opensOn("hover"))return;this.openedByPointer=!0}this.requestTransition(!0)}},this.onLeave=event=>{if(event.type==="focusout"?!this.opensOn("focus"):!this.opensOn("hover"))return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&this.triggerElement&&composedContains(this.triggerElement,next)||(event.type==="focusout"&&(this.focusDescribesTrigger=!1,this.contentSnapshot&&this.bindContentObservation(this.contentSnapshot),this.syncTriggerA11y()),!(this.interactiveContent&&this.isPopupTarget(next))&&this.requestTransition(!1))},this.onTriggerClick=()=>{this.disabled||this.opensOn("click")&&(this.syncTriggerA11y(),this._open?this.hide():this.show())},this.onPopupEnter=()=>{!this.interactiveContent||this.isManual||(this.cancelPendingTransition(),this.show())},this.onPopupLeave=event=>{if(!this.interactiveContent||this.isManual)return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&(this.triggerElement&&composedContains(this.triggerElement,next)||this.isPopupTarget(next))||this.requestTransition(!1)},this.onContentSlotChange=event=>{event.target?.localName==="slot"&&this.updateInteractiveContent()}}static{this.defaultStrings={...super.defaultStrings,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,tooltipStyles]}get open(){return this._open}set open(next){const normalized=!!next;if(normalized||this.cancelPendingTransition(),normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=TOOLTIP_POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}get rendersArrow(){return!this.withoutArrow}get activeContentSlot(){const selector=this.namedTriggerMode?'[part~="body"] slot:not([name])':'[part~="body"] slot[name="content"]';return(this.renderRoot??this.shadowRoot)?.querySelector(selector)??null}syncNamedTriggerMode(schedule=!0){const children=Array.from(this.children),hasNamedTrigger=children.some(child=>child.getAttribute("slot")==="trigger"),hasShoelaceContent=(this.content??"").length>0||children.some(child=>child.getAttribute("slot")==="content"),next=hasNamedTrigger||!hasShoelaceContent;if(next===this.namedTriggerMode)return;const old=this.namedTriggerMode;this.namedTriggerMode=next,schedule&&this.hasUpdated&&this.requestUpdate("namedTriggerMode",old)}get triggerKeywords(){return new Set(String(this.trigger??"").trim().split(/\s+/).filter(Boolean))}get isManual(){const keywords=this.triggerKeywords;return this.manual||keywords.size===0||keywords.has("manual")}opensOn(keyword){return!this.isManual&&this.triggerKeywords.has(keyword)}willUpdate(changed){super.willUpdate(changed);const direction=this.effectiveDirection;this.directionChanged=direction!==this.positioningDirection,this.positioningDirection=direction,this.syncNamedTriggerMode(!1),(changed.has("manual")||changed.has("trigger"))&&this.isManual&&this.cancelPendingTransition(),(changed.has("manual")||changed.has("trigger"))&&this.focusDescribesTrigger&&!this.opensOn("focus")&&(this.focusDescribesTrigger=!1,this.syncTriggerA11y()),changed.has("disabled")&&this.disabled&&(this.cancelPendingTransition(),this.focusDescribesTrigger&&(this.focusDescribesTrigger=!1,this.syncTriggerA11y()),this._open&&(this.hasUpdated?this.hide():this.applyOpenState(!1))),this.anchorIdentity.lostAnchorProperty(changed,this.anchor)&&this.open&&!this.resolveAnchor()&&this.forceClose(),changed.has("showDelay")&&this.delayTimer.pendingDirection==="show"&&this.requestTransition(!0),changed.has("hideDelay")&&this.delayTimer.pendingDirection==="hide"&&this.requestTransition(!1),changed.has("for")&&this.syncInteractionTrigger(),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),changed.has("open")&&this.open&&(this.popupHidden=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){if(super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),this.directionChanged||changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("interactiveContent")){if(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.position(),changed.has("open"))if(this.open)this.updateInteractiveContent(),this.isConnected&&this.requiresOverlayManager&&this.activateTooltipOverlay();else{this.positionedAnchor=void 0;const restoreFocus=this.restoreFocusOnClose;this.suppressTriggerFocusOpen=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.suppressTriggerFocusOpen=!1}this.overlayHandle=void 0,this.restoreFocusOnClose=!1,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger(),this.contentSnapshot&&this.bindContentObservation(this.contentSnapshot)}else changed.has("interactiveContent")&&this.open&&this.isConnected&&this.activateTooltipOverlay();this.syncTriggerA11y()}(changed.has("content")||changed.has("accessibleLabel"))&&this.updateDescriptionProxy()}connectedCallback(){super.connectedCallback();const triggerSyncGeneration=++this.triggerSyncGeneration,triggerSyncDocument=this.ownerDocument;this.syncAnchorIdentityObservation(),this.ensureDescriptionProxy(),this.contentObserver?.disconnect();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.contentObserver=MutationObserverCtor?new MutationObserverCtor((records,observer)=>{accessibleTextRecordsMatter(observer,records)&&(this.syncNamedTriggerMode(),this.updateInteractiveContent())}):void 0,this.updateInteractiveContent(),this.syncInteractionTrigger(),this.updateComplete.then(()=>{if(triggerSyncGeneration!==this.triggerSyncGeneration||!this.isConnected||this.ownerDocument!==triggerSyncDocument)return;const slot=this.renderRoot.querySelector('[part="trigger"] > slot');this.slottedTriggerElement=slot?.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()}),this.hasUpdated&&this.open&&(this.popupHidden=!1,this.position(),this.requiresOverlayManager&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateTooltipOverlay()))}disconnectedCallback(){this.triggerSyncGeneration++,this.anchorIdentity.stop(),this.cancelPendingTransition(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.suspend(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.releaseTriggerA11y(),this.focusDescribesTrigger=!1,this.triggerElement=void 0,this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.cancelShadowContentScan(),this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.popupHidden=!0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.triggerSyncGeneration++,this.anchorIdentity.stop(),this.cancelPendingTransition(),this.cancelShadowContentScan(),this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.anchorIdentity.stop();const directAnchor=this.open?this.anchor??void 0:void 0;this.anchorIdentity.observe(this,directAnchor,this.for,()=>this.anchor,directAnchorRemoved=>{if((this.resolveInteractionTrigger()!==this.triggerElement||this.open||this.focusDescribesTrigger)&&this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose();return}nextAnchor!==this.positionedAnchor&&this.position()})}resolveInteractionTrigger(){return resolveOverlayInteractionTrigger(this,this.virtualAnchor,this.slottedTriggerElement,this.for)}syncInteractionTrigger(){const next=this.resolveInteractionTrigger();this.adoptTrigger(next)}activateTooltipOverlay(){if(!this.isConnected)return;const restoreFocusTarget=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(restoreFocusTarget);return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide({restoreFocus:this.shouldRestoreFocusAfterEscape()})},restoreFocusTo:restoreFocusTarget}),this.overlayHandle.focusAutofocus()}shouldRestoreFocusAfterEscape(){if(this.virtualAnchor)return this.returnFocusTo!==void 0;const active=deepActiveElementIn(this.ownerDocument);return safelyComposedContains(this,active)}get requiresOverlayManager(){return this.open}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.activateTooltipOverlay(),this.position();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}show(){return this.cancelPendingTransition(),this.disabled||this._open?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emit("lr-show",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show")})}hide(options){return this.cancelPendingTransition(),this._open?this.transitionGate.request(!1,()=>{if(this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return options?.restoreFocus&&(this.restoreFocusOnClose=!0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")}):Promise.resolve()}forceClose(){return this.cancelPendingTransition(),this._open?(this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}applyOpenState(next){const old=this._open;this._open=next,next||(this.cancelShadowContentScan(),this.placementPending=!1),next||(this.openedByPointer=!1),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}async settleTransition(event){const token=++this.transitionToken,showing=event==="lr-after-show";return settleOverlayTransition({showing,updateComplete:()=>this.updateComplete,isCurrent:()=>this.transitionToken===token,readyToShow:async()=>{const positioned=await waitForDeferredPlacement(()=>this.cleanup);return this.transitionToken!==token||!this.open?!1:positioned?this.anchorPositioned&&!this.placementPending:(await this.forceClose(),!1)},animate:async()=>{if(!this.isConnected)return;const popup=this.renderRoot.querySelector('[part~="popup"]'),animation=popup?animateRegistered(this,popup,`tooltip.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:["--lr-transition-fast","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken===token&&this.cancelTransitionAnimation()},afterHide:()=>{this.removeAttribute("data-closing"),this.popupHidden=!0},settled:()=>{this.emit(event)}})}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.triggerElement})}position(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1,this.placementPending=!1;return}if(anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.open&&anchor&&popup){const arrowPadding=Math.max(0,finiteNumber(this.arrowPadding,0));this.placementPending=!0,this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,this.topLayer);const operation=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),offset:finiteNumber(this.distance,DEFAULT_DISTANCE),skidding:finiteNumber(this.skidding,0),arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding,onPlaced:({placement,arrow})=>{this.placementPending=!1,this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding,rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-tooltip-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}});this.cleanup=operation,operation.ready.then(positioned=>{!positioned&&this.cleanup===operation&&this.open&&(this.restoreFocusOnClose=safelyComposedContains(this,deepActiveElementIn(this.ownerDocument)),this.forceClose())})}}syncTriggerA11y(){const trigger=this.triggerElement??null,proxy=this.open||this.focusDescribesTrigger?this.descriptionProxy:void 0,contribution={descriptions:proxy?[proxy]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.triggerElement?resolveAccessibleTrigger(this.triggerElement):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}requestTransition(next){if(this.cancelPendingTransition(),this.disabled)return;const delay=this.interactionDelay(next);if(delay<=0){next?this.show():this.hide();return}const view=this.ownerDocument.defaultView;view&&this.delayTimer.schedule(view,delay,next?"show":"hide",()=>{next?this.show():this.hide()})}interactionDelay(showing){const value=showing?this.showDelay:this.hideDelay,fallback=showing?DEFAULT_SHOW_DELAY:DEFAULT_HIDE_DELAY,attribute=showing?"show-delay":"hide-delay";if(this.hasAttribute(attribute)||value!==fallback)return finiteDuration(value,fallback);const property2=showing?"--show-delay":"--hide-delay",raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(property2).trim()??"",token=parseCssTimeToken(raw);return token&&!token.rest?finiteDuration(token.ms,fallback):fallback}cancelPendingTransition(){this.delayTimer.cancel()}bindTrigger(trigger){trigger.addEventListener("mouseenter",this.onEnter),trigger.addEventListener("mouseleave",this.onLeave),trigger.addEventListener("focusin",this.onEnter),trigger.addEventListener("focusout",this.onLeave),trigger.addEventListener("click",this.onTriggerClick)}unbindTrigger(trigger){trigger.removeEventListener("mouseenter",this.onEnter),trigger.removeEventListener("mouseleave",this.onLeave),trigger.removeEventListener("focusin",this.onEnter),trigger.removeEventListener("focusout",this.onLeave),trigger.removeEventListener("click",this.onTriggerClick),this.focusDescribesTrigger=!1}isTriggerHeld(trigger){try{if(trigger.matches(":hover"))return!0}catch{}const active=deepActiveElementIn(trigger.ownerDocument);return safelyComposedContains(trigger,active)}adoptTrigger(next){if(next===this.triggerElement){this.syncTriggerA11y();return}const hadTrigger=this.triggerElement!==void 0;if(this.cancelPendingTransition(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.triggerElement=next,!this.triggerElement){this.syncTriggerA11y(),hadTrigger&&this.open&&!this.resolveAnchor()&&this.forceClose();return}this.bindTrigger(this.triggerElement),this.syncTriggerA11y(),hadTrigger&&this._open&&this.openedByPointer&&!this.isTriggerHeld(this.triggerElement)&&this.forceClose(),this.open&&this.position(),this.open&&this.interactiveContent&&this.activateTooltipOverlay()}isPopupTarget(target){if(target===null||target.nodeType!==1)return!1;const element=target,slot=this.activeContentSlot;return this.renderRoot.querySelector('[part~="popup"]')?.contains(element)===!0||slot?.assignedElements({flatten:!0}).some(root=>composedContains(root,element))===!0}clearContentSlotListeners(){for(const slot of this.contentSlotListeners)slot.removeEventListener("slotchange",this.onContentSlotChange);this.contentSlotListeners.clear()}syncContentSlotListeners(slots){const activeSlot=this.activeContentSlot;for(const slot of this.contentSlotListeners)slots.has(slot)&&slot!==activeSlot||(slot.removeEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.delete(slot));for(const slot of slots)slot===activeSlot||this.contentSlotListeners.has(slot)||(slot.addEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.add(slot))}inspectContent(){const snapshot={actionable:!1,assigned:!1,blank:!1,awaitingShadowRoot:!1,labelReferenceRoots:new Set,labelReferenceIds:new Set,referencedElements:new Set,text:"",externalRoots:new Set,shadowRoots:new Set,forwardingSlots:new Set,composedAncestors:new Set},activeSlot=this.activeContentSlot;if(!activeSlot)return snapshot;const renderRoot=this.renderRoot??this.shadowRoot,assignedNodes=activeSlot.assignedNodes();snapshot.assigned=assignedNodes.some(node=>!isBlankText(node)),snapshot.blank=assignedNodes.length>0&&!snapshot.assigned;const popup=renderRoot?.querySelector('[part~="popup"]'),bypassClosedVisibility=popup?.hasAttribute("data-hidden")===!0||this.placementPending,previousVisibility=popup?.style.getPropertyValue("visibility")??"",previousVisibilityPriority=popup?.style.getPropertyPriority("visibility")??"",previousHidden=popup?.hidden??!1;if(popup&&bypassClosedVisibility){const hostVisibility=this.ownerDocument.defaultView?.getComputedStyle(this).visibility??"visible";popup.style.setProperty("visibility",hostVisibility),popup.hidden=!1}try{const visitedContentElements=new Set,elementStates=new Map,accessibilityText=composedAccessibilityTextResult(activeSlot,{shouldPruneNode:node=>{if(node.getRootNode()!==renderRoot&&!this.contains(node)&&snapshot.externalRoots.add(node),node.nodeType!==1)return!1;const element=node;return visitedContentElements.add(element),element.localName==="slot"&&snapshot.forwardingSlots.add(element),element.shadowRoot?snapshot.shadowRoots.add(element.shadowRoot):element.localName.includes("-")&&(snapshot.awaitingShadowRoot=!0),!1},onElementState:(element,state2)=>elementStates.set(element,state2)});for(const element of elementStates.keys())!visitedContentElements.has(element)&&element!==this&&snapshot.composedAncestors.add(element);for(const element of visitedContentElements){const imageMapElement=element.localName==="map"||element.localName==="area";if(imageMapElement){const image=imageMapImageFor(element);image&&snapshot.externalRoots.add(image)}if(!isActionableElement(element))continue;const state2=imageMapElement?void 0:elementStates.get(element);if(state2?.subtreeExcluded??isAccessibilitySubtreeExcluded(element))continue;(state2?.visibilityHidden??isAccessibilityVisibilityHidden(element))||(snapshot.actionable=!0)}snapshot.text=accessibilityText.text.replace(/\s+/g," ").trim();for(const root of accessibilityText.labelReferenceRoots)snapshot.labelReferenceRoots.add(root);for(const id of accessibilityText.labelReferenceIds)snapshot.labelReferenceIds.add(id);for(const reference of accessibilityText.referencedElements)snapshot.referencedElements.add(reference),snapshot.externalRoots.add(reference)}finally{popup&&bypassClosedVisibility&&(previousVisibility?popup.style.setProperty("visibility",previousVisibility,previousVisibilityPriority):popup.style.removeProperty("visibility"),popup.hidden=previousHidden)}return snapshot}observeContentNode(node){if(this.contentObserver){if(node.nodeType===3){this.contentObserver.observe(node,{characterData:!0});return}node.nodeType!==1&&node.nodeType!==11||this.contentObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","aria-labelledby","alt","class","contenteditable","hidden","href","inert","name","open","role","slot","style","tabindex","usemap"],childList:!0,characterData:!0,subtree:!0})}}bindContentObservation(snapshot){if(this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.isConnected&&snapshot.labelReferenceRoots.size>0){const Observer=this.ownerDocument.defaultView?.MutationObserver,cleanups=[...snapshot.labelReferenceRoots].map(root=>subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:records=>{labelReferenceRecordsMatter(records,snapshot.labelReferenceIds,snapshot.referencedElements)&&this.updateInteractiveContent()}}));this.stopLabelReferenceIdentityObservation=()=>{for(const cleanup of cleanups)cleanup?.()}}if(!this.contentObserver)return;const pendingRecords=this.contentObserver.takeRecords(),pendingMatter=pendingRecords.length>0&&accessibleTextRecordsMatter(this.contentObserver,pendingRecords),observer=this.contentObserver;bindAccessibleTextObserver(observer,this),pendingMatter&&queueMicrotask(()=>{this.isConnected&&this.contentObserver===observer&&this.updateInteractiveContent()}),this.observeContentNode(this);for(const root of snapshot.externalRoots)this.observeContentNode(root);for(const root of snapshot.shadowRoots)this.observeContentNode(root)}updateInteractiveContent(fromShadowContentScan=!1){fromShadowContentScan||(this.shadowContentScanAttempts=0);const snapshot=this.inspectContent();this.contentSnapshot=snapshot,this.interactiveContent=snapshot.actionable,this.blankContentAssignment=snapshot.blank,this.syncContentSlotListeners(snapshot.forwardingSlots),this.bindContentObservation(snapshot),this.scheduleShadowContentScan(snapshot.awaitingShadowRoot),this.updateDescriptionProxy(snapshot.text,snapshot.assigned)}scheduleShadowContentScan(awaitingShadowRoot){if(this.cancelShadowContentScan(!1),!awaitingShadowRoot||!this.open||!this.isConnected||this.shadowContentScanAttempts>=MAX_SHADOW_CONTENT_SCAN_FRAMES)return;const view=this.ownerDocument.defaultView;view&&(this.shadowContentScanView=view,this.shadowContentScanFrame=view.requestAnimationFrame(()=>{this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,this.shadowContentScanAttempts++,this.updateInteractiveContent(!0)}))}cancelShadowContentScan(resetAttempts=!0){this.shadowContentScanFrame!==void 0&&this.shadowContentScanView?.cancelAnimationFrame(this.shadowContentScanFrame),this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,resetAttempts&&(this.shadowContentScanAttempts=0)}ensureDescriptionProxy(){this.descriptionProxy||(this.descriptionProxy=this.ownerDocument.createElement("span"),this.descriptionProxy.id=this.descriptionId,this.descriptionProxy.slot="__lr-tooltip-description",this.descriptionProxy.hidden=!0,this.descriptionProxy.dataset.lyraTooltipDescription=""),this.updateDescriptionProxy()}updateDescriptionProxy(contentText,assigned){if(!this.descriptionProxy)return;this.descriptionProxy.parentNode!==this&&this.append(this.descriptionProxy);const hostLabel=this.getAttribute("aria-label"),snapshot=contentText===void 0||assigned===void 0?this.inspectContent():void 0,visibleContent=contentText??snapshot?.text??"",hasAssignment=assigned??snapshot?.assigned??!1,description=hostLabel!==null?hostLabel.trim():(this.accessibleLabel||visibleContent||(hasAssignment?"":this.content??"")).trim();this.descriptionProxy.textContent!==description&&(this.descriptionProxy.textContent=description)}render(){const hostLabel=this.getAttribute("aria-label"),propertyLabel=this.accessibleLabel??"",hasExplicitLabel=hostLabel!==null||propertyLabel.length>0,label=hostLabel!==null?hostLabel:propertyLabel,popupLabel=this.interactiveContent?hasExplicitLabel?label:this.localize("popover"):hasExplicitLabel?label:nothing;return html`
|
|
2
2
|
<span part="trigger">
|
|
3
3
|
${this.namedTriggerMode?html`<slot name="trigger" @slotchange=${this.onTriggerSlotChange}></slot>`:html`<slot @slotchange=${this.onTriggerSlotChange}></slot>`}
|
|
4
4
|
</span>
|
|
@@ -11,8 +11,8 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
11
11
|
@mouseenter=${this.onPopupEnter} @mouseleave=${this.onPopupLeave}
|
|
12
12
|
@focusin=${this.onPopupEnter} @focusout=${this.onPopupLeave}>
|
|
13
13
|
<span part="body">
|
|
14
|
-
${this.namedTriggerMode?html`<slot @slotchange=${this.onContentSlotChange}>${this.content}</slot>`:html`<slot name="content" @slotchange=${this.onContentSlotChange}>${this.content}</slot>`}
|
|
14
|
+
${this.namedTriggerMode?html`<slot @slotchange=${this.onContentSlotChange}>${this.content}</slot>`:html`<slot name="content" @slotchange=${this.onContentSlotChange}>${this.content}</slot>`}${this.blankContentAssignment?this.content:nothing}
|
|
15
15
|
</span>
|
|
16
16
|
${this.rendersArrow?html`<span part="arrow base__arrow arrow-${this.resolvedSide}"></span>`:nothing}
|
|
17
17
|
</div>
|
|
18
|
-
`}}__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"open",null),__decorate([property()],LyraTooltip.prototype,"trigger",void 0),__decorate([property({type:Boolean})],LyraTooltip.prototype,"manual",void 0),__decorate([property({type:Number,attribute:"show-delay"})],LyraTooltip.prototype,"showDelay",void 0),__decorate([property({type:Number,attribute:"hide-delay"})],LyraTooltip.prototype,"hideDelay",void 0),__decorate([property({reflect:!0})],LyraTooltip.prototype,"placement",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"distance",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"skidding",void 0),__decorate([property({reflect:!0,converter:omittedEmptyStringConverter})],LyraTooltip.prototype,"for",null),__decorate([property({attribute:!1})],LyraTooltip.prototype,"anchor",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"disabled",void 0),__decorate([property({attribute:"positioning-strategy",reflect:!0,converter:TOOLTIP_POSITIONING_STRATEGY})],LyraTooltip.prototype,"positioningStrategy",null),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"hoist",null),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraTooltip.prototype,"topLayer",void 0),__decorate([property({type:Boolean,attribute:"without-arrow",reflect:!0})],LyraTooltip.prototype,"withoutArrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraTooltip.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraTooltip.prototype,"arrowPadding",void 0),__decorate([property()],LyraTooltip.prototype,"content",void 0),__decorate([property({attribute:"aria-label"})],LyraTooltip.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTooltip.prototype,"interactiveContent",void 0),__decorate([state()],LyraTooltip.prototype,"resolvedSide",void 0),__decorate([state()],LyraTooltip.prototype,"anchorPositioned",void 0),__decorate([state()],LyraTooltip.prototype,"popupHidden",void 0);export{LyraTooltip};
|
|
18
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"open",null),__decorate([property()],LyraTooltip.prototype,"trigger",void 0),__decorate([property({type:Boolean})],LyraTooltip.prototype,"manual",void 0),__decorate([property({type:Number,attribute:"show-delay"})],LyraTooltip.prototype,"showDelay",void 0),__decorate([property({type:Number,attribute:"hide-delay"})],LyraTooltip.prototype,"hideDelay",void 0),__decorate([property({reflect:!0})],LyraTooltip.prototype,"placement",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"distance",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"skidding",void 0),__decorate([property({reflect:!0,converter:omittedEmptyStringConverter})],LyraTooltip.prototype,"for",null),__decorate([property({attribute:!1})],LyraTooltip.prototype,"anchor",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"disabled",void 0),__decorate([property({attribute:"positioning-strategy",reflect:!0,converter:TOOLTIP_POSITIONING_STRATEGY})],LyraTooltip.prototype,"positioningStrategy",null),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"hoist",null),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraTooltip.prototype,"topLayer",void 0),__decorate([property({type:Boolean,attribute:"without-arrow",reflect:!0})],LyraTooltip.prototype,"withoutArrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraTooltip.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraTooltip.prototype,"arrowPadding",void 0),__decorate([property()],LyraTooltip.prototype,"content",void 0),__decorate([property({attribute:"aria-label"})],LyraTooltip.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTooltip.prototype,"interactiveContent",void 0),__decorate([state()],LyraTooltip.prototype,"blankContentAssignment",void 0),__decorate([state()],LyraTooltip.prototype,"resolvedSide",void 0),__decorate([state()],LyraTooltip.prototype,"anchorPositioned",void 0),__decorate([state()],LyraTooltip.prototype,"popupHidden",void 0);export{LyraTooltip};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{Engine3dSelection,engine3dFailureReason,webgl2Available}from"../../../internal/engine-3d.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";const embeddingPointsLoader=createEngine3dLoader({entry:"points",tag:tag("embedding-explorer"),load:()=>(async()=>{try{return await import("@aceshooting/lyra-3d/points")}catch(e){throw e}})()}),embeddingEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas"))};class EmbeddingEngineController{constructor(host,changed,fallback,pick){this.host=host,this.changed=changed,this.fallback=fallback,this.pick=pick,this.selection=new Engine3dSelection(!0),this.notice=null,this.loading=!1,this.ready=!1,this.software=!1,this.generation=0,this.revision=0,this.rows=null,this.container=null,this.intersecting=!1,this.pending=!1,this.attempted=!1,this.preference="builtin",this.sourceMode=!1,this.mediaCleanup=[],this.hover=-1,this.selected=-1,this.focus=-1}releaseEngine(){this.generation
|
|
1
|
+
import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{Engine3dSelection,engine3dFailureReason,webgl2Available}from"../../../internal/engine-3d.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";const embeddingPointsLoader=createEngine3dLoader({entry:"points",tag:tag("embedding-explorer"),load:()=>(async()=>{try{return await import("@aceshooting/lyra-3d/points")}catch(e){throw e}})()}),embeddingEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas"))};class EmbeddingEngineController{constructor(host,changed,fallback,pick){this.host=host,this.changed=changed,this.fallback=fallback,this.pick=pick,this.selection=new Engine3dSelection(!0),this.notice=null,this.loading=!1,this.ready=!1,this.software=!1,this.generation=0,this.revision=0,this.disposed=new WeakSet,this.rows=null,this.container=null,this.intersecting=!1,this.pending=!1,this.attempted=!1,this.preference="builtin",this.sourceMode=!1,this.mediaCleanup=[],this.hover=-1,this.selected=-1,this.focus=-1}dispose(engine){if(!(!engine||this.disposed.has(engine))){this.disposed.add(engine);try{engine.dispose()}catch{}}}releaseEngine(){const generation=++this.generation;this.observer?.disconnect(),this.observer=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.intersecting=!1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.styleObserver?.disconnect(),this.styleObserver=void 0;for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;return this.engine=void 0,this.ready=this.loading=this.pending=!1,this.software=!1,this.hover=-1,this.dispose(engine),generation}invalidate(){this.invalidateCycle()}invalidateCycle(){const generation=this.releaseEngine();return generation!==this.generation||(this.attempted=!1,this.selection.prefer(this.preference),this.notice=null),generation}disconnect(){this.invalidateCycle()===this.generation&&(this.container=null,this.rows=null)}update(preference,rows,sourceMode,container,selected,focus){if(preference!==this.preference||rows!==this.rows||sourceMode!==this.sourceMode||container!==this.container){if(this.invalidateCycle()!==this.generation)return;this.preference=preference,this.rows=rows,this.sourceMode=sourceMode,this.container=container,this.selection.prefer(preference),this.notice=null}if(this.selected=selected,this.focus=focus,preference!=="webgl"||!this.host.isConnected)return;if(sourceMode){this.attempted||(this.attempted=!0,this.fail("unsupported"));return}if(!rows?.count||!container)return;if(this.engine&&this.ready){const generation2=this.generation;try{this.engine.setStyle(this.style()),generation2===this.generation&&this.syncState()}catch{generation2===this.generation&&this.fail("error")}return}if(this.pending||this.attempted||this.selection.renderer!=="webgl"||this.observer||this.eligibility)return;const view=this.host.ownerDocument.defaultView,generation=this.generation;this.intersecting=view?.IntersectionObserver===void 0;const admit=()=>{generation!==this.generation||this.pending||this.attempted||!this.intersecting||!isAccessibilityVisible(this.host)||(this.observer?.disconnect(),this.observer=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.start())};if(view?.IntersectionObserver&&(this.observer=new view.IntersectionObserver(entries=>{if(generation===this.generation){for(const entry of entries)entry.target===container&&(this.intersecting=entry.isIntersecting);admit()}}),this.observer.observe(container)),view?.MutationObserver){this.eligibility=new view.MutationObserver(admit);let ancestor=this.host,depth=0;for(;ancestor&&depth++<=256;){this.eligibility.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","inert","hidden","style","class","open"]});const root=ancestor.getRootNode();ancestor=ancestor.assignedSlot??ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}admit()}fail(reason){const detail=this.selection.renderer==="webgl"?this.selection.fail(reason):null;if(this.loading=this.ready=!1,reason!=="context-lost"){if(this.releaseEngine()!==this.generation)return;this.attempted=!0}detail&&(this.notice=detail,this.changed(),this.fallback(detail))}syncState(){this.engine?.setState?.({selected:new Set(this.selected<0?[]:[this.selected]),dimmed:new Set,hover:this.hover,focus:this.focus})}async start(){const container=this.container,rows=this.rows,owner=this.host.ownerDocument;if(!container||!rows||!this.host.isConnected||this.preference!=="webgl")return;const generation=this.generation,current=()=>generation===this.generation&&this.host.isConnected&&this.host.ownerDocument===owner&&this.container===container;if(this.attempted=this.pending=!0,!embeddingEngineEnvironment.available(owner)){this.pending=!1,this.fail("unsupported");return}this.loading=!0,this.changed();let engine=null;try{if(engine=await embeddingPointsLoader.create(),!current()){this.dispose(engine);return}if(!engine){this.pending=!1,this.fail("unavailable");return}if(this.engine=engine,await engine.mount(container,{hover:index=>{if(!(!current()||!this.ready)){this.hover=index!==null&&rows.point(index)?index:-1;try{this.syncState()}catch{current()&&this.fail("error")}}},pick:index=>{current()&&this.ready&&index!==null&&rows.point(index)&&this.pick(index)},camera:()=>{},lost:reason=>{current()&&this.fail(reason)},rendering:info=>{current()&&(this.software=info.software,this.changed())},restored:()=>{if(!(!current()||!this.engine||!this.selection.restore()))try{this.ready=!0,this.notice=null,this.syncState(),current()&&this.changed()}catch{current()&&this.fail("error")}}}),!current()){this.dispose(engine);return}if(engine.setStyle(this.style()),!current()||(engine.setData(rows.data(),++this.revision),!current()))return;const resize=()=>{if(!current())return;const box=container.getBoundingClientRect();engine.resize(Math.max(1,box.width),Math.max(1,box.height))};if(resize(),!current()||(engine.fit?.(),!current()))return;const view=owner.defaultView;view?.ResizeObserver&&(this.resizeObserver=new view.ResizeObserver(()=>{if(!(!current()||!this.ready))try{engine.setStyle(this.style()),resize()}catch{current()&&this.fail("error")}}),this.resizeObserver.observe(container));const refreshStyle=()=>{if(!(!current()||!this.ready))try{engine.setStyle(this.style())}catch{current()&&this.fail("error")}};if(view?.MutationObserver){this.styleObserver=new view.MutationObserver(refreshStyle);let ancestor=this.host;for(;ancestor;){this.styleObserver.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view?.matchMedia(query);media?.addEventListener("change",refreshStyle),media&&this.mediaCleanup.push(()=>media.removeEventListener("change",refreshStyle))}this.pending=this.loading=!1,this.ready=this.selection.renderer==="webgl",this.syncState(),current()&&this.changed()}catch(error){if(!current()){this.dispose(engine);return}this.fail(engine3dFailureReason(error))}}style(){const view=this.host.ownerDocument.defaultView,computed=view.getComputedStyle(this.host),canvas=this.host.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=name=>{const resolved=resolveCanvasColor(this.host,`var(${name})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:Array.from({length:8},(_,index)=>color(`--lr-color-chart-${index+1}`)),fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:12,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}}export{EmbeddingEngineController,embeddingEngineEnvironment,embeddingPointsLoader};
|