@aceshooting/lyra-ui 28.1.0 → 28.1.2
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 +65 -0
- package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
- package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
- package/dist/components/charts/chart/box-plot.class.d.ts +2 -2
- package/dist/components/charts/chart/box-plot.class.js +14 -14
- package/dist/components/charts/chart/chart.class.d.ts +2 -2
- package/dist/components/charts/chart/chart.class.js +14 -14
- package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +8 -8
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.d.ts +2 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/data-grid/data-grid-processing.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/gauge/gauge.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
- package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +2 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/stat/stat.class.d.ts +11 -9
- package/dist/components/data/stat/stat.class.js +4 -2
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/select/select.class.js +4 -3
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/details/accordion.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.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/graph-legend/graph-legend.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/utility/tour/tour.class.js +4 -4
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- package/dist/internal/overlay-manager.d.ts +2 -0
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-push-to-talk.md +3 -0
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-stat.md +4 -0
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +44 -0
- package/llms/shared.md +44 -0
- package/package.json +5 -5
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{isAriaTrue}from"../../../internal/accessibility-visibility.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./page.styles.js";import{LYRA_DEFAULT_closeNavigation,LYRA_DEFAULT_openNavigation,LYRA_DEFAULT_skipToContent}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MOBILE_BREAKPOINT="768px";class LyraPage extends LyraElement{constructor(){super(...arguments),this.view="desktop",this.navOpen=!1,this.mobileBreakpoint="768px",this.navigationPlacement="start",this.disableNavigationToggle=!1,this.accessibleLabel=null,this.mainId=nextId("page-main"),this.navigationId=nextId("page-navigation"),this.drawerId=nextId("page-drawer"),this.skipTargetId=nextId("page-skip-target"),this.skipLabelId=nextId("page-skip-label"),this.fragmentTargetId=this.getAttribute("id")||this.skipTargetId,this.fragmentTabIndex=this.getAttribute("tabindex")??"-1",this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation(),this.navOpen&&this.view==="mobile"&&this.nativeModal.show()}}),this.navigationOpener=null,this.customToggles=[],this.customToggleOwnership=new Map,this.onWindowResize=()=>this.measureAllocation(),this.navigationDeferredReturn=()=>{const owner=this.navigationTriggerOwner,opener=owner?null:this.navigationOpener;if(this.navigationOpener=null,!(!owner&&!opener))return{candidates:()=>[owner?.isConnected?resolveAccessibleTrigger(owner):null,opener,this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]'),this.mainElement],stranded:active=>!!this.drawerElement&&composedContains(this.drawerElement,active),isCurrent:()=>!this.navOpen}},this.resolveNavigationRestoreTarget=()=>{const owner=this.navigationTriggerOwner;if(owner?.isConnected){const accessible=resolveAccessibleTrigger(owner);if(isComposedFocusAvailable(accessible))return accessible}const builtIn=this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]');return builtIn&&isComposedFocusAvailable(builtIn)?builtIn:this.mainElement&&isComposedFocusAvailable(this.mainElement)?this.mainElement:null},this.onDefaultToggleClick=event=>{this.rememberTriggerAndToggle(event.currentTarget)},this.onToggleSlotClick=event=>{const trigger=event.composedPath().find(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle");trigger&&this.customToggles.includes(trigger)&&!this.isUnavailableCustomToggle(trigger)&&this.rememberTriggerAndToggle(trigger)},this.onPageClick=event=>{const path=event.composedPath();if(path.some(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle"))return;const trigger=path.find(candidate=>candidate?.nodeType===1&&candidate.hasAttribute("data-toggle-nav"));trigger&&this.rememberTriggerAndToggle(trigger)},this.onBackdropClick=event=>{event.target===event.currentTarget&&this.overlayHandle?.dismissBackdrop()},this.onSkipClick=event=>{event.preventDefault(),this.mainElement?.focus(),this.mainElement?.scrollIntoView({block:"start"})}}static{this.defaultStrings={...super.defaultStrings,closeNavigation:LYRA_DEFAULT_closeNavigation,navigation:LYRA_DEFAULT_navigation,openNavigation:LYRA_DEFAULT_openNavigation,skipToContent:LYRA_DEFAULT_skipToContent}}static{this.knownUnobservedAttributes=["disable-sticky"]}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.nativeModal.hide(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.releaseCustomToggleA11y(),super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.measureAllocation(),this.observeAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.nativeModal.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.nativeModal.hide(),this.nativeModal.prepare(!1)),changed.has("fragmentTargetId")&&!this.fragmentTargetId&&(this.fragmentTargetId=this.skipTargetId),changed.has("fragmentTabIndex")&&this.fragmentTabIndex===null&&(this.fragmentTabIndex="-1")}updated(changed){super.updated(changed),this.view==="mobile"&&this.navOpen&&this.nativeModal.show();const describedBy=this.view==="mobile"&&this.navOpen?this.getAttribute("aria-describedby"):null;for(const dialog of this.renderRoot.querySelectorAll('[part="drawer"], [data-native-modal-carrier]'))syncAriaDescribedByElements(this,dialog,describedBy);changed.has("mobileBreakpoint")&&changed.get("mobileBreakpoint")!==void 0&&this.measureAllocation(),this.overlayHandle!==void 0&&(!this.isConnected||this.view!=="mobile"||!this.navOpen)?(this.syncOverlay(changed),this.syncCustomToggle()):(this.syncCustomToggle(),this.syncOverlay(changed))}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&view?.requestAnimationFrame(()=>{this.isConnected&&this.applyMeasuredInlineSize(inlineSize)})}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const width=this.getBoundingClientRect().width;width>0&&this.applyMeasuredInlineSize(width)}applyMeasuredInlineSize(width){if(!Number.isFinite(width)||width<0)return;const resolved=resolveCssLength(this.mobileBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_MOBILE_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback),next=width<=breakpoint?"mobile":"desktop";next!==this.view&&(this.view=next)}syncOverlay(changed){if(this.isConnected&&this.view==="mobile"&&this.navOpen){if(this.overlayHandle?.isActive()){this.overlayHandle.resume(),this.navigationTriggerOwner&&this.overlayHandle.updateRestoreFocusTo(this.resolveNavigationRestoreTarget);return}const active=deepActiveElement(this.ownerDocument);this.navigationOpener=active&&typeof active.focus=="function"&&!(this.drawerElement&&composedContains(this.drawerElement,active))?active:null,this.overlayHandle=activateOverlay({host:this,panel:()=>this.drawerElement??null,modalRoot:()=>this.drawerElement??null,onEscape:()=>this.hideNavigation(),onBackdrop:()=>this.hideNavigation(),...this.navigationTriggerOwner?{restoreFocusTo:this.resolveNavigationRestoreTarget}:{},lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:this.navigationDeferredReturn}),this.overlayHandle.focusInitial();return}if(this.overlayHandle){const restoreFocus=!!(changed?.has("navOpen")&&!this.navOpen);this.overlayHandle.deactivate({restoreFocus}),this.overlayHandle=void 0}this.navOpen||(this.navigationTriggerOwner=void 0)}syncCustomToggle(){const nextToggles=(this.shadowRoot?.querySelector('slot[name="navigation-toggle"]')?.assignedElements({flatten:!0})??[]).filter(candidate=>candidate.nodeType===1&&candidate.getRootNode()!==this.shadowRoot),previous=this.customToggle;this.customToggles=nextToggles,this.customToggle=nextToggles[0];for(const[host,ownership]of this.customToggleOwnership)nextToggles.includes(host)||(ownership.accessibleAria?.release(),ownership.hostAria.release(),this.customToggleOwnership.delete(host));const localizedLabel=this.localize(this.navOpen?"closeNavigation":"openNavigation"),drawer=this.drawerElement;for(const host of nextToggles){const accessible=resolveAccessibleTrigger(host);let ownership=this.customToggleOwnership.get(host);ownership?accessible!==ownership.accessible&&(ownership.accessibleAria?.release(),ownership.accessibleAria=void 0,ownership.accessible=accessible,ownership.accessibleAuthoredLabel=accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null):(ownership={accessible,accessibleAuthoredLabel:accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null,hostAria:acquireAriaOwnership(null,{}),hostAuthoredLabel:host.hasAttribute("aria-label")?host.getAttribute("aria-label")??"":null},this.customToggleOwnership.set(host,ownership)),ownership.hostAria.update(host,{attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]});const distinctAccessible=accessible===host?null:accessible,accessibleContribution={attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.accessibleAuthoredLabel??ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]};ownership.accessibleAria?ownership.accessibleAria.update(distinctAccessible,accessibleContribution):ownership.accessibleAria=acquireAriaOwnership(distinctAccessible,accessibleContribution)}this.navOpen&&this.navigationTriggerOwner&&!nextToggles.includes(this.navigationTriggerOwner)?(this.navigationTriggerOwner=this.customToggle,this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)):this.navOpen&&previous&&this.navigationTriggerOwner===previous&&this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)}releaseCustomToggleA11y(){for(const ownership of this.customToggleOwnership.values())ownership.accessibleAria?.release(),ownership.hostAria.release();this.customToggleOwnership.clear(),this.customToggle=void 0,this.customToggles=[]}isUnavailableCustomToggle(trigger){const accessible=resolveAccessibleTrigger(trigger);return[trigger,accessible].some(candidate=>candidate.hasAttribute("hidden")||candidate.hasAttribute("inert")||candidate.matches(":disabled")||isAriaTrue(candidate.getAttribute("aria-hidden"))||isAriaTrue(candidate.getAttribute("aria-disabled")))}rememberTriggerAndToggle(trigger){this.syncCustomToggle(),this.navOpen||(this.navigationTriggerOwner=trigger),this.toggleNavigation()}requestNavOpen(next){this.navOpen===next||this.emit("lr-nav-toggle-request",{open:next},{cancelable:!0}).defaultPrevented||(this.navOpen=next,this.emit("lr-nav-open-change",{open:next}))}showNavigation(){this.requestNavOpen(!0)}hideNavigation(){this.requestNavOpen(!1)}toggleNavigation(){this.requestNavOpen(!this.navOpen)}visiblePixelsInViewport(element){if(!element)return 0;const rect=element.getBoundingClientRect();if(!Number.isFinite(rect.top)||!Number.isFinite(rect.bottom))return 0;const candidateHeight=element.ownerDocument.defaultView?.innerHeight??element.ownerDocument.documentElement.clientHeight;if(!Number.isFinite(candidateHeight)||candidateHeight<=0)return 0;const viewportHeight=finiteRange(candidateHeight,0,0),visible=Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0);return finiteRange(visible,0,0,viewportHeight)}render(){const mobile=this.view==="mobile",overlayOpen=mobile&&this.navOpen,navigationLabel=this.accessibleLabel??this.localize("navigation");return html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{isAriaTrue}from"../../../internal/accessibility-visibility.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{OwnedFrame}from"../../../internal/owned-timer.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./page.styles.js";import{LYRA_DEFAULT_closeNavigation,LYRA_DEFAULT_openNavigation,LYRA_DEFAULT_skipToContent}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MOBILE_BREAKPOINT="768px";class LyraPage extends LyraElement{constructor(){super(...arguments),this.view="desktop",this.navOpen=!1,this.mobileBreakpoint="768px",this.navigationPlacement="start",this.disableNavigationToggle=!1,this.accessibleLabel=null,this.mainId=nextId("page-main"),this.navigationId=nextId("page-navigation"),this.drawerId=nextId("page-drawer"),this.skipTargetId=nextId("page-skip-target"),this.skipLabelId=nextId("page-skip-label"),this.fragmentTargetId=this.getAttribute("id")||this.skipTargetId,this.fragmentTabIndex=this.getAttribute("tabindex")??"-1",this.allocationFrame=new OwnedFrame(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation(),this.navOpen&&this.view==="mobile"&&this.nativeModal.show()}}),this.navigationOpener=null,this.customToggles=[],this.customToggleOwnership=new Map,this.onWindowResize=()=>this.measureAllocation(),this.navigationDeferredReturn=()=>{const owner=this.navigationTriggerOwner,opener=owner?null:this.navigationOpener;if(this.navigationOpener=null,!(!owner&&!opener))return{candidates:()=>[owner?.isConnected?resolveAccessibleTrigger(owner):null,opener,this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]'),this.mainElement],stranded:active=>!!this.drawerElement&&composedContains(this.drawerElement,active),isCurrent:()=>!this.navOpen}},this.resolveNavigationRestoreTarget=()=>{const owner=this.navigationTriggerOwner;if(owner?.isConnected){const accessible=resolveAccessibleTrigger(owner);if(isComposedFocusAvailable(accessible))return accessible}const builtIn=this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]');return builtIn&&isComposedFocusAvailable(builtIn)?builtIn:this.mainElement&&isComposedFocusAvailable(this.mainElement)?this.mainElement:null},this.onDefaultToggleClick=event=>{this.rememberTriggerAndToggle(event.currentTarget)},this.onToggleSlotClick=event=>{const trigger=event.composedPath().find(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle");trigger&&this.customToggles.includes(trigger)&&!this.isUnavailableCustomToggle(trigger)&&this.rememberTriggerAndToggle(trigger)},this.onPageClick=event=>{const path=event.composedPath();if(path.some(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle"))return;const trigger=path.find(candidate=>candidate?.nodeType===1&&candidate.hasAttribute("data-toggle-nav"));trigger&&this.rememberTriggerAndToggle(trigger)},this.onBackdropClick=event=>{event.target===event.currentTarget&&this.overlayHandle?.dismissBackdrop()},this.onSkipClick=event=>{event.preventDefault(),this.mainElement?.focus(),this.mainElement?.scrollIntoView({block:"start"})}}static{this.defaultStrings={...super.defaultStrings,closeNavigation:LYRA_DEFAULT_closeNavigation,navigation:LYRA_DEFAULT_navigation,openNavigation:LYRA_DEFAULT_openNavigation,skipToContent:LYRA_DEFAULT_skipToContent}}static{this.knownUnobservedAttributes=["disable-sticky"]}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.nativeModal.hide(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.allocationFrame.cancel(),this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.releaseCustomToggleA11y(),super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.measureAllocation(),this.observeAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.nativeModal.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.nativeModal.hide(),this.nativeModal.prepare(!1)),changed.has("fragmentTargetId")&&!this.fragmentTargetId&&(this.fragmentTargetId=this.skipTargetId),changed.has("fragmentTabIndex")&&this.fragmentTabIndex===null&&(this.fragmentTabIndex="-1")}updated(changed){super.updated(changed),this.view==="mobile"&&this.navOpen&&this.nativeModal.show();const describedBy=this.view==="mobile"&&this.navOpen?this.getAttribute("aria-describedby"):null;for(const dialog of this.renderRoot.querySelectorAll('[part="drawer"], [data-native-modal-carrier]'))syncAriaDescribedByElements(this,dialog,describedBy);changed.has("mobileBreakpoint")&&changed.get("mobileBreakpoint")!==void 0&&this.measureAllocation(),this.overlayHandle!==void 0&&(!this.isConnected||this.view!=="mobile"||!this.navOpen)?(this.syncOverlay(changed),this.syncCustomToggle()):(this.syncCustomToggle(),this.syncOverlay(changed))}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){if(!this.resizeObserver){const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view||this.resizeObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&this.allocationFrame.schedule(()=>this.applyMeasuredInlineSize(inlineSize))});this.resizeObserver=observer}this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const width=this.getBoundingClientRect().width;width>0&&this.applyMeasuredInlineSize(width)}applyMeasuredInlineSize(width){if(!Number.isFinite(width)||width<0)return;const resolved=resolveCssLength(this.mobileBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_MOBILE_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback),next=width<=breakpoint?"mobile":"desktop";next!==this.view&&(this.view=next)}syncOverlay(changed){if(this.isConnected&&this.view==="mobile"&&this.navOpen){if(this.overlayHandle?.isActive()){this.overlayHandle.resume(),this.navigationTriggerOwner&&this.overlayHandle.updateRestoreFocusTo(this.resolveNavigationRestoreTarget);return}const active=deepActiveElement(this.ownerDocument);this.navigationOpener=active&&typeof active.focus=="function"&&!(this.drawerElement&&composedContains(this.drawerElement,active))?active:null,this.overlayHandle=activateOverlay({host:this,panel:()=>this.drawerElement??null,modalRoot:()=>this.drawerElement??null,onEscape:()=>this.hideNavigation(),onBackdrop:()=>this.hideNavigation(),...this.navigationTriggerOwner?{restoreFocusTo:this.resolveNavigationRestoreTarget}:{},lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:this.navigationDeferredReturn}),this.overlayHandle.focusInitial();return}if(this.overlayHandle){const restoreFocus=!!(changed?.has("navOpen")&&!this.navOpen);this.overlayHandle.deactivate({restoreFocus}),this.overlayHandle=void 0}this.navOpen||(this.navigationTriggerOwner=void 0)}syncCustomToggle(){const nextToggles=(this.shadowRoot?.querySelector('slot[name="navigation-toggle"]')?.assignedElements({flatten:!0})??[]).filter(candidate=>candidate.nodeType===1&&candidate.getRootNode()!==this.shadowRoot),previous=this.customToggle;this.customToggles=nextToggles,this.customToggle=nextToggles[0];const nextToggleSet=new Set(nextToggles);for(const[host,ownership]of this.customToggleOwnership)nextToggleSet.has(host)||(ownership.accessibleAria?.release(),ownership.hostAria.release(),this.customToggleOwnership.delete(host));const localizedLabel=this.localize(this.navOpen?"closeNavigation":"openNavigation"),drawer=this.drawerElement;for(const host of nextToggles){const accessible=resolveAccessibleTrigger(host);let ownership=this.customToggleOwnership.get(host);ownership?accessible!==ownership.accessible&&(ownership.accessibleAria?.release(),ownership.accessibleAria=void 0,ownership.accessible=accessible,ownership.accessibleAuthoredLabel=accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null):(ownership={accessible,accessibleAuthoredLabel:accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null,hostAria:acquireAriaOwnership(null,{}),hostAuthoredLabel:host.hasAttribute("aria-label")?host.getAttribute("aria-label")??"":null},this.customToggleOwnership.set(host,ownership)),ownership.hostAria.update(host,{attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]});const distinctAccessible=accessible===host?null:accessible,accessibleContribution={attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.accessibleAuthoredLabel??ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]};ownership.accessibleAria?ownership.accessibleAria.update(distinctAccessible,accessibleContribution):ownership.accessibleAria=acquireAriaOwnership(distinctAccessible,accessibleContribution)}this.navOpen&&this.navigationTriggerOwner&&!nextToggles.includes(this.navigationTriggerOwner)?(this.navigationTriggerOwner=this.customToggle,this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)):this.navOpen&&previous&&this.navigationTriggerOwner===previous&&this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)}releaseCustomToggleA11y(){for(const ownership of this.customToggleOwnership.values())ownership.accessibleAria?.release(),ownership.hostAria.release();this.customToggleOwnership.clear(),this.customToggle=void 0,this.customToggles=[]}isUnavailableCustomToggle(trigger){const accessible=resolveAccessibleTrigger(trigger);return[trigger,accessible].some(candidate=>candidate.hasAttribute("hidden")||candidate.hasAttribute("inert")||candidate.matches(":disabled")||isAriaTrue(candidate.getAttribute("aria-hidden"))||isAriaTrue(candidate.getAttribute("aria-disabled")))}rememberTriggerAndToggle(trigger){this.syncCustomToggle(),this.navOpen||(this.navigationTriggerOwner=trigger),this.toggleNavigation()}requestNavOpen(next){this.navOpen===next||this.emit("lr-nav-toggle-request",{open:next},{cancelable:!0}).defaultPrevented||(this.navOpen=next,this.emit("lr-nav-open-change",{open:next}))}showNavigation(){this.requestNavOpen(!0)}hideNavigation(){this.requestNavOpen(!1)}toggleNavigation(){this.requestNavOpen(!this.navOpen)}visiblePixelsInViewport(element){if(!element)return 0;const rect=element.getBoundingClientRect();if(!Number.isFinite(rect.top)||!Number.isFinite(rect.bottom))return 0;const candidateHeight=element.ownerDocument.defaultView?.innerHeight??element.ownerDocument.documentElement.clientHeight;if(!Number.isFinite(candidateHeight)||candidateHeight<=0)return 0;const viewportHeight=finiteRange(candidateHeight,0,0),visible=Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0);return finiteRange(visible,0,0,viewportHeight)}render(){const mobile=this.view==="mobile",overlayOpen=mobile&&this.navOpen,navigationLabel=this.accessibleLabel??this.localize("navigation");return html`
|
|
2
2
|
<div part="base page" @click=${this.onPageClick}>
|
|
3
3
|
<a
|
|
4
4
|
part="skip-to-content"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{activateOverlay,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./responsive-panel.styles.js";import{resolveResponsivePanelEffectiveMode}from"./responsive-panel-mode.js";import{LYRA_DEFAULT_responsivePanel}from"../../../internal/default-strings/layout.generated.js";import{resolveResponsivePanelEffectiveMode as resolveResponsivePanelEffectiveMode2}from"./responsive-panel-mode.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]',DEFAULT_OVERLAY_BREAKPOINT="768px",RESPONSIVE_PANEL_MODE=literalSetConverter(["inline","overlay","auto"],"auto");class LyraResponsivePanel extends LyraElement{constructor(){super(...arguments),this.open=!1,this._mode="auto",this.shape="fullscreen",this.label="",this.overlayBreakpoint=DEFAULT_OVERLAY_BREAKPOINT,this.accessibleLabel=null,this.belowBreakpoint=!1,this.resolvedMode="inline",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.close("escape"),this.open&&this.nativeModal.show()}}),this.headerObserverGeneration=0,this.ownerRealmGeneration=0,this.overlayChromeActive=!1,this.focusOverlayAfterUpdate=!1,this.isFirstUpdate=!0,this.onWindowResize=()=>this.measureAllocation(),this.onHeaderSlotChange=e=>{this.syncHeaderSlot(e.target.assignedElements({flatten:!0}))},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,responsivePanel:LYRA_DEFAULT_responsivePanel}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}get mode(){return this._mode}set mode(next){const normalized=RESPONSIVE_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get effectiveMode(){return this.resolvedMode}willUpdate(changed){if(super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,this.isFirstUpdate&&(this.headingText=this.detectHeadingText()),!this.isFirstUpdate&&changed.has("overlayBreakpoint")&&this.isConnected&&this.measureAllocation(),(this.isFirstUpdate||changed.has("mode")||changed.has("belowBreakpoint"))&&(this.resolvedMode=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)),changed.has("open")&&this.open){const active=deepActiveElement(this.ownerDocument);this.lastTrigger=active&&typeof active.focus=="function"?active:void 0}const overlayOpen=this.resolvedMode==="overlay"&&this.open;if(overlayOpen!==this.overlayChromeActive)if(this.overlayChromeActive=overlayOpen,overlayOpen)this.activateOverlayChrome(),this.focusOverlayAfterUpdate=!0;else{const restoreFocus=changed.has("open")&&!this.open;this.deactivateOverlayChrome(restoreFocus)}changed.has("open")&&!this.open&&(this.lastTrigger=void 0)}updated(changed){super.updated(changed),this.open&&this.nativeModal.show(),!this.isFirstUpdate&&changed.has("resolvedMode")&&this.emit("lr-mode-change",{mode:this.resolvedMode}),this.focusOverlayAfterUpdate&&(this.focusOverlayAfterUpdate=!1,this.overlayHandle?.focusInitial())}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation();const overlayOpen=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)==="overlay"&&this.open;this.hasUpdated&&overlayOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateOverlayChrome(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="header"]');slot&&this.syncHeaderSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{activateOverlay,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./responsive-panel.styles.js";import{resolveResponsivePanelEffectiveMode}from"./responsive-panel-mode.js";import{LYRA_DEFAULT_responsivePanel}from"../../../internal/default-strings/layout.generated.js";import{resolveResponsivePanelEffectiveMode as resolveResponsivePanelEffectiveMode2}from"./responsive-panel-mode.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]',DEFAULT_OVERLAY_BREAKPOINT="768px",RESPONSIVE_PANEL_MODE=literalSetConverter(["inline","overlay","auto"],"auto");class LyraResponsivePanel extends LyraElement{constructor(){super(...arguments),this.open=!1,this._mode="auto",this.shape="fullscreen",this.label="",this.overlayBreakpoint=DEFAULT_OVERLAY_BREAKPOINT,this.accessibleLabel=null,this.belowBreakpoint=!1,this.resolvedMode="inline",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.close("escape"),this.open&&this.nativeModal.show()}}),this.headerObserverGeneration=0,this.ownerRealmGeneration=0,this.overlayChromeActive=!1,this.focusOverlayAfterUpdate=!1,this.isFirstUpdate=!0,this.onWindowResize=()=>this.measureAllocation(),this.onHeaderSlotChange=e=>{this.syncHeaderSlot(e.target.assignedElements({flatten:!0}))},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,responsivePanel:LYRA_DEFAULT_responsivePanel}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}get mode(){return this._mode}set mode(next){const normalized=RESPONSIVE_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get effectiveMode(){return this.resolvedMode}willUpdate(changed){if(super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,this.isFirstUpdate&&(this.headingText=this.detectHeadingText()),!this.isFirstUpdate&&changed.has("overlayBreakpoint")&&this.isConnected&&this.measureAllocation(),(this.isFirstUpdate||changed.has("mode")||changed.has("belowBreakpoint"))&&(this.resolvedMode=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)),changed.has("open")&&this.open){const active=deepActiveElement(this.ownerDocument);this.lastTrigger=active&&typeof active.focus=="function"?active:void 0}const overlayOpen=this.resolvedMode==="overlay"&&this.open;if(overlayOpen!==this.overlayChromeActive)if(this.overlayChromeActive=overlayOpen,overlayOpen)this.activateOverlayChrome(),this.focusOverlayAfterUpdate=!0;else{const restoreFocus=changed.has("open")&&!this.open;this.deactivateOverlayChrome(restoreFocus)}changed.has("open")&&!this.open&&(this.lastTrigger=void 0)}updated(changed){super.updated(changed),this.open&&this.nativeModal.show(),!this.isFirstUpdate&&changed.has("resolvedMode")&&this.emit("lr-mode-change",{mode:this.resolvedMode}),this.focusOverlayAfterUpdate&&(this.focusOverlayAfterUpdate=!1,this.overlayHandle?.focusInitial())}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation();const overlayOpen=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)==="overlay"&&this.open;this.hasUpdated&&overlayOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateOverlayChrome(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="header"]');slot&&this.syncHeaderSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork();const resizeObserver=this.resizeObserver;this.resizeObserver=void 0;const resizeView=this.resizeView;this.resizeView=void 0,resizeObserver?.disconnect(),resizeView?.removeEventListener("resize",this.onWindowResize),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.nativeModal.hide(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.resetOwnerRealmWork(),this.isConnected&&(this.measureAllocation(),this.observeAllocation())}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetHeaderObserver()}queueOwnerMicrotask(callback,nextFrame=!1){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,run=()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()};nextFrame?ownerWindow.requestAnimationFrame(run):ownerWindow.queueMicrotask(run)}activateOverlayChrome(){this.nativeModal.prepare(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),restoreFocusTo:this.lastTrigger??null,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.lastTrigger;return opener?{candidates:()=>[opener],isCurrent:()=>!this.open}:void 0}})}deactivateOverlayChrome(restoreFocus=!0){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&this.queueOwnerMicrotask(()=>this.applyMeasuredInlineSize(inlineSize),!0)}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const inlineSize=this.getBoundingClientRect().width;inlineSize>0&&this.applyMeasuredInlineSize(inlineSize)}applyMeasuredInlineSize(inlineSize){if(!Number.isFinite(inlineSize)||inlineSize<0)return;const resolved=resolveCssLength(this.overlayBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_OVERLAY_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback);this.belowBreakpoint=inlineSize<=breakpoint}syncHeaderSlot(assigned){if(this.headingText=this.detectHeadingText(),this.resetHeaderObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headerObserverGeneration,observer=new MutationObserverCtor(()=>{this.headerObserver!==observer||this.headerObserverDocument!==ownerDocument||this.headerObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.headingText=this.detectHeadingText())});this.headerObserver=observer,this.headerObserverDocument=ownerDocument;for(const element of assigned)observer.observe(element,{childList:!0,characterData:!0,subtree:!0})}resetHeaderObserver(){this.headerObserverGeneration+=1,this.headerObserver?.disconnect(),this.headerObserver=void 0,this.headerObserverDocument=void 0}detectHeadingText(){const headerChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="header");if(headerChildren.length===0)return;const heading=headerChildren.find(el=>el.matches(HEADING_SELECTOR));return heading?heading.textContent?.trim()||void 0:headerChildren.map(el=>el.textContent?.trim()).filter(Boolean).join(" ")||void 0}close(reason="api"){this.open&&(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-close",{reason})))}show(){this.open=!0}hide(){this.close()}render(){const overlay=this.effectiveMode==="overlay",accessibleName=this.accessibleLabel??(this.label||this.headingText||this.localize("responsivePanel"));return this.nativeModal.render(html`
|
|
2
2
|
<div part="base" class=${overlay?"overlay":"inline"}>
|
|
3
3
|
${overlay?html`<div part="backdrop" @click=${this.onBackdropClick}></div>`:nothing}
|
|
4
4
|
<div
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./tab-group.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious}from"../../../internal/default-strings/layout.generated.js";function isInertChild(child){return isHtmlElement(child)&&child.inert}function isTabLabelSubtreeExcludedWithoutInert(element){if(element.hasAttribute("hidden")||element.getAttribute("aria-hidden")?.trim().toLowerCase()==="true")return!0;const rendered=element.ownerDocument.defaultView?.getComputedStyle(element);return rendered?.display==="none"||rendered?.contentVisibility==="hidden"}const SYNTHETIC_PANEL_PREFIX="lr-tab-",SCROLL_STEP_RATIO=.8;class LyraTabGroup extends LyraElement{constructor(){super(...arguments),this.active="",this.accessibleLabel=null,this.placement="top",this.activation="auto",this.withoutScrollControls=!1,this.noScrollControls=!1,this.fixedScrollControls=!1,this.tabs=[],this.focusedTab="",this.baseId=nextId("tab-group"),this.nextOpaqueId=0,this.idsBySlot=new Map,this.mutationObserverGeneration=0,this.projectedSourceSnapshots=new Map,this.projectedSlotSnapshots=new Map,this.projectedSourceObserverGeneration=0,this.rehomeTabFocus=!1,this.scrollStartAvailable=!1,this.scrollEndAvailable=!1,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="tablist"]'),()=>this.measureTabScrollEdges()),this.syncTabs=()=>{const children=Array.from(this.children);this.adoptProjectedSourceInertStates(),this.adoptProjectedSlotStates();const projectedSlots=new Set,next=this.readElementModel(children,projectedSlots);this.syncProjectedSlots(projectedSlots),this.syncProjectedSources(next);const liveSlots=new Set(next.map(tab=>tab.slotName));for(const slotName of this.idsBySlot.keys())liveSlots.has(slotName)||this.idsBySlot.delete(slotName);this.tabs=next},this.onTabListKeyDown=e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const navigable=this.tabs.filter(t=>this.isNavigable(t));if(navigable.length===0)return;const origin=this.keyboardOriginTab(e,navigable),currentIndex=origin?navigable.indexOf(origin):-1;if(e.key==="Delete"){if(!origin?.element.closable)return;e.preventDefault(),origin.element.requestCloseFromOwner();return}if(this.activation==="manual"&&(e.key==="Enter"||e.key===" "||e.key==="Spacebar")){if(!origin)return;e.preventDefault(),this.activateTab(origin);return}const targetIndex=resolveListMove(e,{count:navigable.length,current:currentIndex,orientation:this.isVertical?"vertical":"horizontal",direction:this.effectiveDirection});if(targetIndex===null)return;e.preventDefault();const target=navigable[targetIndex];if(this.activation==="manual"){this.focusOnly(target);return}this.activateTab(target),this.focusTab(target.slotName)},this.onTabListScroll=()=>{this.measureTabScrollEdges()},this.onScrollControlMouseDown=event=>{event.preventDefault()},this.onScrollControlPointerDown=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.setAttribute("data-pressed",""),control.setPointerCapture(event.pointerId))},this.onScrollControlPointerEnd=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.removeAttribute("data-pressed"),control.hasPointerCapture(event.pointerId)&&control.releasePointerCapture(event.pointerId))}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious}}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}connectedCallback(){super.connectedCallback(),this.hasUpdated?this.syncTabs():this.seedFirstRenderState(this.syncTabs),this.resetMutationObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.mutationObserverGeneration,observer=new MutationObserverCtor(records=>{if(this.mutationObserver!==observer||this.mutationObserverDocument!==ownerDocument||this.mutationObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const isDirectChild=node=>node.parentNode===this,isElementTabContent=node=>{let current=node.nodeType===1?node:node.parentElement;for(;current&¤t!==this;){if(current.localName===tag("tab")&¤t.parentNode===this)return!0;current=current.parentElement}return!1};records.some(record=>record.type==="childList"?record.target===this||isElementTabContent(record.target):record.type==="characterData"?isElementTabContent(record.target):record.attributeName==="inert"&&this.projectedSourceSnapshots.has(record.target)?!1:isDirectChild(record.target)||isElementTabContent(record.target))&&this.syncTabs()});this.mutationObserver=observer,this.mutationObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","closable","disabled","hidden","inert","id","label","name","open","panel","slot","style"]})}disconnectedCallback(){this.resetMutationObserver(),this.resetProjectedSourceObserver(),this.restoreProjectedSources(),this.restoreProjectedSlots(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMutationObserver(),this.resetProjectedSourceObserver()}resetMutationObserver(){this.mutationObserverGeneration+=1,this.mutationObserver?.disconnect(),this.mutationObserver=void 0,this.mutationObserverDocument=void 0}readElementModel(children,projectedSlots){const seen=new Set,next=[],panels=children.filter(child=>child.localName===tag("tab-panel")),authoredNames=new Set(children.flatMap(child=>{if(child.localName===tag("tab")){const name=child.getAttribute("panel");return name?[name]:[]}if(child.localName===tag("tab-panel")){const name=child.getAttribute("name");return name?[name]:[]}return[]}));let index=0;for(const child of children){if(child.localName!==tag("tab"))continue;const authoredPanel=child.getAttribute("panel")||void 0;let slotName=authoredPanel??`${SYNTHETIC_PANEL_PREFIX}${index}`;if(!authoredPanel){let collision=0;for(;authoredNames.has(slotName)||seen.has(slotName);)collision+=1,slotName=`${SYNTHETIC_PANEL_PREFIX}${index}-${collision}`}if(index+=1,!authoredPanel&&!this.readElementLabel(child,{allowUnprojected:!0})||seen.has(slotName))continue;seen.add(slotName);const tabSlot=this.tabSlotName(slotName);this.projectSlot(child,tabSlot,projectedSlots);const visibleLabel=this.readElementLabel(child);if(!authoredPanel&&!visibleLabel)continue;const label=visibleLabel||slotName,panel=panels.find(candidate=>candidate.getAttribute("name")===slotName);panel&&this.projectSlot(panel,slotName,projectedSlots),next.push({slotName,label,disabled:child.hasAttribute("disabled"),inert:isInertChild(child),element:child}),!this.active&&child.hasAttribute("active")&&(this.active=slotName)}return next}readElementLabel(tab,options={}){const labelNodes=Array.from(tab.childNodes).filter(node=>node.nodeType!==Node.ELEMENT_NODE||node.getAttribute("slot")===null||node.getAttribute("slot")==="");return composedAccessibilityText(labelNodes,{ancestorBoundary:tab,isSubtreeExcluded:element=>this.isTabLabelSubtreeExcluded(element),requireRendered:!options.allowUnprojected,skipRootAncestorValidation:options.allowUnprojected,ignoreInheritedVisibility:!0}).replace(/\s+/g," ").trim()}libraryOwnsSourceInert(element){return this.projectedSourceSnapshots.get(element)?.libraryOwnsInert===!0}isTabLabelSubtreeExcluded(element){return isTabLabelSubtreeExcludedWithoutInert(element)||element.hasAttribute("inert")&&!this.libraryOwnsSourceInert(element)}snapshotProjectedSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert,libraryOwnsInert:!1}}adoptProjectedSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current,snapshot.libraryOwnsInert=!1)}makeProjectedSourceInert(source,snapshot){source.hasAttribute("inert")||(source.setAttribute("inert",""),snapshot.libraryOwnsInert=!0),snapshot.appliedInert=source.getAttribute("inert")}restoreProjectedSource(source,snapshot){this.adoptProjectedSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreProjectedSources(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.restoreProjectedSource(source,snapshot);this.projectedSourceSnapshots.clear()}resetProjectedSourceObserver(){this.projectedSourceObserverGeneration+=1,this.projectedSourceObserver?.disconnect(),this.projectedSourceObserver=void 0,this.projectedSourceObserverDocument=void 0}observeProjectedSources(){this.resetProjectedSourceObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected||this.projectedSourceSnapshots.size===0)return;const generation=this.projectedSourceObserverGeneration,observer=new MutationObserverCtor(records=>{this.projectedSourceObserver!==observer||this.projectedSourceObserverDocument!==ownerDocument||this.projectedSourceObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||records.some(record=>this.projectedSourceSnapshots.has(record.target))&&this.syncTabs()});this.projectedSourceObserver=observer,this.projectedSourceObserverDocument=ownerDocument;for(const source of this.projectedSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}projectedSources(tabs){const sources=new Set;for(const tab of tabs)for(const child of Array.from(tab.element.children))(child.getAttribute("slot")??"")===""&&sources.add(child);return sources}syncProjectedSources(tabs){const sources=this.projectedSources(tabs);for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot),sources.has(source)||(this.restoreProjectedSource(source,snapshot),this.projectedSourceSnapshots.delete(source));for(const source of sources){const snapshot=this.projectedSourceSnapshots.get(source)??this.snapshotProjectedSource(source);this.projectedSourceSnapshots.set(source,snapshot),this.adoptProjectedSourceInert(source,snapshot),this.makeProjectedSourceInert(source,snapshot)}this.observeProjectedSources()}adoptProjectedSourceInertStates(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot)}snapshotProjectedSlot(source){const slot=source.getAttribute("slot");return{slot,appliedSlot:slot,libraryOwnsSlot:!1}}adoptProjectedSlot(source,snapshot){const current=source.getAttribute("slot");current!==snapshot.appliedSlot&&(snapshot.slot=current,snapshot.libraryOwnsSlot=!1)}projectSlot(source,slot,projectedSlots){const snapshot=this.projectedSlotSnapshots.get(source)??this.snapshotProjectedSlot(source);this.projectedSlotSnapshots.set(source,snapshot),this.adoptProjectedSlot(source,snapshot),source.getAttribute("slot")!==slot&&(source.setAttribute("slot",slot),snapshot.libraryOwnsSlot=!0),snapshot.appliedSlot=source.getAttribute("slot"),projectedSlots.add(source)}restoreProjectedSlot(source,snapshot){this.adoptProjectedSlot(source,snapshot),snapshot.slot===null?source.removeAttribute("slot"):source.setAttribute("slot",snapshot.slot)}syncProjectedSlots(projectedSlots){for(const[source,snapshot]of this.projectedSlotSnapshots)projectedSlots.has(source)||(this.restoreProjectedSlot(source,snapshot),this.projectedSlotSnapshots.delete(source))}restoreProjectedSlots(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.restoreProjectedSlot(source,snapshot);this.projectedSlotSnapshots.clear()}adoptProjectedSlotStates(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.adoptProjectedSlot(source,snapshot)}isNavigable(tab){return!tab.disabled&&!tab.inert}willUpdate(changed){if(super.willUpdate(changed),!changed.has("tabs")&&!changed.has("active"))return;const focused=shadowFocusTarget(this),focusedSlot=focused?.getAttribute("part")==="tab"?focused.getAttribute("data-slot"):null;focusedSlot!==null&&!this.tabs.some(tab=>tab.slotName===focusedSlot&&this.isNavigable(tab))&&(this.rehomeTabFocus=!0,this.focusedTab=this.active);const current=this.tabs.find(t=>t.slotName===this.active);if(current&&this.isNavigable(current))return;this.rehomeTabFocus=this.rehomeTabFocus||focusedSlot!==null;const outgoing=this.active,before=changed.get("tabs")??this.tabs,at=this.hasUpdated&&changed.has("tabs")&&!changed.has("active")?before.findIndex(t=>t.slotName===outgoing):-1,renamed=at<0?void 0:this.tabs.find(t=>t.element===before[at].element&&this.isNavigable(t)),candidates=at<0?this.tabs:[...before.slice(at+1),...before.slice(0,at).reverse()].map(t=>this.tabs.find(live=>live.slotName===t.slotName));this.active=(renamed??candidates.find(t=>t&&this.isNavigable(t)))?.slotName??"",this.focusedTab=this.active,at>=0&&!renamed&&(this.emit("lr-tab-hide",{name:outgoing}),this.active&&this.emit("lr-tab-show",{name:this.active}))}updated(changed){super.updated(changed),(changed.has("active")||changed.has("tabs"))&&this.syncElementActiveState(),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="tab"]')),this.measureTabScrollEdges(),this.rehomeTabFocus&&(this.rehomeTabFocus=!1,this.renderRoot.querySelector('[part="tab"][tabindex="0"]')?.focus())}selectTab(tab){if(!this.isNavigable(tab)||tab.slotName===this.active)return;const previous=this.active;this.active=tab.slotName,this.focusedTab=tab.slotName,previous&&this.emit("lr-tab-hide",{name:previous}),this.emit("lr-tab-show",{name:tab.slotName})}activateTab(tab){this.isNavigable(tab)&&(this.selectTab(tab),this.emit("lr-activate",{value:tab.slotName}))}show(panel){const tab=this.tabs.find(candidate=>candidate.slotName===panel);tab&&this.selectTab(tab)}syncElementActiveState(){for(const child of Array.from(this.children))if(child.localName===tag("tab")){const definition=this.tabs.find(tab=>tab.element===child);child.toggleAttribute("active",definition?.slotName===this.active)}else child.localName===tag("tab-panel")&&child.toggleAttribute("active",child.getAttribute("name")===this.active)}focusOnly(tab){this.focusedTab=tab.slotName,this.focusTab(tab.slotName)}get rovingTab(){if(this.activation!=="manual")return this.active;const candidate=this.tabs.find(t=>t.slotName===this.focusedTab&&this.isNavigable(t));return candidate?candidate.slotName:this.active}keyboardOriginTab(event,navigable){const eventButton=event.composedPath().find(candidate=>candidate.nodeType===1&&candidate.getAttribute?.("part")==="tab"&&candidate.getRootNode()===this.renderRoot),focused=shadowFocusTarget(this),owned=(eventButton??(focused?.getAttribute("part")==="tab"?focused:void 0))?.dataset.slot;return navigable.find(tab=>tab.slotName===owned)??navigable.find(tab=>tab.slotName===this.rovingTab)}focusTab(slotName){const buttons=this.renderRoot.querySelectorAll('[part="tab"]');for(const button of Array.from(buttons))if(button.dataset.slot===slotName){button.focus();return}}get isVertical(){return this.placement==="start"||this.placement==="end"}tabId(slotName){return this.idsFor(slotName).tab}panelId(slotName){return this.idsFor(slotName).panel}idsFor(slotName){const existing=this.idsBySlot.get(slotName);if(existing)return existing;const token=`${this.baseId}-${this.nextOpaqueId++}`,ids={tab:`${token}-tab`,panel:`${token}-panel`};return this.idsBySlot.set(slotName,ids),ids}tabSlotName(slotName){return`${slotName}-tab`}get scrollControlsSuppressed(){return this.withoutScrollControls||this.noScrollControls}measureTabScrollEdges(){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||this.isVertical){this.setTabScrollEdges(!1,!1,tablist);return}const maximum=Math.max(0,tablist.scrollWidth-tablist.clientWidth),position=Math.max(0,Math.min(maximum,this.effectiveDirection==="rtl"?-tablist.scrollLeft:tablist.scrollLeft));this.setTabScrollEdges(position>1,position<maximum-1,tablist)}setTabScrollEdges(start,end,tablist){tablist?.toggleAttribute("data-scroll-start",start),tablist?.toggleAttribute("data-scroll-end",end),!(start===this.scrollStartAvailable&&end===this.scrollEndAvailable)&&(this.scrollStartAvailable=start,this.scrollEndAvailable=end)}scrollTabs(edge){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||!isHtmlElement(tablist)||typeof tablist.scrollBy!="function")return;const step=Math.max(1,tablist.clientWidth*SCROLL_STEP_RATIO),towardEnd=edge==="end"?1:-1,physical=this.effectiveDirection==="rtl"?-towardEnd:towardEnd;tablist.scrollBy({left:step*physical,behavior:prefersReducedMotion(this)?"instant":"smooth"})}renderScrollControl(edge){if(this.isVertical||this.scrollControlsSuppressed)return nothing;const available=edge==="start"?this.scrollStartAvailable:this.scrollEndAvailable;return html`<button
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{tag}from"../../../internal/prefix.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{styles}from"./tab-group.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious}from"../../../internal/default-strings/layout.generated.js";function isInertChild(child){return isHtmlElement(child)&&child.inert}function isTabLabelSubtreeExcludedWithoutInert(element){if(element.hasAttribute("hidden")||element.getAttribute("aria-hidden")?.trim().toLowerCase()==="true")return!0;const rendered=element.ownerDocument.defaultView?.getComputedStyle(element);return rendered?.display==="none"||rendered?.contentVisibility==="hidden"}const SYNTHETIC_PANEL_PREFIX="lr-tab-",SCROLL_STEP_RATIO=.8;class LyraTabGroup extends LyraElement{constructor(){super(...arguments),this.active="",this.accessibleLabel=null,this.placement="top",this.activation="auto",this.withoutScrollControls=!1,this.noScrollControls=!1,this.fixedScrollControls=!1,this.tabs=[],this.focusedTab="",this.baseId=nextId("tab-group"),this.nextOpaqueId=0,this.idsBySlot=new Map,this.mutationObserverGeneration=0,this.projectedSourceSnapshots=new Map,this.projectedSlotSnapshots=new Map,this.projectedSourceObserverGeneration=0,this.rehomeTabFocus=!1,this.scrollStartAvailable=!1,this.scrollEndAvailable=!1,this.scrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="tablist"]'),()=>this.measureTabScrollEdges()),this.syncTabs=()=>{const children=Array.from(this.children);this.adoptProjectedSourceInertStates(),this.adoptProjectedSlotStates();const projectedSlots=new Set,next=this.readElementModel(children,projectedSlots);this.syncProjectedSlots(projectedSlots),this.syncProjectedSources(next);const liveSlots=new Set(next.map(tab=>tab.slotName));for(const slotName of this.idsBySlot.keys())liveSlots.has(slotName)||this.idsBySlot.delete(slotName);this.tabs=next},this.onTabListKeyDown=e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const navigable=this.tabs.filter(t=>this.isNavigable(t));if(navigable.length===0)return;const origin=this.keyboardOriginTab(e,navigable),currentIndex=origin?navigable.indexOf(origin):-1;if(e.key==="Delete"){if(!origin?.element.closable)return;e.preventDefault(),origin.element.requestCloseFromOwner();return}if(this.activation==="manual"&&(e.key==="Enter"||e.key===" "||e.key==="Spacebar")){if(!origin)return;e.preventDefault(),this.activateTab(origin);return}const targetIndex=resolveListMove(e,{count:navigable.length,current:currentIndex,orientation:this.isVertical?"vertical":"horizontal",direction:this.effectiveDirection});if(targetIndex===null)return;e.preventDefault();const target=navigable[targetIndex];if(this.activation==="manual"){this.focusOnly(target);return}this.activateTab(target),this.focusTab(target.slotName)},this.onTabListScroll=()=>{this.measureTabScrollEdges()},this.onScrollControlMouseDown=event=>{event.preventDefault()},this.onScrollControlPointerDown=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.setAttribute("data-pressed",""),control.setPointerCapture(event.pointerId))},this.onScrollControlPointerEnd=event=>{const control=event.currentTarget;control instanceof HTMLElement&&(control.removeAttribute("data-pressed"),control.hasPointerCapture(event.pointerId)&&control.releasePointerCapture(event.pointerId))}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious}}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}connectedCallback(){super.connectedCallback(),this.hasUpdated?this.syncTabs():this.seedFirstRenderState(this.syncTabs),this.resetMutationObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.mutationObserverGeneration,observer=new MutationObserverCtor(records=>{if(this.mutationObserver!==observer||this.mutationObserverDocument!==ownerDocument||this.mutationObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const isDirectChild=node=>node.parentNode===this,isElementTabContent=node=>{let current=node.nodeType===1?node:node.parentElement;for(;current&¤t!==this;){if(current.localName===tag("tab")&¤t.parentNode===this)return!0;current=current.parentElement}return!1};records.some(record=>record.type==="childList"?record.target===this||isElementTabContent(record.target):record.type==="characterData"?isElementTabContent(record.target):record.attributeName==="inert"&&this.projectedSourceSnapshots.has(record.target)?!1:isDirectChild(record.target)||isElementTabContent(record.target))&&this.syncTabs()});this.mutationObserver=observer,this.mutationObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","closable","disabled","hidden","inert","id","label","name","open","panel","slot","style"]})}disconnectedCallback(){this.resetMutationObserver(),this.resetProjectedSourceObserver(),this.restoreProjectedSources(),this.restoreProjectedSlots(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMutationObserver(),this.resetProjectedSourceObserver()}resetMutationObserver(){this.mutationObserverGeneration+=1,this.mutationObserver?.disconnect(),this.mutationObserver=void 0,this.mutationObserverDocument=void 0}readElementModel(children,projectedSlots){const seen=new Set,next=[],panelsByName=new Map;for(const child of children){if(child.localName!==tag("tab-panel"))continue;const name=child.getAttribute("name");name!==null&&!panelsByName.has(name)&&panelsByName.set(name,child)}const authoredNames=new Set(children.flatMap(child=>{if(child.localName===tag("tab")){const name=child.getAttribute("panel");return name?[name]:[]}if(child.localName===tag("tab-panel")){const name=child.getAttribute("name");return name?[name]:[]}return[]}));let index=0;for(const child of children){if(child.localName!==tag("tab"))continue;const authoredPanel=child.getAttribute("panel")||void 0;let slotName=authoredPanel??`${SYNTHETIC_PANEL_PREFIX}${index}`;if(!authoredPanel){let collision=0;for(;authoredNames.has(slotName)||seen.has(slotName);)collision+=1,slotName=`${SYNTHETIC_PANEL_PREFIX}${index}-${collision}`}if(index+=1,!authoredPanel&&!this.readElementLabel(child,{allowUnprojected:!0})||seen.has(slotName))continue;seen.add(slotName);const tabSlot=this.tabSlotName(slotName);this.projectSlot(child,tabSlot,projectedSlots);const visibleLabel=this.readElementLabel(child);if(!authoredPanel&&!visibleLabel)continue;const label=visibleLabel||slotName,panel=panelsByName.get(slotName);panel&&this.projectSlot(panel,slotName,projectedSlots),next.push({slotName,label,disabled:child.hasAttribute("disabled"),inert:isInertChild(child),element:child}),!this.active&&child.hasAttribute("active")&&(this.active=slotName)}return next}readElementLabel(tab,options={}){const labelNodes=Array.from(tab.childNodes).filter(node=>node.nodeType!==Node.ELEMENT_NODE||node.getAttribute("slot")===null||node.getAttribute("slot")==="");return composedAccessibilityText(labelNodes,{ancestorBoundary:tab,isSubtreeExcluded:element=>this.isTabLabelSubtreeExcluded(element),requireRendered:!options.allowUnprojected,skipRootAncestorValidation:options.allowUnprojected,ignoreInheritedVisibility:!0}).replace(/\s+/g," ").trim()}libraryOwnsSourceInert(element){return this.projectedSourceSnapshots.get(element)?.libraryOwnsInert===!0}isTabLabelSubtreeExcluded(element){return isTabLabelSubtreeExcludedWithoutInert(element)||element.hasAttribute("inert")&&!this.libraryOwnsSourceInert(element)}snapshotProjectedSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert,libraryOwnsInert:!1}}adoptProjectedSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current,snapshot.libraryOwnsInert=!1)}makeProjectedSourceInert(source,snapshot){source.hasAttribute("inert")||(source.setAttribute("inert",""),snapshot.libraryOwnsInert=!0),snapshot.appliedInert=source.getAttribute("inert")}restoreProjectedSource(source,snapshot){this.adoptProjectedSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreProjectedSources(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.restoreProjectedSource(source,snapshot);this.projectedSourceSnapshots.clear()}resetProjectedSourceObserver(){this.projectedSourceObserverGeneration+=1,this.projectedSourceObserver?.disconnect(),this.projectedSourceObserver=void 0,this.projectedSourceObserverDocument=void 0}observeProjectedSources(){this.resetProjectedSourceObserver();const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected||this.projectedSourceSnapshots.size===0)return;const generation=this.projectedSourceObserverGeneration,observer=new MutationObserverCtor(records=>{this.projectedSourceObserver!==observer||this.projectedSourceObserverDocument!==ownerDocument||this.projectedSourceObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||records.some(record=>this.projectedSourceSnapshots.has(record.target))&&this.syncTabs()});this.projectedSourceObserver=observer,this.projectedSourceObserverDocument=ownerDocument;for(const source of this.projectedSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}projectedSources(tabs){const sources=new Set;for(const tab of tabs)for(const child of Array.from(tab.element.children))(child.getAttribute("slot")??"")===""&&sources.add(child);return sources}syncProjectedSources(tabs){const sources=this.projectedSources(tabs);for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot),sources.has(source)||(this.restoreProjectedSource(source,snapshot),this.projectedSourceSnapshots.delete(source));for(const source of sources){const snapshot=this.projectedSourceSnapshots.get(source)??this.snapshotProjectedSource(source);this.projectedSourceSnapshots.set(source,snapshot),this.adoptProjectedSourceInert(source,snapshot),this.makeProjectedSourceInert(source,snapshot)}this.observeProjectedSources()}adoptProjectedSourceInertStates(){for(const[source,snapshot]of this.projectedSourceSnapshots)this.adoptProjectedSourceInert(source,snapshot)}snapshotProjectedSlot(source){const slot=source.getAttribute("slot");return{slot,appliedSlot:slot,libraryOwnsSlot:!1}}adoptProjectedSlot(source,snapshot){const current=source.getAttribute("slot");current!==snapshot.appliedSlot&&(snapshot.slot=current,snapshot.libraryOwnsSlot=!1)}projectSlot(source,slot,projectedSlots){const snapshot=this.projectedSlotSnapshots.get(source)??this.snapshotProjectedSlot(source);this.projectedSlotSnapshots.set(source,snapshot),this.adoptProjectedSlot(source,snapshot),source.getAttribute("slot")!==slot&&(source.setAttribute("slot",slot),snapshot.libraryOwnsSlot=!0),snapshot.appliedSlot=source.getAttribute("slot"),projectedSlots.add(source)}restoreProjectedSlot(source,snapshot){this.adoptProjectedSlot(source,snapshot),snapshot.slot===null?source.removeAttribute("slot"):source.setAttribute("slot",snapshot.slot)}syncProjectedSlots(projectedSlots){for(const[source,snapshot]of this.projectedSlotSnapshots)projectedSlots.has(source)||(this.restoreProjectedSlot(source,snapshot),this.projectedSlotSnapshots.delete(source))}restoreProjectedSlots(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.restoreProjectedSlot(source,snapshot);this.projectedSlotSnapshots.clear()}adoptProjectedSlotStates(){for(const[source,snapshot]of this.projectedSlotSnapshots)this.adoptProjectedSlot(source,snapshot)}isNavigable(tab){return!tab.disabled&&!tab.inert}willUpdate(changed){if(super.willUpdate(changed),!changed.has("tabs")&&!changed.has("active"))return;const focused=shadowFocusTarget(this),focusedSlot=focused?.getAttribute("part")==="tab"?focused.getAttribute("data-slot"):null;focusedSlot!==null&&!this.tabs.some(tab=>tab.slotName===focusedSlot&&this.isNavigable(tab))&&(this.rehomeTabFocus=!0,this.focusedTab=this.active);const current=this.tabs.find(t=>t.slotName===this.active);if(current&&this.isNavigable(current))return;this.rehomeTabFocus=this.rehomeTabFocus||focusedSlot!==null;const outgoing=this.active,before=changed.get("tabs")??this.tabs,at=this.hasUpdated&&changed.has("tabs")&&!changed.has("active")?before.findIndex(t=>t.slotName===outgoing):-1,renamed=at<0?void 0:this.tabs.find(t=>t.element===before[at].element&&this.isNavigable(t));let candidates=this.tabs;if(at>=0){const liveByName=new Map;for(const tab of this.tabs)liveByName.has(tab.slotName)||liveByName.set(tab.slotName,tab);candidates=[...before.slice(at+1),...before.slice(0,at).reverse()].map(tab=>liveByName.get(tab.slotName))}this.active=(renamed??candidates.find(t=>t&&this.isNavigable(t)))?.slotName??"",this.focusedTab=this.active,at>=0&&!renamed&&(this.emit("lr-tab-hide",{name:outgoing}),this.active&&this.emit("lr-tab-show",{name:this.active}))}updated(changed){super.updated(changed),(changed.has("active")||changed.has("tabs"))&&this.syncElementActiveState(),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="tab"]')),this.measureTabScrollEdges(),this.rehomeTabFocus&&(this.rehomeTabFocus=!1,this.renderRoot.querySelector('[part="tab"][tabindex="0"]')?.focus())}selectTab(tab){if(!this.isNavigable(tab)||tab.slotName===this.active)return;const previous=this.active;this.active=tab.slotName,this.focusedTab=tab.slotName,previous&&this.emit("lr-tab-hide",{name:previous}),this.emit("lr-tab-show",{name:tab.slotName})}activateTab(tab){this.isNavigable(tab)&&(this.selectTab(tab),this.emit("lr-activate",{value:tab.slotName}))}show(panel){const tab=this.tabs.find(candidate=>candidate.slotName===panel);tab&&this.selectTab(tab)}syncElementActiveState(){const definitions=new Map;for(const tab of this.tabs)definitions.has(tab.element)||definitions.set(tab.element,tab);for(const child of Array.from(this.children))if(child.localName===tag("tab")){const definition=definitions.get(child);child.toggleAttribute("active",definition?.slotName===this.active)}else child.localName===tag("tab-panel")&&child.toggleAttribute("active",child.getAttribute("name")===this.active)}focusOnly(tab){this.focusedTab=tab.slotName,this.focusTab(tab.slotName)}get rovingTab(){if(this.activation!=="manual")return this.active;const candidate=this.tabs.find(t=>t.slotName===this.focusedTab&&this.isNavigable(t));return candidate?candidate.slotName:this.active}keyboardOriginTab(event,navigable){const eventButton=event.composedPath().find(candidate=>candidate.nodeType===1&&candidate.getAttribute?.("part")==="tab"&&candidate.getRootNode()===this.renderRoot),focused=shadowFocusTarget(this),owned=(eventButton??(focused?.getAttribute("part")==="tab"?focused:void 0))?.dataset.slot;return navigable.find(tab=>tab.slotName===owned)??navigable.find(tab=>tab.slotName===this.rovingTab)}focusTab(slotName){const buttons=this.renderRoot.querySelectorAll('[part="tab"]');for(const button of Array.from(buttons))if(button.dataset.slot===slotName){button.focus();return}}get isVertical(){return this.placement==="start"||this.placement==="end"}tabId(slotName){return this.idsFor(slotName).tab}panelId(slotName){return this.idsFor(slotName).panel}idsFor(slotName){const existing=this.idsBySlot.get(slotName);if(existing)return existing;const token=`${this.baseId}-${this.nextOpaqueId++}`,ids={tab:`${token}-tab`,panel:`${token}-panel`};return this.idsBySlot.set(slotName,ids),ids}tabSlotName(slotName){return`${slotName}-tab`}get scrollControlsSuppressed(){return this.withoutScrollControls||this.noScrollControls}measureTabScrollEdges(){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||this.isVertical){this.setTabScrollEdges(!1,!1,tablist);return}const maximum=Math.max(0,tablist.scrollWidth-tablist.clientWidth),position=Math.max(0,Math.min(maximum,this.effectiveDirection==="rtl"?-tablist.scrollLeft:tablist.scrollLeft));this.setTabScrollEdges(position>1,position<maximum-1,tablist)}setTabScrollEdges(start,end,tablist){tablist?.toggleAttribute("data-scroll-start",start),tablist?.toggleAttribute("data-scroll-end",end),!(start===this.scrollStartAvailable&&end===this.scrollEndAvailable)&&(this.scrollStartAvailable=start,this.scrollEndAvailable=end)}scrollTabs(edge){const tablist=this.renderRoot.querySelector('[part~="tablist"]');if(!tablist||!isHtmlElement(tablist)||typeof tablist.scrollBy!="function")return;const step=Math.max(1,tablist.clientWidth*SCROLL_STEP_RATIO),towardEnd=edge==="end"?1:-1,physical=this.effectiveDirection==="rtl"?-towardEnd:towardEnd;tablist.scrollBy({left:step*physical,behavior:prefersReducedMotion(this)?"instant":"smooth"})}renderScrollControl(edge){if(this.isVertical||this.scrollControlsSuppressed)return nothing;const available=edge==="start"?this.scrollStartAvailable:this.scrollEndAvailable;return html`<button
|
|
2
2
|
type="button"
|
|
3
3
|
part=${edge==="start"?"scroll-button scroll-button__base scroll-button-start scroll-button--start":"scroll-button scroll-button__base scroll-button-end scroll-button--end"}
|
|
4
4
|
tabindex="-1"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings/layout.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}const collapseWriteGuards=new WeakMap;function collapseWriteGuardFor(widget){let guard=collapseWriteGuards.get(widget);return guard||(guard=new VetoWriteGuard,collapseWriteGuards.set(widget,guard)),guard}function installSynchronousCollapsedReflection(prototype){const installed=Object.getOwnPropertyDescriptor(prototype,"collapsed"),installedSet=installed.set;Object.defineProperty(prototype,"collapsed",{...installed,set(next){installedSet.call(this,next),markVetoGuardWrite(collapseWriteGuardFor(this)),this.toggleAttribute("collapsed",this.collapsed)}})}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.size="m",this.effectiveViews=Object.freeze([]),this.activeViewId="",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen(),this.fullscreen&&this.nativeModal.show()}}),this.labelTextObserver=new AccessibleTextController(this,[],()=>{const assigned=this.shadowRoot?.querySelector('slot[name="label"]')?.assignedElements({flatten:!0})??[];this.syncLabelSlot(assigned)},["alt","aria-labelledby","slot"],!1),this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.setActiveView=viewId=>{if(viewId!==this.activeViewId){if(this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented)return;this.activeViewId=viewId,this.emit("lr-view-change",{viewId})}this.emit("lr-activate",{value:viewId})},this.dispatchingCollapse=!1,this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,scrollOverflowFadeStyles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}static{definePersistedProperty(this.prototype,"collapsed",{initial:!1,attribute:!0,type:Boolean,reflect:!0,coerce:next=>!!next}),installSynchronousCollapsedReflection(this.prototype)}get views(){return this.effectiveViews}set views(value){if(value===this.viewsSource||value===this.effectiveViews)return;this.viewsSource=value;const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.labelSlotText=this.readLabelSlotText(labelChildren);const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!isPersistedPropertyExplicitlySet(this,"collapsed")&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;if(!views.some(view=>view.viewId===this.activeViewId)){const forcedBySibling=this.hasUpdated&&changed.has("views")&&!changed.has("activeViewId");this.activeViewId=views[0]?.viewId??"",forcedBySibling&&this.emit("lr-view-change",{viewId:this.activeViewId})}}}updated(changed){super.updated(changed),this.fullscreen&&this.nativeModal.show();const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.nativeModal.hide(),super.disconnectedCallback(),this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork();const slot=this.shadowRoot?.querySelector('slot[name="label"]');this.isConnected&&slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0})),this.labelTextObserver.adopted()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.labelTextObserver.setEnabled(!1)}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.nativeModal.prepare(),this.fullscreenOpener=this.explicitTrigger??captureFocusReturnOpener(this),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.fullscreenOpener;return opener?{candidates:()=>[opener],isCurrent:()=>!this.fullscreen}:void 0}}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.fullscreenOpener=void 0}syncLabelSlot(assigned){this.labelSlotText=this.readLabelSlotText(assigned),this.labelTextObserver.setEnabled(assigned.length>0),this.labelTextObserver.bind()}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}requestCollapse(next){if(this.dispatchingCollapse)return;const previous=this.collapsed;this.dispatchingCollapse=!0;try{requestThenCommit({requestDetail:{expanded:!next},emitRequest:(proposal,init)=>{const request=this.emit("lr-toggle-request",proposal,init);return this.emit("lr-collapse-request",{collapsed:next},init).defaultPrevented&&request.preventDefault(),request},guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}),this.emit("lr-toggle",{expanded:!next}))}})}finally{this.dispatchingCollapse=!1}}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings/layout.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}const collapseWriteGuards=new WeakMap;function collapseWriteGuardFor(widget){let guard=collapseWriteGuards.get(widget);return guard||(guard=new VetoWriteGuard,collapseWriteGuards.set(widget,guard)),guard}function installSynchronousCollapsedReflection(prototype){const installed=Object.getOwnPropertyDescriptor(prototype,"collapsed"),installedSet=installed.set;Object.defineProperty(prototype,"collapsed",{...installed,set(next){installedSet.call(this,next),markVetoGuardWrite(collapseWriteGuardFor(this)),this.toggleAttribute("collapsed",this.collapsed)}})}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.size="m",this.effectiveViews=Object.freeze([]),this.activeViewId="",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen(),this.fullscreen&&this.nativeModal.show()}}),this.labelTextObserver=new AccessibleTextController(this,[],()=>{const assigned=this.shadowRoot?.querySelector('slot[name="label"]')?.assignedElements({flatten:!0})??[];this.syncLabelSlot(assigned)},["alt","aria-labelledby","slot"],!1),this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.setActiveView=viewId=>{if(viewId!==this.activeViewId){if(this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented)return;this.activeViewId=viewId,this.emit("lr-view-change",{viewId})}this.emit("lr-activate",{value:viewId})},this.dispatchingCollapse=!1,this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,scrollOverflowFadeStyles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}static{definePersistedProperty(this.prototype,"collapsed",{initial:!1,attribute:!0,type:Boolean,reflect:!0,coerce:next=>!!next}),installSynchronousCollapsedReflection(this.prototype)}get views(){return this.effectiveViews}set views(value){if(value===this.viewsSource||value===this.effectiveViews)return;this.viewsSource=value;const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.labelSlotText=this.readLabelSlotText(labelChildren);const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!isPersistedPropertyExplicitlySet(this,"collapsed")&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;if(!views.some(view=>view.viewId===this.activeViewId)){const forcedBySibling=this.hasUpdated&&changed.has("views")&&!changed.has("activeViewId");this.activeViewId=views[0]?.viewId??"",forcedBySibling&&this.emit("lr-view-change",{viewId:this.activeViewId})}}}updated(changed){super.updated(changed),this.fullscreen&&this.nativeModal.show();const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork(),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.nativeModal.hide(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork();const slot=this.shadowRoot?.querySelector('slot[name="label"]');this.isConnected&&slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0})),this.labelTextObserver.adopted()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.labelTextObserver.setEnabled(!1)}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.nativeModal.prepare(),this.fullscreenOpener=this.explicitTrigger??captureFocusReturnOpener(this),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.fullscreenOpener;return opener?{candidates:()=>[opener],isCurrent:()=>!this.fullscreen}:void 0}}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.fullscreenOpener=void 0}syncLabelSlot(assigned){this.labelSlotText=this.readLabelSlotText(assigned),this.labelTextObserver.setEnabled(assigned.length>0),this.labelTextObserver.bind()}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}requestCollapse(next){if(this.dispatchingCollapse)return;const previous=this.collapsed;this.dispatchingCollapse=!0;try{requestThenCommit({requestDetail:{expanded:!next},emitRequest:(proposal,init)=>{const request=this.emit("lr-toggle-request",proposal,init);return this.emit("lr-collapse-request",{collapsed:next},init).defaultPrevented&&request.preventDefault(),request},guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}),this.emit("lr-toggle",{expanded:!next}))}})}finally{this.dispatchingCollapse=!1}}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return this.nativeModal.render(html`
|
|
2
2
|
${this.fullscreen?html`<div
|
|
3
3
|
part="backdrop"
|
|
4
4
|
style=${backdropInset?styleMap({"--lr-widget-backdrop-inset":backdropInset}):nothing}
|
|
@@ -25,7 +25,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
25
25
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
26
26
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
27
27
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
28
|
-
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.hostAccessibleLabel=null,this.multiple=!1,this.disabled=!1,this.appearance="plain",this.size="m",this.descriptionSyncGeneration=0,this.hasSyncedDescribedByElements=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const accept=this.effectiveAccept(this.pendingCapability),files=Array.from(selected),matching=files.filter(file=>matchesAccept(file,accept));this.emit("lr-files",{capability:this.pendingCapability,files:matching,rejected:files.filter(file=>!
|
|
28
|
+
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.hostAccessibleLabel=null,this.multiple=!1,this.disabled=!1,this.appearance="plain",this.size="m",this.descriptionSyncGeneration=0,this.hasSyncedDescribedByElements=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const accept=this.effectiveAccept(this.pendingCapability),files=Array.from(selected),matching=files.filter(file=>matchesAccept(file,accept)),matchingFiles=new Set(matching);this.emit("lr-files",{capability:this.pendingCapability,files:matching,rejected:files.filter(file=>!matchingFiles.has(file)).map(file=>({file,reason:"type"})),remainingFiles:null,remainingTotalSize:null})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get triggerEl(){return this.composedTriggerEl?.control??this.composedTriggerEl}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}updated(changed){super.updated(changed),this.syncTriggerDescription();const composed=this.composedTriggerEl;if(!composed||composed.control)return;const generation=++this.descriptionSyncGeneration;composed.updateComplete.then(()=>{generation!==this.descriptionSyncGeneration||!this.isConnected||this.syncTriggerDescription()})}syncTriggerDescription(){const hostDescribedBy=this.getAttribute("aria-describedby");!hostDescribedBy&&!this.hasSyncedDescribedByElements||(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.triggerEl,hostDescribedBy))}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
29
29
|
<input
|
|
30
30
|
part="hidden-input"
|
|
31
31
|
type="file"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController,isFileValue,readFileList}from"../../../internal/drop-session-controller.js";import{falseDefaultBooleanConverter}from"../../../internal/converters.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{classifyFiles,EMPTY_MIME_TYPES,freezeDetail,handleDrop,mimeTypeFilter,outcomeText,snapshotMimeTypes}from"./file-intake.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize,localizedNumberLabel}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}import{DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_FILES,DEFAULT_MAX_TOTAL_SIZE_BYTES}from"./file-intake.js";const MAX_DROPPED_FOLDER_ENTRIES=1e4,INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}class LyraFileInput extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-files","lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["value"]),"lr-change":Object.freeze(["value"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){if(next===this.inputs.allowed)return;this.inputs.allowed=next;const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){if(next===this.inputs.forbidden)return;this.inputs.forbidden=next;const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this.inputs={},this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>handleDrop(this,this.dropSession,e,this.effectiveMultiple,(files,rejected)=>this.emitFiles(files,rejected)),this.onPaste=e=>{if(this.withoutPaste||this.liveDisabled)return;const files=readFileList(e.clipboardData?.files);files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){if(next===this.inputs.files)return;this.inputs.files=next;const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.disconnectValidatorAttributeObserver(),this.dropSession.reset();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&!this.hasEffectiveValue&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate())}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}classify(fileList,isPreview=!1){const multiple=this.effectiveMultiple;return classifyFiles(this,fileList,multiple,this.nonRetaining||!multiple?[]:this._files,isPreview,mimeTypeFilter(this.allowedMimeTypes,this.forbiddenMimeTypes))}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",void 0,{filename})}}outcomeMessage(key,override,count){return outcomeText(override,()=>this.localize(key,void 0,{count}),count)}emitFiles(fileList,additionalRejected=[]){const detail=freezeDetail(this.classify(fileList),additionalRejected),{files,rejected}=detail;this.rejectedFiles=rejected;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);if(files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length){this.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",{value},detail2=>this.emit("lr-change",detail2))}this.emit("lr-files",detail)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get dropzoneInstruction(){return this.localize("fileInputDefaultLabel")}removeFile(index){if(this.liveDisabled||index<0||index>=this._files.length)return;this.touched=!0;const hadFocus=shadowFocusTarget(this)?.matches('[part="remove-button"]');this.files=this._files.filter((_,candidate)=>candidate!==index);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail)),hadFocus&&this.updateComplete.then(()=>{const buttons=this.renderRoot.querySelectorAll('[part="remove-button"]');(buttons[Math.min(index,buttons.length-1)]??this.baseEl)?.focus()})}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),localizedNumberLabel(this.effectiveLocale))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController,isFileValue,readFileList}from"../../../internal/drop-session-controller.js";import{falseDefaultBooleanConverter}from"../../../internal/converters.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{classifyFiles,EMPTY_MIME_TYPES,freezeDetail,handleDrop,mimeTypeFilter,outcomeText,snapshotMimeTypes}from"./file-intake.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize,localizedNumberLabel}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}import{DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_FILES,DEFAULT_MAX_TOTAL_SIZE_BYTES}from"./file-intake.js";const MAX_DROPPED_FOLDER_ENTRIES=1e4,INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}class LyraFileInput extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-files","lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["value"]),"lr-change":Object.freeze(["value"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){if(next===this.inputs.allowed)return;this.inputs.allowed=next;const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){if(next===this.inputs.forbidden)return;this.inputs.forbidden=next;const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this.inputs={},this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>handleDrop(this,this.dropSession,e,this.effectiveMultiple,(files,rejected)=>this.emitFiles(files,rejected)),this.onPaste=e=>{if(this.withoutPaste||this.liveDisabled)return;const files=readFileList(e.clipboardData?.files);files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){if(next===this.inputs.files)return;this.inputs.files=next;const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.disconnectValidatorAttributeObserver(),this.dropSession.reset();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&!this.hasEffectiveValue&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate())}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function",retainedFiles=new Set(this._files);let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!retainedFiles.has(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}classify(fileList,isPreview=!1){const multiple=this.effectiveMultiple;return classifyFiles(this,fileList,multiple,this.nonRetaining||!multiple?[]:this._files,isPreview,mimeTypeFilter(this.allowedMimeTypes,this.forbiddenMimeTypes))}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",void 0,{filename})}}outcomeMessage(key,override,count){return outcomeText(override,()=>this.localize(key,void 0,{count}),count)}emitFiles(fileList,additionalRejected=[]){const detail=freezeDetail(this.classify(fileList),additionalRejected),{files,rejected}=detail;this.rejectedFiles=rejected;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);if(files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length){this.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",{value},detail2=>this.emit("lr-change",detail2))}this.emit("lr-files",detail)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get dropzoneInstruction(){return this.localize("fileInputDefaultLabel")}removeFile(index){if(this.liveDisabled||index<0||index>=this._files.length)return;this.touched=!0;const hadFocus=shadowFocusTarget(this)?.matches('[part="remove-button"]');this.files=this._files.filter((_,candidate)=>candidate!==index);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail)),hadFocus&&this.updateComplete.then(()=>{const buttons=this.renderRoot.querySelectorAll('[part="remove-button"]');(buttons[Math.min(index,buttons.length-1)]??this.baseEl)?.focus()})}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),localizedNumberLabel(this.effectiveLocale))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){if(super.willUpdate(changed),changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver()}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view,this.geometryFrame=view.requestAnimationFrame(()=>{this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100)})}syncGeometryObserver(){const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const ResizeObserverConstructor=this.ownerDocument.defaultView?.ResizeObserver;ResizeObserverConstructor&&(this.geometryObserver=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)}),this.geometryObserver.observe(wrapper))}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){if(super.willUpdate(changed),changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver()}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){if(!this.isConnected)return;const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view;const frame=view.requestAnimationFrame(()=>{!this.isConnected||this.ownerDocument.defaultView!==view||this.geometryFrameOwner!==view||this.geometryFrame!==frame||(this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100))});this.geometryFrame=frame}syncGeometryObserver(){if(!this.isConnected)return;const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const owner=this.ownerDocument.defaultView,ResizeObserverConstructor=owner?.ResizeObserver;if(!ResizeObserverConstructor)return;const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.geometryObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)});this.geometryObserver=observer,observer.observe(wrapper)}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
|
|
2
2
|
part="highlight-layer"
|
|
3
3
|
role="group"
|
|
4
4
|
aria-label=${this.localize("imageViewerHighlightsLabel")}
|