@aceshooting/lyra-ui 28.1.1 → 28.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +3 -3
- package/dist/components/conversation/push-to-talk/push-to-talk.class.d.ts +2 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/layout/details/accordion.class.js +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/utility/tour/tour.class.js +4 -4
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-push-to-talk.md +3 -0
- package/llms/peers.md +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var _a;import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=[];if(this.items.forEach((item,index)=>{this.isNavigable(item)&&navigable.push({item,index})}),this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(({index})=>index>current)?.item??navigable.find(({index})=>index<current)?.item;next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){if(this.dropdownContained&&this.dropdownOwner){this.focusContained(focus);return}this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot){const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index]))return;this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;const assignedItems=new Set(assigned);for(const item of previousItems)assignedItems.has(item)||this.releaseItemOwner(item);for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}if(this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)return!1;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,match=this.typeBuffer.match(navigable,currentIndex,item=>item.getTextLabel(),this.effectiveLocale);match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
|
|
1
|
+
var _a;import{__decorate}from"tslib";import{maxCssTime}from"../../../internal/css-motion-time.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{isRovingTargetAvailable,resolveListMove}from"../../../internal/list-navigation.js";import{PopupController}from"../../../internal/popup-controller.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectFocusableElements,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./menu.styles.js";import{menuItemOwner,submenuPanelController}from"./menu-shared.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{activeElementIn,isUsableActiveElement,safeDeepActiveElement}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import"./menu-item.class.js";import{LYRA_DEFAULT_menuLabel}from"../../../internal/default-strings/shared.generated.js";const SUBMENU_PLACEMENT="right-start",SUBMENU_FALLBACK_PLACEMENTS=["right-end","left-start","left-end","bottom-start","top-start"],MENUBAR_PLACEMENT="bottom-start",SUBMENU_OPEN_DELAY=150,SUBMENU_CLOSE_DELAY=300;function isLyraMenuItemElement(value){return isHtmlElement(value)?value.localName===tag("menu-item")||value.localName===tag("dropdown-item"):!1}function isLyraMenuElement(value){return isHtmlElement(value)&&value.localName===tag("menu")}let menuWidthScaleRegistered=!1;function registerMenuWidthScale(){if(!menuWidthScaleRegistered&&(menuWidthScaleRegistered=!0,!(typeof CSS>"u"||typeof CSS.registerProperty!="function")))try{CSS.registerProperty({name:"--_lr-menu-max-inline-size",syntax:"<length-percentage>",inherits:!1,initialValue:"100%"})}catch{}}class LyraMenu extends LyraElement{constructor(){super(...arguments),this.presentationOpen=!1,this.presentationHidden=!0,this.submenuAnchor=null,this.submenuStateChange=null,this.dropdownContained=!1,this.dropdownOwner=null,this._dropdownOpen=!1,this.dropdownRendersMenuRole=!1,this.dropdownStayOpenOnSelect=!1,this.items=[],this.activeIndex=-1,this.presentationPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.menubarAnchored=!1,this.pendingFocus="first",this.listId=nextId("menu-list"),this.owningMenu={activate:item=>this.onOwnedItemSelect(item),uncheckRadioGroup:(item,group)=>this.uncheckRadioGroupSiblings(item,group)},this.typeBuffer=new TypeAheadBuffer(this),this[_a]=this.createSubmenuController(),this.onRegionSlotChange=()=>{this.syncRegionState()},this.onDocPointer=e=>{const path=e.composedPath();path.includes(this)||this.submenuAnchor&&path.includes(this.submenuAnchor)||this.closePresentation()},this.onItemsSlotChange=e=>{this.syncItemsFromSlot(e.target)},this.itemStateChangeReconciliationPending=!1,this.onItemStateChangeEvent=event=>{event.stopPropagation(),!this.itemStateChangeReconciliationPending&&(this.itemStateChangeReconciliationPending=!0,queueMicrotask(()=>{this.itemStateChangeReconciliationPending=!1,this.onItemStateChange()}))},this.onItemStateChange=()=>{const navigable=[];if(this.items.forEach((item,index)=>{this.isNavigable(item)&&navigable.push({item,index})}),this.activeIndex>=0&&!this.isNavigable(this.items[this.activeIndex])){const current=this.activeIndex,displaced=this.items[current],focused=safeDeepActiveElement(this.ownerDocument),displacedHadFocus=focused===null||focused===this.ownerDocument.body||focused===displaced||composedContains(displaced,focused),next=navigable.find(({index})=>index>current)?.item??navigable.find(({index})=>index<current)?.item;next?this.setActiveItem(next,displacedHadFocus):(this.activeIndex=-1,this.applyRovingTabIndex(),displacedHadFocus&&this.rehomeZeroSurvivorFocus());return}this.applyRovingTabIndex()},this.onListFocusIn=e=>{const target=e.target;if(!isLyraMenuItemElement(target))return;const index=this.items.indexOf(target);index===-1||index===this.activeIndex||!this.isNavigable(target)||(this.activeIndex=index,this.applyRovingTabIndex(),this.closeSubmenus(target))},this.onListKeyDown=e=>{if(this.isForeignEvent(e)||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;const isItemTarget=isLyraMenuItemElement(e.target);if(e.key==="Escape"&&isItemTarget&&!this.hasStandalonePresentation){e.preventDefault(),this.closePresentation({focusTrigger:!0});return}if(!isItemTarget)return;const navigable=this.items.filter(i=>this.isNavigable(i)),current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentNavIndex=current?navigable.indexOf(current):-1,intoSubmenuKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";switch(e.key){case"ArrowRight":case"ArrowLeft":e.key===intoSubmenuKey?current?.hasSubmenu&&this.isNavigable(current)&&(e.preventDefault(),this.closeSubmenus(current),current.openSubmenu("first")):this.submenuAnchor&&!this.menubarAnchored&&(e.preventDefault(),this.closePresentation({focusTrigger:!0}));break;case"ArrowDown":case"ArrowUp":case"Home":case"End":{e.preventDefault();const nextIndex=resolveListMove(e,{count:navigable.length,current:currentNavIndex,orientation:"vertical"});nextIndex!==null&&this.setActiveItem(navigable[nextIndex]);break}case"Enter":case" ":e.preventDefault(),current?.hasSubmenu?(this.closeSubmenus(current),current.openSubmenu("first")):current?.isLinkItem?current.click():current?.select();break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);return}},this.onPopupPointerOver=e=>{if(!this.interactionOpen)return;const hovered=this.ownItemFromEvent(e);this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&opened===hovered?(this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuCloseTimer=void 0):opened&&this.scheduleSubmenuClose(opened),!(!hovered||hovered===opened||!hovered.hasSubmenu||!this.isNavigable(hovered))&&(this.submenuOpenTimer=this.scheduleOwnedTimeout(()=>{this.submenuOpenTimer=void 0,!(!this.interactionOpen||!this.items.includes(hovered))&&(this.closeSubmenus(hovered),hovered.openSubmenu("none"))},SUBMENU_OPEN_DELAY))},this.onPopupPointerLeave=()=>{this.clearOwnedTimeout(this.submenuOpenTimer),this.submenuOpenTimer=void 0;const opened=this.openSubmenuItem();opened&&this.scheduleSubmenuClose(opened)},this.onNestedSelect=e=>{if(e.target===this)return;const event=e;this.dropdownStayOpenOnSelect&&event.preventDefault(),queueMicrotask(()=>{event.defaultPrevented||this.dismissAfterSelection(!0)})},this.onPopupKeyDown=e=>{const listEl=this.popupPart("list");if(e.key==="Escape"){if(listEl&&e.composedPath().includes(listEl)||this.hasStandalonePresentation)return;e.preventDefault(),this.closePresentation({focusTrigger:!0});return}e.key==="Tab"&&this.tabWouldLeavePopup(e)&&this.closePresentation()}}static{_a=submenuPanelController}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["item"])})}static{this.styles=[LyraElement.styles,styles]}get dropdownOpen(){return this._dropdownOpen}set dropdownOpen(next){const normalized=!!next;if(normalized===this._dropdownOpen)return;const old=this._dropdownOpen;this._dropdownOpen=normalized,this.presentationOpen=normalized,this.requestUpdate("dropdownOpen",old)}createSubmenuController(){const menu=this;return{get open(){return menu.submenuAnchor!==null&&menu.presentationOpen},attach(anchor,onStateChange,options){menu.submenuAnchor&&menu.submenuAnchor!==anchor&&menu.closePresentation(),menu.menubarAnchored=options?.menubar===!0,menu.submenuAnchor=anchor,menu.submenuStateChange=onStateChange,menu.syncPresentationState(),menu.requestUpdate()},detach(anchor){menu.submenuAnchor===anchor&&(menu.closePresentation(),menu.submenuAnchor=null,menu.menubarAnchored=!1,menu.submenuStateChange=null,menu.cleanup?.(),menu.cleanup=void 0,menu.syncPresentationState(),menu.requestUpdate())},async show(focus="first"){menu.submenuAnchor&&(menu.openPresentation(focus),await menu.updateComplete,await menu.focusAfterPlacement(focus))},async hide(options){menu.closePresentation(options),await menu.updateComplete}}}connectedCallback(){if(super.connectedCallback(),registerMenuWidthScale(),this.hasUpdated){const slot=this.renderRoot.querySelector("slot:not([name])");slot&&this.syncItemsFromSlot(slot,!0)}}firstUpdated(changed){super.firstUpdated(changed),this.syncRegionState(),this.syncPresentationState();const slot=this.itemsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.syncItemsFromSlot(s))})}get hasStandalonePresentation(){return!this.dropdownContained&&!this.submenuAnchor}get interactionOpen(){return this.hasStandalonePresentation||this.presentationOpen}syncPresentationState(){const standalone=this.hasStandalonePresentation;if(this.toggleAttribute("data-inline",standalone),this.toggleAttribute("data-submenu",this.submenuAnchor!==null),this.toggleAttribute("data-contained",this.dropdownContained),standalone){const active=this.activeIndex>=0?this.items[this.activeIndex]:void 0;if(!active||!this.isNavigable(active)){const first=this.items.find(item=>this.isNavigable(item));this.activeIndex=first?this.items.indexOf(first):-1}}else this.presentationOpen||(this.activeIndex=-1);this.applyRovingTabIndex()}syncRegionState(){const assigned=selector=>this.renderRoot.querySelector(selector)?.assignedElements({flatten:!0}).length??0;this.toggleAttribute("data-has-header",assigned('slot[name="header"]')>0),this.toggleAttribute("data-has-footer",assigned('slot[name="footer"]')>0),this.toggleAttribute("data-list-empty",assigned("slot:not([name])")===0)}willUpdate(changed){super.willUpdate(changed),this.presentationOpen&&this.submenuAnchor&&(this.cancelPresentationHideWatch(),this.presentationHidden=!1)}updated(changed){super.updated(changed);const list=this.renderRoot.querySelector('[part~="list"]')??void 0;syncAriaDescribedByElements(this,list,this.getAttribute("aria-describedby")),(changed.has("presentationOpen")||changed.has("dropdownOpen")||changed.has("dropdownContained"))&&(this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.presentationOpen?this.submenuAnchor?(this.popupController.bindPointer(),this.reposition()):(this.popupController.unbindPointer(),this.presentationPositioned=!0,this.focusRoving(this.pendingFocus)):(this.popupController.unbindPointer(),this.resetTypeAhead(),this.activeIndex=-1,this.applyRovingTabIndex(),this.clearSubmenuTimers(),this.closeSubmenus(),this.submenuAnchor&&this.schedulePresentationHide())),changed.has("dropdownContained")&&this.syncPresentationState(),changed.has("dropdownSize")&&this.applyDropdownSize()}reposition(){this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1;const popup=this.renderRoot.querySelector(".submenu-surface");if(this.submenuAnchor&&popup){const placement=this.menubarAnchored?MENUBAR_PLACEMENT:rtlAwarePlacement(SUBMENU_PLACEMENT,this),topLayer=this.submenuAnchor.closest(tag("menubar"))?.topLayer===!0;this.placedTopLayer=syncTopLayerRelease(popup,this.placedTopLayer,topLayer),this.cleanup=place(this.submenuAnchor,popup,{placement,flipFallbackPlacements:this.menubarAnchored?void 0:SUBMENU_FALLBACK_PLACEMENTS.map(candidate=>rtlAwarePlacement(candidate,this)),...topLayerPlacement(topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))})}}cancelPresentationHideWatch(){this.presentationHideWatcher?.(),this.presentationHideWatcher=void 0}schedulePresentationHide(){this.cancelPresentationHideWatch();const surface=this.renderRoot.querySelector(".submenu-surface"),view=this.ownerDocument.defaultView,transitionMs=surface&&view?maxCssTime(view.getComputedStyle(surface).transitionDuration)+maxCssTime(view.getComputedStyle(surface).transitionDelay):0,waitForEvent=!!(surface&&view&&transitionMs>0&&!prefersReducedMotion(this));let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd),this.presentationHideWatcher===cancel&&(this.presentationHideWatcher=void 0),this.presentationHidden=!0)},onEnd=event=>{event.target===surface&&finish()},cancel=()=>{settled=!0,timeout!==void 0&&view?.clearTimeout(timeout),surface?.removeEventListener("transitionend",onEnd)};this.presentationHideWatcher=cancel,waitForEvent&&surface&&view?(surface.addEventListener("transitionend",onEnd),timeout=view.setTimeout(finish,transitionMs+50)):queueMicrotask(finish)}async focusAfterPlacement(focus){if(!this.presentationOpen||!this.submenuAnchor)return;const positioned=this.cleanup!==void 0&&(this.presentationPositioned||await waitForDeferredPlacement(()=>this.cleanup));if(!(!this.presentationOpen||!this.submenuAnchor)){if(!positioned){this.closePresentation(),await this.updateComplete;return}this.presentationPositioned=!0,this.focusRoving(focus)}}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.presentationPositioned=!1,this.resetTypeAhead(),this.clearSubmenuTimers(),this.itemStateObserver?.disconnect(),this.itemStateObserver=void 0,this.popupController.unbindPointer();for(const item of this.items)this.releaseItemOwner(item);this._dropdownOpen=!1,this.presentationOpen=!1,this.cancelPresentationHideWatch(),this.presentationHidden=!0,this.submenuStateChange?.(!1)}scheduleOwnedTimeout(callback,delay){const owner=this.ownerDocument.defaultView;if(owner)return{owner,handle:owner.setTimeout(callback,delay)}}clearOwnedTimeout(timer){timer&&timer.owner.clearTimeout(timer.handle)}focusContained(focus="first"){if(this.dropdownContained&&this.dropdownOwner)if(this.dropdownOwner.open)this.pendingFocus=focus,this.focusRoving(focus);else{const transition=this.dropdownOwner.show();this.dropdownOwner.open&&(this.pendingFocus=focus)}}openPresentation(focus="first"){if(this.dropdownContained&&this.dropdownOwner){this.focusContained(focus);return}this.pendingFocus=focus,this.presentationOpen?(!this.submenuAnchor||this.presentationPositioned)&&this.focusRoving(focus):(this.presentationOpen=!0,this.submenuStateChange?.(!0))}closePresentation(options){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide(options);return}this.presentationOpen&&(this.presentationOpen=!1,this.submenuStateChange?.(!1),options?.focusTrigger&&this.submenuAnchor&&resolveAccessibleTrigger(this.submenuAnchor).focus())}syncItemsFromSlot(slot,reconnect=!1){if(!this.isConnected)return;const assigned=slot.assignedElements({flatten:!0}).filter(isLyraMenuItemElement);if(assigned.length===this.items.length&&assigned.every((item,index)=>item===this.items[index])){reconnect&&(this.observeItems(),this.syncPresentationState());return}this.itemStateObserver?.disconnect();const previousItems=this.items,previouslyActive=this.activeIndex>=0?this.items[this.activeIndex]:void 0,focusedBefore=safeDeepActiveElement(this.ownerDocument),activeItemLostFocus=!!previouslyActive&&(focusedBefore===null||focusedBefore===this.ownerDocument.body||focusedBefore===previouslyActive||composedContains(previouslyActive,focusedBefore));this.items=assigned;const assignedItems=new Set(assigned);for(const item of previousItems)assignedItems.has(item)||this.releaseItemOwner(item);if(this.observeItems(),this.activeIndex=previouslyActive?this.items.indexOf(previouslyActive):-1,this.syncPresentationState(),this.syncRegionState(),this.interactionOpen)if(this.activeIndex===-1){const successor=this.items.find(item=>this.isNavigable(item));previouslyActive&&successor?this.setActiveItem(successor,activeItemLostFocus):this.focusRoving(this.pendingFocus),activeItemLostFocus&&!this.items.some(item=>this.isNavigable(item))&&this.rehomeZeroSurvivorFocus()}else{const active=activeElementIn(this.ownerDocument);!(isUsableActiveElement(active)&&this.contains(active))&&activeItemLostFocus&&this.items[this.activeIndex].focus()}}observeItems(){for(const item of this.items)this.acquireItemOwner(item);this.applyDropdownSize();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){const owner=this.ownerDocument;let observer;observer=new MutationObserverCtor(()=>{this.itemStateObserver!==observer||this.ownerDocument!==owner||this.onItemStateChange()}),this.itemStateObserver=observer;for(const item of this.items)this.itemStateObserver.observe(item,{attributes:!0,attributeFilter:["disabled","hidden","aria-hidden","inert"]})}}acquireItemOwner(item){item[menuItemOwner]?.(this.owningMenu)}releaseItemOwner(item){item[menuItemOwner]?.(null,this.owningMenu)}uncheckRadioGroupSiblings(item,group){for(const sibling of this.items)sibling!==item&&sibling.type==="radio"&&sibling.group===group&&sibling.checked&&(sibling.checked=!1)}isNavigable(item){return!item.interactionDisabled&&isRovingTargetAvailable(item)}applyDropdownSize(){if(this.dropdownSize)for(const item of this.items)item.size=this.dropdownSize}rehomeZeroSurvivorFocus(){if(this.dropdownContained&&this.dropdownOwner){this.dropdownOwner.hide({focusTrigger:!0});return}if(this.submenuAnchor){this.closePresentation({focusTrigger:!0});return}const list=this.renderRoot.querySelector('[part~="list"]');list&&(list.tabIndex=-1,list.focus({preventScroll:!0}))}onOwnedItemSelect(item){if(!isLyraMenuItemElement(item)||!this.items.includes(item))return;!this.emit("lr-select",{item},{cancelable:!0}).defaultPrevented&&!this.dropdownStayOpenOnSelect&&this.dismissAfterSelection(!0)}dismissAfterSelection(focusTrigger){this.closeSubmenus(),this.dropdownContained?this.dropdownOwner&&this.dropdownOwner.hide({focusTrigger}):this.submenuAnchor&&this.closePresentation({focusTrigger})}applyRovingTabIndex(){this.items.forEach((item,i)=>{item.tabIndex=i===this.activeIndex?0:-1})}focusRoving(which){if(which==="none")return;const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const item=which==="first"?navigable[0]:navigable[navigable.length-1];item&&this.setActiveItem(item)}setActiveItem(item,moveFocus=!0){this.activeIndex=this.items.indexOf(item),this.applyRovingTabIndex(),this.closeSubmenus(item),moveFocus&&item.focus()}closeSubmenus(keep){for(const item of this.items)item!==keep&&item.submenuOpen&&item.closeSubmenu()}openSubmenuItem(){return this.items.find(item=>item.submenuOpen)}clearSubmenuTimers(){this.clearOwnedTimeout(this.submenuOpenTimer),this.clearOwnedTimeout(this.submenuCloseTimer),this.submenuOpenTimer=void 0,this.submenuCloseTimer=void 0}ownItemFromEvent(e){let owner;for(const node of e.composedPath()){if(node===this)break;isLyraMenuItemElement(node)&&(owner=node)}return owner}isForeignEvent(e){for(const node of e.composedPath()){if(node===this)return!1;if(isLyraMenuElement(node))return!0}return!1}scheduleSubmenuClose(item){this.submenuCloseTimer||(this.submenuCloseTimer=this.scheduleOwnedTimeout(()=>{this.submenuCloseTimer=void 0,item.submenuOpen&&(composedContains(item,safeDeepActiveElement(this.ownerDocument))||item.closeSubmenu())},SUBMENU_CLOSE_DELAY))}popupPart(name){return this.renderRoot.querySelector(`[part="${name}"]`)}tabWouldLeavePopup(e){const header=this.popupPart("header"),footer=this.popupPart("footer"),listEl=this.popupPart("list"),backwards=e.shiftKey,active=safeDeepActiveElement(this.ownerDocument),headerStops=header?collectFocusableElements(header):[],footerStops=footer?collectFocusableElements(footer):[],listStops=listEl?collectFocusableElements(listEl):[],hasNeighbor=stops=>{const index=active?stops.indexOf(active):-1;return index===-1?!1:backwards?index>0:index<stops.length-1},path=e.composedPath();return footer&&path.includes(footer)?hasNeighbor(footerStops)?!1:backwards?listStops.length===0&&headerStops.length===0:!0:header&&path.includes(header)?hasNeighbor(headerStops)?!1:backwards?!0:listStops.length===0&&footerStops.length===0:!isLyraMenuItemElement(e.target)&&hasNeighbor(listStops)?!1:backwards?headerStops.length===0:footerStops.length===0}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.items.filter(i=>this.isNavigable(i));if(!navigable.length)return;const current=this.activeIndex>=0?this.items[this.activeIndex]:void 0,currentIndex=current?navigable.indexOf(current):-1,match=this.typeBuffer.match(navigable,currentIndex,item=>item.getTextLabel(),this.effectiveLocale);match!==null&&this.setActiveItem(navigable[match])}resetTypeAhead(){this.typeBuffer.clear()}get effectiveLabel(){const hostLabel=this.getAttribute("aria-label");return hostLabel!==null?hostLabel:this.label!==void 0?this.label:this.dropdownLabel!==void 0?this.dropdownLabel:this.localize("menuLabel")}renderContents(bindPointerOver=!0){return html`
|
|
2
2
|
<div part="header">
|
|
3
3
|
<slot name="header" @slotchange=${this.onRegionSlotChange}></slot>
|
|
4
4
|
</div>
|
|
@@ -145,7 +145,7 @@ mobileBreakpoint:string;
|
|
|
145
145
|
/** Logical edge occupied by desktop navigation and the mobile drawer. */
|
|
146
146
|
navigationPlacement:PageNavigationPlacement;
|
|
147
147
|
/** Hides the default mobile toggle. Slotted `data-toggle-nav` controls remain available. */
|
|
148
|
-
disableNavigationToggle:boolean;private accessibleLabel;private readonly mainId;private readonly navigationId;private readonly drawerId;private readonly skipTargetId;private readonly skipLabelId;private fragmentTargetId;private fragmentTabIndex;private resizeObserver?;private resizeView?;private overlayHandle?;private readonly nativeModal;private navigationTriggerOwner?;private navigationOpener;private customToggle?;private customToggles;private readonly customToggleOwnership;private mainElement?;private drawerElement?;connectedCallback():void;disconnectedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues<this>):void;private observeAllocation;private readonly onWindowResize;private measureAllocation;private applyMeasuredInlineSize;private syncOverlay;private readonly navigationDeferredReturn;private readonly resolveNavigationRestoreTarget;private syncCustomToggle;private releaseCustomToggleA11y;private isUnavailableCustomToggle;private rememberTriggerAndToggle;private readonly onDefaultToggleClick;private readonly onToggleSlotClick;private readonly onPageClick;private readonly onBackdropClick;private readonly onSkipClick;private requestNavOpen;
|
|
148
|
+
disableNavigationToggle:boolean;private accessibleLabel;private readonly mainId;private readonly navigationId;private readonly drawerId;private readonly skipTargetId;private readonly skipLabelId;private fragmentTargetId;private fragmentTabIndex;private resizeObserver?;private readonly allocationFrame;private resizeView?;private overlayHandle?;private readonly nativeModal;private navigationTriggerOwner?;private navigationOpener;private customToggle?;private customToggles;private readonly customToggleOwnership;private mainElement?;private drawerElement?;connectedCallback():void;disconnectedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues<this>):void;private observeAllocation;private readonly onWindowResize;private measureAllocation;private applyMeasuredInlineSize;private syncOverlay;private readonly navigationDeferredReturn;private readonly resolveNavigationRestoreTarget;private syncCustomToggle;private releaseCustomToggleA11y;private isUnavailableCustomToggle;private rememberTriggerAndToggle;private readonly onDefaultToggleClick;private readonly onToggleSlotClick;private readonly onPageClick;private readonly onBackdropClick;private readonly onSkipClick;private requestNavOpen;
|
|
149
149
|
/** Open mobile navigation. Desktop navigation is already visible, but the state is retained so
|
|
150
150
|
* an open drawer can move through desktop and back without replacing its content. */
|
|
151
151
|
showNavigation():void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{isAriaTrue}from"../../../internal/accessibility-visibility.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./page.styles.js";import{LYRA_DEFAULT_closeNavigation,LYRA_DEFAULT_openNavigation,LYRA_DEFAULT_skipToContent}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MOBILE_BREAKPOINT="768px";class LyraPage extends LyraElement{constructor(){super(...arguments),this.view="desktop",this.navOpen=!1,this.mobileBreakpoint="768px",this.navigationPlacement="start",this.disableNavigationToggle=!1,this.accessibleLabel=null,this.mainId=nextId("page-main"),this.navigationId=nextId("page-navigation"),this.drawerId=nextId("page-drawer"),this.skipTargetId=nextId("page-skip-target"),this.skipLabelId=nextId("page-skip-label"),this.fragmentTargetId=this.getAttribute("id")||this.skipTargetId,this.fragmentTabIndex=this.getAttribute("tabindex")??"-1",this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation(),this.navOpen&&this.view==="mobile"&&this.nativeModal.show()}}),this.navigationOpener=null,this.customToggles=[],this.customToggleOwnership=new Map,this.onWindowResize=()=>this.measureAllocation(),this.navigationDeferredReturn=()=>{const owner=this.navigationTriggerOwner,opener=owner?null:this.navigationOpener;if(this.navigationOpener=null,!(!owner&&!opener))return{candidates:()=>[owner?.isConnected?resolveAccessibleTrigger(owner):null,opener,this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]'),this.mainElement],stranded:active=>!!this.drawerElement&&composedContains(this.drawerElement,active),isCurrent:()=>!this.navOpen}},this.resolveNavigationRestoreTarget=()=>{const owner=this.navigationTriggerOwner;if(owner?.isConnected){const accessible=resolveAccessibleTrigger(owner);if(isComposedFocusAvailable(accessible))return accessible}const builtIn=this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]');return builtIn&&isComposedFocusAvailable(builtIn)?builtIn:this.mainElement&&isComposedFocusAvailable(this.mainElement)?this.mainElement:null},this.onDefaultToggleClick=event=>{this.rememberTriggerAndToggle(event.currentTarget)},this.onToggleSlotClick=event=>{const trigger=event.composedPath().find(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle");trigger&&this.customToggles.includes(trigger)&&!this.isUnavailableCustomToggle(trigger)&&this.rememberTriggerAndToggle(trigger)},this.onPageClick=event=>{const path=event.composedPath();if(path.some(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle"))return;const trigger=path.find(candidate=>candidate?.nodeType===1&&candidate.hasAttribute("data-toggle-nav"));trigger&&this.rememberTriggerAndToggle(trigger)},this.onBackdropClick=event=>{event.target===event.currentTarget&&this.overlayHandle?.dismissBackdrop()},this.onSkipClick=event=>{event.preventDefault(),this.mainElement?.focus(),this.mainElement?.scrollIntoView({block:"start"})}}static{this.defaultStrings={...super.defaultStrings,closeNavigation:LYRA_DEFAULT_closeNavigation,navigation:LYRA_DEFAULT_navigation,openNavigation:LYRA_DEFAULT_openNavigation,skipToContent:LYRA_DEFAULT_skipToContent}}static{this.knownUnobservedAttributes=["disable-sticky"]}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.nativeModal.hide(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.releaseCustomToggleA11y(),super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.measureAllocation(),this.observeAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.nativeModal.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.nativeModal.hide(),this.nativeModal.prepare(!1)),changed.has("fragmentTargetId")&&!this.fragmentTargetId&&(this.fragmentTargetId=this.skipTargetId),changed.has("fragmentTabIndex")&&this.fragmentTabIndex===null&&(this.fragmentTabIndex="-1")}updated(changed){super.updated(changed),this.view==="mobile"&&this.navOpen&&this.nativeModal.show();const describedBy=this.view==="mobile"&&this.navOpen?this.getAttribute("aria-describedby"):null;for(const dialog of this.renderRoot.querySelectorAll('[part="drawer"], [data-native-modal-carrier]'))syncAriaDescribedByElements(this,dialog,describedBy);changed.has("mobileBreakpoint")&&changed.get("mobileBreakpoint")!==void 0&&this.measureAllocation(),this.overlayHandle!==void 0&&(!this.isConnected||this.view!=="mobile"||!this.navOpen)?(this.syncOverlay(changed),this.syncCustomToggle()):(this.syncCustomToggle(),this.syncOverlay(changed))}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&view?.requestAnimationFrame(()=>{this.isConnected&&this.applyMeasuredInlineSize(inlineSize)})}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const width=this.getBoundingClientRect().width;width>0&&this.applyMeasuredInlineSize(width)}applyMeasuredInlineSize(width){if(!Number.isFinite(width)||width<0)return;const resolved=resolveCssLength(this.mobileBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_MOBILE_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback),next=width<=breakpoint?"mobile":"desktop";next!==this.view&&(this.view=next)}syncOverlay(changed){if(this.isConnected&&this.view==="mobile"&&this.navOpen){if(this.overlayHandle?.isActive()){this.overlayHandle.resume(),this.navigationTriggerOwner&&this.overlayHandle.updateRestoreFocusTo(this.resolveNavigationRestoreTarget);return}const active=deepActiveElement(this.ownerDocument);this.navigationOpener=active&&typeof active.focus=="function"&&!(this.drawerElement&&composedContains(this.drawerElement,active))?active:null,this.overlayHandle=activateOverlay({host:this,panel:()=>this.drawerElement??null,modalRoot:()=>this.drawerElement??null,onEscape:()=>this.hideNavigation(),onBackdrop:()=>this.hideNavigation(),...this.navigationTriggerOwner?{restoreFocusTo:this.resolveNavigationRestoreTarget}:{},lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:this.navigationDeferredReturn}),this.overlayHandle.focusInitial();return}if(this.overlayHandle){const restoreFocus=!!(changed?.has("navOpen")&&!this.navOpen);this.overlayHandle.deactivate({restoreFocus}),this.overlayHandle=void 0}this.navOpen||(this.navigationTriggerOwner=void 0)}syncCustomToggle(){const nextToggles=(this.shadowRoot?.querySelector('slot[name="navigation-toggle"]')?.assignedElements({flatten:!0})??[]).filter(candidate=>candidate.nodeType===1&&candidate.getRootNode()!==this.shadowRoot),previous=this.customToggle;this.customToggles=nextToggles,this.customToggle=nextToggles[0];const nextToggleSet=new Set(nextToggles);for(const[host,ownership]of this.customToggleOwnership)nextToggleSet.has(host)||(ownership.accessibleAria?.release(),ownership.hostAria.release(),this.customToggleOwnership.delete(host));const localizedLabel=this.localize(this.navOpen?"closeNavigation":"openNavigation"),drawer=this.drawerElement;for(const host of nextToggles){const accessible=resolveAccessibleTrigger(host);let ownership=this.customToggleOwnership.get(host);ownership?accessible!==ownership.accessible&&(ownership.accessibleAria?.release(),ownership.accessibleAria=void 0,ownership.accessible=accessible,ownership.accessibleAuthoredLabel=accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null):(ownership={accessible,accessibleAuthoredLabel:accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null,hostAria:acquireAriaOwnership(null,{}),hostAuthoredLabel:host.hasAttribute("aria-label")?host.getAttribute("aria-label")??"":null},this.customToggleOwnership.set(host,ownership)),ownership.hostAria.update(host,{attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]});const distinctAccessible=accessible===host?null:accessible,accessibleContribution={attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.accessibleAuthoredLabel??ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]};ownership.accessibleAria?ownership.accessibleAria.update(distinctAccessible,accessibleContribution):ownership.accessibleAria=acquireAriaOwnership(distinctAccessible,accessibleContribution)}this.navOpen&&this.navigationTriggerOwner&&!nextToggles.includes(this.navigationTriggerOwner)?(this.navigationTriggerOwner=this.customToggle,this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)):this.navOpen&&previous&&this.navigationTriggerOwner===previous&&this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)}releaseCustomToggleA11y(){for(const ownership of this.customToggleOwnership.values())ownership.accessibleAria?.release(),ownership.hostAria.release();this.customToggleOwnership.clear(),this.customToggle=void 0,this.customToggles=[]}isUnavailableCustomToggle(trigger){const accessible=resolveAccessibleTrigger(trigger);return[trigger,accessible].some(candidate=>candidate.hasAttribute("hidden")||candidate.hasAttribute("inert")||candidate.matches(":disabled")||isAriaTrue(candidate.getAttribute("aria-hidden"))||isAriaTrue(candidate.getAttribute("aria-disabled")))}rememberTriggerAndToggle(trigger){this.syncCustomToggle(),this.navOpen||(this.navigationTriggerOwner=trigger),this.toggleNavigation()}requestNavOpen(next){this.navOpen===next||this.emit("lr-nav-toggle-request",{open:next},{cancelable:!0}).defaultPrevented||(this.navOpen=next,this.emit("lr-nav-open-change",{open:next}))}showNavigation(){this.requestNavOpen(!0)}hideNavigation(){this.requestNavOpen(!1)}toggleNavigation(){this.requestNavOpen(!this.navOpen)}visiblePixelsInViewport(element){if(!element)return 0;const rect=element.getBoundingClientRect();if(!Number.isFinite(rect.top)||!Number.isFinite(rect.bottom))return 0;const candidateHeight=element.ownerDocument.defaultView?.innerHeight??element.ownerDocument.documentElement.clientHeight;if(!Number.isFinite(candidateHeight)||candidateHeight<=0)return 0;const viewportHeight=finiteRange(candidateHeight,0,0),visible=Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0);return finiteRange(visible,0,0,viewportHeight)}render(){const mobile=this.view==="mobile",overlayOpen=mobile&&this.navOpen,navigationLabel=this.accessibleLabel??this.localize("navigation");return html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{isAriaTrue}from"../../../internal/accessibility-visibility.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{OwnedFrame}from"../../../internal/owned-timer.js";import{finiteRange}from"../../../internal/numbers.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./page.styles.js";import{LYRA_DEFAULT_closeNavigation,LYRA_DEFAULT_openNavigation,LYRA_DEFAULT_skipToContent}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MOBILE_BREAKPOINT="768px";class LyraPage extends LyraElement{constructor(){super(...arguments),this.view="desktop",this.navOpen=!1,this.mobileBreakpoint="768px",this.navigationPlacement="start",this.disableNavigationToggle=!1,this.accessibleLabel=null,this.mainId=nextId("page-main"),this.navigationId=nextId("page-navigation"),this.drawerId=nextId("page-drawer"),this.skipTargetId=nextId("page-skip-target"),this.skipLabelId=nextId("page-skip-label"),this.fragmentTargetId=this.getAttribute("id")||this.skipTargetId,this.fragmentTabIndex=this.getAttribute("tabindex")??"-1",this.allocationFrame=new OwnedFrame(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.hideNavigation(),this.navOpen&&this.view==="mobile"&&this.nativeModal.show()}}),this.navigationOpener=null,this.customToggles=[],this.customToggleOwnership=new Map,this.onWindowResize=()=>this.measureAllocation(),this.navigationDeferredReturn=()=>{const owner=this.navigationTriggerOwner,opener=owner?null:this.navigationOpener;if(this.navigationOpener=null,!(!owner&&!opener))return{candidates:()=>[owner?.isConnected?resolveAccessibleTrigger(owner):null,opener,this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]'),this.mainElement],stranded:active=>!!this.drawerElement&&composedContains(this.drawerElement,active),isCurrent:()=>!this.navOpen}},this.resolveNavigationRestoreTarget=()=>{const owner=this.navigationTriggerOwner;if(owner?.isConnected){const accessible=resolveAccessibleTrigger(owner);if(isComposedFocusAvailable(accessible))return accessible}const builtIn=this.disableNavigationToggle?null:this.renderRoot.querySelector('[part~="navigation-toggle"]');return builtIn&&isComposedFocusAvailable(builtIn)?builtIn:this.mainElement&&isComposedFocusAvailable(this.mainElement)?this.mainElement:null},this.onDefaultToggleClick=event=>{this.rememberTriggerAndToggle(event.currentTarget)},this.onToggleSlotClick=event=>{const trigger=event.composedPath().find(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle");trigger&&this.customToggles.includes(trigger)&&!this.isUnavailableCustomToggle(trigger)&&this.rememberTriggerAndToggle(trigger)},this.onPageClick=event=>{const path=event.composedPath();if(path.some(candidate=>candidate?.nodeType===1&&candidate.getAttribute("slot")==="navigation-toggle"))return;const trigger=path.find(candidate=>candidate?.nodeType===1&&candidate.hasAttribute("data-toggle-nav"));trigger&&this.rememberTriggerAndToggle(trigger)},this.onBackdropClick=event=>{event.target===event.currentTarget&&this.overlayHandle?.dismissBackdrop()},this.onSkipClick=event=>{event.preventDefault(),this.mainElement?.focus(),this.mainElement?.scrollIntoView({block:"start"})}}static{this.defaultStrings={...super.defaultStrings,closeNavigation:LYRA_DEFAULT_closeNavigation,navigation:LYRA_DEFAULT_navigation,openNavigation:LYRA_DEFAULT_openNavigation,skipToContent:LYRA_DEFAULT_skipToContent}}static{this.knownUnobservedAttributes=["disable-sticky"]}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.nativeModal.hide(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.allocationFrame.cancel(),this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.releaseCustomToggleA11y(),super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.measureAllocation(),this.observeAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.nativeModal.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.nativeModal.hide(),this.nativeModal.prepare(!1)),changed.has("fragmentTargetId")&&!this.fragmentTargetId&&(this.fragmentTargetId=this.skipTargetId),changed.has("fragmentTabIndex")&&this.fragmentTabIndex===null&&(this.fragmentTabIndex="-1")}updated(changed){super.updated(changed),this.view==="mobile"&&this.navOpen&&this.nativeModal.show();const describedBy=this.view==="mobile"&&this.navOpen?this.getAttribute("aria-describedby"):null;for(const dialog of this.renderRoot.querySelectorAll('[part="drawer"], [data-native-modal-carrier]'))syncAriaDescribedByElements(this,dialog,describedBy);changed.has("mobileBreakpoint")&&changed.get("mobileBreakpoint")!==void 0&&this.measureAllocation(),this.overlayHandle!==void 0&&(!this.isConnected||this.view!=="mobile"||!this.navOpen)?(this.syncOverlay(changed),this.syncCustomToggle()):(this.syncCustomToggle(),this.syncOverlay(changed))}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){if(!this.resizeObserver){const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==view||this.resizeObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&this.allocationFrame.schedule(()=>this.applyMeasuredInlineSize(inlineSize))});this.resizeObserver=observer}this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const width=this.getBoundingClientRect().width;width>0&&this.applyMeasuredInlineSize(width)}applyMeasuredInlineSize(width){if(!Number.isFinite(width)||width<0)return;const resolved=resolveCssLength(this.mobileBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_MOBILE_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback),next=width<=breakpoint?"mobile":"desktop";next!==this.view&&(this.view=next)}syncOverlay(changed){if(this.isConnected&&this.view==="mobile"&&this.navOpen){if(this.overlayHandle?.isActive()){this.overlayHandle.resume(),this.navigationTriggerOwner&&this.overlayHandle.updateRestoreFocusTo(this.resolveNavigationRestoreTarget);return}const active=deepActiveElement(this.ownerDocument);this.navigationOpener=active&&typeof active.focus=="function"&&!(this.drawerElement&&composedContains(this.drawerElement,active))?active:null,this.overlayHandle=activateOverlay({host:this,panel:()=>this.drawerElement??null,modalRoot:()=>this.drawerElement??null,onEscape:()=>this.hideNavigation(),onBackdrop:()=>this.hideNavigation(),...this.navigationTriggerOwner?{restoreFocusTo:this.resolveNavigationRestoreTarget}:{},lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:this.navigationDeferredReturn}),this.overlayHandle.focusInitial();return}if(this.overlayHandle){const restoreFocus=!!(changed?.has("navOpen")&&!this.navOpen);this.overlayHandle.deactivate({restoreFocus}),this.overlayHandle=void 0}this.navOpen||(this.navigationTriggerOwner=void 0)}syncCustomToggle(){const nextToggles=(this.shadowRoot?.querySelector('slot[name="navigation-toggle"]')?.assignedElements({flatten:!0})??[]).filter(candidate=>candidate.nodeType===1&&candidate.getRootNode()!==this.shadowRoot),previous=this.customToggle;this.customToggles=nextToggles,this.customToggle=nextToggles[0];const nextToggleSet=new Set(nextToggles);for(const[host,ownership]of this.customToggleOwnership)nextToggleSet.has(host)||(ownership.accessibleAria?.release(),ownership.hostAria.release(),this.customToggleOwnership.delete(host));const localizedLabel=this.localize(this.navOpen?"closeNavigation":"openNavigation"),drawer=this.drawerElement;for(const host of nextToggles){const accessible=resolveAccessibleTrigger(host);let ownership=this.customToggleOwnership.get(host);ownership?accessible!==ownership.accessible&&(ownership.accessibleAria?.release(),ownership.accessibleAria=void 0,ownership.accessible=accessible,ownership.accessibleAuthoredLabel=accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null):(ownership={accessible,accessibleAuthoredLabel:accessible.hasAttribute("aria-label")?accessible.getAttribute("aria-label")??"":null,hostAria:acquireAriaOwnership(null,{}),hostAuthoredLabel:host.hasAttribute("aria-label")?host.getAttribute("aria-label")??"":null},this.customToggleOwnership.set(host,ownership)),ownership.hostAria.update(host,{attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]});const distinctAccessible=accessible===host?null:accessible,accessibleContribution={attributes:{"aria-haspopup":"dialog","aria-expanded":this.navOpen?"true":"false","aria-label":ownership.accessibleAuthoredLabel??ownership.hostAuthoredLabel??localizedLabel},controls:drawer?[drawer]:[]};ownership.accessibleAria?ownership.accessibleAria.update(distinctAccessible,accessibleContribution):ownership.accessibleAria=acquireAriaOwnership(distinctAccessible,accessibleContribution)}this.navOpen&&this.navigationTriggerOwner&&!nextToggles.includes(this.navigationTriggerOwner)?(this.navigationTriggerOwner=this.customToggle,this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)):this.navOpen&&previous&&this.navigationTriggerOwner===previous&&this.overlayHandle?.updateRestoreFocusTo(this.resolveNavigationRestoreTarget)}releaseCustomToggleA11y(){for(const ownership of this.customToggleOwnership.values())ownership.accessibleAria?.release(),ownership.hostAria.release();this.customToggleOwnership.clear(),this.customToggle=void 0,this.customToggles=[]}isUnavailableCustomToggle(trigger){const accessible=resolveAccessibleTrigger(trigger);return[trigger,accessible].some(candidate=>candidate.hasAttribute("hidden")||candidate.hasAttribute("inert")||candidate.matches(":disabled")||isAriaTrue(candidate.getAttribute("aria-hidden"))||isAriaTrue(candidate.getAttribute("aria-disabled")))}rememberTriggerAndToggle(trigger){this.syncCustomToggle(),this.navOpen||(this.navigationTriggerOwner=trigger),this.toggleNavigation()}requestNavOpen(next){this.navOpen===next||this.emit("lr-nav-toggle-request",{open:next},{cancelable:!0}).defaultPrevented||(this.navOpen=next,this.emit("lr-nav-open-change",{open:next}))}showNavigation(){this.requestNavOpen(!0)}hideNavigation(){this.requestNavOpen(!1)}toggleNavigation(){this.requestNavOpen(!this.navOpen)}visiblePixelsInViewport(element){if(!element)return 0;const rect=element.getBoundingClientRect();if(!Number.isFinite(rect.top)||!Number.isFinite(rect.bottom))return 0;const candidateHeight=element.ownerDocument.defaultView?.innerHeight??element.ownerDocument.documentElement.clientHeight;if(!Number.isFinite(candidateHeight)||candidateHeight<=0)return 0;const viewportHeight=finiteRange(candidateHeight,0,0),visible=Math.min(rect.bottom,viewportHeight)-Math.max(rect.top,0);return finiteRange(visible,0,0,viewportHeight)}render(){const mobile=this.view==="mobile",overlayOpen=mobile&&this.navOpen,navigationLabel=this.accessibleLabel??this.localize("navigation");return html`
|
|
2
2
|
<div part="base page" @click=${this.onPageClick}>
|
|
3
3
|
<a
|
|
4
4
|
part="skip-to-content"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{activateOverlay,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./responsive-panel.styles.js";import{resolveResponsivePanelEffectiveMode}from"./responsive-panel-mode.js";import{LYRA_DEFAULT_responsivePanel}from"../../../internal/default-strings/layout.generated.js";import{resolveResponsivePanelEffectiveMode as resolveResponsivePanelEffectiveMode2}from"./responsive-panel-mode.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]',DEFAULT_OVERLAY_BREAKPOINT="768px",RESPONSIVE_PANEL_MODE=literalSetConverter(["inline","overlay","auto"],"auto");class LyraResponsivePanel extends LyraElement{constructor(){super(...arguments),this.open=!1,this._mode="auto",this.shape="fullscreen",this.label="",this.overlayBreakpoint=DEFAULT_OVERLAY_BREAKPOINT,this.accessibleLabel=null,this.belowBreakpoint=!1,this.resolvedMode="inline",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.close("escape"),this.open&&this.nativeModal.show()}}),this.headerObserverGeneration=0,this.ownerRealmGeneration=0,this.overlayChromeActive=!1,this.focusOverlayAfterUpdate=!1,this.isFirstUpdate=!0,this.onWindowResize=()=>this.measureAllocation(),this.onHeaderSlotChange=e=>{this.syncHeaderSlot(e.target.assignedElements({flatten:!0}))},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,responsivePanel:LYRA_DEFAULT_responsivePanel}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}get mode(){return this._mode}set mode(next){const normalized=RESPONSIVE_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get effectiveMode(){return this.resolvedMode}willUpdate(changed){if(super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,this.isFirstUpdate&&(this.headingText=this.detectHeadingText()),!this.isFirstUpdate&&changed.has("overlayBreakpoint")&&this.isConnected&&this.measureAllocation(),(this.isFirstUpdate||changed.has("mode")||changed.has("belowBreakpoint"))&&(this.resolvedMode=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)),changed.has("open")&&this.open){const active=deepActiveElement(this.ownerDocument);this.lastTrigger=active&&typeof active.focus=="function"?active:void 0}const overlayOpen=this.resolvedMode==="overlay"&&this.open;if(overlayOpen!==this.overlayChromeActive)if(this.overlayChromeActive=overlayOpen,overlayOpen)this.activateOverlayChrome(),this.focusOverlayAfterUpdate=!0;else{const restoreFocus=changed.has("open")&&!this.open;this.deactivateOverlayChrome(restoreFocus)}changed.has("open")&&!this.open&&(this.lastTrigger=void 0)}updated(changed){super.updated(changed),this.open&&this.nativeModal.show(),!this.isFirstUpdate&&changed.has("resolvedMode")&&this.emit("lr-mode-change",{mode:this.resolvedMode}),this.focusOverlayAfterUpdate&&(this.focusOverlayAfterUpdate=!1,this.overlayHandle?.focusInitial())}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation();const overlayOpen=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)==="overlay"&&this.open;this.hasUpdated&&overlayOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateOverlayChrome(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="header"]');slot&&this.syncHeaderSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{activateOverlay,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./responsive-panel.styles.js";import{resolveResponsivePanelEffectiveMode}from"./responsive-panel-mode.js";import{LYRA_DEFAULT_responsivePanel}from"../../../internal/default-strings/layout.generated.js";import{resolveResponsivePanelEffectiveMode as resolveResponsivePanelEffectiveMode2}from"./responsive-panel-mode.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]',DEFAULT_OVERLAY_BREAKPOINT="768px",RESPONSIVE_PANEL_MODE=literalSetConverter(["inline","overlay","auto"],"auto");class LyraResponsivePanel extends LyraElement{constructor(){super(...arguments),this.open=!1,this._mode="auto",this.shape="fullscreen",this.label="",this.overlayBreakpoint=DEFAULT_OVERLAY_BREAKPOINT,this.accessibleLabel=null,this.belowBreakpoint=!1,this.resolvedMode="inline",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.close("escape"),this.open&&this.nativeModal.show()}}),this.headerObserverGeneration=0,this.ownerRealmGeneration=0,this.overlayChromeActive=!1,this.focusOverlayAfterUpdate=!1,this.isFirstUpdate=!0,this.onWindowResize=()=>this.measureAllocation(),this.onHeaderSlotChange=e=>{this.syncHeaderSlot(e.target.assignedElements({flatten:!0}))},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,responsivePanel:LYRA_DEFAULT_responsivePanel}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}get mode(){return this._mode}set mode(next){const normalized=RESPONSIVE_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get effectiveMode(){return this.resolvedMode}willUpdate(changed){if(super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,this.isFirstUpdate&&(this.headingText=this.detectHeadingText()),!this.isFirstUpdate&&changed.has("overlayBreakpoint")&&this.isConnected&&this.measureAllocation(),(this.isFirstUpdate||changed.has("mode")||changed.has("belowBreakpoint"))&&(this.resolvedMode=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)),changed.has("open")&&this.open){const active=deepActiveElement(this.ownerDocument);this.lastTrigger=active&&typeof active.focus=="function"?active:void 0}const overlayOpen=this.resolvedMode==="overlay"&&this.open;if(overlayOpen!==this.overlayChromeActive)if(this.overlayChromeActive=overlayOpen,overlayOpen)this.activateOverlayChrome(),this.focusOverlayAfterUpdate=!0;else{const restoreFocus=changed.has("open")&&!this.open;this.deactivateOverlayChrome(restoreFocus)}changed.has("open")&&!this.open&&(this.lastTrigger=void 0)}updated(changed){super.updated(changed),this.open&&this.nativeModal.show(),!this.isFirstUpdate&&changed.has("resolvedMode")&&this.emit("lr-mode-change",{mode:this.resolvedMode}),this.focusOverlayAfterUpdate&&(this.focusOverlayAfterUpdate=!1,this.overlayHandle?.focusInitial())}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation();const overlayOpen=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)==="overlay"&&this.open;this.hasUpdated&&overlayOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateOverlayChrome(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="header"]');slot&&this.syncHeaderSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork();const resizeObserver=this.resizeObserver;this.resizeObserver=void 0;const resizeView=this.resizeView;this.resizeView=void 0,resizeObserver?.disconnect(),resizeView?.removeEventListener("resize",this.onWindowResize),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.nativeModal.hide(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.resetOwnerRealmWork(),this.isConnected&&(this.measureAllocation(),this.observeAllocation())}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetHeaderObserver()}queueOwnerMicrotask(callback,nextFrame=!1){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,run=()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()};nextFrame?ownerWindow.requestAnimationFrame(run):ownerWindow.queueMicrotask(run)}activateOverlayChrome(){this.nativeModal.prepare(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),restoreFocusTo:this.lastTrigger??null,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.lastTrigger;return opener?{candidates:()=>[opener],isCurrent:()=>!this.open}:void 0}})}deactivateOverlayChrome(restoreFocus=!0){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&this.queueOwnerMicrotask(()=>this.applyMeasuredInlineSize(inlineSize),!0)}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){const inlineSize=this.getBoundingClientRect().width;inlineSize>0&&this.applyMeasuredInlineSize(inlineSize)}applyMeasuredInlineSize(inlineSize){if(!Number.isFinite(inlineSize)||inlineSize<0)return;const resolved=resolveCssLength(this.overlayBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_OVERLAY_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback);this.belowBreakpoint=inlineSize<=breakpoint}syncHeaderSlot(assigned){if(this.headingText=this.detectHeadingText(),this.resetHeaderObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headerObserverGeneration,observer=new MutationObserverCtor(()=>{this.headerObserver!==observer||this.headerObserverDocument!==ownerDocument||this.headerObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.headingText=this.detectHeadingText())});this.headerObserver=observer,this.headerObserverDocument=ownerDocument;for(const element of assigned)observer.observe(element,{childList:!0,characterData:!0,subtree:!0})}resetHeaderObserver(){this.headerObserverGeneration+=1,this.headerObserver?.disconnect(),this.headerObserver=void 0,this.headerObserverDocument=void 0}detectHeadingText(){const headerChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="header");if(headerChildren.length===0)return;const heading=headerChildren.find(el=>el.matches(HEADING_SELECTOR));return heading?heading.textContent?.trim()||void 0:headerChildren.map(el=>el.textContent?.trim()).filter(Boolean).join(" ")||void 0}close(reason="api"){this.open&&(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-close",{reason})))}show(){this.open=!0}hide(){this.close()}render(){const overlay=this.effectiveMode==="overlay",accessibleName=this.accessibleLabel??(this.label||this.headingText||this.localize("responsivePanel"));return this.nativeModal.render(html`
|
|
2
2
|
<div part="base" class=${overlay?"overlay":"inline"}>
|
|
3
3
|
${overlay?html`<div part="backdrop" @click=${this.onBackdropClick}></div>`:nothing}
|
|
4
4
|
<div
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings/layout.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}const collapseWriteGuards=new WeakMap;function collapseWriteGuardFor(widget){let guard=collapseWriteGuards.get(widget);return guard||(guard=new VetoWriteGuard,collapseWriteGuards.set(widget,guard)),guard}function installSynchronousCollapsedReflection(prototype){const installed=Object.getOwnPropertyDescriptor(prototype,"collapsed"),installedSet=installed.set;Object.defineProperty(prototype,"collapsed",{...installed,set(next){installedSet.call(this,next),markVetoGuardWrite(collapseWriteGuardFor(this)),this.toggleAttribute("collapsed",this.collapsed)}})}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.size="m",this.effectiveViews=Object.freeze([]),this.activeViewId="",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen(),this.fullscreen&&this.nativeModal.show()}}),this.labelTextObserver=new AccessibleTextController(this,[],()=>{const assigned=this.shadowRoot?.querySelector('slot[name="label"]')?.assignedElements({flatten:!0})??[];this.syncLabelSlot(assigned)},["alt","aria-labelledby","slot"],!1),this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.setActiveView=viewId=>{if(viewId!==this.activeViewId){if(this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented)return;this.activeViewId=viewId,this.emit("lr-view-change",{viewId})}this.emit("lr-activate",{value:viewId})},this.dispatchingCollapse=!1,this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,scrollOverflowFadeStyles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}static{definePersistedProperty(this.prototype,"collapsed",{initial:!1,attribute:!0,type:Boolean,reflect:!0,coerce:next=>!!next}),installSynchronousCollapsedReflection(this.prototype)}get views(){return this.effectiveViews}set views(value){if(value===this.viewsSource||value===this.effectiveViews)return;this.viewsSource=value;const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.labelSlotText=this.readLabelSlotText(labelChildren);const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!isPersistedPropertyExplicitlySet(this,"collapsed")&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;if(!views.some(view=>view.viewId===this.activeViewId)){const forcedBySibling=this.hasUpdated&&changed.has("views")&&!changed.has("activeViewId");this.activeViewId=views[0]?.viewId??"",forcedBySibling&&this.emit("lr-view-change",{viewId:this.activeViewId})}}}updated(changed){super.updated(changed),this.fullscreen&&this.nativeModal.show();const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.nativeModal.hide(),super.disconnectedCallback(),this.overlayHandle?.suspend(),cancelDeferredFocusReturn(this),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork();const slot=this.shadowRoot?.querySelector('slot[name="label"]');this.isConnected&&slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0})),this.labelTextObserver.adopted()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.labelTextObserver.setEnabled(!1)}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.nativeModal.prepare(),this.fullscreenOpener=this.explicitTrigger??captureFocusReturnOpener(this),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.fullscreenOpener;return opener?{candidates:()=>[opener],isCurrent:()=>!this.fullscreen}:void 0}}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.fullscreenOpener=void 0}syncLabelSlot(assigned){this.labelSlotText=this.readLabelSlotText(assigned),this.labelTextObserver.setEnabled(assigned.length>0),this.labelTextObserver.bind()}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}requestCollapse(next){if(this.dispatchingCollapse)return;const previous=this.collapsed;this.dispatchingCollapse=!0;try{requestThenCommit({requestDetail:{expanded:!next},emitRequest:(proposal,init)=>{const request=this.emit("lr-toggle-request",proposal,init);return this.emit("lr-collapse-request",{collapsed:next},init).defaultPrevented&&request.preventDefault(),request},guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}),this.emit("lr-toggle",{expanded:!next}))}})}finally{this.dispatchingCollapse=!1}}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings/layout.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}const collapseWriteGuards=new WeakMap;function collapseWriteGuardFor(widget){let guard=collapseWriteGuards.get(widget);return guard||(guard=new VetoWriteGuard,collapseWriteGuards.set(widget,guard)),guard}function installSynchronousCollapsedReflection(prototype){const installed=Object.getOwnPropertyDescriptor(prototype,"collapsed"),installedSet=installed.set;Object.defineProperty(prototype,"collapsed",{...installed,set(next){installedSet.call(this,next),markVetoGuardWrite(collapseWriteGuardFor(this)),this.toggleAttribute("collapsed",this.collapsed)}})}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.size="m",this.effectiveViews=Object.freeze([]),this.activeViewId="",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen(),this.fullscreen&&this.nativeModal.show()}}),this.labelTextObserver=new AccessibleTextController(this,[],()=>{const assigned=this.shadowRoot?.querySelector('slot[name="label"]')?.assignedElements({flatten:!0})??[];this.syncLabelSlot(assigned)},["alt","aria-labelledby","slot"],!1),this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.setActiveView=viewId=>{if(viewId!==this.activeViewId){if(this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented)return;this.activeViewId=viewId,this.emit("lr-view-change",{viewId})}this.emit("lr-activate",{value:viewId})},this.dispatchingCollapse=!1,this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,scrollOverflowFadeStyles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}static{definePersistedProperty(this.prototype,"collapsed",{initial:!1,attribute:!0,type:Boolean,reflect:!0,coerce:next=>!!next}),installSynchronousCollapsedReflection(this.prototype)}get views(){return this.effectiveViews}set views(value){if(value===this.viewsSource||value===this.effectiveViews)return;this.viewsSource=value;const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.labelSlotText=this.readLabelSlotText(labelChildren);const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!isPersistedPropertyExplicitlySet(this,"collapsed")&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;if(!views.some(view=>view.viewId===this.activeViewId)){const forcedBySibling=this.hasUpdated&&changed.has("views")&&!changed.has("activeViewId");this.activeViewId=views[0]?.viewId??"",forcedBySibling&&this.emit("lr-view-change",{viewId:this.activeViewId})}}}updated(changed){super.updated(changed),this.fullscreen&&this.nativeModal.show();const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork(),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.nativeModal.hide(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork();const slot=this.shadowRoot?.querySelector('slot[name="label"]');this.isConnected&&slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0})),this.labelTextObserver.adopted()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.labelTextObserver.setEnabled(!1)}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.nativeModal.prepare(),this.fullscreenOpener=this.explicitTrigger??captureFocusReturnOpener(this),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.fullscreenOpener;return opener?{candidates:()=>[opener],isCurrent:()=>!this.fullscreen}:void 0}}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.fullscreenOpener=void 0}syncLabelSlot(assigned){this.labelSlotText=this.readLabelSlotText(assigned),this.labelTextObserver.setEnabled(assigned.length>0),this.labelTextObserver.bind()}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}requestCollapse(next){if(this.dispatchingCollapse)return;const previous=this.collapsed;this.dispatchingCollapse=!0;try{requestThenCommit({requestDetail:{expanded:!next},emitRequest:(proposal,init)=>{const request=this.emit("lr-toggle-request",proposal,init);return this.emit("lr-collapse-request",{collapsed:next},init).defaultPrevented&&request.preventDefault(),request},guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}),this.emit("lr-toggle",{expanded:!next}))}})}finally{this.dispatchingCollapse=!1}}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return this.nativeModal.render(html`
|
|
2
2
|
${this.fullscreen?html`<div
|
|
3
3
|
part="backdrop"
|
|
4
4
|
style=${backdropInset?styleMap({"--lr-widget-backdrop-inset":backdropInset}):nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){if(super.willUpdate(changed),changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver()}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view,this.geometryFrame=view.requestAnimationFrame(()=>{this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100)})}syncGeometryObserver(){const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const ResizeObserverConstructor=this.ownerDocument.defaultView?.ResizeObserver;ResizeObserverConstructor&&(this.geometryObserver=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)}),this.geometryObserver.observe(wrapper))}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){if(super.willUpdate(changed),changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver()}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){if(!this.isConnected)return;const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view;const frame=view.requestAnimationFrame(()=>{!this.isConnected||this.ownerDocument.defaultView!==view||this.geometryFrameOwner!==view||this.geometryFrame!==frame||(this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100))});this.geometryFrame=frame}syncGeometryObserver(){if(!this.isConnected)return;const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const owner=this.ownerDocument.defaultView,ResizeObserverConstructor=owner?.ResizeObserver;if(!ResizeObserverConstructor)return;const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.geometryObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)});this.geometryObserver=observer,observer.observe(wrapper)}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
|
|
2
2
|
part="highlight-layer"
|
|
3
3
|
role="group"
|
|
4
4
|
aria-label=${this.localize("imageViewerHighlightsLabel")}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property,query,state}from"lit/decorators.js";import{html as staticHtml,unsafeStatic}from"lit/static-html.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{tag}from"../../../internal/prefix.js";import{LyraPopover}from"./popover.class.js";import{styles}from"./dropdown.styles.js";const menuTag=unsafeStatic(tag("menu"));class LyraDropdown extends LyraPopover{static{this.styles=[LyraPopover.styles,styles]}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}constructor(){super(),this.distance=0,this.placement="bottom-start",this.size="m",this.stayOpenOnSelect=!1,this.onContentSlotChange=event=>{this.collectConsumerMenuFromSlot(event.target)},this.popupRole="menu"}get popupRole(){return"menu"}set popupRole(_next){super.popupRole!=="menu"&&(super.popupRole="menu")}attributeChangedCallback(name,oldValue,newValue){if(name==="popup-role"&&newValue!==null&&newValue!=="menu"){this.setAttribute("popup-role","menu");return}super.attributeChangedCallback(name,oldValue,newValue)}get defaultDistance(){return 0}get defaultPositioningStrategy(){return"absolute"}onPositioningStrategyChanged(previous,next){const wasHoisted=previous==="fixed";wasHoisted!==(next==="fixed")&&this.requestUpdate("hoist",wasHoisted)}get positioningSync(){return this.sync}get animationNamespace(){return"dropdown"}get popupSurfaceRole(){}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-transition-fast"]}get popupPartNames(){return["popup","dialog","popup-popup","base","base__popup","panel"].join(" ")}get arrowPartNames(){return"arrow popup-arrow"}isInsideLightDismissBoundary(path){return super.isInsideLightDismissBoundary(path)||!!(this.containingElement&&path.includes(this.containingElement))}onPopupPositioned(){if(super.onPopupPositioned(),this.openedByInteraction)return;const menu=this.menuEngine;if(!menu?.dropdownOpen)return;menu.shadowRoot?.querySelector("slot:not([name])")?.assignedElements({flatten:!0}).find(element=>element.tabIndex===0)?.focus()}get menuEngine(){return this.consumerMenu??this.renderRoot.querySelector('[part~="menu"]')??void 0}configureMenu(menu){menu
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property,query,state}from"lit/decorators.js";import{html as staticHtml,unsafeStatic}from"lit/static-html.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{tag}from"../../../internal/prefix.js";import{LyraPopover}from"./popover.class.js";import{styles}from"./dropdown.styles.js";const menuTag=unsafeStatic(tag("menu"));class LyraDropdown extends LyraPopover{static{this.styles=[LyraPopover.styles,styles]}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}constructor(){super(),this.distance=0,this.placement="bottom-start",this.size="m",this.stayOpenOnSelect=!1,this.onContentSlotChange=event=>{this.collectConsumerMenuFromSlot(event.target)},this.popupRole="menu"}get popupRole(){return"menu"}set popupRole(_next){super.popupRole!=="menu"&&(super.popupRole="menu")}attributeChangedCallback(name,oldValue,newValue){if(name==="popup-role"&&newValue!==null&&newValue!=="menu"){this.setAttribute("popup-role","menu");return}super.attributeChangedCallback(name,oldValue,newValue)}get defaultDistance(){return 0}get defaultPositioningStrategy(){return"absolute"}onPositioningStrategyChanged(previous,next){const wasHoisted=previous==="fixed";wasHoisted!==(next==="fixed")&&this.requestUpdate("hoist",wasHoisted)}get positioningSync(){return this.sync}get animationNamespace(){return"dropdown"}get popupSurfaceRole(){}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-transition-fast"]}get popupPartNames(){return["popup","dialog","popup-popup","base","base__popup","panel"].join(" ")}get arrowPartNames(){return"arrow popup-arrow"}isInsideLightDismissBoundary(path){return super.isInsideLightDismissBoundary(path)||!!(this.containingElement&&path.includes(this.containingElement))}onPopupPositioned(){if(super.onPopupPositioned(),this.openedByInteraction)return;const menu=this.menuEngine;if(!menu?.dropdownOpen)return;menu.shadowRoot?.querySelector("slot:not([name])")?.assignedElements({flatten:!0}).find(element=>element.tabIndex===0)?.focus()}get menuEngine(){return this.consumerMenu??this.renderRoot.querySelector('[part~="menu"]')??void 0}configureMenu(menu){!this.isConnected||!menu||(menu===this.consumerMenu&&!this.consumerMenuSnapshot&&(this.consumerMenuSnapshot={dropdownOwner:menu.dropdownOwner,dropdownContained:menu.dropdownContained,dropdownRendersMenuRole:menu.dropdownRendersMenuRole,dropdownStayOpenOnSelect:menu.dropdownStayOpenOnSelect,dropdownSize:menu.dropdownSize,dropdownLabel:menu.dropdownLabel,dropdownOpen:menu.dropdownOpen}),menu.dropdownOwner=this,menu.dropdownContained=!0,menu.dropdownRendersMenuRole=!0,menu.dropdownStayOpenOnSelect=this.stayOpenOnSelect,menu.dropdownSize=this.size,menu.dropdownLabel=this.effectivePopupLabel,menu.dropdownOpen=this.open)}connectedCallback(){super.connectedCallback(),this.updateComplete.then(()=>{this.isConnected&&this.configureMenu(this.menuEngine)})}releaseConsumerMenu(menu){if(!menu)return;const snapshot=menu===this.consumerMenu?this.consumerMenuSnapshot:void 0;menu.dropdownOpen=!1,menu.dropdownOwner=snapshot?.dropdownOwner??null,menu.dropdownContained=snapshot?.dropdownContained??!1,menu.dropdownRendersMenuRole=snapshot?.dropdownRendersMenuRole??!1,menu.dropdownStayOpenOnSelect=snapshot?.dropdownStayOpenOnSelect??!1,menu.dropdownSize=snapshot?.dropdownSize,menu.dropdownLabel=snapshot?.dropdownLabel,snapshot&&(menu.dropdownOpen=snapshot.dropdownOpen),menu===this.consumerMenu&&(this.consumerMenuSnapshot=void 0)}collectConsumerMenuFromSlot(slot){const next=slot.assignedElements({flatten:!0}).find(element=>element.localName===tag("menu"));next!==this.consumerMenu&&(this.releaseConsumerMenu(this.consumerMenu),this.consumerMenu=next),this.configureMenu(next??this.menuEngine)}onTriggerKeyDown(event){if(this.disabled||this.open)return;let focus;if(event.key==="ArrowDown"?focus="first":event.key==="ArrowUp"&&(focus="last"),!focus)return;event.preventDefault();const menu=this.menuEngine;this.configureMenu(menu),menu?menu.focusContained(focus):this.show()}reposition(){this.positionPopup()}focusOnTrigger(options){this.renderRoot.querySelector('slot[name="trigger"]')?.assignedElements({flatten:!0})[0]?.focus(options)}getMenu(){return this.menuEngine??null}updated(changed){super.updated(changed),this.configureMenu(this.menuEngine),this.open&&changed.has("sync")&&this.reposition()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.contentSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.collectConsumerMenuFromSlot(s))})}disconnectedCallback(){this.releaseConsumerMenu(this.consumerMenu),super.disconnectedCallback()}renderPopupContent(){return this.consumerMenu?html`<slot @slotchange=${this.onContentSlotChange}></slot>`:staticHtml`
|
|
2
2
|
<${menuTag}
|
|
3
3
|
part="menu"
|
|
4
4
|
.dropdownOwner=${this}
|