@aceshooting/lyra-ui 30.3.0 → 30.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +3 -3
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +4 -1
- package/dist/components/layout/multi-split/multi-split.class.js +6 -3
- package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/scroller/scroller.class.d.ts +1 -1
- package/dist/components/layout/scroller/scroller.class.js +1 -1
- package/dist/components/layout/split-panel/split-panel.class.d.ts +1 -1
- package/dist/components/layout/split-panel/split-panel.class.js +1 -1
- package/dist/components/layout/stepper/stepper.class.d.ts +1 -1
- package/dist/components/layout/stepper/stepper.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +2 -2
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +13 -15
- package/dist/components/utility/copy-button/copy-button.class.js +3 -3
- package/dist/components/utility/copy-button/copy-button.styles.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +2 -2
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/modal-host.styles.js +1 -0
- package/dist/internal/modal-surface-controller.js +1 -1
- package/dist/internal/overlay-stack.d.ts +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/style-property-lease.js +1 -1
- package/llms/components/lr-app-rail.md +4 -0
- package/llms/components/lr-badge.md +3 -0
- package/llms/components/lr-copy-button.md +15 -7
- package/llms/components/lr-multi-split.md +4 -0
- package/llms/components/lr-page.md +5 -1
- package/llms/components/lr-responsive-panel.md +5 -1
- package/llms/components/lr-token-input.md +4 -3
- package/llms/components/lr-tooltip.md +4 -4
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +11 -0
- package/llms/shared/styles-and-tokens.md +75 -14
- package/llms/shared.md +86 -14
- package/package.json +2 -2
- package/skills/compose-lyra-interfaces/references/composition-patterns.md +1 -1
- package/skills/lyra-ui/SKILL.md +3 -2
- package/skills/lyra-ui/lyra-gen.md +10 -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.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)=>this.emit("lr-toggle-request",proposal,init),guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.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{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{modalHostStyles}from"../../../internal/modal-host.styles.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.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal),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,modalHostStyles,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.overlayHandle?.resume(),this.modalSurface.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.fullscreen&&(this.modalSurface.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.modalSurface.disconnect(),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.modalSurface.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.modalSurface.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)=>this.emit("lr-toggle-request",proposal,init),guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.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}
|
|
@@ -242,7 +242,7 @@ size:LyraSize;private hostAriaLabel;
|
|
|
242
242
|
* backdrop dismissal on, so a mechanical `wa-dialog` → `lr-dialog` rename silently flipped the
|
|
243
243
|
* behaviour of every migrated dialog. A rename that changes what the markup does with nothing
|
|
244
244
|
* to warn on is worse than no rename at all, so the polarity now matches upstream exactly. */
|
|
245
|
-
lightDismiss:boolean;private hasFooterSlot;private hasLabelSlot;private hasHeaderActionsSlot;private headingText?;private overlay?;private focusReturnOpener;private hideSettled?;private readonly nativeModal;private pendingScrollLockRelease?;private headingObserver?;private headingObserverDocument?;private headingObserverOpen?;private headingObserverGeneration;private bodyOverflowObserver?;private bodyOverflowObservedBody?;private transitionToken;private openRequestTarget?;private openRequestDuringPreflight?;private transitionAnimations;private initialFocusDecision?;private readonly headingId;private externalModalDepth;
|
|
245
|
+
lightDismiss:boolean;private hasFooterSlot;private hasLabelSlot;private hasHeaderActionsSlot;private headingText?;private overlay?;private focusReturnOpener;private hideSettled?;private readonly nativeModal;private readonly modalPresentation;private pendingScrollLockRelease?;private headingObserver?;private headingObserverDocument?;private headingObserverOpen?;private headingObserverGeneration;private bodyOverflowObserver?;private bodyOverflowObservedBody?;private transitionToken;private openRequestTarget?;private openRequestDuringPreflight?;private transitionAnimations;private initialFocusDecision?;private readonly headingId;private externalModalDepth;
|
|
246
246
|
/** Shoelace-compatible modal controller. External activation suspends this dialog's focus/Escape
|
|
247
247
|
* ownership without changing its logical `open` state; deactivation restores it. */
|
|
248
248
|
modal:LyraDialogModalController;
|
|
@@ -281,4 +281,4 @@ close(reason?:DialogCloseReason):Promise<void>;private closeFrom;private coalesc
|
|
|
281
281
|
* dialog reacts, and an `auto` popover would close on the user agent's terms instead. The
|
|
282
282
|
* `z-index` in the stylesheet remains as the fallback for a user agent without popover support.
|
|
283
283
|
*/
|
|
284
|
-
protected enterTopLayer():void;protected leaveTopLayer():void;private onNativeCancel;private
|
|
284
|
+
protected enterTopLayer():void;protected leaveTopLayer():void;private onNativeCancel;private onBackdropClick;private onCloseButtonClick;private requestClose;protected focusInitial():void;protected activateOverlay():void;protected deactivateOverlay(options?:OverlayDeactivateOptions):(()=>void)|undefined;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dialog':LyraDialog;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";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{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener,scheduleDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{closeIcon}from"../../../internal/icons.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{styles}from"./dialog.styles.js";import{LYRA_DEFAULT_close}from"../../../internal/default-strings/shared.generated.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]';class LyraDialog extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close}}constructor(){super(),this._open=!1,this.label="",this.headingLevel="3",this.withoutCloseButton=!1,this.withoutHeader=!1,this.noHeader=!1,this.withFooter=!1,this.size="m",this.hostAriaLabel=null,this.lightDismiss=!1,this.hasFooterSlot=!1,this.hasLabelSlot=!1,this.hasHeaderActionsSlot=!1,this.focusReturnOpener=null,this.nativeModal=new NativeModalCarrier(this,{onCancel:event=>this.onNativeCancel(event),onUnexpectedClose:carrier=>{!this.open||!this.modalSurface||(this.closeFrom("api",carrier),this.open&&this.enterTopLayer())}}),this.headingObserverGeneration=0,this.transitionToken=0,this.transitionAnimations=[],this.headingId=nextId("dialog-heading"),this.externalModalDepth=0,this.modal={activateExternal:()=>{this.externalModalDepth++,this.externalModalDepth===1&&this.overlay?.suspend()},deactivateExternal:()=>{this.externalModalDepth!==0&&(this.externalModalDepth--,this.externalModalDepth===0&&this.open&&this.modalSurface&&(this.overlay?.resume(),queueMicrotask(()=>this.focusInitial())))}},this.onDefaultSlotChange=()=>{this.detectLightDomChrome(),this.syncBodyTabIndex(),this.resetBodyOverflowObserver(),this.armBodyOverflowObserver()},this.onFooterSlotChange=()=>{this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")},this.onNativeCancel=event=>{if(event.preventDefault(),!this.open||!this.overlay?.isTopmost())return;const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part~="close-button"]')??this;this.requestClose("close-button","close-button",button)},new GlassScrollLayer(this,'[part~="panel"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles,nativeModalCarrierStyles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get modalSurface(){return!0}willUpdate(changed){if(super.willUpdate(changed),(!this.hasUpdated||changed.has("open")&&this.open)&&(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer"),this.detectLightDomChrome()),this.open&&(changed.has("open")||changed.has("contained"))&&this.nativeModal.prepare(this.modalSurface),changed.has("open")){if(this.flushPendingScrollLockRelease(),this.open)cancelDeferredFocusReturn(this),this.focusReturnOpener=captureFocusReturnOpener(this),this.isConnected&&this.modalSurface&&this.activateOverlay();else{const returnsFocus=this.overlay!==void 0||composedContains(this,deepActiveElement(this.ownerDocument));this.pendingScrollLockRelease=this.deactivateOverlay({deferScrollLockRelease:!0});const opener=this.focusReturnOpener;this.focusReturnOpener=null,returnsFocus&&opener&&this.isConnected&&scheduleDeferredFocusReturn({host:this,candidates:()=>[opener],settled:this.hideSettled,isCurrent:()=>!this.open})}this.hideSettled=void 0}}flushPendingScrollLockRelease(){const release=this.pendingScrollLockRelease;this.pendingScrollLockRelease=void 0,release?.()}updated(changed){super.updated(changed),changed.has("open")&&this.armHeadingObserver(),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),changed.has("open")&&this.open&&this.isConnected&&(this.modalSurface&&(this.enterTopLayer(),this.focusInitial()),queueMicrotask(()=>{this.open&&this.isConnected&&this.detectLightDomChrome()}))}connectedCallback(){super.connectedCallback(),this.armHeadingObserver(),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),this.hasUpdated&&this.open&&(this.modalSurface&&(this.overlay?.isActive()?this.externalModalDepth===0&&this.overlay.resume():this.activateOverlay(),this.enterTopLayer()),queueMicrotask(()=>{!this.open||!this.isConnected||(this.detectLightDomChrome(),this.modalSurface&&this.focusInitial())}))}disconnectedCallback(){this.resetHeadingObserver(),this.resetBodyOverflowObserver(),super.disconnectedCallback(),this.overlay?.suspend(),this.nativeModal.hide(),cancelDeferredFocusReturn(this),this.transitionToken++,this.flushPendingScrollLockRelease(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.open&&queueMicrotask(()=>{if(!this.isConnected&&this.open){if(this.emit("lr-hide",{source:this},{cancelable:this.disconnectHideCancelable}).defaultPrevented){this.syncOpenAttribute();return}this.applyOpenState(!1),this.emit("lr-close",{reason:"unmount"}),this.emit("lr-after-hide")}})}adoptedCallback(){super.adoptedCallback(),this.resetHeadingObserver(),this.resetBodyOverflowObserver(),this.isConnected&&(this.armHeadingObserver(),this.armBodyOverflowObserver(),this.syncBodyTabIndex())}armHeadingObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.headingObserver&&this.headingObserverDocument===ownerDocument&&this.headingObserverOpen===this.open)return;this.resetHeadingObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headingObserverGeneration,observer=new MutationObserverCtor(()=>{this.headingObserver!==observer||this.headingObserverDocument!==ownerDocument||this.headingObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.detectLightDomChrome(),this.syncBodyTabIndex(),this.resetHeadingObserver(),this.armHeadingObserver())});if(this.headingObserver=observer,this.headingObserverDocument=ownerDocument,this.headingObserverOpen=this.open,observer.observe(this,{childList:!0}),this.open){for(const child of this.children)observer.observe(child,{attributes:!0,attributeFilter:["slot"]});const heading=Array.from(this.children).find(child=>child.getAttribute("slot")===null&&child.matches(HEADING_SELECTOR));heading&&observer.observe(heading,{attributes:!0,attributeFilter:["aria-label","aria-labelledby","aria-hidden","hidden","inert","class","style","slot"],characterData:!0,childList:!0,subtree:!0})}}resetHeadingObserver(){this.headingObserverGeneration+=1,this.headingObserver?.disconnect(),this.headingObserver=void 0,this.headingObserverDocument=void 0,this.headingObserverOpen=void 0}syncBodyTabIndex(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body)return;const next=this.open&&(body.scrollHeight>body.clientHeight&&body.scrollHeight>0||body.scrollWidth>body.clientWidth&&body.scrollWidth>0)?0:-1;body.tabIndex!==next&&(body.tabIndex=next)}armBodyOverflowObserver(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body||!this.isConnected||this.bodyOverflowObservedBody===body)return;this.resetBodyOverflowObserver();const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{this.bodyOverflowObserver!==observer||this.bodyOverflowObservedBody!==body||!this.isConnected||this.syncBodyTabIndex()});this.bodyOverflowObserver=observer,this.bodyOverflowObservedBody=body,observer.observe(body);for(const element of this.defaultSlotElements())observer.observe(element)}resetBodyOverflowObserver(){this.bodyOverflowObserver?.disconnect(),this.bodyOverflowObserver=void 0,this.bodyOverflowObservedBody=void 0}defaultSlotElements(){return this.renderRoot?.querySelector('[part="body"] slot:not([name])')?.assignedElements({flatten:!0})??[]}get disconnectHideCancelable(){return!1}detectLightDomChrome(){const children=Array.from(this.children),heading=children.find(el=>el.getAttribute("slot")===null&&el.matches(HEADING_SELECTOR));!heading||isAccessibilitySubtreeExcluded(heading)?this.headingText=void 0:heading.hasAttribute("aria-label")?this.headingText=heading.getAttribute("aria-label")??"":heading.hasAttribute("aria-labelledby")?this.headingText=composedAccessibilityText(heading,{ancestorBoundary:this}).trim()||void 0:this.headingText=composedAccessibilityText(Array.from(heading.childNodes),{ancestorBoundary:heading}).trim()||void 0,this.hasLabelSlot=children.some(el=>el.getAttribute("slot")==="label"),this.hasHeaderActionsSlot=children.some(el=>el.getAttribute("slot")==="header-actions")}show(){if(this.coalesceOpenRequest(!0)||this._open)return Promise.resolve();this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);return this.finishOpenRequest(),prevented||superseded?(this.syncOpenAttribute(),Promise.resolve()):(this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show"))}hide(){return this.close("api")}close(reason="api"){return this.closeFrom(reason,this)}closeFrom(reason,source){if(this.coalesceOpenRequest(!1)||!this._open)return Promise.resolve();if(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1))return this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve();if(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1))return this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve();this.finishOpenRequest(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1);const settled=this.settleTransition("lr-after-hide");return this.hideSettled=settled,this.emit("lr-close",{reason}),settled}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,next&&(this.initialFocusDecision=void 0),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}panelAnimationName(showing){return showing?"dialog.show":"dialog.hide"}overlayAnimationName(showing){return showing?"dialog.overlay.show":"dialog.overlay.hide"}panelAnimationSpec(showing){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}overlayAnimationSpec(showing){return{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-backdrop-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const root=this.renderRoot,panel=root.querySelector('[part~="panel"]'),backdrop=root.querySelector('[part~="backdrop"]'),showing=event==="lr-after-show",animations=[panel?animateRegistered(this,panel,this.panelAnimationName(showing),this.effectiveDirection,this.panelAnimationSpec(showing)):void 0,this.modalSurface&&backdrop?animateRegistered(this,backdrop,this.overlayAnimationName(showing),this.effectiveDirection,this.overlayAnimationSpec(showing)):void 0].filter(animation=>animation!==void 0);if(this.transitionAnimations=animations,await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return;this.cancelTransitionAnimations()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.leaveTopLayer(),this.flushPendingScrollLockRelease()),this.emit(event)}}enterTopLayer(){if(this.isConnected&&!this.nativeModal.show()&&typeof this.showPopover=="function"){this.getAttribute("popover")!=="manual"&&this.setAttribute("popover","manual");try{this.isTopLayer()||this.showPopover()}catch{}}}leaveTopLayer(){if(this.nativeModal.hide(),typeof this.hidePopover=="function")try{this.isTopLayer()&&this.hidePopover()}catch{}}isTopLayer(){try{return this.matches(":popover-open")}catch{return!1}}requestClose(source,reason,sourceElement){this.emit("lr-request-close",{source},{cancelable:!0}).defaultPrevented||this.closeFrom(reason,sourceElement)}focusInitial(){this.overlay?.focusInitial()}activateOverlay(){!this.isConnected||this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part~="backdrop"]')??this;this.requestClose("overlay","backdrop",backdrop)},preferredInitialFocus:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]'),body=this.renderRoot.querySelector('[part="body"]'),stops=body?collectFocusableElements(body):[];return stops.find(stop=>stop!==body)??stops[0]??panel},beforeInitialFocus:()=>(this.initialFocusDecision===void 0&&(this.initialFocusDecision=!this.emit("lr-initial-focus",null,{cancelable:!0}).defaultPrevented),this.initialFocusDecision),lockScroll:!0,suspendWhenUnrendered:!0}),this.externalModalDepth>0&&this.overlay.suspend())}deactivateOverlay(options){const overlay=this.overlay;return this.overlay=void 0,overlay?.deactivate(options)}render(){const suppressHeader=this.withoutHeader||this.noHeader,renderHeading=!suppressHeader&&!this.headingText&&(this.hasLabelSlot||(this.label??"").length>0||!!this.heading),hasHostName=this.hostAriaLabel!==null,explicitName=hasHostName?this.hostAriaLabel:this.headingText,hasExplicitName=hasHostName||!!explicitName,useHeadingForName=!hasExplicitName&&renderHeading,showHeader=!suppressHeader&&(renderHeading||this.hasHeaderActionsSlot||!this.withoutCloseButton),headingLevel=resolveHeadingLevel(this.headingLevel);return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener,scheduleDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{closeIcon}from"../../../internal/icons.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{styles}from"./dialog.styles.js";import{LYRA_DEFAULT_close}from"../../../internal/default-strings/shared.generated.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]';class LyraDialog extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close}}constructor(){super(),this._open=!1,this.label="",this.headingLevel="3",this.withoutCloseButton=!1,this.withoutHeader=!1,this.noHeader=!1,this.withFooter=!1,this.size="m",this.hostAriaLabel=null,this.lightDismiss=!1,this.hasFooterSlot=!1,this.hasLabelSlot=!1,this.hasHeaderActionsSlot=!1,this.focusReturnOpener=null,this.nativeModal=new NativeModalCarrier(this,{onCancel:event=>this.onNativeCancel(event),onUnexpectedClose:carrier=>{!this.open||!this.modalSurface||(this.closeFrom("api",carrier),this.open&&this.enterTopLayer())}}),this.modalPresentation=new ModalSurfaceController(this,this.nativeModal),this.headingObserverGeneration=0,this.transitionToken=0,this.transitionAnimations=[],this.headingId=nextId("dialog-heading"),this.externalModalDepth=0,this.modal={activateExternal:()=>{this.externalModalDepth++,this.externalModalDepth===1&&this.overlay?.suspend()},deactivateExternal:()=>{this.externalModalDepth!==0&&(this.externalModalDepth--,this.externalModalDepth===0&&this.open&&this.modalSurface&&(this.overlay?.resume(),queueMicrotask(()=>this.focusInitial())))}},this.onDefaultSlotChange=()=>{this.detectLightDomChrome(),this.syncBodyTabIndex(),this.resetBodyOverflowObserver(),this.armBodyOverflowObserver()},this.onFooterSlotChange=()=>{this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")},this.onNativeCancel=event=>{if(event.preventDefault(),!this.open||!this.overlay?.isTopmost())return;const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part~="close-button"]')??this;this.requestClose("close-button","close-button",button)},new GlassScrollLayer(this,'[part~="panel"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles,nativeModalCarrierStyles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get modalSurface(){return!0}willUpdate(changed){if(super.willUpdate(changed),(!this.hasUpdated||changed.has("open")&&this.open)&&(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer"),this.detectLightDomChrome()),this.open&&(changed.has("open")||changed.has("contained"))&&this.nativeModal.prepare(this.modalSurface),changed.has("open")){if(this.flushPendingScrollLockRelease(),this.open)cancelDeferredFocusReturn(this),this.focusReturnOpener=captureFocusReturnOpener(this),this.isConnected&&this.modalSurface&&this.activateOverlay();else{this.modalPresentation.beginClose();const returnsFocus=this.overlay!==void 0||composedContains(this,deepActiveElement(this.ownerDocument));this.pendingScrollLockRelease=this.deactivateOverlay({deferScrollLockRelease:!0});const opener=this.focusReturnOpener;this.focusReturnOpener=null,returnsFocus&&opener&&this.isConnected&&scheduleDeferredFocusReturn({host:this,candidates:()=>[opener],settled:this.hideSettled,isCurrent:()=>!this.open})}this.hideSettled=void 0}}flushPendingScrollLockRelease(){const release=this.pendingScrollLockRelease;this.pendingScrollLockRelease=void 0,release?.()}updated(changed){super.updated(changed),changed.has("open")&&this.armHeadingObserver(),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),changed.has("open")&&this.open&&this.isConnected&&(this.modalSurface&&(this.enterTopLayer(),this.focusInitial()),queueMicrotask(()=>{this.open&&this.isConnected&&this.detectLightDomChrome()}))}connectedCallback(){super.connectedCallback(),this.armHeadingObserver(),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),this.hasUpdated&&this.open&&(this.modalSurface&&(this.overlay?.isActive()?this.externalModalDepth===0&&this.overlay.resume():this.activateOverlay(),this.enterTopLayer()),queueMicrotask(()=>{!this.open||!this.isConnected||(this.detectLightDomChrome(),this.modalSurface&&this.focusInitial())}))}disconnectedCallback(){this.resetHeadingObserver(),this.resetBodyOverflowObserver(),super.disconnectedCallback(),this.modalPresentation.disconnect(),this.overlay?.suspend(),cancelDeferredFocusReturn(this),this.transitionToken++,this.flushPendingScrollLockRelease(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.open&&queueMicrotask(()=>{if(!this.isConnected&&this.open){if(this.emit("lr-hide",{source:this},{cancelable:this.disconnectHideCancelable}).defaultPrevented){this.syncOpenAttribute();return}this.applyOpenState(!1),this.emit("lr-close",{reason:"unmount"}),this.emit("lr-after-hide")}})}adoptedCallback(){super.adoptedCallback(),this.resetHeadingObserver(),this.resetBodyOverflowObserver(),this.isConnected&&(this.armHeadingObserver(),this.armBodyOverflowObserver(),this.syncBodyTabIndex())}armHeadingObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.headingObserver&&this.headingObserverDocument===ownerDocument&&this.headingObserverOpen===this.open)return;this.resetHeadingObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headingObserverGeneration,observer=new MutationObserverCtor(()=>{this.headingObserver!==observer||this.headingObserverDocument!==ownerDocument||this.headingObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.detectLightDomChrome(),this.syncBodyTabIndex(),this.resetHeadingObserver(),this.armHeadingObserver())});if(this.headingObserver=observer,this.headingObserverDocument=ownerDocument,this.headingObserverOpen=this.open,observer.observe(this,{childList:!0}),this.open){for(const child of this.children)observer.observe(child,{attributes:!0,attributeFilter:["slot"]});const heading=Array.from(this.children).find(child=>child.getAttribute("slot")===null&&child.matches(HEADING_SELECTOR));heading&&observer.observe(heading,{attributes:!0,attributeFilter:["aria-label","aria-labelledby","aria-hidden","hidden","inert","class","style","slot"],characterData:!0,childList:!0,subtree:!0})}}resetHeadingObserver(){this.headingObserverGeneration+=1,this.headingObserver?.disconnect(),this.headingObserver=void 0,this.headingObserverDocument=void 0,this.headingObserverOpen=void 0}syncBodyTabIndex(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body)return;const next=this.open&&(body.scrollHeight>body.clientHeight&&body.scrollHeight>0||body.scrollWidth>body.clientWidth&&body.scrollWidth>0)?0:-1;body.tabIndex!==next&&(body.tabIndex=next)}armBodyOverflowObserver(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body||!this.isConnected||this.bodyOverflowObservedBody===body)return;this.resetBodyOverflowObserver();const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{this.bodyOverflowObserver!==observer||this.bodyOverflowObservedBody!==body||!this.isConnected||this.syncBodyTabIndex()});this.bodyOverflowObserver=observer,this.bodyOverflowObservedBody=body,observer.observe(body);for(const element of this.defaultSlotElements())observer.observe(element)}resetBodyOverflowObserver(){this.bodyOverflowObserver?.disconnect(),this.bodyOverflowObserver=void 0,this.bodyOverflowObservedBody=void 0}defaultSlotElements(){return this.renderRoot?.querySelector('[part="body"] slot:not([name])')?.assignedElements({flatten:!0})??[]}get disconnectHideCancelable(){return!1}detectLightDomChrome(){const children=Array.from(this.children),heading=children.find(el=>el.getAttribute("slot")===null&&el.matches(HEADING_SELECTOR));!heading||isAccessibilitySubtreeExcluded(heading)?this.headingText=void 0:heading.hasAttribute("aria-label")?this.headingText=heading.getAttribute("aria-label")??"":heading.hasAttribute("aria-labelledby")?this.headingText=composedAccessibilityText(heading,{ancestorBoundary:this}).trim()||void 0:this.headingText=composedAccessibilityText(Array.from(heading.childNodes),{ancestorBoundary:heading}).trim()||void 0,this.hasLabelSlot=children.some(el=>el.getAttribute("slot")==="label"),this.hasHeaderActionsSlot=children.some(el=>el.getAttribute("slot")==="header-actions")}show(){if(this.coalesceOpenRequest(!0)||this._open)return Promise.resolve();this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);return this.finishOpenRequest(),prevented||superseded?(this.syncOpenAttribute(),Promise.resolve()):(this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show"))}hide(){return this.close("api")}close(reason="api"){return this.closeFrom(reason,this)}closeFrom(reason,source){if(this.coalesceOpenRequest(!1)||!this._open)return Promise.resolve();if(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1))return this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve();if(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1))return this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve();this.finishOpenRequest(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1);const settled=this.settleTransition("lr-after-hide");return this.hideSettled=settled,this.emit("lr-close",{reason}),settled}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,next&&(this.initialFocusDecision=void 0),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}panelAnimationName(showing){return showing?"dialog.show":"dialog.hide"}overlayAnimationName(showing){return showing?"dialog.overlay.show":"dialog.overlay.hide"}panelAnimationSpec(showing){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}overlayAnimationSpec(showing){return{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-backdrop-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const root=this.renderRoot,panel=root.querySelector('[part~="panel"]'),backdrop=root.querySelector('[part~="backdrop"]'),showing=event==="lr-after-show",animations=[panel?animateRegistered(this,panel,this.panelAnimationName(showing),this.effectiveDirection,this.panelAnimationSpec(showing)):void 0,this.modalSurface&&backdrop?animateRegistered(this,backdrop,this.overlayAnimationName(showing),this.effectiveDirection,this.overlayAnimationSpec(showing)):void 0].filter(animation=>animation!==void 0);if(this.transitionAnimations=animations,await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return;this.cancelTransitionAnimations()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.leaveTopLayer(),this.flushPendingScrollLockRelease()),this.emit(event)}}enterTopLayer(){this.externalModalDepth===0&&this.overlay?.resume(),this.modalPresentation.show()}leaveTopLayer(){this.modalPresentation.hide()}requestClose(source,reason,sourceElement){this.emit("lr-request-close",{source},{cancelable:!0}).defaultPrevented||this.closeFrom(reason,sourceElement)}focusInitial(){this.overlay?.focusInitial()}activateOverlay(){!this.isConnected||this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part~="backdrop"]')??this;this.requestClose("overlay","backdrop",backdrop)},preferredInitialFocus:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]'),body=this.renderRoot.querySelector('[part="body"]'),stops=body?collectFocusableElements(body):[];return stops.find(stop=>stop!==body)??stops[0]??panel},beforeInitialFocus:()=>(this.initialFocusDecision===void 0&&(this.initialFocusDecision=!this.emit("lr-initial-focus",null,{cancelable:!0}).defaultPrevented),this.initialFocusDecision),lockScroll:!0,suspendWhenUnrendered:!0}),this.externalModalDepth>0&&this.overlay.suspend())}deactivateOverlay(options){const overlay=this.overlay;return this.overlay=void 0,overlay?.deactivate(options)}render(){const suppressHeader=this.withoutHeader||this.noHeader,renderHeading=!suppressHeader&&!this.headingText&&(this.hasLabelSlot||(this.label??"").length>0||!!this.heading),hasHostName=this.hostAriaLabel!==null,explicitName=hasHostName?this.hostAriaLabel:this.headingText,hasExplicitName=hasHostName||!!explicitName,useHeadingForName=!hasExplicitName&&renderHeading,showHeader=!suppressHeader&&(renderHeading||this.hasHeaderActionsSlot||!this.withoutCloseButton),headingLevel=resolveHeadingLevel(this.headingLevel);return this.nativeModal.render(html`
|
|
2
2
|
<div part="backdrop overlay" @click=${this.onBackdropClick}></div>
|
|
3
3
|
<div
|
|
4
4
|
part="panel dialog"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraClipboardWriteFailure,type LyraClipboardWriteSuccess}from'../../../internal/clipboard.js';import type{LyraToolbarAction}from'../../conversation/message-actions/toolbar-actions.js';export type{LyraClipboardWriteFailure,LyraClipboardWriteOutcome,LyraClipboardWriteSuccess,LyraCopyErrorReason,}from'../../../internal/clipboard.js';
|
|
1
|
+
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraSize}from'../../../internal/variants.js';import{type LyraClipboardWriteFailure,type LyraClipboardWriteSuccess}from'../../../internal/clipboard.js';import type{LyraToolbarAction}from'../../conversation/message-actions/toolbar-actions.js';export type{LyraClipboardWriteFailure,LyraClipboardWriteOutcome,LyraClipboardWriteSuccess,LyraCopyErrorReason,}from'../../../internal/clipboard.js';
|
|
2
2
|
/** When the copy button's tooltip is available.*/
|
|
3
3
|
export type LyraCopyButtonTooltip='full'|'copy'|'none';
|
|
4
4
|
/** Side on which the copy button's tooltip appears.*/
|
|
@@ -21,19 +21,15 @@ export type LyraCopyButtonTooltipPlacement='top'|'right'|'bottom'|'left';export
|
|
|
21
21
|
* glyph, announces itself through the live region, and emits both `lr-error` and the retained,
|
|
22
22
|
* detailed `lr-copy-error` alias.
|
|
23
23
|
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* a library-wide floor change. A coarse-pointer/no-hover safety net (`internal/tokens.styles.ts`'s
|
|
34
|
-
* `baseTokens`) then floors the rendered hit area back at 2.75rem/44px regardless of how far the
|
|
35
|
-
* dense-row override lowered it, so an intentionally cramped desktop toolbar is still comfortably
|
|
36
|
-
* tappable the moment the pointer reaching it is a finger rather than a mouse.
|
|
24
|
+
* Optional `size` selects the shared `2xs` through `xl` height, glyph-font and radius ladder for
|
|
25
|
+
* the built-in trigger; `small`/`medium`/`large` alias `s`/`m`/`l`. Unset preserves its established
|
|
26
|
+
* shared `--lr-icon-button-size` floor (2.25rem by default) and inherited glyph font. A selected
|
|
27
|
+
* tier supplies the composed icon button's `--lr-icon-button-size-scope` input, retaining its
|
|
28
|
+
* coarse-pointer/no-hover minimum of 2.75rem/44px and allowing larger icon content to grow it.
|
|
29
|
+
* Shared form-control theme inputs retune the selected tier; public `--lr-icon-button-*` paint
|
|
30
|
+
* tokens and `::part(base-control)` remain available. With `size` unset, ancestor
|
|
31
|
+
* `--lr-icon-button-size-scope` and `--lr-theme-icon-button-size` inputs still control the hit
|
|
32
|
+
* area. A custom default-slot trigger keeps its caller-owned geometry at every tier.
|
|
37
33
|
*
|
|
38
34
|
* @customElement lr-copy-button
|
|
39
35
|
* @slot - A custom trigger. When present, it replaces the built-in icon button.
|
|
@@ -107,7 +103,9 @@ hoist:boolean;
|
|
|
107
103
|
* unnamed. */
|
|
108
104
|
accessibleLabel:string|null;
|
|
109
105
|
/** Prevent activation and remove the internal button from the tab order.*/
|
|
110
|
-
disabled:boolean;
|
|
106
|
+
disabled:boolean;private _size?;
|
|
107
|
+
/** Optional shared density tier for the built-in trigger. Unset preserves its original geometry.*/
|
|
108
|
+
get size():LyraSize|undefined;set size(next:LyraSize|undefined);
|
|
111
109
|
/** How long, in milliseconds, the copied confirmation or failure state remains visible.*/
|
|
112
110
|
feedbackDuration:number;private status;private sink?;private hasCustomTrigger;private triggerCollected;private lastObservedTrigger;private buttonEl?;private defaultSlot?;private readonly internals;private readonly toolbarAction;constructor();private copyTimer?;private copyGeneration;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;protected firstUpdated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private cancelFeedbackTimer;private resetFeedback;private setStatus;private customTrigger;private activeTrigger;private composedTriggerAction;private createToolbarAction;
|
|
113
111
|
/** The stable logical copy action exposed to an enclosing composite toolbar. Its optional
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{finiteDuration}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{styles}from"./copy-button.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_FEEDBACK_DURATION=COPY_FEEDBACK_MS,ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function copyIcon(){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{finiteDuration}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{sizes}from"../../../internal/sizes.styles.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{styles}from"./copy-button.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_FEEDBACK_DURATION=COPY_FEEDBACK_MS,ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function copyIcon(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -37,7 +37,7 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
|
|
|
37
37
|
aria-hidden="true"
|
|
38
38
|
focusable="false"
|
|
39
39
|
><circle cx="12" cy="12" r="9"></circle><path d="M12 7.25v5.5"></path><path d="M12 16.4v.01"></path></svg>
|
|
40
|
-
`}function isElementValue(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getAttribute=="function"}function isHtmlElementValue(value){if(!isElementValue(value))return!1;const candidate=value;return candidate.namespaceURI==="http://www.w3.org/1999/xhtml"&&typeof candidate.focus=="function"&&typeof candidate.blur=="function"&&typeof candidate.click=="function"}class CopySourceError extends Error{constructor(message){super(message),this.name="CopySourceError"}}class LyraCopyButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.styles=[LyraElement.styles,styles]}constructor(){super(),this.value="",this.from="",this.tooltip="full",this.tooltipPlacement="top",this.hoist=!1,this.accessibleLabel=null,this.disabled=!1,this.feedbackDuration=DEFAULT_FEEDBACK_DURATION,this.status="rest",this.hasCustomTrigger=!1,this.triggerCollected=!1,this.internals=attachInternalsSafely(this),this.toolbarAction=this.createToolbarAction(),this.copyGeneration=0,this.onClick=()=>{this.copy()},this.onDefaultSlotChange=event=>{this.onDefaultSlotChangeFromSlot(event.currentTarget)},this.onCustomTriggerClick=()=>{this.hasCustomTrigger&&this.copy()},this.stopInternalTooltipEvent=event=>{event.stopPropagation()},this.internals.role="group"}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("value")||changed.has("from"))&&this.resetFeedback()}updated(changed){super.updated(changed),(changed.has("disabled")||changed.has("hasCustomTrigger"))&&this.emit("lr-toolbar-actions-change")}firstUpdated(changed){super.firstUpdated(changed);const slot=this.defaultSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onDefaultSlotChangeFromSlot(s))})}connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","group"),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),super.disconnectedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}cancelFeedbackTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetFeedback(){this.copyGeneration+=1,this.cancelFeedbackTimer(),this.setStatus("rest")}setStatus(status){this.status=status,setCustomState(this.internals,"success",status==="success"),setCustomState(this.internals,"error",status==="error")}customTrigger(){return this.defaultSlot?.assignedElements({flatten:!0}).find(isHtmlElementValue)}activeTrigger(){return this.hasCustomTrigger?this.customTrigger():this.buttonEl}composedTriggerAction(){if(this.hasCustomTrigger)return;const[action]=this.buttonEl?.getToolbarActions()??[];return action}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1,delegated;const releaseDelegated=()=>{const previous=delegated;delegated=void 0,previous?.releaseTabIndex?.()},releaseTabIndex=()=>{releaseDelegated();const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"copy",get disabled(){const trigger=host.activeTrigger();return!trigger||host.disabled||trigger.disabled===!0},focus(options){host.activeTrigger()?.focus(options)},setTabIndex(tabIndex){const composed=host.composedTriggerAction();if(composed){delegated!==composed&&(releaseTabIndex(),delegated=composed),composed.setTabIndex(tabIndex);return}releaseDelegated();const trigger=host.activeTrigger();if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const trigger=host.activeTrigger();return trigger!=null&&path.includes(trigger)}}}getToolbarActions(){return[this.toolbarAction]}focus(options){this.activeTrigger()?.focus(options)}blur(){this.activeTrigger()?.blur()}click(){this.activeTrigger()?.click()}sourceById(id){const root=this.getRootNode();if((root.nodeType===9||root.nodeType===11)&&typeof root.getElementById=="function"){const source=root.getElementById(id);if(isElementValue(source))return source}const documentSource=this.ownerDocument.getElementById(id);return isElementValue(documentSource)?documentSource:null}resolveCopyText(){if(!this.from){if(!this.value)throw new CopySourceError("The copy value is empty.");return this.value}const expression=this.from.trim(),attributeMatch=/^(.*?)\[([^\]]+)\]$/.exec(expression),propertyMatch=attributeMatch?null:/^(.*?)\.([^.]*)$/.exec(expression),id=(attributeMatch?.[1]??propertyMatch?.[1]??expression).trim(),source=id?this.sourceById(id):null;if(!source)throw new CopySourceError(`The copy source "${id}" was not found.`);let resolved;if(attributeMatch){const attribute=attributeMatch[2].trim();resolved=attribute?source.getAttribute(attribute):null}else if(propertyMatch){const propertyName=propertyMatch[2].trim();resolved=propertyName?source[propertyName]:void 0}else resolved=source.textContent;const text=resolved==null?"":String(resolved);if(!text)throw new CopySourceError(`The copy source "${expression}" resolved to an empty value.`);return text}showStatus(status){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner)return;this.setStatus(status),this.sink?.announce(this.statusLabel(status)),this.cancelFeedbackTimer();const duration=finiteDuration(this.feedbackDuration,DEFAULT_FEEDBACK_DURATION,0),generation=this.copyGeneration;let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.setStatus("rest"))},duration),this.copyTimer={owner,handle,generation}}reportFailure(outcome){this.showStatus("error"),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}async copy(){if(this.disabled)return;const generation=++this.copyGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;let text="";try{text=this.resolveCopyText()}catch(error){this.isCurrentCopy(generation)&&this.reportFailure(Object.freeze({ok:!1,text,reason:"failed",error}));return}if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.reportFailure(outcome);return}this.showStatus("success"),this.emit("lr-copy",outcome)}}isCurrentCopy(generation,owner){return this.isConnected&&generation===this.copyGeneration&&(owner===void 0||this.ownerDocument.defaultView===owner)}onDefaultSlotChangeFromSlot(slot){const trigger=slot.assignedElements({flatten:!0}).find(isHtmlElementValue);if(this.triggerCollected&&trigger===this.lastObservedTrigger)return;this.triggerCollected=!0,this.lastObservedTrigger=trigger;const hasCustomTrigger=trigger!==void 0;if(hasCustomTrigger!==this.hasCustomTrigger){this.hasCustomTrigger=hasCustomTrigger;return}this.emit("lr-toolbar-actions-change")}statusLabel(status){return status==="success"?this.successLabel==null?this.localize("copied"):this.successLabel:status==="error"?this.errorLabel==null?this.localize("copyFailed"):this.errorLabel:this.copyLabel==null?this.localize("copy"):this.copyLabel}renderIcon(){return this.status==="error"?html`<span part="error-icon" aria-hidden="true"><slot name="error-icon">${errorIcon()}</slot></span>`:this.status==="success"?html`<span part="success-icon" aria-hidden="true"><slot name="success-icon">${checkIcon()}</slot></span>`:html`<span part="copy-icon" aria-hidden="true"><slot name="copy-icon">${copyIcon()}</slot></span>`}render(){const statusLabel=this.statusLabel(this.status),feedback=this.status==="rest"?"":statusLabel,part=this.status==="success"?"base button base-success":this.status==="error"?"base button base-error":"base button",tooltipDisabled=this.tooltip==="none"||statusLabel.trim()==="",tooltipOpen=!tooltipDisabled&&this.status!=="rest",buttonLabel=this.accessibleLabel?.trim()?this.accessibleLabel:statusLabel;return html`
|
|
40
|
+
`}function isElementValue(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getAttribute=="function"}function isHtmlElementValue(value){if(!isElementValue(value))return!1;const candidate=value;return candidate.namespaceURI==="http://www.w3.org/1999/xhtml"&&typeof candidate.focus=="function"&&typeof candidate.blur=="function"&&typeof candidate.click=="function"}class CopySourceError extends Error{constructor(message){super(message),this.name="CopySourceError"}}class LyraCopyButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed}}static{this.styles=[LyraElement.styles,sizes,styles]}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}constructor(){super(),this.value="",this.from="",this.tooltip="full",this.tooltipPlacement="top",this.hoist=!1,this.accessibleLabel=null,this.disabled=!1,this.feedbackDuration=DEFAULT_FEEDBACK_DURATION,this.status="rest",this.hasCustomTrigger=!1,this.triggerCollected=!1,this.internals=attachInternalsSafely(this),this.toolbarAction=this.createToolbarAction(),this.copyGeneration=0,this.onClick=()=>{this.copy()},this.onDefaultSlotChange=event=>{this.onDefaultSlotChangeFromSlot(event.currentTarget)},this.onCustomTriggerClick=()=>{this.hasCustomTrigger&&this.copy()},this.stopInternalTooltipEvent=event=>{event.stopPropagation()},this.internals.role="group"}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("value")||changed.has("from"))&&this.resetFeedback()}updated(changed){super.updated(changed),(changed.has("disabled")||changed.has("hasCustomTrigger"))&&this.emit("lr-toolbar-actions-change")}firstUpdated(changed){super.firstUpdated(changed);const slot=this.defaultSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onDefaultSlotChangeFromSlot(s))})}connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","group"),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),super.disconnectedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}cancelFeedbackTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetFeedback(){this.copyGeneration+=1,this.cancelFeedbackTimer(),this.setStatus("rest")}setStatus(status){this.status=status,setCustomState(this.internals,"success",status==="success"),setCustomState(this.internals,"error",status==="error")}customTrigger(){return this.defaultSlot?.assignedElements({flatten:!0}).find(isHtmlElementValue)}activeTrigger(){return this.hasCustomTrigger?this.customTrigger():this.buttonEl}composedTriggerAction(){if(this.hasCustomTrigger)return;const[action]=this.buttonEl?.getToolbarActions()??[];return action}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1,delegated;const releaseDelegated=()=>{const previous=delegated;delegated=void 0,previous?.releaseTabIndex?.()},releaseTabIndex=()=>{releaseDelegated();const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"copy",get disabled(){const trigger=host.activeTrigger();return!trigger||host.disabled||trigger.disabled===!0},focus(options){host.activeTrigger()?.focus(options)},setTabIndex(tabIndex){const composed=host.composedTriggerAction();if(composed){delegated!==composed&&(releaseTabIndex(),delegated=composed),composed.setTabIndex(tabIndex);return}releaseDelegated();const trigger=host.activeTrigger();if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const trigger=host.activeTrigger();return trigger!=null&&path.includes(trigger)}}}getToolbarActions(){return[this.toolbarAction]}focus(options){this.activeTrigger()?.focus(options)}blur(){this.activeTrigger()?.blur()}click(){this.activeTrigger()?.click()}sourceById(id){const root=this.getRootNode();if((root.nodeType===9||root.nodeType===11)&&typeof root.getElementById=="function"){const source=root.getElementById(id);if(isElementValue(source))return source}const documentSource=this.ownerDocument.getElementById(id);return isElementValue(documentSource)?documentSource:null}resolveCopyText(){if(!this.from){if(!this.value)throw new CopySourceError("The copy value is empty.");return this.value}const expression=this.from.trim(),attributeMatch=/^(.*?)\[([^\]]+)\]$/.exec(expression),propertyMatch=attributeMatch?null:/^(.*?)\.([^.]*)$/.exec(expression),id=(attributeMatch?.[1]??propertyMatch?.[1]??expression).trim(),source=id?this.sourceById(id):null;if(!source)throw new CopySourceError(`The copy source "${id}" was not found.`);let resolved;if(attributeMatch){const attribute=attributeMatch[2].trim();resolved=attribute?source.getAttribute(attribute):null}else if(propertyMatch){const propertyName=propertyMatch[2].trim();resolved=propertyName?source[propertyName]:void 0}else resolved=source.textContent;const text=resolved==null?"":String(resolved);if(!text)throw new CopySourceError(`The copy source "${expression}" resolved to an empty value.`);return text}showStatus(status){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner)return;this.setStatus(status),this.sink?.announce(this.statusLabel(status)),this.cancelFeedbackTimer();const duration=finiteDuration(this.feedbackDuration,DEFAULT_FEEDBACK_DURATION,0),generation=this.copyGeneration;let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.setStatus("rest"))},duration),this.copyTimer={owner,handle,generation}}reportFailure(outcome){this.showStatus("error"),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}async copy(){if(this.disabled)return;const generation=++this.copyGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;let text="";try{text=this.resolveCopyText()}catch(error){this.isCurrentCopy(generation)&&this.reportFailure(Object.freeze({ok:!1,text,reason:"failed",error}));return}if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.reportFailure(outcome);return}this.showStatus("success"),this.emit("lr-copy",outcome)}}isCurrentCopy(generation,owner){return this.isConnected&&generation===this.copyGeneration&&(owner===void 0||this.ownerDocument.defaultView===owner)}onDefaultSlotChangeFromSlot(slot){const trigger=slot.assignedElements({flatten:!0}).find(isHtmlElementValue);if(this.triggerCollected&&trigger===this.lastObservedTrigger)return;this.triggerCollected=!0,this.lastObservedTrigger=trigger;const hasCustomTrigger=trigger!==void 0;if(hasCustomTrigger!==this.hasCustomTrigger){this.hasCustomTrigger=hasCustomTrigger;return}this.emit("lr-toolbar-actions-change")}statusLabel(status){return status==="success"?this.successLabel==null?this.localize("copied"):this.successLabel:status==="error"?this.errorLabel==null?this.localize("copyFailed"):this.errorLabel:this.copyLabel==null?this.localize("copy"):this.copyLabel}renderIcon(){return this.status==="error"?html`<span part="error-icon" aria-hidden="true"><slot name="error-icon">${errorIcon()}</slot></span>`:this.status==="success"?html`<span part="success-icon" aria-hidden="true"><slot name="success-icon">${checkIcon()}</slot></span>`:html`<span part="copy-icon" aria-hidden="true"><slot name="copy-icon">${copyIcon()}</slot></span>`}render(){const statusLabel=this.statusLabel(this.status),feedback=this.status==="rest"?"":statusLabel,part=this.status==="success"?"base button base-success":this.status==="error"?"base button base-error":"base button",tooltipDisabled=this.tooltip==="none"||statusLabel.trim()==="",tooltipOpen=!tooltipDisabled&&this.status!=="rest",buttonLabel=this.accessibleLabel?.trim()?this.accessibleLabel:statusLabel;return html`
|
|
41
41
|
<lr-tooltip
|
|
42
42
|
.trigger=${this.tooltip==="full"?"hover focus":"manual"}
|
|
43
43
|
.placement=${this.tooltipPlacement}
|
|
@@ -66,4 +66,4 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
|
|
|
66
66
|
<span>${statusLabel}</span>
|
|
67
67
|
</lr-tooltip>
|
|
68
68
|
<span part="feedback" aria-hidden="true">${feedback}</span>
|
|
69
|
-
`}}__decorate([property()],LyraCopyButton.prototype,"value",void 0),__decorate([property()],LyraCopyButton.prototype,"from",void 0),__decorate([property({attribute:"copy-label"})],LyraCopyButton.prototype,"copyLabel",void 0),__decorate([property({attribute:"success-label"})],LyraCopyButton.prototype,"successLabel",void 0),__decorate([property({attribute:"error-label"})],LyraCopyButton.prototype,"errorLabel",void 0),__decorate([property({reflect:!0})],LyraCopyButton.prototype,"tooltip",void 0),__decorate([property({attribute:"tooltip-placement",reflect:!0})],LyraCopyButton.prototype,"tooltipPlacement",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCopyButton.prototype,"hoist",void 0),__decorate([property({attribute:"aria-label"})],LyraCopyButton.prototype,"accessibleLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCopyButton.prototype,"disabled",void 0),__decorate([property({type:Number,attribute:"feedback-duration"})],LyraCopyButton.prototype,"feedbackDuration",void 0),__decorate([state()],LyraCopyButton.prototype,"status",void 0),__decorate([state()],LyraCopyButton.prototype,"hasCustomTrigger",void 0),__decorate([query('[part~="base"]')],LyraCopyButton.prototype,"buttonEl",void 0),__decorate([query("slot:not([name])")],LyraCopyButton.prototype,"defaultSlot",void 0);export{LyraCopyButton};
|
|
69
|
+
`}}__decorate([property()],LyraCopyButton.prototype,"value",void 0),__decorate([property()],LyraCopyButton.prototype,"from",void 0),__decorate([property({attribute:"copy-label"})],LyraCopyButton.prototype,"copyLabel",void 0),__decorate([property({attribute:"success-label"})],LyraCopyButton.prototype,"successLabel",void 0),__decorate([property({attribute:"error-label"})],LyraCopyButton.prototype,"errorLabel",void 0),__decorate([property({reflect:!0})],LyraCopyButton.prototype,"tooltip",void 0),__decorate([property({attribute:"tooltip-placement",reflect:!0})],LyraCopyButton.prototype,"tooltipPlacement",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCopyButton.prototype,"hoist",void 0),__decorate([property({attribute:"aria-label"})],LyraCopyButton.prototype,"accessibleLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCopyButton.prototype,"disabled",void 0),__decorate([property({reflect:!0,converter:optionalSizeConverter})],LyraCopyButton.prototype,"size",null),__decorate([property({type:Number,attribute:"feedback-duration"})],LyraCopyButton.prototype,"feedbackDuration",void 0),__decorate([state()],LyraCopyButton.prototype,"status",void 0),__decorate([state()],LyraCopyButton.prototype,"hasCustomTrigger",void 0),__decorate([query('[part~="base"]')],LyraCopyButton.prototype,"buttonEl",void 0),__decorate([query("slot:not([name])")],LyraCopyButton.prototype,"defaultSlot",void 0);export{LyraCopyButton};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{visuallyHidden}from"../../../internal/a11y.js";import{css}from"lit";const styles=css` :host { display: inline-flex; --_lr-copy-button-color: var(--lr-color-text-quiet); --_lr-copy-button-color-hover: var(--lr-icon-button-color, var(--lr-color-text)); --_lr-copy-button-color-active: var( --lr-icon-button-color-hover, var(--lr-icon-button-color, var(--lr-color-text)) ); } lr-tooltip { display: inline-flex; } slot:not([name]) { display: contents; } [part~='base'] { --_lr-icon-button-color-default: var(--_lr-copy-button-color); --_lr-icon-button-color-hover-default: var(--_lr-copy-button-color-hover); --_lr-icon-button-color-active-default: var(--_lr-copy-button-color-active); } [part~='base'][part~='base-success'] { --lr-icon-button-color: var(--success-color, var(--lr-color-success)); --lr-icon-button-color-hover: var(--success-color, var(--lr-color-success)); --lr-icon-button-color-active: var(--success-color, var(--lr-color-success)); } [part~='base'][part~='base-error'] { --lr-icon-button-color: var(--error-color, var(--lr-color-danger)); --lr-icon-button-color-hover: var(--error-color, var(--lr-color-danger)); --lr-icon-button-color-active: var(--error-color, var(--lr-color-danger)); } [part~='copy-icon'], [part~='success-icon'], [part~='error-icon'] { display: inline-flex; } [part~='copy-icon'] svg, [part~='success-icon'] svg, [part~='error-icon'] svg { display: block; } [part='feedback'] { ${visuallyHidden} } `;export{styles};
|
|
1
|
+
import{visuallyHidden}from"../../../internal/a11y.js";import{css}from"lit";const styles=css` :host { display: inline-flex; --_lr-copy-button-color: var(--lr-color-text-quiet); --_lr-copy-button-color-hover: var(--lr-icon-button-color, var(--lr-color-text)); --_lr-copy-button-color-active: var( --lr-icon-button-color-hover, var(--lr-icon-button-color, var(--lr-color-text)) ); } lr-tooltip { display: inline-flex; } slot:not([name]) { display: contents; } [part~='base'] { --_lr-icon-button-color-default: var(--_lr-copy-button-color); --_lr-icon-button-color-hover-default: var(--_lr-copy-button-color-hover); --_lr-icon-button-color-active-default: var(--_lr-copy-button-color-active); } :host([size='2xs']) [part~='base'], :host([size='xs']) [part~='base'], :host([size='s']) [part~='base'], :host([size='small']) [part~='base'], :host([size='m']) [part~='base'], :host([size='medium']) [part~='base'], :host([size='l']) [part~='base'], :host([size='large']) [part~='base'], :host([size='xl']) [part~='base'] { --lr-icon-button-size-scope: var(--lr-form-control-height); --_lr-icon-button-radius-default: var(--lr-form-control-radius); font-size: var(--lr-form-control-font-size); } [part~='base'][part~='base-success'] { --lr-icon-button-color: var(--success-color, var(--lr-color-success)); --lr-icon-button-color-hover: var(--success-color, var(--lr-color-success)); --lr-icon-button-color-active: var(--success-color, var(--lr-color-success)); } [part~='base'][part~='base-error'] { --lr-icon-button-color: var(--error-color, var(--lr-color-danger)); --lr-icon-button-color-hover: var(--error-color, var(--lr-color-danger)); --lr-icon-button-color-active: var(--error-color, var(--lr-color-danger)); } [part~='copy-icon'], [part~='success-icon'], [part~='error-icon'] { display: inline-flex; } [part~='copy-icon'] svg, [part~='success-icon'] svg, [part~='error-icon'] svg { display: block; } [part='feedback'] { ${visuallyHidden} } `;export{styles};
|
|
@@ -197,7 +197,7 @@ spotlightPadding:number|string;
|
|
|
197
197
|
* default avoids losing onboarding progress to a stray click. Set it to opt in. */
|
|
198
198
|
lightDismiss:boolean;
|
|
199
199
|
/** Omits the built-in "Step X of Y" progress indicator (dots + text) from the footer.*/
|
|
200
|
-
withoutProgress:boolean;private accessibleLabel;private unanchored;private hasSlotContent;private spotlightPositioned;private overlay?;private readonly nativeModal;private placeCleanup?;private spotlightCleanup?;private interactiveKeyboardTarget?;private interactiveKeyboardDocument?;private overlayInteractive?;private activeTargetSnapshot;private focusReturnTarget;private escapedInset?;private readonly maskId;private readonly headingId;private readonly bodyId;private readonly progressTextId;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;
|
|
200
|
+
withoutProgress:boolean;private accessibleLabel;private unanchored;private hasSlotContent;private spotlightPositioned;private overlay?;private readonly nativeModal;private readonly modalSurface;private placeCleanup?;private spotlightCleanup?;private interactiveKeyboardTarget?;private interactiveKeyboardDocument?;private overlayInteractive?;private activeTargetSnapshot;private focusReturnTarget;private escapedInset?;private readonly maskId;private readonly headingId;private readonly bodyId;private readonly progressTextId;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;
|
|
201
201
|
/** Opens the tour at `index` (default `0`), clamped to `[0, steps.length - 1]`. Equivalent to
|
|
202
202
|
* `this.activeIndex = index; this.open = true;` plus the `lr-tour-start` event. */
|
|
203
203
|
start(index?:number):void;
|
|
@@ -213,4 +213,4 @@ goToStep(index:number):void;
|
|
|
213
213
|
/** Sugar for `end('skip')`. What the built-in Skip button calls.*/
|
|
214
214
|
skip():void;
|
|
215
215
|
/** Requests an ordinary end, then closes and publishes the accepted reason.*/
|
|
216
|
-
end(reason?:LyraTourEndReason):void;private clampIndex;private transitionTo;private resolveTarget;private canPreserveInteractiveTargetFocus;private activateStep;private spotlightPaddingPx;private focusAfterPlacement;private paintSpotlight;private resetSpotlightGeometry;private escapeContainingBlock;private releaseContainingBlockEscape;private disposePositioning;private activateOverlayInternal;private deactivateOverlayInternal;private onBackdropClick;private onDefaultSlotChange;private ownsDirectionalKeys;private onInteractiveScopeKeyDown;private onPopoverKeyDown;private formatProgressNumber;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-tour':LyraTour;}}
|
|
216
|
+
end(reason?:LyraTourEndReason):void;private clampIndex;private transitionTo;private resolveTarget;private canPreserveInteractiveTargetFocus;private activateStep;private spotlightPaddingPx;private focusAfterPlacement;private paintSpotlight;private resetSpotlightGeometry;private escapeContainingBlock;private applyViewportInset;private releaseContainingBlockEscape;private disposePositioning;private activateOverlayInternal;private deactivateOverlayInternal;private onBackdropClick;private onDefaultSlotChange;private ownsDirectionalKeys;private onInteractiveScopeKeyDown;private onPopoverKeyDown;private formatProgressNumber;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-tour':LyraTour;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{isCrossRealmPlainRecord}from"../../../internal/object-guards.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{hasTopLayerAncestor,needsTopLayerEscape,promoteToTopLayer,releaseTopLayer}from"../../../internal/top-layer-escape.js";import{styles}from"./tour.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256;import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings/utility.generated.js";const MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,SPOTLIGHT_PADDING_LENGTH=new RegExp(`^${CSS_NUMBER_SOURCE}(?:px|rem|em|vw|vh)$`,"i"),spotlightPaddingConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return SPOTLIGHT_PADDING_LENGTH.test(trimmed)?trimmed:Number(value)}},TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isCrossRealmPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this._open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.withoutProgress=!1,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.end("escape")},onUnexpectedClose:()=>{this.end("escape"),this.open&&this.nativeModal.show()}}),this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get open(){return this._open}set open(next){const normalized=!!next;if(normalized!==this._open){if(!this.hasUpdated){this.commitOpen(normalized);return}normalized?this.start(this.activeIndex):this.end("api"),this._open!==normalized&&this.toggleAttribute("open",this._open)}}commitOpen(next){const old=this._open;this._open=next,this.requestUpdate("open",old)}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;interactive&&this.nativeModal.hide(),this.nativeModal.prepare(!interactive)}if(this.open&&this.steps.length===0)this.commitOpen(!1),this.deactivateOverlayInternal(),this.hasUpdated&&this.emit("lr-tour-end",{reason:"unavailable"});else if(changed.has("open"))if(this.open){const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal();this.nativeModal.show();const shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;this.nativeModal.show();const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.nativeModal.hide(),this.overlay?.suspend(),cancelDeferredFocusReturn(this),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.commitOpen(!1),this.emit("lr-tour-end",{reason:"unmount"}))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.commitOpen(!0),this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end-request",{reason},{cancelable:!0}).defaultPrevented||(this.commitOpen(!1),this.emit("lr-tour-end",{reason}))}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change-request",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;this.escapeContainingBlock();const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const reducedMotion=!target.ownerDocument.defaultView||prefersReducedMotion(this);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,this.spotlightPaddingPx(step),interactive)),this.placeCleanup}spotlightPaddingPx(step){const value=step.spotlightPadding??this.spotlightPadding,px=typeof value=="string"?resolveCssLength(value,{host:this})??Number.NaN:value;return finiteRange(px,DEFAULT_SPOTLIGHT_PADDING,0)}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.commitOpen(!1),this.deactivateOverlayInternal(),this.emit("lr-tour-end",{reason:"unavailable"})}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=backdrop?.querySelector(".cutout"),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]'),cutout=backdrop?.querySelector(".cutout");if(cutout)for(const attribute of["x","y","width","height"])cutout.setAttribute(attribute,"0");if(spotlight){spotlight.hidden=!0;for(const property2 of["left","top","width","height"])spotlight.style.removeProperty(property2)}backdrop?.style.removeProperty("clip-path")}escapeContainingBlock(){const target=this.activeTargetSnapshot;if(this.steps[this.activeIndex]?.interactiveTarget&&!needsTopLayerEscape(this)&&!(target&&hasTopLayerAncestor(target))){this.releaseContainingBlockEscape();return}if(promoteToTopLayer(this)&&!this.escapedInset){const previous=["top","right","bottom","left"].map(property2=>({property:property2,value:this.style.getPropertyValue(property2),priority:this.style.getPropertyPriority(property2)}));this.style.setProperty("inset","0"),this.escapedInset={previous,written:this.style.getPropertyValue("top")}}}releaseContainingBlockEscape(){releaseTopLayer(this);const inset=this.escapedInset;if(this.escapedInset=void 0,!!inset)for(const{property:property2,value,priority}of inset.previous)this.style.getPropertyValue(property2)!==inset.written||this.style.getPropertyPriority(property2)!==""||(this.style.removeProperty(property2),value&&this.style.setProperty(property2,value,priority))}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const trigger=this.focusReturnTarget;if(!(!trigger||!this.isConnected))return{candidates:()=>[trigger.isConnected&&trigger.ownerDocument===this.ownerDocument?trigger:null],isCurrent:()=>!this.open}}}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.releaseContainingBlockEscape(),this.activeTargetSnapshot=null,this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0,this.focusReturnTarget=null}ownsDirectionalKeys(event){return keyEventOwnedByInnerControl(event,{container:this})}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.withoutProgress?"":this.progressTextId].filter(id=>id.length>0).join(" ");return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{isCrossRealmPlainRecord}from"../../../internal/object-guards.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{hasTopLayerAncestor,needsTopLayerEscape,promoteToTopLayer,releaseTopLayer}from"../../../internal/top-layer-escape.js";import{styles}from"./tour.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256;import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings/utility.generated.js";const MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,SPOTLIGHT_PADDING_LENGTH=new RegExp(`^${CSS_NUMBER_SOURCE}(?:px|rem|em|vw|vh)$`,"i"),spotlightPaddingConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return SPOTLIGHT_PADDING_LENGTH.test(trimmed)?trimmed:Number(value)}},TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isCrossRealmPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this._open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.withoutProgress=!1,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.end("escape")},onUnexpectedClose:()=>{this.end("escape"),this.open&&this.escapeContainingBlock()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal,()=>this),this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get open(){return this._open}set open(next){const normalized=!!next;if(normalized!==this._open){if(!this.hasUpdated){this.commitOpen(normalized);return}normalized?this.start(this.activeIndex):this.end("api"),this._open!==normalized&&this.toggleAttribute("open",this._open)}}commitOpen(next){const old=this._open;this._open=next,this.requestUpdate("open",old)}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;interactive&&(this.modalSurface.hide(),this.releaseContainingBlockEscape()),this.nativeModal.prepare(!interactive)}if(this.open&&this.steps.length===0)this.commitOpen(!1),this.deactivateOverlayInternal(),this.hasUpdated&&this.emit("lr-tour-end",{reason:"unavailable"});else if(changed.has("open"))if(this.open){const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal(),shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.modalSurface.disconnect(),this.releaseContainingBlockEscape(),this.overlay?.suspend(),cancelDeferredFocusReturn(this),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.commitOpen(!1),this.emit("lr-tour-end",{reason:"unmount"}))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.commitOpen(!0),this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end-request",{reason},{cancelable:!0}).defaultPrevented||(this.commitOpen(!1),this.emit("lr-tour-end",{reason}))}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change-request",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;this.escapeContainingBlock();const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const reducedMotion=!target.ownerDocument.defaultView||prefersReducedMotion(this);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,this.spotlightPaddingPx(step),interactive)),this.placeCleanup}spotlightPaddingPx(step){const value=step.spotlightPadding??this.spotlightPadding,px=typeof value=="string"?resolveCssLength(value,{host:this})??Number.NaN:value;return finiteRange(px,DEFAULT_SPOTLIGHT_PADDING,0)}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.commitOpen(!1),this.deactivateOverlayInternal(),this.emit("lr-tour-end",{reason:"unavailable"})}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=backdrop?.querySelector(".cutout"),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]'),cutout=backdrop?.querySelector(".cutout");if(cutout)for(const attribute of["x","y","width","height"])cutout.setAttribute(attribute,"0");if(spotlight){spotlight.hidden=!0;for(const property2 of["left","top","width","height"])spotlight.style.removeProperty(property2)}backdrop?.style.removeProperty("clip-path")}escapeContainingBlock(){const target=this.activeTargetSnapshot;if(!this.steps[this.activeIndex]?.interactiveTarget){this.overlay?.resume(),this.modalSurface.show(),this.applyViewportInset();return}if(this.steps[this.activeIndex]?.interactiveTarget&&!needsTopLayerEscape(this)&&!(target&&hasTopLayerAncestor(target))){this.releaseContainingBlockEscape();return}promoteToTopLayer(this)&&this.applyViewportInset()}applyViewportInset(){if(!this.escapedInset){const previous=["top","right","bottom","left"].map(property2=>({property:property2,value:this.style.getPropertyValue(property2),priority:this.style.getPropertyPriority(property2)}));this.style.setProperty("inset","0"),this.escapedInset={previous,written:this.style.getPropertyValue("top")}}}releaseContainingBlockEscape(){releaseTopLayer(this);const inset=this.escapedInset;if(this.escapedInset=void 0,!!inset)for(const{property:property2,value,priority}of inset.previous)this.style.getPropertyValue(property2)!==inset.written||this.style.getPropertyPriority(property2)!==""||(this.style.removeProperty(property2),value&&this.style.setProperty(property2,value,priority))}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const trigger=this.focusReturnTarget;if(!(!trigger||!this.isConnected))return{candidates:()=>[trigger.isConnected&&trigger.ownerDocument===this.ownerDocument?trigger:null],isCurrent:()=>!this.open}}}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.releaseContainingBlockEscape(),this.activeTargetSnapshot=null,this.modalSurface.hide(),this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0,this.focusReturnTarget=null}ownsDirectionalKeys(event){return keyEventOwnedByInnerControl(event,{container:this})}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.withoutProgress?"":this.progressTextId].filter(id=>id.length>0).join(" ");return this.nativeModal.render(html`
|
|
2
2
|
<svg part="backdrop" aria-hidden="true" @click=${this.onBackdropClick}>
|
|
3
3
|
${this.unanchored?nothing:svg`
|
|
4
4
|
<defs>
|