@aceshooting/lyra-ui 30.3.0 → 30.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +3 -3
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +4 -1
- package/dist/components/layout/multi-split/multi-split.class.js +6 -3
- package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/scroller/scroller.class.d.ts +1 -1
- package/dist/components/layout/scroller/scroller.class.js +1 -1
- package/dist/components/layout/split-panel/split-panel.class.d.ts +1 -1
- package/dist/components/layout/split-panel/split-panel.class.js +1 -1
- package/dist/components/layout/stepper/stepper.class.d.ts +1 -1
- package/dist/components/layout/stepper/stepper.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +2 -2
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +13 -15
- package/dist/components/utility/copy-button/copy-button.class.js +3 -3
- package/dist/components/utility/copy-button/copy-button.styles.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +2 -2
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/modal-host.styles.js +1 -0
- package/dist/internal/modal-surface-controller.js +1 -1
- package/dist/internal/overlay-stack.d.ts +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/style-property-lease.js +1 -1
- package/llms/components/lr-app-rail.md +4 -0
- package/llms/components/lr-badge.md +3 -0
- package/llms/components/lr-copy-button.md +15 -7
- package/llms/components/lr-multi-split.md +4 -0
- package/llms/components/lr-page.md +5 -1
- package/llms/components/lr-responsive-panel.md +5 -1
- package/llms/components/lr-token-input.md +4 -3
- package/llms/components/lr-tooltip.md +4 -4
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +11 -0
- package/llms/shared/styles-and-tokens.md +75 -14
- package/llms/shared.md +86 -14
- package/package.json +2 -2
- package/skills/compose-lyra-interfaces/references/composition-patterns.md +1 -1
- package/skills/lyra-ui/SKILL.md +3 -2
- package/skills/lyra-ui/lyra-gen.md +10 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{literalSetConverter}from"../../../internal/converters.js";import{resolveCssLength}from"../../../internal/css-length.js";import{setCustomState}from"../../../internal/custom-states.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.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{prefersReducedMotion}from"../../../internal/motion.js";import{composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{finiteDuration,finiteRange}from"../../../internal/numbers.js";import{collectFocusableElements}from"../../../internal/overlay-stack.js";import{tag}from"../../../internal/prefix.js";import{bindNavigationMenuItem,navigationMenuItemController,releaseNavigationMenuItem}from"./navigation-menu-owner.js";import{styles}from"./navigation-menu.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const PANEL_ANCHOR=literalSetConverter(["menu","item"],"menu"),DEFAULT_SHOW_DELAY=200,DEFAULT_HIDE_DELAY=150,DEFAULT_SKIP_DELAY=300,DEFAULT_DISTANCE=6,PANEL_KEY_ORIGIN='a[href], button, [role="link"], [role="button"]',IGNORED_CHILDREN=new Set(["template","script","style"]);function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1}function isAnchorWithHref(value){return isElementNode(value)&&value.localName==="a"&&value.hasAttribute("href")}class LyraNavigationMenu extends LyraElement{constructor(){super(...arguments),this._expanded=!1,this.expansionWriteGuard=new VetoWriteGuard,this.expansionNotificationSequence=0,this.indicator=!1,this._panelAnchor="menu",this.showDelay=DEFAULT_SHOW_DELAY,this.hideDelay=DEFAULT_HIDE_DELAY,this.skipDelay=DEFAULT_SKIP_DELAY,this.distance=DEFAULT_DISTANCE,this.topLayer=!1,this.collapsedLayout=!1,this.listId=nextId("navigation-menu-list"),this.menuInternals=attachInternalsSafely(this),this.ownedRoles=new WeakSet,this.context={owner:this,layout:()=>this.layout,anchor:item=>this._panelAnchor==="item"?this.controllerFor(item)?.base()??null:this.listElement,distance:()=>finiteRange(this.distance,DEFAULT_DISTANCE,0),topLayer:()=>this.topLayer,activate:item=>this.activateItem(item),willOpen:item=>this.itemWillOpen(item),changed:(item,open,source)=>this.itemChanged(item,open,source),escape:item=>this.itemEscape(item)},this.items=[],this.lastCloseAt=Number.NEGATIVE_INFINITY,this.pressActive=!1,this.observedIndicatorTargets=new Set,this.indicatorQueued=!1,this.onSlotChange=()=>{this.updateBrowserDerivedState(()=>this.bindItems())},this.onPointerOver=event=>{if(event.pointerType!=="mouse"||this.layout!=="bar")return;const target=event.composedPath()[0],item=this.itemContaining(target),controller=this.controllerFor(item);if(!item||!controller||!isElementNode(target))return;if(this.openItem===item){this.hideTimer?.item===item&&this.cancelHide();return}const base=controller.base();!base||!composedContains(base,target)||(controller.isTrigger()?this.hoverTrigger(item):this.hoverNonTrigger())},this.onPointerOut=event=>{if(event.pointerType!=="mouse"||this.layout!=="bar")return;const item=this.itemContaining(event.composedPath()[0]);if(!item)return;const next=event.relatedTarget;isElementNode(next)&&composedContains(item,next)||(this.showTimer?.item===item&&this.cancelShow(),this.requestHoverClose(item))},this.onDocumentPointerDown=event=>{const open=this.openItem,controller=this.controllerFor(open);if(!open||!controller||this.layout!=="bar"||!controller.isTopmost())return;const path=event.composedPath();if(!path.includes(open)){for(const item of this.items){if(item===open)continue;const other=this.controllerFor(item),base=other?.base();if(other?.isTrigger()&&base&&path.includes(base))return}this.cancelShow(),this.cancelHide(),controller.close("user",{repairFocus:!1})}},this.onPointerDownCapture=event=>{if(event.button!==0||!event.isPrimary)return;this.clearPressTimer(),this.pressActive=!0,this.pressOpenItem=this.openItem;const doc=this.ownerDocument;this.pressDocument!==doc&&(this.stopPressListeners(),doc.addEventListener("pointerup",this.onPressEnd,!0),doc.addEventListener("pointercancel",this.onPressEnd,!0),this.pressDocument=doc)},this.onPressEnd=()=>{this.stopPressListeners(),this.clearPressTimer();const view=this.ownerDocument.defaultView;if(!view){this.clearPress();return}const id=view.setTimeout(()=>{this.pressTimer?.id===id&&(this.pressTimer=void 0,this.reevaluatePress())},0);this.pressTimer={id,view}},this.onFocusOut=event=>{const open=this.openItem;if(!open||this.layout!=="bar")return;const target=event.composedPath()[0];if(!isElementNode(target)||!composedContains(open,target))return;const next=event.relatedTarget;!isElementNode(next)||composedContains(open,next)||this.pressActive||(this.cancelShow(),this.cancelHide(),this.controllerFor(open)?.close("user",{repairFocus:!1}))},this.onClickCapture=event=>{if(event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const path=event.composedPath();if(!this.items.some(item=>{const controller=this.controllerFor(item);if(!controller)return!1;const base=controller.base();if(controller.isLink()&&base&&path.includes(base))return!0;const panel=controller.panel();if(!panel)return!1;const panelIndex=path.indexOf(panel);return panelIndex===-1?!1:path.slice(0,panelIndex).some(isAnchorWithHref)}))return;this.cancelShow(),this.cancelHide();const listHides=this.layout==="stacked"&&this._expanded;this.closeOpenItem("user",listHides?{focusTarget:this.toggleElement}:{}),listHides&&this.setExpanded(!1,"user")},this.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.altKey||event.ctrlKey||event.metaKey)return;if(this.layout==="stacked"){event.key==="Escape"&&this.handleStackedEscape(event);return}const origin=event.composedPath()[0];if(!isElementNode(origin))return;const topLevel=this.items.find(item=>this.controllerFor(item)?.base()===origin);if(topLevel){this.handleBaseKey(event,topLevel);return}const panel=this.controllerFor(this.openItem)?.panel();panel&&composedContains(panel,origin)&&this.handlePanelKey(event,panel,origin)},this.requestingExpansion=!1,this.onToggleClick=()=>{this.setExpanded(!this._expanded,"user")}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,navigation:LYRA_DEFAULT_navigation}}static{this.styles=[LyraElement.styles,styles]}get expanded(){return this._expanded}set expanded(next){markVetoGuardWrite(this.expansionWriteGuard),this.setExpanded(!!next,this.hasUpdated?"programmatic":null)}get panelAnchor(){return this._panelAnchor}set panelAnchor(next){const normalized=PANEL_ANCHOR.normalizeReflected(this,"panel-anchor",next);if(normalized===this._panelAnchor)return;const old=this._panelAnchor;this._panelAnchor=normalized,this.requestUpdate("panelAnchor",old)}get collapsed(){return this.collapsedLayout}get layout(){return this.collapsedLayout?"stacked":"bar"}get listElement(){return this.renderRoot?.querySelector('[part~="list"]')??null}get toggleElement(){return this.renderRoot?.querySelector('[part~="toggle"]')??null}controllerFor(item){return item?navigationMenuItemController(item):void 0}connectedCallback(){super.connectedCallback(),this.addEventListener("pointerover",this.onPointerOver),this.addEventListener("pointerout",this.onPointerOut),this.addEventListener("pointerdown",this.onPointerDownCapture,!0),this.addEventListener("click",this.onClickCapture,!0),this.addEventListener("keydown",this.onKeyDown),this.addEventListener("focusout",this.onFocusOut),this.observeAllocation(),this.hasUpdated&&this.updateBrowserDerivedState(()=>this.bindItems())}disconnectedCallback(){this.removeEventListener("pointerover",this.onPointerOver),this.removeEventListener("pointerout",this.onPointerOut),this.removeEventListener("pointerdown",this.onPointerDownCapture,!0),this.removeEventListener("click",this.onClickCapture,!0),this.removeEventListener("keydown",this.onKeyDown),this.removeEventListener("focusout",this.onFocusOut),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.cancelAllocationFrame(),this.observedIndicatorTargets.clear(),this.stopLightDismiss(),this.cancelShow(),this.cancelHide(),this.clearPress();for(const item of this.items)this.releaseItem(item);this.items=[],super.disconnectedCallback()}close(){this.cancelShow(),this.cancelHide();const listHides=this.collapsedLayout&&this._expanded;this.closeOpenItem("programmatic",listHides?{focusTarget:this.toggleElement}:{}),this.setExpanded(!1,"programmatic")}show(){this.setExpanded(!0,"programmatic")}hide(){this.close()}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{this.isConnected&&this.updateBrowserDerivedState(()=>this.bindItems())})}willUpdate(changed){super.willUpdate(changed),changed.has("mobileBreakpoint")&&this.hasUpdated&&this.applyAllocation(this.measureContentInlineSize())}updated(changed){super.updated(changed);const pending=this.pendingFocus;this.pendingFocus=void 0,pending==="toggle"?this.toggleElement?.focus({preventScroll:!0}):pending==="first-base"&&this.firstNavigableBase()?.focus({preventScroll:!0});const direction=this.effectiveDirection,directionChanged=this.lastDirection!==void 0&&direction!==this.lastDirection;this.lastDirection=direction,(changed.has("distance")||changed.has("topLayer")||changed.has("panelAnchor")||directionChanged)&&this.controllerFor(this.openItem)?.reposition(),(changed.has("indicator")||changed.has("panelAnchor")||changed.has("collapsedLayout")||directionChanged)&&(this.observeIndicatorTargets(),this.queueIndicatorMeasure())}bindItems(){if(!this.isConnected)return;const slot=this.renderRoot?.querySelector('[part~="list"] > slot'),assigned=slot?slot.assignedElements():[...this.children].filter(child=>!child.hasAttribute("slot")),itemTag=tag("navigation-menu-item"),next=[];for(const child of assigned)child.localName===itemTag?next.push(child):IGNORED_CHILDREN.has(child.localName)||devWarnOnce("lr-navigation-menu:non-item-child",`<${tag("navigation-menu")}> received <${child.localName}> in its default slot, which renders inside its list without a list item role. Only <${itemTag}> children belong there; place header chrome such as a logo, search or actions outside the menu.`);const kept=new Set(next);for(const previous of this.items)kept.has(previous)||this.releaseItem(previous);for(const item of next)bindNavigationMenuItem(item,this.context),item.hasAttribute("role")||(item.setAttribute("role","listitem"),this.ownedRoles.add(item));this.items=next,this.openItem&&(!kept.has(this.openItem)||!this.controllerFor(this.openItem)?.isOpen())&&(this.openItem=void 0);for(const item of next){const controller=this.controllerFor(item);controller?.isOpen()&&(this.openItem?this.openItem!==item&&controller.close(null,{repairFocus:!1,instant:!0}):this.openItem=item)}this.openItem&&this.layout==="bar"?this.startLightDismiss():this.stopLightDismiss(),this.observeIndicatorTargets(),this.queueIndicatorMeasure()}releaseItem(item){releaseNavigationMenuItem(item,this),this.ownedRoles.has(item)&&(item.getAttribute("role")==="listitem"&&item.removeAttribute("role"),this.ownedRoles.delete(item)),this.showTimer?.item===item&&this.cancelShow(),this.hideTimer?.item===item&&this.cancelHide(),this.openItem===item&&(this.openItem=void 0,this.stopLightDismiss())}now(){return this.ownerDocument.defaultView?.performance.now()??Date.now()}isNavigable(item){if(item.hidden||item.inert||item.closest("[inert]")!==null||item.getAttribute("aria-hidden")==="true")return!1;const base=this.controllerFor(item)?.base();return base!=null&&isComposedFocusAvailable(base)}firstNavigableBase(){const item=this.items.find(candidate=>this.isNavigable(candidate));return this.controllerFor(item)?.base()??null}itemContaining(target){if(isElementNode(target))return this.items.find(item=>composedContains(item,target))}focusWithinPanel(item){const active=deepActiveElement(this.ownerDocument);if(!active||!composedContains(item,active))return!1;const base=this.controllerFor(item)?.base();return!(base&&composedContains(base,active))}closeOpenItem(source,options={}){this.controllerFor(this.openItem)?.close(source,options)}activateItem(item){const controller=this.controllerFor(item);if(controller){if(this.cancelShow(),this.cancelHide(),controller.isTrigger()){controller.isOpen()?this.layout==="bar"&&controller.mode()==="hover"?controller.pin():controller.close("user"):controller.open("pinned","user");return}this.closeOpenItem("user"),this.layout==="stacked"&&this.setExpanded(!1,"user")}}itemWillOpen(item){this.showTimer?.item!==item&&this.cancelShow();const current=this.openItem;if(!current||current===item)return;const currentController=this.controllerFor(current);let morph;if(this.layout==="bar"&&this._panelAnchor==="menu"&&!prefersReducedMotion(this)){const panel=currentController?.panel(),from=panel&&!panel.hidden?panel.getBoundingClientRect():void 0;from&&from.width>0&&from.height>0&&(morph={from,direction:this.items.indexOf(item)>this.items.indexOf(current)?"end":"start"})}return currentController?.close("peer",{instant:!0,focusTarget:this.controllerFor(item)?.base()??null}),morph}itemChanged(item,open,source){open?(this.openItem=item,this.hideTimer?.item===item&&this.cancelHide(),this.layout==="bar"&&this.startLightDismiss()):this.openItem===item&&(this.openItem=void 0,this.layout==="bar"&&source!=="peer"&&(this.lastCloseAt=this.now()),this.hideTimer?.item===item&&this.cancelHide(),this.stopLightDismiss()),this.observeIndicatorTargets(),this.queueIndicatorMeasure()}itemEscape(item){this.cancelShow(),this.cancelHide();const within=composedContains(item,deepActiveElement(this.ownerDocument));this.controllerFor(item)?.close("user",{repairFocus:!1,restoreFocus:within})}hoverTrigger(item){this.cancelHide();const open=this.openItem;if(open&&open!==item){if(this.focusWithinPanel(open))return;this.cancelShow(),this.controllerFor(item)?.open("hover","user");return}if(this.showTimer?.item===item)return;const skip=finiteDuration(this.skipDelay,DEFAULT_SKIP_DELAY);if(skip>0&&this.now()-this.lastCloseAt<=skip){this.cancelShow(),this.controllerFor(item)?.open("hover","user");return}this.scheduleShow(item)}hoverNonTrigger(){this.cancelShow();const open=this.openItem;open&&this.requestHoverClose(open)}requestHoverClose(item){this.openItem===item&&(this.controllerFor(item)?.mode()!=="hover"||this.focusWithinPanel(item)||this.scheduleHide(item))}scheduleShow(item){this.cancelShow();const delay=finiteDuration(this.showDelay,DEFAULT_SHOW_DELAY),view=this.ownerDocument.defaultView,commit=()=>{if(this.layout!=="bar"||!this.items.includes(item))return;const open=this.openItem;open&&open!==item&&this.focusWithinPanel(open)||this.controllerFor(item)?.open("hover","user")};if(!view||delay<=0){commit();return}const id=view.setTimeout(()=>{this.showTimer?.id===id&&(this.showTimer=void 0,commit())},delay);this.showTimer={item,id,view}}scheduleHide(item){this.cancelHide();const delay=finiteDuration(this.hideDelay,DEFAULT_HIDE_DELAY),view=this.ownerDocument.defaultView,commit=()=>{if(this.openItem!==item)return;const controller=this.controllerFor(item);controller?.mode()!=="hover"||this.focusWithinPanel(item)||controller.close("user")};if(!view||delay<=0){commit();return}const id=view.setTimeout(()=>{this.hideTimer?.id===id&&(this.hideTimer=void 0,commit())},delay);this.hideTimer={item,id,view}}cancelShow(){const timer=this.showTimer;this.showTimer=void 0,timer&&timer.view.clearTimeout(timer.id)}cancelHide(){const timer=this.hideTimer;this.hideTimer=void 0,timer&&timer.view.clearTimeout(timer.id)}startLightDismiss(){const doc=this.ownerDocument;!this.isConnected||this.lightDismissDocument===doc||(this.stopLightDismiss(),doc.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=doc)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0}reevaluatePress(){const pressed=this.pressOpenItem;if(this.pressActive=!1,this.pressOpenItem=void 0,!pressed||pressed!==this.openItem||this.layout!=="bar")return;const controller=this.controllerFor(pressed);if(!controller?.isOpen())return;const doc=this.ownerDocument,active=deepActiveElement(doc);!active||active===doc.body||active===doc.documentElement||composedContains(pressed,active)||controller.close("user",{repairFocus:!1})}stopPressListeners(){this.pressDocument?.removeEventListener("pointerup",this.onPressEnd,!0),this.pressDocument?.removeEventListener("pointercancel",this.onPressEnd,!0),this.pressDocument=void 0}clearPressTimer(){const timer=this.pressTimer;this.pressTimer=void 0,timer&&timer.view.clearTimeout(timer.id)}clearPress(){this.stopPressListeners(),this.clearPressTimer(),this.pressActive=!1,this.pressOpenItem=void 0}handleBaseKey(event,item){const rtl=this.effectiveDirection==="rtl";switch(event.key){case"ArrowRight":case"ArrowLeft":{event.preventDefault();const forward=event.key==="ArrowRight"!==rtl;this.focusSibling(item,forward?1:-1);return}case"Home":case"End":{event.preventDefault();const navigable=this.items.filter(candidate=>this.isNavigable(candidate)),target=event.key==="Home"?navigable[0]:navigable.at(-1);this.controllerFor(target)?.base()?.focus();return}case"ArrowDown":{const controller=this.controllerFor(item);if(!controller?.isTrigger()||!controller.isOpen())return;event.preventDefault(),this.enterPanel(controller);return}}}focusSibling(item,step){const navigable=this.items.filter(candidate=>this.isNavigable(candidate)),index=navigable.indexOf(item);index!==-1&&this.controllerFor(navigable[index+step])?.base()?.focus()}async enterPanel(controller){if(await controller.placementReady(),!controller.isOpen())return;const panel=controller.panel();panel&&collectFocusableElements(panel)[0]?.focus()}handlePanelKey(event,panel,origin){if(!["ArrowDown","ArrowUp","Home","End"].includes(event.key)||!origin.matches(PANEL_KEY_ORIGIN))return;event.preventDefault();const focusable=collectFocusableElements(panel),index=focusable.findIndex(candidate=>candidate===origin);let target;event.key==="Home"?target=focusable[0]:event.key==="End"?target=focusable.at(-1):event.key==="ArrowDown"?target=focusable[index+1]:index>0&&(target=focusable[index-1]),target?.focus()}handleStackedEscape(event){const open=this.openItem,active=deepActiveElement(this.ownerDocument);if(open&&active&&composedContains(open,active)){event.preventDefault();const controller=this.controllerFor(open),base=controller?.base();controller?.close("user"),base?.focus();return}this._expanded&&(event.preventDefault(),this.setExpanded(!1,"user"),this.toggleElement?.focus())}setExpanded(next,source){if(next===this._expanded)return;if(source==="user"){if(this.requestingExpansion)return;const previous=this._expanded;this.requestingExpansion=!0;try{let accepted=!1;if(requestThenCommit({requestDetail:{expanded:next,source},emitRequest:(detail,init)=>this.emit("lr-toggle-request",detail,init),guard:this.expansionWriteGuard,commit:()=>{accepted=this._expanded===previous}}),!accepted)return}finally{this.requestingExpansion=!1}}if(!next&&this.collapsedLayout){const list=this.listElement,active=deepActiveElement(this.ownerDocument);list&&active&&composedContains(list,active)&&this.toggleElement?.focus({preventScroll:!0}),this.closeOpenItem(source,{repairFocus:!1})}const old=this._expanded;this._expanded=next;const notificationSequence=++this.expansionNotificationSequence;this.requestUpdate("expanded",old),source!==null&&this.updateComplete.then(()=>{!this.isConnected||this._expanded!==next||this.expansionNotificationSequence!==notificationSequence||this.emit("lr-toggle",{expanded:next,source})})}observeAllocation(){const ResizeObserverConstructor=this.ownerDocument.defaultView?.ResizeObserver;ResizeObserverConstructor&&(this.resizeObserver??=new ResizeObserverConstructor(entries=>this.onResize(entries)),this.resizeObserver.observe(this),this.observedIndicatorTargets.clear(),this.observeIndicatorTargets())}onResize(entries){for(const entry of entries)entry.target===this&&(this.lastInlineSize=entry.contentBoxSize?.[0]?.inlineSize??entry.contentRect.width,this.scheduleAllocation());this.queueIndicatorMeasure()}scheduleAllocation(){if(this.allocationFrame)return;const view=this.ownerDocument.defaultView;if(!view){this.applyAllocation(this.lastInlineSize);return}const id=view.requestAnimationFrame(()=>{this.allocationFrame?.id===id&&(this.allocationFrame=void 0,this.isConnected&&this.applyAllocation(this.lastInlineSize))});this.allocationFrame={id,view}}cancelAllocationFrame(){const frame=this.allocationFrame;this.allocationFrame=void 0,frame&&frame.view.cancelAnimationFrame(frame.id)}measureContentInlineSize(){const view=this.ownerDocument.defaultView;if(!view||!this.isConnected)return this.lastInlineSize;const style=view.getComputedStyle(this),edges=["paddingLeft","paddingRight","borderLeftWidth","borderRightWidth"];let width=this.getBoundingClientRect().width;for(const edge of edges)width-=Number.parseFloat(style[edge])||0;return Math.max(0,width)}applyAllocation(width){if(width===void 0||!Number.isFinite(width))return;const breakpoint=resolveCssLength(this.mobileBreakpoint,{host:this}),next=breakpoint!==void 0&&Number.isFinite(breakpoint)&&width<=breakpoint;this.updateBrowserDerivedState(()=>this.setCollapsed(next))}setCollapsed(next){if(next===this.collapsedLayout)return;this.cancelShow(),this.cancelHide();const active=deepActiveElement(this.ownerDocument),open=this.openItem;if(next){const list=this.listElement,listHides=!this._expanded,focusInList=!!(active&&list&&composedContains(list,active));this.controllerFor(open)?.close("programmatic",{instant:!0,repairFocus:!listHides}),listHides&&focusInList&&(this.pendingFocus="toggle"),this.stopLightDismiss()}else{const toggle=this.toggleElement,onToggle=!!(active&&toggle&&composedContains(toggle,active));this.controllerFor(open)?.close("programmatic",{instant:!0}),onToggle&&(this.pendingFocus="first-base")}this.collapsedLayout=next,setCustomState(this.menuInternals,"collapsed",next);for(const item of this.items)item.requestUpdate?.();!next&&this._expanded&&this.setExpanded(!1,"programmatic")}observeIndicatorTargets(){const observer=this.resizeObserver;if(!observer)return;const wanted=new Set;if(this.indicator){const list=this.listElement;list&&wanted.add(list);for(const item of this.items)wanted.add(item)}for(const target of this.observedIndicatorTargets)wanted.has(target)||observer.unobserve(target);for(const target of wanted)this.observedIndicatorTargets.has(target)||observer.observe(target);this.observedIndicatorTargets=wanted}queueIndicatorMeasure(){this.indicatorQueued||!this.indicator||(this.indicatorQueued=!0,queueMicrotask(()=>{const open=this.openItem;Promise.all([this.updateComplete,open?.updateComplete]).then(()=>{this.indicatorQueued=!1,this.measureIndicator()})}))}measureIndicator(){if(!this.indicator||this.collapsedLayout||!this.isConnected)return;const nav=this.renderRoot.querySelector('[part~="base"]'),base=this.controllerFor(this.openItem)?.base(),previous=this.indicatorBox;if(!nav||!base){previous?.visible&&(this.indicatorBox={...previous,visible:!1});return}const navRect=nav.getBoundingClientRect(),trigger=base.getBoundingClientRect(),list=this.listElement,rtl=this.effectiveDirection==="rtl",bottom=this._panelAnchor==="menu"&&list?list.getBoundingClientRect().bottom:trigger.bottom,next={start:rtl?navRect.right-trigger.right:trigger.left-navRect.left,size:trigger.width,top:bottom-navRect.top,visible:!0};previous&&previous.visible===next.visible&&Math.abs(previous.start-next.start)<.5&&Math.abs(previous.size-next.size)<.5&&Math.abs(previous.top-next.top)<.5||(this.indicatorBox=next)}render(){const label=hostAriaLabel(this)??this.label??this.localize("navigation"),collapsed=this.collapsedLayout,box=this.indicatorBox;return html`<nav part="base" aria-label=${label}>
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{literalSetConverter}from"../../../internal/converters.js";import{resolveCssLength}from"../../../internal/css-length.js";import{setCustomState}from"../../../internal/custom-states.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{menuIcon}from"../../../internal/icons.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{prefersReducedMotion}from"../../../internal/motion.js";import{composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{finiteDuration,finiteRange}from"../../../internal/numbers.js";import{collectFocusableElements}from"../../../internal/overlay-stack.js";import{tag}from"../../../internal/prefix.js";import{bindNavigationMenuItem,navigationMenuItemController,releaseNavigationMenuItem}from"./navigation-menu-owner.js";import{styles}from"./navigation-menu.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_navigation}from"../../../internal/default-strings/shared.generated.js";const PANEL_ANCHOR=literalSetConverter(["menu","item"],"menu"),DEFAULT_SHOW_DELAY=200,DEFAULT_HIDE_DELAY=150,DEFAULT_SKIP_DELAY=300,DEFAULT_DISTANCE=6,PANEL_KEY_ORIGIN='a[href], button, [role="link"], [role="button"]',IGNORED_CHILDREN=new Set(["template","script","style"]);function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1}function isAnchorWithHref(value){return isElementNode(value)&&value.localName==="a"&&value.hasAttribute("href")}class LyraNavigationMenu extends LyraElement{constructor(){super(...arguments),this._expanded=!1,this.expansionWriteGuard=new VetoWriteGuard,this.expansionNotificationSequence=0,this.indicator=!1,this._panelAnchor="menu",this.showDelay=DEFAULT_SHOW_DELAY,this.hideDelay=DEFAULT_HIDE_DELAY,this.skipDelay=DEFAULT_SKIP_DELAY,this.distance=DEFAULT_DISTANCE,this.topLayer=!1,this.collapsedLayout=!1,this.listId=nextId("navigation-menu-list"),this.menuInternals=attachInternalsSafely(this),this.ownedRoles=new WeakSet,this.context={owner:this,layout:()=>this.layout,anchor:item=>this._panelAnchor==="item"?this.controllerFor(item)?.base()??null:this.listElement,distance:()=>finiteRange(this.distance,DEFAULT_DISTANCE,0),topLayer:()=>this.topLayer,activate:item=>this.activateItem(item),willOpen:item=>this.itemWillOpen(item),changed:(item,open,source)=>this.itemChanged(item,open,source),escape:item=>this.itemEscape(item)},this.items=[],this.lastCloseAt=Number.NEGATIVE_INFINITY,this.pressActive=!1,this.observedIndicatorTargets=new Set,this.indicatorQueued=!1,this.onSlotChange=()=>{this.updateBrowserDerivedState(()=>this.bindItems())},this.onPointerOver=event=>{if(event.pointerType!=="mouse"||this.layout!=="bar")return;const target=event.composedPath()[0],item=this.itemContaining(target),controller=this.controllerFor(item);if(!item||!controller||!isElementNode(target))return;if(this.openItem===item){this.hideTimer?.item===item&&this.cancelHide();return}const base=controller.base();!base||!composedContains(base,target)||(controller.isTrigger()?this.hoverTrigger(item):this.hoverNonTrigger())},this.onPointerOut=event=>{if(event.pointerType!=="mouse"||this.layout!=="bar")return;const item=this.itemContaining(event.composedPath()[0]);if(!item)return;const next=event.relatedTarget;isElementNode(next)&&composedContains(item,next)||(this.showTimer?.item===item&&this.cancelShow(),this.requestHoverClose(item))},this.onDocumentPointerDown=event=>{const open=this.openItem,controller=this.controllerFor(open);if(!open||!controller||this.layout!=="bar"||!controller.isTopmost())return;const path=event.composedPath();if(!path.includes(open)){for(const item of this.items){if(item===open)continue;const other=this.controllerFor(item),base=other?.base();if(other?.isTrigger()&&base&&path.includes(base))return}this.cancelShow(),this.cancelHide(),controller.close("user",{repairFocus:!1})}},this.onPointerDownCapture=event=>{if(event.button!==0||!event.isPrimary)return;this.clearPressTimer(),this.pressActive=!0,this.pressOpenItem=this.openItem;const doc=this.ownerDocument;this.pressDocument!==doc&&(this.stopPressListeners(),doc.addEventListener("pointerup",this.onPressEnd,!0),doc.addEventListener("pointercancel",this.onPressEnd,!0),this.pressDocument=doc)},this.onPressEnd=()=>{this.stopPressListeners(),this.clearPressTimer();const view=this.ownerDocument.defaultView;if(!view){this.clearPress();return}const id=view.setTimeout(()=>{this.pressTimer?.id===id&&(this.pressTimer=void 0,this.reevaluatePress())},0);this.pressTimer={id,view}},this.onFocusOut=event=>{const open=this.openItem;if(!open||this.layout!=="bar")return;const target=event.composedPath()[0];if(!isElementNode(target)||!composedContains(open,target))return;const next=event.relatedTarget;!isElementNode(next)||composedContains(open,next)||this.pressActive||(this.cancelShow(),this.cancelHide(),this.controllerFor(open)?.close("user",{repairFocus:!1}))},this.onClickCapture=event=>{if(event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const path=event.composedPath();if(!this.items.some(item=>{const controller=this.controllerFor(item);if(!controller)return!1;const base=controller.base();if(controller.isLink()&&base&&path.includes(base))return!0;const panel=controller.panel();if(!panel)return!1;const panelIndex=path.indexOf(panel);return panelIndex===-1?!1:path.slice(0,panelIndex).some(isAnchorWithHref)}))return;this.cancelShow(),this.cancelHide();const listHides=this.layout==="stacked"&&this._expanded;this.closeOpenItem("user",listHides?{focusTarget:this.toggleElement}:{}),listHides&&this.setExpanded(!1,"user")},this.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.altKey||event.ctrlKey||event.metaKey)return;if(this.layout==="stacked"){event.key==="Escape"&&this.handleStackedEscape(event);return}const origin=event.composedPath()[0];if(!isElementNode(origin))return;const topLevel=this.items.find(item=>this.controllerFor(item)?.base()===origin);if(topLevel){this.handleBaseKey(event,topLevel);return}const panel=this.controllerFor(this.openItem)?.panel();panel&&composedContains(panel,origin)&&this.handlePanelKey(event,panel,origin)},this.requestingExpansion=!1,this.onToggleClick=()=>{this.setExpanded(!this._expanded,"user")}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,navigation:LYRA_DEFAULT_navigation}}static{this.styles=[LyraElement.styles,styles]}get expanded(){return this._expanded}set expanded(next){markVetoGuardWrite(this.expansionWriteGuard),this.setExpanded(!!next,this.hasUpdated?"programmatic":null)}get panelAnchor(){return this._panelAnchor}set panelAnchor(next){const normalized=PANEL_ANCHOR.normalizeReflected(this,"panel-anchor",next);if(normalized===this._panelAnchor)return;const old=this._panelAnchor;this._panelAnchor=normalized,this.requestUpdate("panelAnchor",old)}get collapsed(){return this.collapsedLayout}get layout(){return this.collapsedLayout?"stacked":"bar"}get listElement(){return this.renderRoot?.querySelector('[part~="list"]')??null}get toggleElement(){return this.renderRoot?.querySelector('[part~="toggle"]')??null}controllerFor(item){return item?navigationMenuItemController(item):void 0}connectedCallback(){super.connectedCallback(),this.addEventListener("pointerover",this.onPointerOver),this.addEventListener("pointerout",this.onPointerOut),this.addEventListener("pointerdown",this.onPointerDownCapture,!0),this.addEventListener("click",this.onClickCapture,!0),this.addEventListener("keydown",this.onKeyDown),this.addEventListener("focusout",this.onFocusOut),this.observeAllocation(),this.hasUpdated&&this.updateBrowserDerivedState(()=>this.bindItems())}disconnectedCallback(){this.removeEventListener("pointerover",this.onPointerOver),this.removeEventListener("pointerout",this.onPointerOut),this.removeEventListener("pointerdown",this.onPointerDownCapture,!0),this.removeEventListener("click",this.onClickCapture,!0),this.removeEventListener("keydown",this.onKeyDown),this.removeEventListener("focusout",this.onFocusOut),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.cancelAllocationFrame(),this.observedIndicatorTargets.clear(),this.stopLightDismiss(),this.cancelShow(),this.cancelHide(),this.clearPress();for(const item of this.items)this.releaseItem(item);this.items=[],super.disconnectedCallback()}close(){this.cancelShow(),this.cancelHide();const listHides=this.collapsedLayout&&this._expanded;this.closeOpenItem("programmatic",listHides?{focusTarget:this.toggleElement}:{}),this.setExpanded(!1,"programmatic")}show(){this.setExpanded(!0,"programmatic")}hide(){this.close()}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{this.isConnected&&this.updateBrowserDerivedState(()=>this.bindItems())})}willUpdate(changed){super.willUpdate(changed),changed.has("mobileBreakpoint")&&this.hasUpdated&&this.applyAllocation(this.measureContentInlineSize())}updated(changed){super.updated(changed);const pending=this.pendingFocus;this.pendingFocus=void 0,pending==="toggle"?this.toggleElement?.focus({preventScroll:!0}):pending==="first-base"&&this.firstNavigableBase()?.focus({preventScroll:!0});const direction=this.effectiveDirection,directionChanged=this.lastDirection!==void 0&&direction!==this.lastDirection;this.lastDirection=direction,(changed.has("distance")||changed.has("topLayer")||changed.has("panelAnchor")||directionChanged)&&this.controllerFor(this.openItem)?.reposition(),(changed.has("indicator")||changed.has("panelAnchor")||changed.has("collapsedLayout")||directionChanged)&&(this.observeIndicatorTargets(),this.queueIndicatorMeasure())}bindItems(){if(!this.isConnected)return;const slot=this.renderRoot?.querySelector('[part~="list"] > slot'),assigned=slot?slot.assignedElements():[...this.children].filter(child=>!child.hasAttribute("slot")),itemTag=tag("navigation-menu-item"),next=[];for(const child of assigned)child.localName===itemTag?next.push(child):IGNORED_CHILDREN.has(child.localName)||devWarnOnce("lr-navigation-menu:non-item-child",`<${tag("navigation-menu")}> received <${child.localName}> in its default slot, which renders inside its list without a list item role. Only <${itemTag}> children belong there; place header chrome such as a logo, search or actions outside the menu.`);const kept=new Set(next);for(const previous of this.items)kept.has(previous)||this.releaseItem(previous);for(const item of next)bindNavigationMenuItem(item,this.context),item.hasAttribute("role")||(item.setAttribute("role","listitem"),this.ownedRoles.add(item));this.items=next,this.openItem&&(!kept.has(this.openItem)||!this.controllerFor(this.openItem)?.isOpen())&&(this.openItem=void 0);for(const item of next){const controller=this.controllerFor(item);controller?.isOpen()&&(this.openItem?this.openItem!==item&&controller.close(null,{repairFocus:!1,instant:!0}):this.openItem=item)}this.openItem&&this.layout==="bar"?this.startLightDismiss():this.stopLightDismiss(),this.observeIndicatorTargets(),this.queueIndicatorMeasure()}releaseItem(item){releaseNavigationMenuItem(item,this),this.ownedRoles.has(item)&&(item.getAttribute("role")==="listitem"&&item.removeAttribute("role"),this.ownedRoles.delete(item)),this.showTimer?.item===item&&this.cancelShow(),this.hideTimer?.item===item&&this.cancelHide(),this.openItem===item&&(this.openItem=void 0,this.stopLightDismiss())}now(){return this.ownerDocument.defaultView?.performance.now()??Date.now()}isNavigable(item){if(item.hidden||item.inert||item.closest("[inert]")!==null||item.getAttribute("aria-hidden")==="true")return!1;const base=this.controllerFor(item)?.base();return base!=null&&isComposedFocusAvailable(base)}firstNavigableBase(){const item=this.items.find(candidate=>this.isNavigable(candidate));return this.controllerFor(item)?.base()??null}itemContaining(target){if(isElementNode(target))return this.items.find(item=>composedContains(item,target))}focusWithinPanel(item){const active=deepActiveElement(this.ownerDocument);if(!active||!composedContains(item,active))return!1;const base=this.controllerFor(item)?.base();return!(base&&composedContains(base,active))}closeOpenItem(source,options={}){this.controllerFor(this.openItem)?.close(source,options)}activateItem(item){const controller=this.controllerFor(item);if(controller){if(this.cancelShow(),this.cancelHide(),controller.isTrigger()){controller.isOpen()?this.layout==="bar"&&controller.mode()==="hover"?controller.pin():controller.close("user"):controller.open("pinned","user");return}this.closeOpenItem("user"),this.layout==="stacked"&&this.setExpanded(!1,"user")}}itemWillOpen(item){this.showTimer?.item!==item&&this.cancelShow();const current=this.openItem;if(!current||current===item)return;const currentController=this.controllerFor(current);let morph;if(this.layout==="bar"&&this._panelAnchor==="menu"&&!prefersReducedMotion(this)){const panel=currentController?.panel(),from=panel&&!panel.hidden?panel.getBoundingClientRect():void 0;from&&from.width>0&&from.height>0&&(morph={from,direction:this.items.indexOf(item)>this.items.indexOf(current)?"end":"start"})}return currentController?.close("peer",{instant:!0,focusTarget:this.controllerFor(item)?.base()??null}),morph}itemChanged(item,open,source){open?(this.openItem=item,this.hideTimer?.item===item&&this.cancelHide(),this.layout==="bar"&&this.startLightDismiss()):this.openItem===item&&(this.openItem=void 0,this.layout==="bar"&&source!=="peer"&&(this.lastCloseAt=this.now()),this.hideTimer?.item===item&&this.cancelHide(),this.stopLightDismiss()),this.observeIndicatorTargets(),this.queueIndicatorMeasure()}itemEscape(item){this.cancelShow(),this.cancelHide();const within=composedContains(item,deepActiveElement(this.ownerDocument));this.controllerFor(item)?.close("user",{repairFocus:!1,restoreFocus:within})}hoverTrigger(item){this.cancelHide();const open=this.openItem;if(open&&open!==item){if(this.focusWithinPanel(open))return;this.cancelShow(),this.controllerFor(item)?.open("hover","user");return}if(this.showTimer?.item===item)return;const skip=finiteDuration(this.skipDelay,DEFAULT_SKIP_DELAY);if(skip>0&&this.now()-this.lastCloseAt<=skip){this.cancelShow(),this.controllerFor(item)?.open("hover","user");return}this.scheduleShow(item)}hoverNonTrigger(){this.cancelShow();const open=this.openItem;open&&this.requestHoverClose(open)}requestHoverClose(item){this.openItem===item&&(this.controllerFor(item)?.mode()!=="hover"||this.focusWithinPanel(item)||this.scheduleHide(item))}scheduleShow(item){this.cancelShow();const delay=finiteDuration(this.showDelay,DEFAULT_SHOW_DELAY),view=this.ownerDocument.defaultView,commit=()=>{if(this.layout!=="bar"||!this.items.includes(item))return;const open=this.openItem;open&&open!==item&&this.focusWithinPanel(open)||this.controllerFor(item)?.open("hover","user")};if(!view||delay<=0){commit();return}const id=view.setTimeout(()=>{this.showTimer?.id===id&&(this.showTimer=void 0,commit())},delay);this.showTimer={item,id,view}}scheduleHide(item){this.cancelHide();const delay=finiteDuration(this.hideDelay,DEFAULT_HIDE_DELAY),view=this.ownerDocument.defaultView,commit=()=>{if(this.openItem!==item)return;const controller=this.controllerFor(item);controller?.mode()!=="hover"||this.focusWithinPanel(item)||controller.close("user")};if(!view||delay<=0){commit();return}const id=view.setTimeout(()=>{this.hideTimer?.id===id&&(this.hideTimer=void 0,commit())},delay);this.hideTimer={item,id,view}}cancelShow(){const timer=this.showTimer;this.showTimer=void 0,timer&&timer.view.clearTimeout(timer.id)}cancelHide(){const timer=this.hideTimer;this.hideTimer=void 0,timer&&timer.view.clearTimeout(timer.id)}startLightDismiss(){const doc=this.ownerDocument;!this.isConnected||this.lightDismissDocument===doc||(this.stopLightDismiss(),doc.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=doc)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0}reevaluatePress(){const pressed=this.pressOpenItem;if(this.pressActive=!1,this.pressOpenItem=void 0,!pressed||pressed!==this.openItem||this.layout!=="bar")return;const controller=this.controllerFor(pressed);if(!controller?.isOpen())return;const doc=this.ownerDocument,active=deepActiveElement(doc);!active||active===doc.body||active===doc.documentElement||composedContains(pressed,active)||controller.close("user",{repairFocus:!1})}stopPressListeners(){this.pressDocument?.removeEventListener("pointerup",this.onPressEnd,!0),this.pressDocument?.removeEventListener("pointercancel",this.onPressEnd,!0),this.pressDocument=void 0}clearPressTimer(){const timer=this.pressTimer;this.pressTimer=void 0,timer&&timer.view.clearTimeout(timer.id)}clearPress(){this.stopPressListeners(),this.clearPressTimer(),this.pressActive=!1,this.pressOpenItem=void 0}handleBaseKey(event,item){const rtl=this.effectiveDirection==="rtl";switch(event.key){case"ArrowRight":case"ArrowLeft":{event.preventDefault();const forward=event.key==="ArrowRight"!==rtl;this.focusSibling(item,forward?1:-1);return}case"Home":case"End":{event.preventDefault();const navigable=this.items.filter(candidate=>this.isNavigable(candidate)),target=event.key==="Home"?navigable[0]:navigable.at(-1);this.controllerFor(target)?.base()?.focus();return}case"ArrowDown":{const controller=this.controllerFor(item);if(!controller?.isTrigger()||!controller.isOpen())return;event.preventDefault(),this.enterPanel(controller);return}}}focusSibling(item,step){const navigable=this.items.filter(candidate=>this.isNavigable(candidate)),index=navigable.indexOf(item);index!==-1&&this.controllerFor(navigable[index+step])?.base()?.focus()}async enterPanel(controller){if(await controller.placementReady(),!controller.isOpen())return;const panel=controller.panel();panel&&collectFocusableElements(panel)[0]?.focus()}handlePanelKey(event,panel,origin){if(!["ArrowDown","ArrowUp","Home","End"].includes(event.key)||!origin.matches(PANEL_KEY_ORIGIN))return;event.preventDefault();const focusable=collectFocusableElements(panel),index=focusable.findIndex(candidate=>candidate===origin);let target;event.key==="Home"?target=focusable[0]:event.key==="End"?target=focusable.at(-1):event.key==="ArrowDown"?target=focusable[index+1]:index>0&&(target=focusable[index-1]),target?.focus()}handleStackedEscape(event){const open=this.openItem,active=deepActiveElement(this.ownerDocument);if(open&&active&&composedContains(open,active)){event.preventDefault();const controller=this.controllerFor(open),base=controller?.base();controller?.close("user"),base?.focus();return}this._expanded&&(event.preventDefault(),this.setExpanded(!1,"user"),this.toggleElement?.focus())}setExpanded(next,source){if(next===this._expanded)return;if(source==="user"){if(this.requestingExpansion)return;const previous=this._expanded;this.requestingExpansion=!0;try{let accepted=!1;if(requestThenCommit({requestDetail:{expanded:next,source},emitRequest:(detail,init)=>this.emit("lr-toggle-request",detail,init),guard:this.expansionWriteGuard,commit:()=>{accepted=this._expanded===previous}}),!accepted)return}finally{this.requestingExpansion=!1}}if(!next&&this.collapsedLayout){const list=this.listElement,active=deepActiveElement(this.ownerDocument);list&&active&&composedContains(list,active)&&this.toggleElement?.focus({preventScroll:!0}),this.closeOpenItem(source,{repairFocus:!1})}const old=this._expanded;this._expanded=next;const notificationSequence=++this.expansionNotificationSequence;this.requestUpdate("expanded",old),source!==null&&this.updateComplete.then(()=>{!this.isConnected||this._expanded!==next||this.expansionNotificationSequence!==notificationSequence||this.emit("lr-toggle",{expanded:next,source})})}observeAllocation(){const ownerDocument=this.ownerDocument,ResizeObserverConstructor=ownerDocument.defaultView?.ResizeObserver;if(ResizeObserverConstructor){if(!this.resizeObserver){const observer=new ResizeObserverConstructor(entries=>{this.resizeObserver!==observer||!this.isConnected||this.ownerDocument!==ownerDocument||this.onResize(entries)});this.resizeObserver=observer}this.resizeObserver.observe(this),this.observedIndicatorTargets.clear(),this.observeIndicatorTargets()}}onResize(entries){for(const entry of entries)entry.target===this&&(this.lastInlineSize=entry.contentBoxSize?.[0]?.inlineSize??entry.contentRect.width,this.scheduleAllocation());this.queueIndicatorMeasure()}scheduleAllocation(){if(this.allocationFrame)return;const view=this.ownerDocument.defaultView;if(!view){this.applyAllocation(this.lastInlineSize);return}const id=view.requestAnimationFrame(()=>{this.allocationFrame?.id===id&&(this.allocationFrame=void 0,this.isConnected&&this.applyAllocation(this.lastInlineSize))});this.allocationFrame={id,view}}cancelAllocationFrame(){const frame=this.allocationFrame;this.allocationFrame=void 0,frame&&frame.view.cancelAnimationFrame(frame.id)}measureContentInlineSize(){const view=this.ownerDocument.defaultView;if(!view||!this.isConnected)return this.lastInlineSize;const style=view.getComputedStyle(this),edges=["paddingLeft","paddingRight","borderLeftWidth","borderRightWidth"];let width=this.getBoundingClientRect().width;for(const edge of edges)width-=Number.parseFloat(style[edge])||0;return Math.max(0,width)}applyAllocation(width){if(width===void 0||!Number.isFinite(width))return;const breakpoint=resolveCssLength(this.mobileBreakpoint,{host:this}),next=breakpoint!==void 0&&Number.isFinite(breakpoint)&&width<=breakpoint;this.updateBrowserDerivedState(()=>this.setCollapsed(next))}setCollapsed(next){if(next===this.collapsedLayout)return;this.cancelShow(),this.cancelHide();const active=deepActiveElement(this.ownerDocument),open=this.openItem;if(next){const list=this.listElement,listHides=!this._expanded,focusInList=!!(active&&list&&composedContains(list,active));this.controllerFor(open)?.close("programmatic",{instant:!0,repairFocus:!listHides}),listHides&&focusInList&&(this.pendingFocus="toggle"),this.stopLightDismiss()}else{const toggle=this.toggleElement,onToggle=!!(active&&toggle&&composedContains(toggle,active));this.controllerFor(open)?.close("programmatic",{instant:!0}),onToggle&&(this.pendingFocus="first-base")}this.collapsedLayout=next,setCustomState(this.menuInternals,"collapsed",next);for(const item of this.items)item.requestUpdate?.();!next&&this._expanded&&this.setExpanded(!1,"programmatic")}observeIndicatorTargets(){const observer=this.resizeObserver;if(!observer)return;const wanted=new Set;if(this.indicator){const list=this.listElement;list&&wanted.add(list);for(const item of this.items)wanted.add(item)}for(const target of this.observedIndicatorTargets)wanted.has(target)||observer.unobserve(target);for(const target of wanted)this.observedIndicatorTargets.has(target)||observer.observe(target);this.observedIndicatorTargets=wanted}queueIndicatorMeasure(){this.indicatorQueued||!this.indicator||(this.indicatorQueued=!0,queueMicrotask(()=>{const open=this.openItem;Promise.all([this.updateComplete,open?.updateComplete]).then(()=>{this.indicatorQueued=!1,this.measureIndicator()})}))}measureIndicator(){if(!this.indicator||this.collapsedLayout||!this.isConnected)return;const nav=this.renderRoot.querySelector('[part~="base"]'),base=this.controllerFor(this.openItem)?.base(),previous=this.indicatorBox;if(!nav||!base){previous?.visible&&(this.indicatorBox={...previous,visible:!1});return}const navRect=nav.getBoundingClientRect(),trigger=base.getBoundingClientRect(),list=this.listElement,rtl=this.effectiveDirection==="rtl",bottom=this._panelAnchor==="menu"&&list?list.getBoundingClientRect().bottom:trigger.bottom,next={start:rtl?navRect.right-trigger.right:trigger.left-navRect.left,size:trigger.width,top:bottom-navRect.top,visible:!0};previous&&previous.visible===next.visible&&Math.abs(previous.start-next.start)<.5&&Math.abs(previous.size-next.size)<.5&&Math.abs(previous.top-next.top)<.5||(this.indicatorBox=next)}render(){const label=hostAriaLabel(this)??this.label??this.localize("navigation"),collapsed=this.collapsedLayout,box=this.indicatorBox;return html`<nav part="base" aria-label=${label}>
|
|
2
2
|
${collapsed?html`<button
|
|
3
3
|
type="button"
|
|
4
4
|
part="toggle"
|
|
@@ -12,6 +12,8 @@ export type PageNavigationPlacement='start'|'end';export interface LyraPageEvent
|
|
|
12
12
|
* from its own allocated inline size. A single static navigation subtree participates in the
|
|
13
13
|
* desktop grid and is promoted in place to a modal mobile drawer, so assigned nodes, component
|
|
14
14
|
* instances, focus, form state, and scroll state are never cloned or replaced at a breakpoint.
|
|
15
|
+
* The mobile drawer enters the browser top layer, remaining above fixed headers and outside
|
|
16
|
+
* ancestor clipping or transformed containing blocks while the Page host stays in place.
|
|
15
17
|
*
|
|
16
18
|
* Each instance owns unique main/drawer/navigation IDs. Its skip link therefore targets its own
|
|
17
19
|
* main landmark even when several Pages coexist. The default skip and navigation controls are
|
|
@@ -145,7 +147,7 @@ mobileBreakpoint:string;
|
|
|
145
147
|
/** Logical edge occupied by desktop navigation and the mobile drawer.*/
|
|
146
148
|
navigationPlacement:PageNavigationPlacement;
|
|
147
149
|
/** 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 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;
|
|
150
|
+
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 allocationMeasured;private readonly allocationFrame;private resizeView?;private overlayHandle?;private readonly nativeModal;private readonly modalSurface;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
151
|
/** Open mobile navigation. Desktop navigation is already visible, but the state is retained so
|
|
150
152
|
* an open drawer can move through desktop and back without replacing its content. */
|
|
151
153
|
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{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`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,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.allocationMeasured=!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.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal,()=>this.shadowRoot?.querySelector('[part="dialog-wrapper"]')??null),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.allocationMeasured=!1,this.measureAllocation(),this.observeAllocation(),this.hasUpdated&&this.view==="mobile"&&this.navOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.syncOverlay(),queueMicrotask(()=>{!this.isConnected||this.view!=="mobile"||!this.navOpen||(this.modalSurface.show(),this.overlayHandle?.focusInitial())})),this.hasUpdated&&queueMicrotask(()=>this.isConnected&&this.syncCustomToggle())}disconnectedCallback(){this.modalSurface.disconnect(),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.allocationMeasured||this.measureAllocation()}willUpdate(changed){super.willUpdate(changed),this.view==="mobile"&&this.navOpen&&!this.overlayHandle&&this.modalSurface.prepare(),(this.view!=="mobile"||!this.navOpen)&&(this.modalSurface.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.modalSurface.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.allocationMeasured=!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"
|
|
@@ -20,8 +20,8 @@ export interface LyraResponsivePanelCloseDetail{reason:LyraResponsivePanelCloseR
|
|
|
20
20
|
* `mode="auto"` (the default) updates the
|
|
21
21
|
* effective presentation without unmounting or re-creating the slotted
|
|
22
22
|
* content: inline and overlay presentation share the exact same shadow DOM
|
|
23
|
-
* structure (only a css class,
|
|
24
|
-
* attributes and backdrop element
|
|
23
|
+
* structure (only a css class, top-layer presentation, overlay-only `role`/`aria-modal`
|
|
24
|
+
* attributes, and backdrop element differ), so lit-html's diffing keeps
|
|
25
25
|
* `[part="body"]` and its `<slot>` as the same DOM node across the
|
|
26
26
|
* transition -- scroll position and focus inside the slotted content survive
|
|
27
27
|
* it for free. When an open inline panel becomes modal, focus already inside
|
|
@@ -39,6 +39,8 @@ export interface LyraResponsivePanelCloseDetail{reason:LyraResponsivePanelCloseR
|
|
|
39
39
|
* The overlay presentation uses the library's shared overlay coordinator for
|
|
40
40
|
* focus trapping, Escape/backdrop dismissal, inerting, and stack ordering,
|
|
41
41
|
* while retaining this component's own responsive rendering and close event.
|
|
42
|
+
* Its surface enters the browser top layer, so sticky headers and ancestor
|
|
43
|
+
* stacking contexts cannot cover it. The host stays in its authored slot.
|
|
42
44
|
*
|
|
43
45
|
* Accessible name (overlay presentation only -- the inline presentation has
|
|
44
46
|
* no dialog semantics to name), in priority order: if the host element itself
|
|
@@ -116,9 +118,9 @@ shape:LyraResponsivePanelShape;
|
|
|
116
118
|
label:string;
|
|
117
119
|
/** CSS length compared with this element's allocated inline size in `mode="auto"`.
|
|
118
120
|
* At or below the breakpoint, the effective presentation is `'overlay'`. */
|
|
119
|
-
overlayBreakpoint:string;private accessibleLabel;private belowBreakpoint;private resolvedMode;private readonly slotPresence;private headingText?;private resizeObserver?;private resizeView?;private lastTrigger?;private overlayHandle?;private readonly nativeModal;private headerObserver?;private headerObserverDocument?;private headerObserverGeneration;private ownerRealmGeneration;private overlayChromeActive;private focusOverlayAfterUpdate;private isFirstUpdate;
|
|
121
|
+
overlayBreakpoint:string;private accessibleLabel;private belowBreakpoint;private resolvedMode;private readonly slotPresence;private headingText?;private resizeObserver?;private resizeView?;private lastTrigger?;private overlayHandle?;private readonly nativeModal;private readonly modalSurface;private headerObserver?;private headerObserverDocument?;private headerObserverGeneration;private ownerRealmGeneration;private overlayChromeActive;private focusOverlayAfterUpdate;private isFirstUpdate;
|
|
120
122
|
/** The currently resolved presentation. Composition/measurement is the sole write authority.*/
|
|
121
|
-
get effectiveMode():LyraResponsivePanelEffectiveMode;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resetOwnerRealmWork;private queueOwnerMicrotask;private activateOverlayChrome;private deactivateOverlayChrome;private observeAllocation;private readonly onWindowResize;private measureAllocation;private applyMeasuredInlineSize;private onHeaderSlotChange;private syncHeaderSlot;private resetHeaderObserver;private detectHeadingText;
|
|
123
|
+
get effectiveMode():LyraResponsivePanelEffectiveMode;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resetOwnerRealmWork;private queueOwnerMicrotask;private activateOverlayChrome;private deactivateOverlayChrome;private showOverlaySurface;private observeAllocation;private readonly onWindowResize;private measureAllocation;private applyMeasuredInlineSize;private onHeaderSlotChange;private syncHeaderSlot;private resetHeaderObserver;private detectHeadingText;
|
|
122
124
|
/**
|
|
123
125
|
* Close the panel. `reason` is forwarded as `lr-close` detail.reason --
|
|
124
126
|
* built-in overlay triggers pass `'escape'`/`'backdrop'`; a consumer's own
|
|
@@ -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.
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{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.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal,()=>this.shadowRoot?.querySelector('[part="base"]')??null),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")||changed.has("mode"))&&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.showOverlaySurface(),!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.showOverlaySurface(),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.modalSurface.disconnect(),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()}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.modalSurface.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.modalSurface.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0}showOverlaySurface(){!this.isConnected||!this.open||this.effectiveMode!=="overlay"||(this.overlayHandle?.resume(),this.modalSurface.show())}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(){if(this.mode!=="auto")return;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
|
|
@@ -44,4 +44,4 @@ export declare class LyraScroller extends LyraElement<LyraScrollerEventMap>{stat
|
|
|
44
44
|
/** Hides the native scrollbar while preserving scrolling.*/
|
|
45
45
|
withoutScrollbar:boolean;
|
|
46
46
|
/** Removes both visual edge cues while leaving native scrolling untouched.*/
|
|
47
|
-
withoutShadow:boolean;scrollStep:number;label:string;private atStart;private atEnd;private measured;private viewport?;private content?;private resizeObserver?;private resizeObserverDocument?;private ownerRealmGeneration;connectedCallback():void;firstUpdated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private armResizeObserver;private resetOwnerRealmWork;private scheduleEdgeUpdate;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private edgeDetail;private updateEdges;private syncEdges;private scrollFrame?;private scrollFrameWindow?;private cancelScrollFrame;private onScroll;private onSlotChange;private get safeScrollStep();private scrollByDirection;private scrollToEdge;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-scroller':LyraScroller;}}
|
|
47
|
+
withoutShadow:boolean;scrollStep:number;label:string;private atStart;private atEnd;private measured;private viewport?;private content?;private resizeObserver?;private resizeObserverDocument?;private ownerRealmGeneration;private edgeUpdatePending;connectedCallback():void;firstUpdated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private armResizeObserver;private resetOwnerRealmWork;private scheduleEdgeUpdate;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private edgeDetail;private updateEdges;private syncEdges;private scrollFrame?;private scrollFrameWindow?;private cancelScrollFrame;private onScroll;private onSlotChange;private get safeScrollStep();private scrollByDirection;private scrollToEdge;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-scroller':LyraScroller;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{styles}from"./scroller.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious,LYRA_DEFAULT_scrollerLabel}from"../../../internal/default-strings/layout.generated.js";class LyraScroller extends LyraElement{constructor(){super(...arguments),this.orientation="horizontal",this.controls=!1,this.withoutScrollbar=!1,this.withoutShadow=!1,this.scrollStep=0,this.label="",this.atStart=!1,this.atEnd=!1,this.measured=!1,this.ownerRealmGeneration=0,this.updateEdges=()=>this.syncEdges(!1),this.onScroll=()=>{if(this.scrollFrame!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.scrollFrame!==handle||this.scrollFrameWindow!==ownerWindow||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollFrame=void 0,this.scrollFrameWindow=void 0,this.syncEdges(!0))});this.scrollFrame=handle,this.scrollFrameWindow=ownerWindow},this.onSlotChange=()=>{this.content&&this.resizeObserver?.observe(this.content),this.scheduleEdgeUpdate()}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious,scrollerLabel:LYRA_DEFAULT_scrollerLabel}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.armResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver(),this.scheduleEdgeUpdate()}disconnectedCallback(){this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}armResizeObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.resizeObserver&&this.resizeObserverDocument===ownerDocument){this.viewport&&this.resizeObserver.observe(this.viewport),this.content&&this.resizeObserver.observe(this.content);return}this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0;const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.updateEdges()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this),this.viewport&&observer.observe(this.viewport),this.content&&observer.observe(this.content)}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.cancelScrollFrame(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.measured=!1}scheduleEdgeUpdate(){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||this.updateEdges()})}willUpdate(changed){super.willUpdate(changed);const active=this.hasUpdated?shadowFocusTarget(this):null;(active?.matches('[part~="previous"]')?this.atStart:active?.matches('[part~="next"]')&&this.atEnd)&&this.viewport?.focus()}updated(changed){super.updated(changed),(changed.has("orientation")||changed.has("controls"))&&this.scheduleEdgeUpdate()}edgeDetail(){const viewport=this.viewport;if(!viewport)return{scrollStart:!1,scrollEnd:!1,scrollLeft:0,scrollTop:0};const horizontal=this.orientation==="horizontal",max=horizontal?Math.max(0,viewport.scrollWidth-viewport.clientWidth):Math.max(0,viewport.scrollHeight-viewport.clientHeight),position=horizontal?viewport.scrollLeft:viewport.scrollTop,startPosition=horizontal&&this.effectiveDirection==="rtl"?-position:position;return{scrollStart:startPosition<=1,scrollEnd:startPosition>=max-1,scrollLeft:viewport.scrollLeft,scrollTop:viewport.scrollTop}}syncEdges(emitForPositionChange){const detail=this.edgeDetail(),changed=!this.measured||detail.scrollStart!==this.atStart||detail.scrollEnd!==this.atEnd;this.measured=!0,this.atStart=detail.scrollStart,this.atEnd=detail.scrollEnd,(changed||emitForPositionChange)&&this.emit("lr-scroll",detail)}cancelScrollFrame(){this.scrollFrame!==void 0&&this.scrollFrameWindow?.cancelAnimationFrame(this.scrollFrame),this.scrollFrame=void 0,this.scrollFrameWindow=void 0}get safeScrollStep(){return finiteRange(this.scrollStep,0,0)}scrollByDirection(direction){const viewport=this.viewport;if(!viewport)return;const horizontal=this.orientation==="horizontal",step=this.safeScrollStep,amount=step>0?step:horizontal?Math.max(1,viewport.clientWidth*.8):Math.max(1,viewport.clientHeight*.8),physicalDirection=horizontal&&this.effectiveDirection==="rtl"?-direction:direction;viewport.scrollBy(horizontal?{left:amount*physicalDirection}:{top:amount*direction})}scrollToEdge(edge){const viewport=this.viewport;if(!viewport)return;if(this.orientation==="horizontal"){const max=Math.max(0,viewport.scrollWidth-viewport.clientWidth),rtl=this.effectiveDirection==="rtl";viewport.scrollTo({left:edge==="start"?0:rtl?-max:max})}else viewport.scrollTo({top:edge==="start"?0:viewport.scrollHeight})}render(){const label=this.getAttribute("aria-label")??(this.label||this.localize("scrollerLabel")),vertical=this.orientation==="vertical";return html`<div part="base">
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{styles}from"./scroller.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious,LYRA_DEFAULT_scrollerLabel}from"../../../internal/default-strings/layout.generated.js";class LyraScroller extends LyraElement{constructor(){super(...arguments),this.orientation="horizontal",this.controls=!1,this.withoutScrollbar=!1,this.withoutShadow=!1,this.scrollStep=0,this.label="",this.atStart=!1,this.atEnd=!1,this.measured=!1,this.ownerRealmGeneration=0,this.edgeUpdatePending=!1,this.updateEdges=()=>this.syncEdges(!1),this.onScroll=()=>{if(this.scrollFrame!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.scrollFrame!==handle||this.scrollFrameWindow!==ownerWindow||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollFrame=void 0,this.scrollFrameWindow=void 0,this.syncEdges(!0))});this.scrollFrame=handle,this.scrollFrameWindow=ownerWindow},this.onSlotChange=()=>{this.content&&this.resizeObserver?.observe(this.content),this.scheduleEdgeUpdate()}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious,scrollerLabel:LYRA_DEFAULT_scrollerLabel}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.armResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver(),this.scheduleEdgeUpdate()}disconnectedCallback(){this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}armResizeObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.resizeObserver&&this.resizeObserverDocument===ownerDocument){this.viewport&&this.resizeObserver.observe(this.viewport),this.content&&this.resizeObserver.observe(this.content);return}this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0;const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.updateEdges()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this),this.viewport&&observer.observe(this.viewport),this.content&&observer.observe(this.content)}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.edgeUpdatePending=!1,this.cancelScrollFrame(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.measured=!1}scheduleEdgeUpdate(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected||this.edgeUpdatePending)return;this.edgeUpdatePending=!0;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.edgeUpdatePending=!1,this.updateEdges())})}willUpdate(changed){super.willUpdate(changed);const active=this.hasUpdated?shadowFocusTarget(this):null;(active?.matches('[part~="previous"]')?this.atStart:active?.matches('[part~="next"]')&&this.atEnd)&&this.viewport?.focus()}updated(changed){super.updated(changed),(changed.has("orientation")||changed.has("controls"))&&this.scheduleEdgeUpdate()}edgeDetail(){const viewport=this.viewport;if(!viewport)return{scrollStart:!1,scrollEnd:!1,scrollLeft:0,scrollTop:0};const horizontal=this.orientation==="horizontal",max=horizontal?Math.max(0,viewport.scrollWidth-viewport.clientWidth):Math.max(0,viewport.scrollHeight-viewport.clientHeight),position=horizontal?viewport.scrollLeft:viewport.scrollTop,startPosition=horizontal&&this.effectiveDirection==="rtl"?-position:position;return{scrollStart:startPosition<=1,scrollEnd:startPosition>=max-1,scrollLeft:viewport.scrollLeft,scrollTop:viewport.scrollTop}}syncEdges(emitForPositionChange){const detail=this.edgeDetail(),changed=!this.measured||detail.scrollStart!==this.atStart||detail.scrollEnd!==this.atEnd;this.measured=!0,this.atStart=detail.scrollStart,this.atEnd=detail.scrollEnd,(changed||emitForPositionChange)&&this.emit("lr-scroll",detail)}cancelScrollFrame(){this.scrollFrame!==void 0&&this.scrollFrameWindow?.cancelAnimationFrame(this.scrollFrame),this.scrollFrame=void 0,this.scrollFrameWindow=void 0}get safeScrollStep(){return finiteRange(this.scrollStep,0,0)}scrollByDirection(direction){const viewport=this.viewport;if(!viewport)return;const horizontal=this.orientation==="horizontal",step=this.safeScrollStep,amount=step>0?step:horizontal?Math.max(1,viewport.clientWidth*.8):Math.max(1,viewport.clientHeight*.8),physicalDirection=horizontal&&this.effectiveDirection==="rtl"?-direction:direction;viewport.scrollBy(horizontal?{left:amount*physicalDirection}:{top:amount*direction})}scrollToEdge(edge){const viewport=this.viewport;if(!viewport)return;if(this.orientation==="horizontal"){const max=Math.max(0,viewport.scrollWidth-viewport.clientWidth),rtl=this.effectiveDirection==="rtl";viewport.scrollTo({left:edge==="start"?0:rtl?-max:max})}else viewport.scrollTo({top:edge==="start"?0:viewport.scrollHeight})}render(){const label=this.getAttribute("aria-label")??(this.label||this.localize("scrollerLabel")),vertical=this.orientation==="vertical";return html`<div part="base">
|
|
2
2
|
${this.controls?html`<button
|
|
3
3
|
part="control previous"
|
|
4
4
|
type="button"
|
|
@@ -61,7 +61,7 @@ positionInPixels:number;}export interface LyraSplitPanelEventMap{
|
|
|
61
61
|
* @status stable
|
|
62
62
|
* @since 8.0.0
|
|
63
63
|
*/
|
|
64
|
-
export declare class LyraSplitPanel extends LyraElement<LyraSplitPanelEventMap>{static styles:import("lit").CSSResultGroup[];private _startPosition;private _orientation;private _primary?;private _snapThreshold;private availableSize;private measuredConstraintBounds;private readonly resizeWriteGuard;private resizeRequestSequence;private pendingPositionInPixels?;private preservedPrimaryPixels?;private resizeObserver?;private resizeView?;private drag?;private readonly dragController;private readonly dividerSourceSnapshots;private dividerSourceObserver?;private dividerSourceObserverDocument?;private dividerSourceObserverGeneration;private normalizedSnapSource?;private cachedNormalizedSnapTokens;private baseElement?;private dividerElement?;private dividerSlot?;private minProbe?;private maxProbe?;
|
|
64
|
+
export declare class LyraSplitPanel extends LyraElement<LyraSplitPanelEventMap>{static styles:import("lit").CSSResultGroup[];private _startPosition;private _orientation;private _primary?;private _snapThreshold;private availableSize;private initialUpdate;private measuredConstraintBounds;private readonly resizeWriteGuard;private resizeRequestSequence;private pendingPositionInPixels?;private preservedPrimaryPixels?;private resizeObserver?;private resizeView?;private drag?;private readonly dragController;private readonly dividerSourceSnapshots;private dividerSourceObserver?;private dividerSourceObserverDocument?;private dividerSourceObserverGeneration;private normalizedSnapSource?;private cachedNormalizedSnapTokens;private baseElement?;private dividerElement?;private dividerSlot?;private minProbe?;private maxProbe?;
|
|
65
65
|
/** Divider position as a percentage from the primary panel's edge.
|
|
66
66
|
* @default 50 */
|
|
67
67
|
get position():number;set position(value:number);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteRange}from"../../../internal/numbers.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate,separatorDelta}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./split-panel.styles.js";import{LYRA_DEFAULT_resizeDivider,LYRA_DEFAULT_resizeValuePercent}from"../../../internal/default-strings/layout.generated.js";const DEFAULT_POSITION=50,DEFAULT_SNAP_THRESHOLD=12,KEYBOARD_STEP_PERCENT=1,MAX_SNAP_SOURCE_CODE_UNITS=16384,MAX_SNAP_TOKENS=256,POSITION_EPSILON=1e-4;import{SNAP_NONE}from"./split-panel-snap.js";const snapConverter={fromAttribute(value){return value??""},toAttribute(value){return typeof value=="string"&&value!==""?value:null}};function isAsciiDigit(code){return code>=48&&code<=57}function matchesAsciiToken(source,index,token){if(index+token.length>source.length)return!1;for(let offset=0;offset<token.length;offset+=1){const sourceCode=source.charCodeAt(index+offset);if((sourceCode>=65&&sourceCode<=90?sourceCode+32:sourceCode)!==token.charCodeAt(offset))return!1}return!0}function isSnapWhitespace(code){return code>=9&&code<=13||code===32||code===160||code===5760||code>=8192&&code<=8202||code===8232||code===8233||code===8239||code===8287||code===12288||code===65279}function skipSnapWhitespace(source,start){let cursor=start;for(;cursor<source.length&&isSnapWhitespace(source.charCodeAt(cursor));)cursor+=1;return cursor}function scanSnapLength(source,start){let cursor=start;if(isAsciiDigit(source.charCodeAt(cursor))){for(;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1}else if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;else return{end:start+1,recognized:!1};const numberEnd=cursor;let unit;if(source.charCodeAt(cursor)===37?(unit="%",cursor+=1):matchesAsciiToken(source,cursor,"px")&&(unit="px",cursor+=2),unit===void 0)return{end:Math.max(start+1,numberEnd),recognized:!1};const numericValue=Number(source.slice(start,numberEnd));return{end:cursor,recognized:!0,token:Number.isFinite(numericValue)?Object.freeze({value:numericValue,unit}):void 0}}function normalizeSnapTokens(value){const source=value.slice(0,MAX_SNAP_SOURCE_CODE_UNITS),tokens=[];let index=0;for(;index<source.length&&tokens.length<MAX_SNAP_TOKENS;){if(matchesAsciiToken(source,index,"repeat(")){const innerStart=skipSnapWhitespace(source,index+7),scanned2=scanSnapLength(source,innerStart);if(scanned2.recognized){const close=skipSnapWhitespace(source,scanned2.end);if(source.charCodeAt(close)===41){scanned2.token&&tokens.push(Object.freeze({repeated:!0,...scanned2.token})),index=close+1;continue}scanned2.token&&tokens.push(Object.freeze({repeated:!1,...scanned2.token}))}index=Math.max(index+7,scanned2.end);continue}const scanned=scanSnapLength(source,index);scanned.recognized&&scanned.token&&tokens.push(Object.freeze({repeated:!1,...scanned.token})),index=Math.max(index+1,scanned.end)}return Object.freeze(tokens)}function nearlyEqual(left,right){return left===right?!0:left==null||right==null?!1:Math.abs(left-right)<=POSITION_EPSILON}class LyraSplitPanel extends LyraElement{constructor(){super(...arguments),this._startPosition=DEFAULT_POSITION,this._orientation="horizontal",this._snapThreshold=DEFAULT_SNAP_THRESHOLD,this.availableSize=0,this.measuredConstraintBounds={min:0,max:0},this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>this.onPointerEnd(event)),this.dividerSourceSnapshots=new Map,this.dividerSourceObserverGeneration=0,this.cachedNormalizedSnapTokens=Object.freeze([]),this.disabled=!1,this._snap="",this.onWindowResize=()=>{this.measureAndSynchronize(!1)},this.onDividerSlotChange=()=>{this.syncDividerSources()},this.onPointerMove=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;if(this.disabled||this.effectiveDirection==="rtl"!==drag.rtl||this.effectiveOrientation!==drag.orientation||this.primary!==drag.primary||!nearlyEqual(this.availableSize,drag.size)){this.stopDragging();return}let delta=separatorDelta(drag.startCoordinate,event,this.effectiveOrientation==="vertical"?"block":"inline",drag.rtl);this.primary==="end"&&(delta*=-1),this.requestReposition(drag.startPrimaryPixels+delta,!0,drag.bounds)&&(drag.acceptedResize=!0)},this.onPointerEnd=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;const bounds=this.constraintBounds(),shouldSettle=event.type==="pointerup"&&drag.acceptedResize&&!this.disabled&&this.effectiveOrientation===drag.orientation&&this.primary===drag.primary&&this.effectiveDirection==="rtl"===drag.rtl&&nearlyEqual(this.availableSize,drag.size)&&nearlyEqual(bounds.min,drag.bounds.min)&&nearlyEqual(bounds.max,drag.bounds.max);this.stopDragging(),shouldSettle&&this.emitResizeChange()}}static{this.defaultStrings={...super.defaultStrings,resizeDivider:LYRA_DEFAULT_resizeDivider,resizeValuePercent:LYRA_DEFAULT_resizeValuePercent}}static{this.styles=[LyraElement.styles,styles]}get position(){const start=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);return this.primary==="end"?100-start:start}set position(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels,next=finiteRange(value,DEFAULT_POSITION,0,100);this.pendingPositionInPixels=void 0;const layoutSize=this.measuredLayoutSize();if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next/100*layoutSize,!1,oldPosition,oldPixels);return}this._startPosition=this.primary==="end"?100-next:next,this.preservedPrimaryPixels=void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get positionInPixels(){return this.pendingPositionInPixels!=null?this.pendingPositionInPixels:this.availableSize<=0?0:this.position/100*this.availableSize}set positionInPixels(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels;if(value==null){this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=this.availableSize>0?this.positionInPixels:void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels);return}const fallback=this.positionInPixels??DEFAULT_POSITION/100*this.availableSize,layoutSize=this.measuredLayoutSize(),next=finiteRange(value,fallback,0,layoutSize>0?layoutSize:Number.MAX_VALUE);if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next,!1,oldPosition,oldPixels);return}this.pendingPositionInPixels=next,this.preservedPrimaryPixels=next,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get orientation(){return this._orientation}set orientation(value){const next=value==="vertical"?"vertical":"horizontal";if(next===this._orientation)return;const old=this._orientation,oldVertical=this.vertical;this._orientation=next,this.requestUpdate("orientation",old),this.requestUpdate("vertical",oldVertical)}get vertical(){return this.orientation==="vertical"}set vertical(value){this.orientation=value?"vertical":"horizontal"}get primary(){return this._primary}set primary(value){const next=value==="start"||value==="end"?value:void 0;if(next===this._primary)return;this.stopDragging();const oldPrimary=this._primary,oldPosition=this.position,oldPixels=this.positionInPixels,layoutSize=this.measuredLayoutSize(),referencePixels=layoutSize>0&&!oldPrimary?oldPosition/100*layoutSize:oldPixels;this._primary=next,layoutSize>0?(this.availableSize=layoutSize,this.applyPrimaryPixels(referencePixels,!1,oldPosition,oldPixels)):(this._startPosition=next==="end"?100-oldPosition:oldPosition,this.preservedPrimaryPixels=this.pendingPositionInPixels??oldPixels),this.requestUpdate("primary",oldPrimary)}get snap(){return this._snap}set snap(value){const old=this._snap;this._snap=value??"",this.requestUpdate("snap",old)}get snapThreshold(){return this._snapThreshold}set snapThreshold(value){const old=this._snapThreshold;this._snapThreshold=finiteRange(value,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE),this.requestUpdate("snapThreshold",old)}get effectiveOrientation(){return this.orientation}measuredLayoutSize(){return this.isConnected?this.axisSize(this.baseElement):0}connectedCallback(){const authoredOrientation=this.getAttribute("orientation");super.connectedCallback(),authoredOrientation!==null&&(this.orientation=authoredOrientation==="vertical"?"vertical":"horizontal"),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&(this.syncDividerSources(),this.observeSize(),this.measureAndSynchronize(!1))})}disconnectedCallback(){this.stopDragging(),this.resetDividerSourceObserver(),this.restoreDividerSources(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.syncDividerSources(),this.measureAndSynchronize(!0),this.observeSize()}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&this.stopDragging(),(changed.has("orientation")||changed.has("vertical"))&&(this.stopDragging(),this.measureAndSynchronize(!1))}requestSynchronizedUpdate(oldPosition,oldPixels){nearlyEqual(oldPosition,this.position)||this.requestUpdate("position",oldPosition),nearlyEqual(oldPixels,this.positionInPixels)||this.requestUpdate("positionInPixels",oldPixels)}axisSize(element){if(!element)return 0;const rect=element.getBoundingClientRect(),measured=this.effectiveOrientation==="vertical"?rect.height:rect.width;return finiteRange(measured,0,0,Number.MAX_VALUE)}constraintBounds(){const size=this.availableSize,min=finiteRange(this.axisSize(this.minProbe),0,0,size),rawMax=this.maxProbe?this.axisSize(this.maxProbe):size,max=finiteRange(rawMax,size,min,size);return{min,max}}resolvePrimaryPixels(requestedPixels,useSnap,fallbackPixels,bounds=this.constraintBounds()){const size=this.availableSize,proposed=finiteRange(requestedPixels,fallbackPixels??DEFAULT_POSITION/100*size,0,size),snapped=useSnap?this.applySnap(proposed,size):proposed,{min,max}=bounds;return finiteRange(snapped,proposed,min,max)}applyPrimaryPixels(requestedPixels,useSnap,oldPosition=this.position,oldPixels=this.positionInPixels,scheduleUpdate=!0,resolvedPrimaryPixels){const size=this.availableSize;if(size<=0)return this.pendingPositionInPixels=finiteRange(requestedPixels,0,0,Number.MAX_VALUE),this.preservedPrimaryPixels=this.pendingPositionInPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!1;const primaryPixels=resolvedPrimaryPixels??this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels),primaryPercent=primaryPixels/size*100;return this._startPosition=this.primary==="end"?100-primaryPercent:primaryPercent,this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=primaryPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!nearlyEqual(oldPosition,this.position)||!nearlyEqual(oldPixels,this.positionInPixels)}requestReposition(requestedPixels,useSnap,bounds=this.constraintBounds()){if(this.availableSize<=0)return!1;const oldPosition=this.position,oldPixels=this.positionInPixels,primaryPixels=this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels,bounds),position=primaryPixels/this.availableSize*100;if(nearlyEqual(oldPosition,position)&&nearlyEqual(oldPixels,primaryPixels))return!1;const detail=Object.freeze({position,positionInPixels:primaryPixels}),snapshot={drag:this.drag,disabled:this.disabled,primary:this.primary,orientation:this.effectiveOrientation,direction:this.effectiveDirection,size:this.availableSize,snap:this.snap,snapThreshold:this.snapThreshold},requestSequence=++this.resizeRequestSequence;this.resizeWriteGuard.open();const resizeRequest=this.emit("lr-resize-request",detail,{cancelable:!0}),request=this.emit("lr-reposition-request",detail,{cancelable:!0});if(resizeRequest.defaultPrevented||request.defaultPrevented||this.resizeWriteGuard.touched)return!1;const currentBounds=this.constraintBounds();return this.drag!==snapshot.drag||this.resizeRequestSequence!==requestSequence||this.disabled||this.disabled!==snapshot.disabled||this.primary!==snapshot.primary||this.effectiveOrientation!==snapshot.orientation||this.effectiveDirection!==snapshot.direction||!nearlyEqual(this.availableSize,snapshot.size)||this.snap!==snapshot.snap||this.snapThreshold!==snapshot.snapThreshold||!nearlyEqual(this.position,oldPosition)||!nearlyEqual(this.positionInPixels,oldPixels)||!nearlyEqual(currentBounds.min,bounds.min)||!nearlyEqual(currentBounds.max,bounds.max)?(snapshot.drag&&this.drag===snapshot.drag&&this.stopDragging(),!1):this.applyPrimaryPixels(requestedPixels,useSnap,oldPosition,oldPixels,!0,primaryPixels)?(this.emit("lr-resize",Object.freeze({position:this.position,positionInPixels:this.positionInPixels})),this.emit("lr-reposition",null),!0):!1}measureAndSynchronize(initial){const nextSize=this.axisSize(this.baseElement);if(nextSize<=0)return;const oldPosition=this.position,oldPixels=this.positionInPixels,pending=this.pendingPositionInPixels,preserved=this.preservedPrimaryPixels,sizeChanged=!nearlyEqual(this.availableSize,nextSize);this.availableSize=nextSize;const nextBounds=this.constraintBounds();this.drag&&(sizeChanged||!nearlyEqual(nextBounds.min,this.drag.bounds.min)||!nearlyEqual(nextBounds.max,this.drag.bounds.max))&&this.stopDragging(),this.measuredConstraintBounds=nextBounds,pending!=null?this.applyPrimaryPixels(pending,!1,oldPosition,oldPixels,!1):!initial&&sizeChanged&&this.primary&&preserved!=null?this.applyPrimaryPixels(preserved,!1,oldPosition,oldPixels,!1):this.applyPrimaryPixels(this.position/100*nextSize,!1,oldPosition,oldPixels,!1),this.synchronizeMeasuredDom()}synchronizeMeasuredDom(){const startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);if(this.baseElement?.style.setProperty("--_lr-split-panel-start-position",`${startPosition}%`),this.dividerElement){const bounds=this.ariaBounds,position=Math.round(this.position);this.dividerElement.setAttribute("aria-valuenow",String(position)),this.dividerElement.setAttribute("aria-valuetext",this.resizeValueText(position)),this.dividerElement.setAttribute("aria-valuemin",String(Math.round(bounds.min))),this.dividerElement.setAttribute("aria-valuemax",String(Math.round(bounds.max)))}const reflectedPosition=String(this.position);this.getAttribute("position")!==reflectedPosition&&this.setAttribute("position",reflectedPosition)}observeSize(){if(this.resizeObserver||this.resizeView||!this.isConnected)return;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver=new ResizeObserverConstructor(()=>this.measureAndSynchronize(!1)),this.baseElement&&this.resizeObserver.observe(this.baseElement),this.minProbe&&this.resizeObserver.observe(this.minProbe),this.maxProbe&&this.resizeObserver.observe(this.maxProbe);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}snapshotDividerSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert}}adoptDividerSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current)}makeDividerSourceInert(source,snapshot){source.hasAttribute("inert")||source.setAttribute("inert",""),snapshot.appliedInert=source.getAttribute("inert")}restoreDividerSource(source,snapshot){this.adoptDividerSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreDividerSources(){for(const[source,snapshot]of this.dividerSourceSnapshots)this.restoreDividerSource(source,snapshot);this.dividerSourceSnapshots.clear()}resetDividerSourceObserver(){this.dividerSourceObserverGeneration+=1,this.dividerSourceObserver?.disconnect(),this.dividerSourceObserver=void 0,this.dividerSourceObserverDocument=void 0}observeDividerSources(){this.resetDividerSourceObserver();const MutationObserverConstructor=this.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverConstructor||!this.isConnected||this.dividerSourceSnapshots.size===0)return;const generation=this.dividerSourceObserverGeneration,observer=new MutationObserverConstructor(records=>{this.dividerSourceObserver!==observer||this.dividerSourceObserverDocument!==this.ownerDocument||this.dividerSourceObserverGeneration!==generation||!this.isConnected||records.some(record=>this.dividerSourceSnapshots.has(record.target))&&this.syncDividerSources()});this.dividerSourceObserver=observer,this.dividerSourceObserverDocument=this.ownerDocument;for(const source of this.dividerSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}syncDividerSources(){const assigned=new Set(this.dividerSlot?.assignedElements({flatten:!0})??[]);for(const[source,snapshot]of this.dividerSourceSnapshots)this.adoptDividerSourceInert(source,snapshot),assigned.has(source)||(this.restoreDividerSource(source,snapshot),this.dividerSourceSnapshots.delete(source));for(const source of assigned){const snapshot=this.dividerSourceSnapshots.get(source)??this.snapshotDividerSource(source);this.dividerSourceSnapshots.set(source,snapshot),this.adoptDividerSourceInert(source,snapshot),this.makeDividerSourceInert(source,snapshot)}this.observeDividerSources()}resolveNormalizedSnapLength(token,size){const resolved=token.unit==="%"?token.value/100*size:token.value;return Number.isFinite(resolved)&&resolved>=0?resolved:void 0}get normalizedSnapTokens(){const source=typeof this.snap=="string"?this.snap:"";return source===this.normalizedSnapSource?this.cachedNormalizedSnapTokens:(this.normalizedSnapSource=source,this.cachedNormalizedSnapTokens=normalizeSnapTokens(source),this.cachedNormalizedSnapTokens)}applySnap(position,size){const threshold=finiteRange(this.snapThreshold,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE);if(typeof this.snap=="function")try{return finiteRange(this.snap({pos:position,size,snapThreshold:threshold}),position,0,size)}catch{return position}const tokens=this.normalizedSnapTokens;if(tokens.length===0)return position;let nearest=position,nearestDistance=Number.POSITIVE_INFINITY;for(const token of tokens){const point=this.resolveNormalizedSnapLength(token,size);if(point==null||point<0)continue;const candidates=token.repeated?[Math.floor(position/point)*point,Math.round(position/point)*point,Math.ceil(position/point)*point]:[point];for(const candidate of candidates){if(!Number.isFinite(candidate)||candidate<0||candidate>size)continue;const distance=Math.abs(position-candidate);distance<nearestDistance&&(nearest=candidate,nearestDistance=distance)}}return nearestDistance<=threshold?nearest:position}pointerCoordinate(event){return separatorCoordinate(event,this.effectiveOrientation==="vertical"?"block":"inline")}onPointerDown(event){if(this.disabled||this.drag||event.button!==0)return;const primaryPixels=this.positionInPixels;primaryPixels==null||this.availableSize<=0||this.dragController.start(event,event.currentTarget)&&(event.preventDefault(),this.drag={pointerId:event.pointerId,startCoordinate:this.pointerCoordinate(event),startPrimaryPixels:primaryPixels,bounds:this.constraintBounds(),rtl:this.effectiveDirection==="rtl",orientation:this.effectiveOrientation,primary:this.primary,size:this.availableSize,acceptedResize:!1},this.dividerElement?.setAttribute("data-dragging",""))}stopDragging(){const pointerId=this.drag?.pointerId;this.drag=void 0,this.dividerElement?.removeAttribute("data-dragging"),pointerId!=null&&this.dragController.end(pointerId)}emitResizeChange(){const positionInPixels=this.positionInPixels;positionInPixels!=null&&this.emit("lr-resize-change",Object.freeze({position:this.position,positionInPixels}))}onKeyDown(event){if(this.disabled||this.availableSize<=0||event.altKey||event.ctrlKey||event.metaKey||event.isComposing)return;const current=this.positionInPixels;if(current==null)return;let next;const{min,max}=this.constraintBounds();if(event.key==="Home")next=min;else if(event.key==="End")next=max;else{const physicalDirection=separatorArrowDirection(event,this.effectiveOrientation==="vertical"?"block":"inline",this.effectiveDirection==="rtl");if(physicalDirection!==0){const primaryDirection=this.primary==="end"?-physicalDirection:physicalDirection;next=current+primaryDirection*KEYBOARD_STEP_PERCENT*this.availableSize/100}}next!=null&&(event.preventDefault(),this.requestReposition(next,!1)&&this.emitResizeChange())}get separatorLabel(){const hostLabel=this.getAttribute("aria-label");if(hostLabel!==null)return hostLabel;const number=getNumberFormat(this.effectiveLocale);return this.localize("resizeDivider",void 0,{a:number.format(1),b:number.format(2)})}resizeValueText(position){return this.localize("resizeValuePercent",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(position))})}get ariaBounds(){if(this.availableSize<=0)return{min:0,max:100};const bounds=this.measuredConstraintBounds;return{min:bounds.min/this.availableSize*100,max:bounds.max/this.availableSize*100}}render(){const orientation=this.effectiveOrientation,startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100),ariaBounds=this.ariaBounds,position=Math.round(this.position);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteRange}from"../../../internal/numbers.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate,separatorDelta}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./split-panel.styles.js";import{LYRA_DEFAULT_resizeDivider,LYRA_DEFAULT_resizeValuePercent}from"../../../internal/default-strings/layout.generated.js";const DEFAULT_POSITION=50,DEFAULT_SNAP_THRESHOLD=12,KEYBOARD_STEP_PERCENT=1,MAX_SNAP_SOURCE_CODE_UNITS=16384,MAX_SNAP_TOKENS=256,POSITION_EPSILON=1e-4;import{SNAP_NONE}from"./split-panel-snap.js";const snapConverter={fromAttribute(value){return value??""},toAttribute(value){return typeof value=="string"&&value!==""?value:null}};function isAsciiDigit(code){return code>=48&&code<=57}function matchesAsciiToken(source,index,token){if(index+token.length>source.length)return!1;for(let offset=0;offset<token.length;offset+=1){const sourceCode=source.charCodeAt(index+offset);if((sourceCode>=65&&sourceCode<=90?sourceCode+32:sourceCode)!==token.charCodeAt(offset))return!1}return!0}function isSnapWhitespace(code){return code>=9&&code<=13||code===32||code===160||code===5760||code>=8192&&code<=8202||code===8232||code===8233||code===8239||code===8287||code===12288||code===65279}function skipSnapWhitespace(source,start){let cursor=start;for(;cursor<source.length&&isSnapWhitespace(source.charCodeAt(cursor));)cursor+=1;return cursor}function scanSnapLength(source,start){let cursor=start;if(isAsciiDigit(source.charCodeAt(cursor))){for(;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1}else if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;else return{end:start+1,recognized:!1};const numberEnd=cursor;let unit;if(source.charCodeAt(cursor)===37?(unit="%",cursor+=1):matchesAsciiToken(source,cursor,"px")&&(unit="px",cursor+=2),unit===void 0)return{end:Math.max(start+1,numberEnd),recognized:!1};const numericValue=Number(source.slice(start,numberEnd));return{end:cursor,recognized:!0,token:Number.isFinite(numericValue)?Object.freeze({value:numericValue,unit}):void 0}}function normalizeSnapTokens(value){const source=value.slice(0,MAX_SNAP_SOURCE_CODE_UNITS),tokens=[];let index=0;for(;index<source.length&&tokens.length<MAX_SNAP_TOKENS;){if(matchesAsciiToken(source,index,"repeat(")){const innerStart=skipSnapWhitespace(source,index+7),scanned2=scanSnapLength(source,innerStart);if(scanned2.recognized){const close=skipSnapWhitespace(source,scanned2.end);if(source.charCodeAt(close)===41){scanned2.token&&tokens.push(Object.freeze({repeated:!0,...scanned2.token})),index=close+1;continue}scanned2.token&&tokens.push(Object.freeze({repeated:!1,...scanned2.token}))}index=Math.max(index+7,scanned2.end);continue}const scanned=scanSnapLength(source,index);scanned.recognized&&scanned.token&&tokens.push(Object.freeze({repeated:!1,...scanned.token})),index=Math.max(index+1,scanned.end)}return Object.freeze(tokens)}function nearlyEqual(left,right){return left===right?!0:left==null||right==null?!1:Math.abs(left-right)<=POSITION_EPSILON}class LyraSplitPanel extends LyraElement{constructor(){super(...arguments),this._startPosition=DEFAULT_POSITION,this._orientation="horizontal",this._snapThreshold=DEFAULT_SNAP_THRESHOLD,this.availableSize=0,this.initialUpdate=!0,this.measuredConstraintBounds={min:0,max:0},this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>this.onPointerEnd(event)),this.dividerSourceSnapshots=new Map,this.dividerSourceObserverGeneration=0,this.cachedNormalizedSnapTokens=Object.freeze([]),this.disabled=!1,this._snap="",this.onWindowResize=()=>{this.measureAndSynchronize(!1)},this.onDividerSlotChange=()=>{this.syncDividerSources()},this.onPointerMove=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;if(this.disabled||this.effectiveDirection==="rtl"!==drag.rtl||this.effectiveOrientation!==drag.orientation||this.primary!==drag.primary||!nearlyEqual(this.availableSize,drag.size)){this.stopDragging();return}let delta=separatorDelta(drag.startCoordinate,event,this.effectiveOrientation==="vertical"?"block":"inline",drag.rtl);this.primary==="end"&&(delta*=-1),this.requestReposition(drag.startPrimaryPixels+delta,!0,drag.bounds)&&(drag.acceptedResize=!0)},this.onPointerEnd=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;const bounds=this.constraintBounds(),shouldSettle=event.type==="pointerup"&&drag.acceptedResize&&!this.disabled&&this.effectiveOrientation===drag.orientation&&this.primary===drag.primary&&this.effectiveDirection==="rtl"===drag.rtl&&nearlyEqual(this.availableSize,drag.size)&&nearlyEqual(bounds.min,drag.bounds.min)&&nearlyEqual(bounds.max,drag.bounds.max);this.stopDragging(),shouldSettle&&this.emitResizeChange()}}static{this.defaultStrings={...super.defaultStrings,resizeDivider:LYRA_DEFAULT_resizeDivider,resizeValuePercent:LYRA_DEFAULT_resizeValuePercent}}static{this.styles=[LyraElement.styles,styles]}get position(){const start=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);return this.primary==="end"?100-start:start}set position(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels,next=finiteRange(value,DEFAULT_POSITION,0,100);this.pendingPositionInPixels=void 0;const layoutSize=this.measuredLayoutSize();if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next/100*layoutSize,!1,oldPosition,oldPixels);return}this._startPosition=this.primary==="end"?100-next:next,this.preservedPrimaryPixels=void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get positionInPixels(){return this.pendingPositionInPixels!=null?this.pendingPositionInPixels:this.availableSize<=0?0:this.position/100*this.availableSize}set positionInPixels(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels;if(value==null){this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=this.availableSize>0?this.positionInPixels:void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels);return}const fallback=this.positionInPixels??DEFAULT_POSITION/100*this.availableSize,layoutSize=this.measuredLayoutSize(),next=finiteRange(value,fallback,0,layoutSize>0?layoutSize:Number.MAX_VALUE);if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next,!1,oldPosition,oldPixels);return}this.pendingPositionInPixels=next,this.preservedPrimaryPixels=next,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get orientation(){return this._orientation}set orientation(value){const next=value==="vertical"?"vertical":"horizontal";if(next===this._orientation)return;const old=this._orientation,oldVertical=this.vertical;this._orientation=next,this.requestUpdate("orientation",old),this.requestUpdate("vertical",oldVertical)}get vertical(){return this.orientation==="vertical"}set vertical(value){this.orientation=value?"vertical":"horizontal"}get primary(){return this._primary}set primary(value){const next=value==="start"||value==="end"?value:void 0;if(next===this._primary)return;this.stopDragging();const oldPrimary=this._primary,oldPosition=this.position,oldPixels=this.positionInPixels,layoutSize=this.measuredLayoutSize(),referencePixels=layoutSize>0&&!oldPrimary?oldPosition/100*layoutSize:oldPixels;this._primary=next,layoutSize>0?(this.availableSize=layoutSize,this.applyPrimaryPixels(referencePixels,!1,oldPosition,oldPixels)):(this._startPosition=next==="end"?100-oldPosition:oldPosition,this.preservedPrimaryPixels=this.pendingPositionInPixels??oldPixels),this.requestUpdate("primary",oldPrimary)}get snap(){return this._snap}set snap(value){const old=this._snap;this._snap=value??"",this.requestUpdate("snap",old)}get snapThreshold(){return this._snapThreshold}set snapThreshold(value){const old=this._snapThreshold;this._snapThreshold=finiteRange(value,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE),this.requestUpdate("snapThreshold",old)}get effectiveOrientation(){return this.orientation}measuredLayoutSize(){return this.isConnected?this.axisSize(this.baseElement):0}connectedCallback(){const authoredOrientation=this.getAttribute("orientation");super.connectedCallback(),authoredOrientation!==null&&(this.orientation=authoredOrientation==="vertical"?"vertical":"horizontal"),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&(this.syncDividerSources(),this.observeSize(),this.measureAndSynchronize(!1))})}disconnectedCallback(){this.stopDragging(),this.resetDividerSourceObserver(),this.restoreDividerSources(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.syncDividerSources(),this.measureAndSynchronize(!0),this.observeSize()}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&this.stopDragging(),!this.initialUpdate&&(changed.has("orientation")||changed.has("vertical"))&&(this.stopDragging(),this.measureAndSynchronize(!1)),this.initialUpdate=!1}requestSynchronizedUpdate(oldPosition,oldPixels){nearlyEqual(oldPosition,this.position)||this.requestUpdate("position",oldPosition),nearlyEqual(oldPixels,this.positionInPixels)||this.requestUpdate("positionInPixels",oldPixels)}axisSize(element){if(!element)return 0;const rect=element.getBoundingClientRect(),measured=this.effectiveOrientation==="vertical"?rect.height:rect.width;return finiteRange(measured,0,0,Number.MAX_VALUE)}constraintBounds(){const size=this.availableSize,min=finiteRange(this.axisSize(this.minProbe),0,0,size),rawMax=this.maxProbe?this.axisSize(this.maxProbe):size,max=finiteRange(rawMax,size,min,size);return{min,max}}resolvePrimaryPixels(requestedPixels,useSnap,fallbackPixels,bounds=this.constraintBounds()){const size=this.availableSize,proposed=finiteRange(requestedPixels,fallbackPixels??DEFAULT_POSITION/100*size,0,size),snapped=useSnap?this.applySnap(proposed,size):proposed,{min,max}=bounds;return finiteRange(snapped,proposed,min,max)}applyPrimaryPixels(requestedPixels,useSnap,oldPosition=this.position,oldPixels=this.positionInPixels,scheduleUpdate=!0,resolvedPrimaryPixels){const size=this.availableSize;if(size<=0)return this.pendingPositionInPixels=finiteRange(requestedPixels,0,0,Number.MAX_VALUE),this.preservedPrimaryPixels=this.pendingPositionInPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!1;const primaryPixels=resolvedPrimaryPixels??this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels),primaryPercent=primaryPixels/size*100;return this._startPosition=this.primary==="end"?100-primaryPercent:primaryPercent,this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=primaryPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!nearlyEqual(oldPosition,this.position)||!nearlyEqual(oldPixels,this.positionInPixels)}requestReposition(requestedPixels,useSnap,bounds=this.constraintBounds()){if(this.availableSize<=0)return!1;const oldPosition=this.position,oldPixels=this.positionInPixels,primaryPixels=this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels,bounds),position=primaryPixels/this.availableSize*100;if(nearlyEqual(oldPosition,position)&&nearlyEqual(oldPixels,primaryPixels))return!1;const detail=Object.freeze({position,positionInPixels:primaryPixels}),snapshot={drag:this.drag,disabled:this.disabled,primary:this.primary,orientation:this.effectiveOrientation,direction:this.effectiveDirection,size:this.availableSize,snap:this.snap,snapThreshold:this.snapThreshold},requestSequence=++this.resizeRequestSequence;this.resizeWriteGuard.open();const resizeRequest=this.emit("lr-resize-request",detail,{cancelable:!0}),request=this.emit("lr-reposition-request",detail,{cancelable:!0});if(resizeRequest.defaultPrevented||request.defaultPrevented||this.resizeWriteGuard.touched)return!1;const currentBounds=this.constraintBounds();return this.drag!==snapshot.drag||this.resizeRequestSequence!==requestSequence||this.disabled||this.disabled!==snapshot.disabled||this.primary!==snapshot.primary||this.effectiveOrientation!==snapshot.orientation||this.effectiveDirection!==snapshot.direction||!nearlyEqual(this.availableSize,snapshot.size)||this.snap!==snapshot.snap||this.snapThreshold!==snapshot.snapThreshold||!nearlyEqual(this.position,oldPosition)||!nearlyEqual(this.positionInPixels,oldPixels)||!nearlyEqual(currentBounds.min,bounds.min)||!nearlyEqual(currentBounds.max,bounds.max)?(snapshot.drag&&this.drag===snapshot.drag&&this.stopDragging(),!1):this.applyPrimaryPixels(requestedPixels,useSnap,oldPosition,oldPixels,!0,primaryPixels)?(this.emit("lr-resize",Object.freeze({position:this.position,positionInPixels:this.positionInPixels})),this.emit("lr-reposition",null),!0):!1}measureAndSynchronize(initial){const nextSize=this.axisSize(this.baseElement);if(nextSize<=0)return;const oldPosition=this.position,oldPixels=this.positionInPixels,pending=this.pendingPositionInPixels,preserved=this.preservedPrimaryPixels,sizeChanged=!nearlyEqual(this.availableSize,nextSize);this.availableSize=nextSize;const nextBounds=this.constraintBounds();this.drag&&(sizeChanged||!nearlyEqual(nextBounds.min,this.drag.bounds.min)||!nearlyEqual(nextBounds.max,this.drag.bounds.max))&&this.stopDragging(),this.measuredConstraintBounds=nextBounds,pending!=null?this.applyPrimaryPixels(pending,!1,oldPosition,oldPixels,!1):!initial&&sizeChanged&&this.primary&&preserved!=null?this.applyPrimaryPixels(preserved,!1,oldPosition,oldPixels,!1):this.applyPrimaryPixels(this.position/100*nextSize,!1,oldPosition,oldPixels,!1),this.synchronizeMeasuredDom()}synchronizeMeasuredDom(){const startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);if(this.baseElement?.style.setProperty("--_lr-split-panel-start-position",`${startPosition}%`),this.dividerElement){const bounds=this.ariaBounds,position=Math.round(this.position);this.dividerElement.setAttribute("aria-valuenow",String(position)),this.dividerElement.setAttribute("aria-valuetext",this.resizeValueText(position)),this.dividerElement.setAttribute("aria-valuemin",String(Math.round(bounds.min))),this.dividerElement.setAttribute("aria-valuemax",String(Math.round(bounds.max)))}const reflectedPosition=String(this.position);this.getAttribute("position")!==reflectedPosition&&this.setAttribute("position",reflectedPosition)}observeSize(){if(this.resizeObserver||this.resizeView||!this.isConnected)return;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver=new ResizeObserverConstructor(()=>this.measureAndSynchronize(!1)),this.baseElement&&this.resizeObserver.observe(this.baseElement),this.minProbe&&this.resizeObserver.observe(this.minProbe),this.maxProbe&&this.resizeObserver.observe(this.maxProbe);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}snapshotDividerSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert}}adoptDividerSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current)}makeDividerSourceInert(source,snapshot){source.hasAttribute("inert")||source.setAttribute("inert",""),snapshot.appliedInert=source.getAttribute("inert")}restoreDividerSource(source,snapshot){this.adoptDividerSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreDividerSources(){for(const[source,snapshot]of this.dividerSourceSnapshots)this.restoreDividerSource(source,snapshot);this.dividerSourceSnapshots.clear()}resetDividerSourceObserver(){this.dividerSourceObserverGeneration+=1,this.dividerSourceObserver?.disconnect(),this.dividerSourceObserver=void 0,this.dividerSourceObserverDocument=void 0}observeDividerSources(){this.resetDividerSourceObserver();const MutationObserverConstructor=this.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverConstructor||!this.isConnected||this.dividerSourceSnapshots.size===0)return;const generation=this.dividerSourceObserverGeneration,observer=new MutationObserverConstructor(records=>{this.dividerSourceObserver!==observer||this.dividerSourceObserverDocument!==this.ownerDocument||this.dividerSourceObserverGeneration!==generation||!this.isConnected||records.some(record=>this.dividerSourceSnapshots.has(record.target))&&this.syncDividerSources()});this.dividerSourceObserver=observer,this.dividerSourceObserverDocument=this.ownerDocument;for(const source of this.dividerSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}syncDividerSources(){const assigned=new Set(this.dividerSlot?.assignedElements({flatten:!0})??[]);for(const[source,snapshot]of this.dividerSourceSnapshots)this.adoptDividerSourceInert(source,snapshot),assigned.has(source)||(this.restoreDividerSource(source,snapshot),this.dividerSourceSnapshots.delete(source));for(const source of assigned){const snapshot=this.dividerSourceSnapshots.get(source)??this.snapshotDividerSource(source);this.dividerSourceSnapshots.set(source,snapshot),this.adoptDividerSourceInert(source,snapshot),this.makeDividerSourceInert(source,snapshot)}this.observeDividerSources()}resolveNormalizedSnapLength(token,size){const resolved=token.unit==="%"?token.value/100*size:token.value;return Number.isFinite(resolved)&&resolved>=0?resolved:void 0}get normalizedSnapTokens(){const source=typeof this.snap=="string"?this.snap:"";return source===this.normalizedSnapSource?this.cachedNormalizedSnapTokens:(this.normalizedSnapSource=source,this.cachedNormalizedSnapTokens=normalizeSnapTokens(source),this.cachedNormalizedSnapTokens)}applySnap(position,size){const threshold=finiteRange(this.snapThreshold,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE);if(typeof this.snap=="function")try{return finiteRange(this.snap({pos:position,size,snapThreshold:threshold}),position,0,size)}catch{return position}const tokens=this.normalizedSnapTokens;if(tokens.length===0)return position;let nearest=position,nearestDistance=Number.POSITIVE_INFINITY;for(const token of tokens){const point=this.resolveNormalizedSnapLength(token,size);if(point==null||point<0)continue;const candidates=token.repeated?[Math.floor(position/point)*point,Math.round(position/point)*point,Math.ceil(position/point)*point]:[point];for(const candidate of candidates){if(!Number.isFinite(candidate)||candidate<0||candidate>size)continue;const distance=Math.abs(position-candidate);distance<nearestDistance&&(nearest=candidate,nearestDistance=distance)}}return nearestDistance<=threshold?nearest:position}pointerCoordinate(event){return separatorCoordinate(event,this.effectiveOrientation==="vertical"?"block":"inline")}onPointerDown(event){if(this.disabled||this.drag||event.button!==0)return;const primaryPixels=this.positionInPixels;primaryPixels==null||this.availableSize<=0||this.dragController.start(event,event.currentTarget)&&(event.preventDefault(),this.drag={pointerId:event.pointerId,startCoordinate:this.pointerCoordinate(event),startPrimaryPixels:primaryPixels,bounds:this.constraintBounds(),rtl:this.effectiveDirection==="rtl",orientation:this.effectiveOrientation,primary:this.primary,size:this.availableSize,acceptedResize:!1},this.dividerElement?.setAttribute("data-dragging",""))}stopDragging(){const pointerId=this.drag?.pointerId;this.drag=void 0,this.dividerElement?.removeAttribute("data-dragging"),pointerId!=null&&this.dragController.end(pointerId)}emitResizeChange(){const positionInPixels=this.positionInPixels;positionInPixels!=null&&this.emit("lr-resize-change",Object.freeze({position:this.position,positionInPixels}))}onKeyDown(event){if(this.disabled||this.availableSize<=0||event.altKey||event.ctrlKey||event.metaKey||event.isComposing)return;const current=this.positionInPixels;if(current==null)return;let next;const{min,max}=this.constraintBounds();if(event.key==="Home")next=min;else if(event.key==="End")next=max;else{const physicalDirection=separatorArrowDirection(event,this.effectiveOrientation==="vertical"?"block":"inline",this.effectiveDirection==="rtl");if(physicalDirection!==0){const primaryDirection=this.primary==="end"?-physicalDirection:physicalDirection;next=current+primaryDirection*KEYBOARD_STEP_PERCENT*this.availableSize/100}}next!=null&&(event.preventDefault(),this.requestReposition(next,!1)&&this.emitResizeChange())}get separatorLabel(){const hostLabel=this.getAttribute("aria-label");if(hostLabel!==null)return hostLabel;const number=getNumberFormat(this.effectiveLocale);return this.localize("resizeDivider",void 0,{a:number.format(1),b:number.format(2)})}resizeValueText(position){return this.localize("resizeValuePercent",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(position))})}get ariaBounds(){if(this.availableSize<=0)return{min:0,max:100};const bounds=this.measuredConstraintBounds;return{min:bounds.min/this.availableSize*100,max:bounds.max/this.availableSize*100}}render(){const orientation=this.effectiveOrientation,startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100),ariaBounds=this.ariaBounds,position=Math.round(this.position);return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
data-orientation=${orientation}
|
|
@@ -162,4 +162,4 @@ readonly:boolean;
|
|
|
162
162
|
accessibleLabel:string|null;private _effectiveOrientation;private resizeObserver?;private resizeObservedElement?;private resizeObserverOwnerDocument?;private resizeObserverGeneration;private pendingStepFocus?;private baseEl?;private measuredInlineSize;private orientationBreakpoints;private scrollOverflow;
|
|
163
163
|
/** The live layout/navigation axis after applying `orientationBreakpoint` -- identical to
|
|
164
164
|
* `orientation` whenever that's unset. See the class doc. */
|
|
165
|
-
get effectiveOrientation():LyraOrientation;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncScrollTabStop;private updateEffectiveOrientation;private armResizeObserver;private resetResizeObserver;private selectStep;private focusStep;private onKeyDown;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-stepper':LyraStepper;}}
|
|
165
|
+
get effectiveOrientation():LyraOrientation;connectedCallback():void;private seedInlineSize;private orientationInlineSize;disconnectedCallback():void;adoptedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncScrollTabStop;private updateEffectiveOrientation;private armResizeObserver;private resetResizeObserver;private selectStep;private focusStep;private onKeyDown;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-stepper':LyraStepper;}}
|
|
@@ -12,7 +12,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,quer
|
|
|
12
12
|
focusable="false"
|
|
13
13
|
>
|
|
14
14
|
<polyline points="5 12.5 10 17.5 19 6.5"></polyline>
|
|
15
|
-
</svg>`}class LyraStepper extends LyraElement{constructor(){super(...arguments),this.effectiveSteps=Object.freeze([]),this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.wrapLabels=!1,this.readonly=!1,this.accessibleLabel=null,this._effectiveOrientation="horizontal",this.resizeObserverGeneration=0,this.measuredInlineSize=Number.POSITIVE_INFINITY,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.
|
|
15
|
+
</svg>`}class LyraStepper extends LyraElement{constructor(){super(...arguments),this.effectiveSteps=Object.freeze([]),this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.wrapLabels=!1,this.readonly=!1,this.accessibleLabel=null,this._effectiveOrientation="horizontal",this.resizeObserverGeneration=0,this.measuredInlineSize=Number.POSITIVE_INFINITY,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.orientationInlineSize(),!0)),this.scrollOverflow=observeScrollOverflow(this,()=>this.baseEl,()=>this.syncScrollTabStop()),this.onKeyDown=e=>{if(this.readonly||e.isComposing||e.keyCode===229||e.altKey||e.ctrlKey||e.metaKey)return;const navigable=this.steps.map((step,index)=>({step,index})).filter(({step})=>!step.disabled);if(navigable.length===0)return;const focused=shadowFocusTarget(this),focusedIndex=Number(focused?.dataset.index),currentIndex=navigable.findIndex(item=>item.index===focusedIndex);if(e.key==="Enter"||e.key===" "){if(e.preventDefault(),currentIndex>=0){const target=navigable[currentIndex];this.selectStep(target.step,target.index)}return}const targetIndex=resolveListMove(e,{count:navigable.length,current:currentIndex,orientation:this.effectiveOrientation==="vertical"?"vertical":"horizontal",direction:this.effectiveDirection,wrap:!1,clamp:!0,backwardFromMissing:"first"});targetIndex!==null&&(e.preventDefault(),this.focusStep(navigable[targetIndex].index))}}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}get steps(){return this.effectiveSteps}set steps(value){if(value===this.stepsSource||value===this.effectiveSteps)return;this.stepsSource=value;const previous=this.effectiveSteps;this.effectiveSteps=snapshotSteps(value),this.requestUpdate("steps",previous)}get effectiveOrientation(){return this._effectiveOrientation}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.orientationBreakpoints.containerObservationEnabled&&this.seedInlineSize(),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}seedInlineSize(){const hostWidth=this.getBoundingClientRect().width;hostWidth>0&&(this.measuredInlineSize=hostWidth)}orientationInlineSize(){return this.orientationBreakpoints.containerObservationEnabled?this.baseEl?.clientWidth??this.measuredInlineSize:this.measuredInlineSize}disconnectedCallback(){super.disconnectedCallback(),this.resetResizeObserver()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),changed.has("steps")){const focusedStep=shadowFocusTarget(this);focusedStep?.getAttribute("part")==="step"&&(this.pendingStepFocus={stepId:focusedStep.dataset.stepId??"",index:Number(focusedStep.dataset.index)})}(changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.orientationBreakpoints.configure(this.orientationBreakpoint,this.orientationBreakpointBasis),!this.hasUpdated&&this.isConnected&&this.orientationBreakpoints.containerObservationEnabled&&this.seedInlineSize(),(changed.has("orientation")||changed.has("narrowOrientation")||changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.updateEffectiveOrientation(this.orientationInlineSize(),this.hasUpdated&&this.orientationBreakpointBasis==="viewport")}updated(changed){super.updated(changed);const base=this.renderRoot.querySelector('[part~="base"]')??void 0;if(syncAriaDescribedByElements(this,base,this.getAttribute("aria-describedby")),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="step"]')),this.syncScrollTabStop(),this.pendingStepFocus!==void 0){const focusedOccurrence=this.pendingStepFocus;this.pendingStepFocus=void 0;const enabledIdentityMatches=[...this.renderRoot.querySelectorAll('[part="step"]')].filter(step=>step.dataset.stepId===focusedOccurrence.stepId&&step.getAttribute("aria-disabled")!=="true");(enabledIdentityMatches.find(step=>Number(step.dataset.index)===focusedOccurrence.index)??(enabledIdentityMatches.length===1?enabledIdentityMatches[0]:void 0)??this.renderRoot.querySelector('[part="step"][tabindex="0"]'))?.focus()}(changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&(this.orientationBreakpoints.containerObservationEnabled?this.armResizeObserver():this.resetResizeObserver())}syncScrollTabStop(){const base=this.baseEl;if(!base)return;const scrollable=this.effectiveOrientation==="horizontal"&&base.hasAttribute(SCROLL_OVERFLOW_ATTRIBUTE);this.readonly&&scrollable?base.setAttribute("tabindex","0"):base.removeAttribute("tabindex")}updateEffectiveOrientation(width,emitOnChange){const next=this.orientationBreakpoints.isBelow(width)?this.narrowOrientation:this.orientation;this.orientationBreakpoints.active?this.setAttribute("data-effective-orientation",next):this.removeAttribute("data-effective-orientation"),next!==this._effectiveOrientation&&(this._effectiveOrientation=next,this.requestUpdate(),emitOnChange&&this.emit("lr-stepper-orientation-change",{orientation:next}))}armResizeObserver(){const observedElement=this.baseEl;if(!this.isConnected||!observedElement)return;const ownerDocument=this.ownerDocument;if(this.resizeObserver&&this.resizeObservedElement===observedElement&&this.resizeObserverOwnerDocument===ownerDocument)return;this.resetResizeObserver();const ResizeObserverConstructor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverConstructor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverConstructor(entries=>{const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:observedElement.getBoundingClientRect().width;ownerDocument.defaultView?.requestAnimationFrame(()=>{this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.baseEl!==observedElement||(this.measuredInlineSize=width,this.updateEffectiveOrientation(width,!0))})});this.resizeObserver=observer,this.resizeObservedElement=observedElement,this.resizeObserverOwnerDocument=ownerDocument,observer.observe(observedElement)}resetResizeObserver(){this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObservedElement=void 0,this.resizeObserverOwnerDocument=void 0}selectStep(step,index){this.readonly||step.disabled||this.emit("lr-step-select",{stepId:step.stepId,index})}focusStep(index){this.renderRoot.querySelector(`[part="step"][data-index="${index}"]`)?.focus()}render(){const currentIndex=this.steps.findIndex(step=>step.state==="current"),rovingIndex=this.readonly?-1:currentIndex>=0&&!this.steps[currentIndex].disabled?currentIndex:this.steps.findIndex(step=>!step.disabled),numberFormat=getNumberFormat(this.effectiveLocale),stepGlyphs=(step,index)=>html`${step.icon!==void 0?html`<span part="step-icon" aria-hidden="true" inert
|
|
16
16
|
>${step.icon}</span
|
|
17
17
|
>`:nothing}
|
|
18
18
|
${step.state==="completed"?checkmarkGlyph():html`<span part="step-index"
|
|
@@ -168,4 +168,4 @@ get views():readonly LyraWidgetView[];set views(value:readonly LyraWidgetView[])
|
|
|
168
168
|
/** The currently active view's `viewId` -- defaults to the first entry of `views` (or `''` when
|
|
169
169
|
* `views` is empty). Settable directly by a consumer wanting to control the active view
|
|
170
170
|
* externally; also updated internally when a view toggle is clicked. */
|
|
171
|
-
activeViewId:string;private readonly slotPresence;private labelSlotText?;private overlayHandle?;private readonly nativeModal;private explicitTrigger?;private fullscreenOpener?;private readonly labelTextObserver;private ownerRealmGeneration;private readonly bodyId;private focusedViewIdBeforeUpdate?;private get storageFullKey();private persistReady;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resetOwnerRealmWork;private queueOwnerMicrotask;private activateFullscreenOverlay;private deactivateFullscreenOverlay;private onLabelSlotChange;private syncLabelSlot;private readLabelSlotText;private setActiveView;private dispatchingCollapse;private requestCollapse;private toggleCollapsed;private requestFullscreenChange;private toggleFullscreen;private dismissFullscreen;private onBackdropClick;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-widget':LyraWidget;}}
|
|
171
|
+
activeViewId:string;private readonly slotPresence;private labelSlotText?;private overlayHandle?;private readonly nativeModal;private readonly modalSurface;private explicitTrigger?;private fullscreenOpener?;private readonly labelTextObserver;private ownerRealmGeneration;private readonly bodyId;private focusedViewIdBeforeUpdate?;private get storageFullKey();private persistReady;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resetOwnerRealmWork;private queueOwnerMicrotask;private activateFullscreenOverlay;private deactivateFullscreenOverlay;private onLabelSlotChange;private syncLabelSlot;private readLabelSlotText;private setActiveView;private dispatchingCollapse;private requestCollapse;private toggleCollapsed;private requestFullscreenChange;private toggleFullscreen;private dismissFullscreen;private onBackdropClick;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-widget':LyraWidget;}}
|